briefcase-core 5.0.0

Compliance monitoring, auditing, and evaluating third-party artificial intelligence systems and models.
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
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
use crate::models::DecisionSnapshot;
#[cfg(feature = "sqlite-storage")]
use crate::models::Output;

#[cfg(all(feature = "sqlite-storage", feature = "async"))]
use crate::storage::StorageBackend;
use serde::{Deserialize, Serialize};
use thiserror::Error;

pub mod executor;
#[cfg(feature = "async")]
pub use executor::ModelExecutor;
pub use executor::{
    ComparisonResult, ExecutionConfig, ExecutionResult, FieldComparison, SyncModelExecutor,
};

#[cfg(feature = "sqlite-storage")]
pub mod sync;
#[cfg(feature = "sqlite-storage")]
pub use sync::SyncReplayEngine;

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ReplayMode {
    Strict,         // Exact byte-for-byte match required
    Tolerant,       // Allow minor differences (whitespace, formatting)
    ValidationOnly, // Validate inputs/context without re-executing
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ReplayStatus {
    Pending,
    Running,
    Success,
    Failed,
    Partial, // Some decisions matched, some didn't
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReplayResult {
    pub status: ReplayStatus,
    pub original_snapshot: DecisionSnapshot,
    pub replay_output: Option<serde_json::Value>,
    pub outputs_match: bool,
    pub diff: Option<SnapshotDiff>,
    pub policy_violations: Vec<PolicyViolation>,
    pub execution_time_ms: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SnapshotDiff {
    pub inputs_changed: bool,
    pub outputs_changed: bool,
    pub model_params_changed: bool,
    pub execution_time_delta_ms: f64,
    pub changes: Vec<FieldChange>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FieldChange {
    pub field_path: String,
    pub old_value: serde_json::Value,
    pub new_value: serde_json::Value,
    pub change_type: ChangeType,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ChangeType {
    Added,
    Removed,
    Modified,
}

#[derive(Debug, Clone)]
pub struct ReplayPolicy {
    pub name: String,
    pub rules: Vec<ValidationRule>,
}

impl ReplayPolicy {
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            rules: Vec::new(),
        }
    }

    pub fn add_rule(mut self, rule: ValidationRule) -> Self {
        self.rules.push(rule);
        self
    }

    pub fn with_exact_match(mut self, field: impl Into<String>) -> Self {
        self.rules.push(ValidationRule {
            field: field.into(),
            comparator: Comparator::ExactMatch,
            threshold: 1.0,
        });
        self
    }

    pub fn with_similarity_threshold(mut self, field: impl Into<String>, threshold: f64) -> Self {
        self.rules.push(ValidationRule {
            field: field.into(),
            comparator: Comparator::SemanticSimilarity,
            threshold,
        });
        self
    }
}

#[derive(Debug, Clone)]
pub struct ValidationRule {
    pub field: String,
    pub comparator: Comparator,
    pub threshold: f64,
}

#[derive(Debug, Clone, PartialEq)]
pub enum Comparator {
    ExactMatch,
    SemanticSimilarity,
    MaxIncreasePercent,
    MaxDecreasePercent,
    WithinRange,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PolicyViolation {
    pub rule_name: String,
    pub field: String,
    pub expected: String,
    pub actual: String,
    pub message: String,
}

/// The outputs a replay produced, or `None` when nothing re-executed.
#[cfg(feature = "sqlite-storage")]
fn replayed_outputs(result: &ReplayResult) -> Option<Vec<Output>> {
    let value = result.replay_output.as_ref()?;
    serde_json::from_value::<Vec<Output>>(value.clone()).ok()
}

/// Resolve a rule's field against a replay's outputs. `output` and an empty
/// field both mean "the first output", matching `recorded_field_value`.
#[cfg(feature = "sqlite-storage")]
fn field_from_outputs(outputs: &[Output], field: &str) -> Option<serde_json::Value> {
    if field == "output" || field.is_empty() {
        return outputs.first().map(|o| o.value.clone());
    }
    outputs
        .iter()
        .find(|o| o.name == field)
        .map(|o| o.value.clone())
}

/// Render a JSON value for a violation message: strings unquoted, everything
/// else as compact JSON.
#[cfg(feature = "sqlite-storage")]
fn value_text(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::String(s) => s.clone(),
        other => other.to_string(),
    }
}

#[cfg(feature = "sqlite-storage")]
fn text_similarity(a: &str, b: &str) -> f64 {
    if a == b {
        1.0
    } else {
        strsim::normalized_levenshtein(a, b)
    }
}

/// What a replay produced, as far as a policy rule can see it.
#[cfg(feature = "sqlite-storage")]
pub(crate) struct Replayed<'a> {
    pub outputs: &'a [Output],
    /// How long the re-execution took.
    pub execution_time_ms: f64,
}

/// Build the replayed view of a result, or `None` when nothing re-executed.
#[cfg(feature = "sqlite-storage")]
pub(crate) fn check_result_policy(
    result: &ReplayResult,
    policy: &ReplayPolicy,
) -> Vec<PolicyViolation> {
    let outputs = replayed_outputs(result);
    let replayed = outputs.as_deref().map(|outputs| Replayed {
        outputs,
        execution_time_ms: result.execution_time_ms,
    });
    check_policy(&result.original_snapshot, replayed.as_ref(), policy)
}

/// Check each rule by comparing the recorded value against the replayed
/// one. `replayed` is `None` when nothing re-executed, which makes every
/// rule a violation: an unchecked rule must never read as a pass.
#[cfg(feature = "sqlite-storage")]
pub(crate) fn check_policy(
    original: &DecisionSnapshot,
    replayed: Option<&Replayed<'_>>,
    policy: &ReplayPolicy,
) -> Vec<PolicyViolation> {
    policy
        .rules
        .iter()
        .filter_map(|rule| check_rule(original, replayed, rule))
        .collect()
}

/// The recorded value a rule's field names. A rule can reference the
/// snapshot-level fields `function_name` and `execution_time_ms`, the first
/// output (`output` or an empty field), or any output by name.
#[cfg(feature = "sqlite-storage")]
fn recorded_field_value(snapshot: &DecisionSnapshot, field: &str) -> Option<serde_json::Value> {
    match field {
        "function_name" => Some(serde_json::Value::String(snapshot.function_name.clone())),
        "execution_time_ms" => snapshot
            .execution_time_ms
            .and_then(serde_json::Number::from_f64)
            .map(serde_json::Value::Number),
        // Anything else names an output. A policy is written against the
        // fields a decision produced, so `with_exact_match("category")`
        // has to resolve to the output called "category".
        other => field_from_outputs(&snapshot.outputs, other),
    }
}

/// The replayed counterpart of `recorded_field_value`, resolving the same
/// field names so that a snapshot-level rule compares like with like.
#[cfg(feature = "sqlite-storage")]
fn replayed_field_value(
    original: &DecisionSnapshot,
    replayed: &Replayed<'_>,
    field: &str,
) -> Option<serde_json::Value> {
    match field {
        // A replay re-executes the recorded decision, so the function it
        // ran is the recorded one by construction.
        "function_name" => Some(serde_json::Value::String(original.function_name.clone())),
        "execution_time_ms" => {
            serde_json::Number::from_f64(replayed.execution_time_ms).map(serde_json::Value::Number)
        }
        other => field_from_outputs(replayed.outputs, other),
    }
}

#[cfg(feature = "sqlite-storage")]
fn check_rule(
    original: &DecisionSnapshot,
    replayed: Option<&Replayed<'_>>,
    rule: &ValidationRule,
) -> Option<PolicyViolation> {
    // A rule on a field the decision never recorded cannot be checked,
    // and an unchecked rule must never read as a pass.
    let Some(recorded) = recorded_field_value(original, &rule.field) else {
        return Some(PolicyViolation {
            rule_name: rule.field.clone(),
            field: rule.field.clone(),
            expected: "a recorded value".to_string(),
            actual: "absent".to_string(),
            message: format!(
                "Rule names field '{}', which the recorded decision does not have",
                rule.field
            ),
        });
    };

    let Some(replayed) = replayed else {
        return Some(PolicyViolation {
            rule_name: rule.field.clone(),
            field: rule.field.clone(),
            expected: value_text(&recorded),
            actual: "not replayed".to_string(),
            message: format!(
                "Rule on '{}' could not be checked: no executor is set, so nothing \
                 re-executed. Set one with with_executor.",
                rule.field
            ),
        });
    };

    let Some(actual) = replayed_field_value(original, replayed, &rule.field) else {
        return Some(PolicyViolation {
            rule_name: rule.field.clone(),
            field: rule.field.clone(),
            expected: value_text(&recorded),
            actual: "absent".to_string(),
            message: format!("Replay produced no '{}' output", rule.field),
        });
    };

    let violation = |expected: String, message: String| {
        Some(PolicyViolation {
            rule_name: rule.field.clone(),
            field: rule.field.clone(),
            expected,
            actual: value_text(&actual),
            message,
        })
    };

    match rule.comparator {
        Comparator::ExactMatch => {
            if recorded == actual {
                None
            } else {
                violation(
                    value_text(&recorded),
                    format!("Field '{}' changed on replay", rule.field),
                )
            }
        }
        Comparator::SemanticSimilarity => {
            let similarity = text_similarity(&value_text(&recorded), &value_text(&actual));
            if similarity >= rule.threshold {
                None
            } else {
                violation(
                    format!("similarity >= {}", rule.threshold),
                    format!(
                        "Field '{}' similarity {:.3} is below the {} threshold",
                        rule.field, similarity, rule.threshold
                    ),
                )
            }
        }
        Comparator::MaxIncreasePercent
        | Comparator::MaxDecreasePercent
        | Comparator::WithinRange => {
            let (Some(before), Some(after)) = (recorded.as_f64(), actual.as_f64()) else {
                return violation(
                    "a number".to_string(),
                    format!(
                        "Field '{}' is not numeric, so {:?} cannot be applied",
                        rule.field, rule.comparator
                    ),
                );
            };
            let ok = match rule.comparator {
                Comparator::MaxIncreasePercent => {
                    before == 0.0 || (after - before) / before * 100.0 <= rule.threshold
                }
                Comparator::MaxDecreasePercent => {
                    before == 0.0 || (before - after) / before * 100.0 <= rule.threshold
                }
                _ => (after - before).abs() <= rule.threshold,
            };
            if ok {
                None
            } else {
                violation(
                    format!("{:?} within {}", rule.comparator, rule.threshold),
                    format!("Field '{}' moved from {} to {}", rule.field, before, after),
                )
            }
        }
    }
}

#[cfg(all(feature = "sqlite-storage", feature = "async"))]
#[derive(Clone)]
pub struct ReplayEngine<S: StorageBackend> {
    storage: S,
    default_mode: ReplayMode,
    executor: Option<std::sync::Arc<dyn ModelExecutor>>,
    execution_config: ExecutionConfig,
}

#[cfg(all(feature = "sqlite-storage", feature = "async"))]
impl<S: StorageBackend> ReplayEngine<S> {
    pub fn new(storage: S) -> Self {
        Self {
            storage,
            default_mode: ReplayMode::Tolerant,
            executor: None,
            execution_config: ExecutionConfig::default(),
        }
    }

    pub fn with_mode(storage: S, mode: ReplayMode) -> Self {
        Self {
            storage,
            default_mode: mode,
            executor: None,
            execution_config: ExecutionConfig::default(),
        }
    }

    /// Set a model executor for the replay engine
    pub fn with_executor(mut self, executor: std::sync::Arc<dyn ModelExecutor>) -> Self {
        self.executor = Some(executor);
        self
    }

    /// Set the configuration handed to the executor on every replay. Its
    /// `timeout_ms` bounds each execution; 0 disables the bound.
    pub fn with_execution_config(mut self, config: ExecutionConfig) -> Self {
        self.execution_config = config;
        self
    }

    /// Set the executor in place, for callers holding the engine behind a
    /// `&mut` (the Python binding, chiefly).
    pub fn set_executor(&mut self, executor: std::sync::Arc<dyn ModelExecutor>) {
        self.executor = Some(executor);
    }

    /// Get a reference to the current executor, if any
    pub fn executor(&self) -> Option<&dyn ModelExecutor> {
        self.executor.as_ref().map(|arc| arc.as_ref())
    }

    /// Get the default replay mode
    pub fn default_mode(&self) -> &ReplayMode {
        &self.default_mode
    }

    /// Replay a snapshot by ID
    pub async fn replay(
        &self,
        snapshot_id: &str,
        mode: Option<ReplayMode>,
        _context_overrides: Option<std::collections::HashMap<String, serde_json::Value>>,
    ) -> Result<ReplayResult, ReplayError> {
        let start_time = std::time::Instant::now();
        let replay_mode = mode.unwrap_or_else(|| self.default_mode.clone());

        // Load the original snapshot
        let original_snapshot = match self.storage.load_decision(snapshot_id).await {
            Ok(snapshot) => snapshot,
            Err(e) => {
                return Err(ReplayError::SnapshotNotFound(format!(
                    "Failed to load snapshot {}: {}",
                    snapshot_id, e
                )))
            }
        };

        match replay_mode {
            ReplayMode::ValidationOnly => {
                // The snapshot loaded and deserialized; nothing re-executed.
                // As in `simulate_replay`, that is Pending with no match
                // claimed: "not compared" must never read as "matched".
                let execution_time = start_time.elapsed().as_millis() as f64;

                Ok(ReplayResult {
                    status: ReplayStatus::Pending,
                    original_snapshot,
                    replay_output: None,
                    outputs_match: false,
                    diff: None,
                    policy_violations: Vec::new(),
                    execution_time_ms: execution_time,
                })
            }
            ReplayMode::Strict | ReplayMode::Tolerant => {
                // Use the executor if available, otherwise fall back to simulation
                self.execute_replay(&original_snapshot, replay_mode, start_time)
                    .await
            }
        }
    }

    /// Replay with policy validation
    pub async fn replay_with_policy(
        &self,
        snapshot_id: &str,
        policy: &ReplayPolicy,
        mode: Option<ReplayMode>,
    ) -> Result<ReplayResult, ReplayError> {
        let mut result = self.replay(snapshot_id, mode, None).await?;

        // Rules are checked against what the replay produced, so a policy can
        // only pass when something actually re-executed.
        result.policy_violations = check_result_policy(&result, policy);

        if !result.policy_violations.is_empty() {
            result.status = ReplayStatus::Failed;
        }

        Ok(result)
    }

    /// Compare two snapshots
    pub async fn diff(&self, original_id: &str, new_id: &str) -> Result<SnapshotDiff, ReplayError> {
        let original = self.storage.load_decision(original_id).await.map_err(|e| {
            ReplayError::SnapshotNotFound(format!("Original snapshot not found: {}", e))
        })?;

        let new =
            self.storage.load_decision(new_id).await.map_err(|e| {
                ReplayError::SnapshotNotFound(format!("New snapshot not found: {}", e))
            })?;

        Ok(self.calculate_diff(&original, &new))
    }

    /// Validate a snapshot against a policy (without re-executing)
    pub async fn validate(
        &self,
        snapshot_id: &str,
        policy: &ReplayPolicy,
    ) -> Result<Vec<PolicyViolation>, ReplayError> {
        let snapshot = self
            .storage
            .load_decision(snapshot_id)
            .await
            .map_err(|e| ReplayError::SnapshotNotFound(e.to_string()))?;

        self.validate_against_policy(&snapshot, policy).await
    }

    /// Batch replay multiple snapshots, at most `concurrency` at a time. A
    /// `concurrency` of 0 is treated as 1.
    pub async fn replay_batch(
        &self,
        snapshot_ids: &[String],
        mode: Option<ReplayMode>,
        concurrency: usize,
    ) -> Vec<Result<ReplayResult, ReplayError>> {
        let semaphore = tokio::sync::Semaphore::new(concurrency.max(1));
        let replay_mode = mode.unwrap_or_else(|| self.default_mode.clone());

        let tasks: Vec<_> = snapshot_ids
            .iter()
            .map(|id| {
                let id = id.clone();
                let mode = replay_mode.clone();
                let semaphore = &semaphore;
                async move {
                    let _permit = semaphore.acquire().await.unwrap();
                    self.replay(&id, Some(mode), None).await
                }
            })
            .collect();

        futures::future::join_all(tasks).await
    }

    /// Get replay statistics for a set of snapshots
    pub async fn get_replay_stats(
        &self,
        snapshot_ids: &[String],
    ) -> Result<ReplayStats, ReplayError> {
        let results = self.replay_batch(snapshot_ids, None, 4).await;

        let mut stats = ReplayStats {
            total_replays: results.len(),
            ..Default::default()
        };

        for result in results {
            match result {
                Ok(replay_result) => {
                    stats.total_execution_time_ms += replay_result.execution_time_ms;

                    // Pending/Running mean nothing re-executed, so there was
                    // no comparison to count as a match or a mismatch.
                    if matches!(
                        replay_result.status,
                        ReplayStatus::Pending | ReplayStatus::Running
                    ) {
                        stats.unverified_replays += 1;
                    } else {
                        stats.successful_replays += 1;
                        if replay_result.outputs_match {
                            stats.exact_matches += 1;
                        } else {
                            stats.mismatches += 1;
                        }
                    }
                }
                Err(_) => {
                    stats.failed_replays += 1;
                }
            }
        }

        let completed = stats.successful_replays + stats.unverified_replays;
        stats.average_execution_time_ms = if completed > 0 {
            stats.total_execution_time_ms / completed as f64
        } else {
            0.0
        };

        Ok(stats)
    }

    // Private helper methods

    async fn execute_replay(
        &self,
        original: &DecisionSnapshot,
        mode: ReplayMode,
        start_time: std::time::Instant,
    ) -> Result<ReplayResult, ReplayError> {
        if let Some(ref executor) = self.executor {
            // Check model support
            if let Some(ref params) = original.model_parameters {
                if !executor.supports_model(&params.model_name) {
                    return Err(ReplayError::ExecutionError(format!(
                        "Executor '{}' does not support model '{}'",
                        executor.executor_name(),
                        params.model_name
                    )));
                }
            }

            let config = &self.execution_config;
            let execution = executor.execute(
                &original.inputs,
                original.model_parameters.as_ref(),
                &original.context,
                config,
            );
            let exec_result = if config.timeout_ms == 0 {
                execution.await?
            } else {
                let limit = std::time::Duration::from_millis(config.timeout_ms);
                match tokio::time::timeout(limit, execution).await {
                    Ok(result) => result?,
                    Err(_) => {
                        return Err(ReplayError::ExecutionError(format!(
                            "Executor '{}' timed out after {} ms",
                            executor.executor_name(),
                            config.timeout_ms
                        )))
                    }
                }
            };

            let execution_time = start_time.elapsed().as_millis() as f64;

            // Compare outputs based on mode
            let tolerance = match mode {
                ReplayMode::Strict => 1.0,         // Exact match
                ReplayMode::Tolerant => 0.8,       // 80% similarity
                ReplayMode::ValidationOnly => 0.0, // Don't care about outputs
            };

            let comparison =
                executor.compare_outputs(&original.outputs, &exec_result.outputs, tolerance);

            let replay_output = serde_json::to_value(&exec_result.outputs).ok();

            Ok(ReplayResult {
                status: if comparison.is_match {
                    ReplayStatus::Success
                } else {
                    ReplayStatus::Failed
                },
                original_snapshot: original.clone(),
                replay_output,
                outputs_match: comparison.is_match,
                diff: Some(SnapshotDiff {
                    inputs_changed: false,
                    outputs_changed: !comparison.is_match,
                    model_params_changed: false,
                    execution_time_delta_ms: execution_time
                        - original.execution_time_ms.unwrap_or(0.0),
                    changes: comparison
                        .field_comparisons
                        .iter()
                        .filter(|c| !c.is_match)
                        .map(|c| FieldChange {
                            field_path: format!("output.{}", c.field_name),
                            old_value: c.original_value.clone(),
                            new_value: c.replayed_value.clone(),
                            change_type: ChangeType::Modified,
                        })
                        .collect(),
                }),
                policy_violations: Vec::new(),
                execution_time_ms: execution_time,
            })
        } else {
            // Fall back to simulation if no executor is set
            self.simulate_replay(original, mode, start_time).await
        }
    }

    async fn simulate_replay(
        &self,
        original: &DecisionSnapshot,
        mode: ReplayMode,
        start_time: std::time::Instant,
    ) -> Result<ReplayResult, ReplayError> {
        // In a real implementation, this would:
        // 1. Recreate the execution environment
        // 2. Call the original function with the same inputs
        // 3. Compare outputs

        // For simulation, we'll create a "replay" that matches the original
        // Use the original execution time from the snapshot, not the replay elapsed time
        let execution_time = original
            .execution_time_ms
            .unwrap_or_else(|| start_time.elapsed().as_millis() as f64);

        // Simulate some processing time
        tokio::time::sleep(tokio::time::Duration::from_millis(1)).await;

        // Nothing re-executed, so there is no second answer to compare
        // against. Reporting a match here would turn "not checked" into
        // "verified", which is the one thing a replay must never do.
        let outputs_match = false;
        let _ = mode;

        Ok(ReplayResult {
            // Pending, not Failed: the decision did not disagree, it was never
            // re-run. Set an executor with `with_executor` to get a verdict.
            status: ReplayStatus::Pending,
            original_snapshot: original.clone(),
            replay_output: None,
            outputs_match,
            diff: None,
            policy_violations: Vec::new(),
            execution_time_ms: execution_time,
        })
    }

    async fn validate_against_policy(
        &self,
        snapshot: &DecisionSnapshot,
        policy: &ReplayPolicy,
    ) -> Result<Vec<PolicyViolation>, ReplayError> {
        // No replay ran, so there is nothing to compare the recorded values
        // against. Every rule reports as unverified rather than passing.
        Ok(check_policy(snapshot, None, policy))
    }

    fn calculate_diff(&self, original: &DecisionSnapshot, new: &DecisionSnapshot) -> SnapshotDiff {
        let mut changes = Vec::new();

        // Compare function names
        if original.function_name != new.function_name {
            changes.push(FieldChange {
                field_path: "function_name".to_string(),
                old_value: serde_json::Value::String(original.function_name.clone()),
                new_value: serde_json::Value::String(new.function_name.clone()),
                change_type: ChangeType::Modified,
            });
        }

        // Compare inputs
        let inputs_changed = original.inputs != new.inputs;
        if inputs_changed {
            changes.push(FieldChange {
                field_path: "inputs".to_string(),
                old_value: serde_json::to_value(&original.inputs).unwrap(),
                new_value: serde_json::to_value(&new.inputs).unwrap(),
                change_type: ChangeType::Modified,
            });
        }

        // Compare outputs
        let outputs_changed = original.outputs != new.outputs;
        if outputs_changed {
            changes.push(FieldChange {
                field_path: "outputs".to_string(),
                old_value: serde_json::to_value(&original.outputs).unwrap(),
                new_value: serde_json::to_value(&new.outputs).unwrap(),
                change_type: ChangeType::Modified,
            });
        }

        // Compare model parameters
        let model_params_changed = original.model_parameters != new.model_parameters;
        if model_params_changed {
            changes.push(FieldChange {
                field_path: "model_parameters".to_string(),
                old_value: serde_json::to_value(&original.model_parameters).unwrap(),
                new_value: serde_json::to_value(&new.model_parameters).unwrap(),
                change_type: ChangeType::Modified,
            });
        }

        let execution_time_delta_ms = match (original.execution_time_ms, new.execution_time_ms) {
            (Some(old), Some(new)) => new - old,
            _ => 0.0,
        };

        SnapshotDiff {
            inputs_changed,
            outputs_changed,
            model_params_changed,
            execution_time_delta_ms,
            changes,
        }
    }
}

#[derive(Debug, Clone, Default)]
pub struct ReplayStats {
    pub total_replays: usize,
    /// Replays that re-executed and produced a verdict (match or mismatch).
    pub successful_replays: usize,
    /// Replays that returned an error.
    pub failed_replays: usize,
    /// Replays that loaded the snapshot but re-executed nothing (no executor,
    /// or validation-only mode), so there is no verdict to count.
    pub unverified_replays: usize,
    pub exact_matches: usize,
    pub mismatches: usize,
    pub total_execution_time_ms: f64,
    pub average_execution_time_ms: f64,
}

#[derive(Error, Debug, Clone, PartialEq)]
pub enum ReplayError {
    #[error("Snapshot not found: {0}")]
    SnapshotNotFound(String),
    #[error("Storage error: {0}")]
    StorageError(String),
    #[error("Execution error: {0}")]
    ExecutionError(String),
    #[error("Policy violations: {0:?}")]
    PolicyViolation(Vec<PolicyViolation>),
}

#[cfg(feature = "sqlite-storage")]
impl From<crate::storage::StorageError> for ReplayError {
    fn from(err: crate::storage::StorageError) -> Self {
        ReplayError::StorageError(err.to_string())
    }
}

#[cfg(all(test, feature = "sqlite-storage", feature = "async"))]
mod tests {
    use super::*;
    use crate::models::*;
    use crate::storage::SqliteBackend;
    use serde_json::json;

    async fn create_test_decision() -> DecisionSnapshot {
        let input = Input::new("test_input", json!("hello"), "string");
        let output = Output::new("test_output", json!("world"), "string");
        let model_params = ModelParameters::new("gpt-4");

        DecisionSnapshot::new("test_function")
            .add_input(input)
            .add_output(output)
            .with_model_parameters(model_params)
            .with_execution_time(100.0)
    }

    #[tokio::test]
    async fn test_replay_engine_creation() {
        let storage = SqliteBackend::in_memory().unwrap();
        let engine = ReplayEngine::new(storage);
        assert!(matches!(engine.default_mode, ReplayMode::Tolerant));
    }

    #[tokio::test]
    async fn test_replay_validation_only() {
        let storage = SqliteBackend::in_memory().unwrap();
        let engine = ReplayEngine::new(storage);
        let decision = create_test_decision().await;

        // Save the decision first
        let decision_id = engine.storage.save_decision(&decision).await.unwrap();

        // Replay in validation-only mode
        let result = engine
            .replay(&decision_id, Some(ReplayMode::ValidationOnly), None)
            .await
            .unwrap();

        // Nothing was compared, so no match may be claimed.
        assert_eq!(result.status, ReplayStatus::Pending);
        assert!(!result.outputs_match);
        assert!(result.replay_output.is_none());
    }

    #[tokio::test]
    async fn test_replay_tolerant_mode() {
        let storage = SqliteBackend::in_memory().unwrap();
        let engine = ReplayEngine::new(storage);
        let decision = create_test_decision().await;

        // Save the decision first
        let decision_id = engine.storage.save_decision(&decision).await.unwrap();

        // Replay in tolerant mode. No executor is set, so this loads the
        // snapshot and reports that nothing was verified.
        let result = engine
            .replay(&decision_id, Some(ReplayMode::Tolerant), None)
            .await
            .unwrap();

        assert_eq!(result.status, ReplayStatus::Pending);
        assert!(!result.outputs_match);
        assert!(result.replay_output.is_none());
        assert_eq!(result.original_snapshot.function_name, "test_function");
    }

    #[tokio::test]
    async fn test_replay_with_policy() {
        let storage = SqliteBackend::in_memory().unwrap();
        let engine = ReplayEngine::new(storage);
        let decision = create_test_decision().await;

        // Save the decision first
        let decision_id = engine.storage.save_decision(&decision).await.unwrap();

        // Create a policy
        let policy = ReplayPolicy::new("test_policy")
            .with_exact_match("function_name")
            .with_similarity_threshold("output", 0.9);

        // Replay with policy. Without an executor there is nothing to compare
        // against, so every rule reports as unchecked rather than passing.
        let result = engine
            .replay_with_policy(&decision_id, &policy, None)
            .await
            .unwrap();

        assert_eq!(result.status, ReplayStatus::Failed);
        assert_eq!(result.policy_violations.len(), 2);
        assert!(result
            .policy_violations
            .iter()
            .all(|v| v.actual == "not replayed"));
    }

    #[tokio::test]
    async fn test_diff_calculation() {
        let storage = SqliteBackend::in_memory().unwrap();
        let engine = ReplayEngine::new(storage);

        let decision1 = create_test_decision().await;
        let mut decision2 = create_test_decision().await;
        decision2.function_name = "different_function".to_string();

        // Save both decisions
        let id1 = engine.storage.save_decision(&decision1).await.unwrap();
        let id2 = engine.storage.save_decision(&decision2).await.unwrap();

        // Calculate diff
        let diff = engine.diff(&id1, &id2).await.unwrap();

        assert!(!diff.changes.is_empty());
        assert!(diff.changes.iter().any(|c| c.field_path == "function_name"));
    }

    #[tokio::test]
    async fn test_batch_replay() {
        let storage = SqliteBackend::in_memory().unwrap();
        let engine = ReplayEngine::new(storage);

        let mut snapshot_ids = Vec::new();

        // Save multiple decisions
        for i in 0..3 {
            let mut decision = create_test_decision().await;
            decision.function_name = format!("test_function_{}", i);
            let id = engine.storage.save_decision(&decision).await.unwrap();
            snapshot_ids.push(id);
        }

        // Batch replay
        let results = engine.replay_batch(&snapshot_ids, None, 2).await;

        assert_eq!(results.len(), 3);
        assert!(results.iter().all(|r| r.is_ok()));
    }

    #[tokio::test]
    async fn test_replay_stats() {
        let storage = SqliteBackend::in_memory().unwrap();
        let engine = ReplayEngine::new(storage);

        let mut snapshot_ids = Vec::new();

        // Save multiple decisions
        for i in 0..5 {
            let mut decision = create_test_decision().await;
            decision.function_name = format!("test_function_{}", i);
            let id = engine.storage.save_decision(&decision).await.unwrap();
            snapshot_ids.push(id);
        }

        // Get stats
        let stats = engine.get_replay_stats(&snapshot_ids).await.unwrap();

        // No executor is set, so nothing was verified: these are neither
        // successes nor matches.
        assert_eq!(stats.total_replays, 5);
        assert_eq!(stats.successful_replays, 0);
        assert_eq!(stats.unverified_replays, 5);
        assert_eq!(stats.exact_matches, 0);
        assert_eq!(stats.mismatches, 0);
        assert_eq!(stats.failed_replays, 0);
        assert!(stats.average_execution_time_ms > 0.0);
    }

    #[tokio::test]
    async fn test_replay_batch_zero_concurrency_does_not_hang() {
        let storage = SqliteBackend::in_memory().unwrap();
        let engine = ReplayEngine::new(storage);
        let id = engine
            .storage
            .save_decision(&create_test_decision().await)
            .await
            .unwrap();

        let results = tokio::time::timeout(
            std::time::Duration::from_secs(10),
            engine.replay_batch(&[id], None, 0),
        )
        .await
        .expect("replay_batch with concurrency 0 must complete");
        assert_eq!(results.len(), 1);
        assert!(results[0].is_ok());
    }

    #[tokio::test]
    async fn test_policy_rule_on_missing_field_is_a_violation() {
        let storage = SqliteBackend::in_memory().unwrap();
        let engine = ReplayEngine::new(storage);
        let id = engine
            .storage
            .save_decision(&create_test_decision().await)
            .await
            .unwrap();

        let policy = ReplayPolicy::new("typo").with_exact_match("no_such_field");
        let violations = engine.validate(&id, &policy).await.unwrap();
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].field, "no_such_field");
        assert_eq!(violations[0].actual, "absent");
    }

    #[tokio::test]
    async fn test_nonexistent_snapshot() {
        let storage = SqliteBackend::in_memory().unwrap();
        let engine = ReplayEngine::new(storage);

        let result = engine.replay("nonexistent-id", None, None).await;
        assert!(matches!(result, Err(ReplayError::SnapshotNotFound(_))));
    }

    #[tokio::test]
    async fn test_policy_validation() {
        let storage = SqliteBackend::in_memory().unwrap();
        let engine = ReplayEngine::new(storage);
        let decision = create_test_decision().await;

        // Save the decision first
        let decision_id = engine.storage.save_decision(&decision).await.unwrap();

        // Create a policy that should fail
        let policy = ReplayPolicy::new("strict_policy").with_similarity_threshold("output", 0.3); // Low threshold should trigger violation

        let violations = engine.validate(&decision_id, &policy).await.unwrap();
        assert!(!violations.is_empty());
    }
}

#[cfg(all(test, feature = "sqlite-storage", feature = "async"))]
mod honest_replay_tests {
    use super::executor::{ExecutionConfig, ExecutionResult, ModelExecutor};
    use super::*;
    use crate::models::*;
    use crate::storage::SqliteBackend;
    use async_trait::async_trait;
    use serde_json::json;
    use std::collections::HashMap;
    use std::sync::Arc;

    /// Returns whatever it was told to, so a test can make a replay disagree.
    struct FixedExecutor {
        value: serde_json::Value,
    }

    #[async_trait]
    impl ModelExecutor for FixedExecutor {
        async fn execute(
            &self,
            _inputs: &[Input],
            _model_params: Option<&ModelParameters>,
            _context: &ExecutionContext,
            _config: &ExecutionConfig,
        ) -> Result<ExecutionResult, ReplayError> {
            Ok(ExecutionResult {
                outputs: vec![Output::new("answer", self.value.clone(), "string")],
                execution_time_ms: 1.0,
                metadata: HashMap::new(),
                raw_response: None,
            })
        }
        fn supports_model(&self, _model_name: &str) -> bool {
            true
        }
        fn executor_name(&self) -> &str {
            "fixed"
        }
    }

    async fn stored(answer: &str) -> (SqliteBackend, String) {
        let storage = SqliteBackend::in_memory().unwrap();
        let decision = DecisionSnapshot::new("classify_ticket")
            .add_input(Input::new("text", json!("reset my password"), "string"))
            .add_output(Output::new("answer", json!(answer), "string"))
            .with_model_parameters(ModelParameters::new("gpt-4"));
        let id = storage.save_decision(&decision).await.unwrap();
        (storage, id)
    }

    #[tokio::test]
    async fn a_policy_rule_can_name_snapshot_level_fields() {
        let storage = SqliteBackend::in_memory().unwrap();
        let decision = DecisionSnapshot::new("classify_ticket")
            .add_input(Input::new("text", json!("reset my password"), "string"))
            .add_output(Output::new("answer", json!("account_access"), "string"))
            .with_execution_time(60_000.0);
        let id = storage.save_decision(&decision).await.unwrap();
        let engine = ReplayEngine::new(storage).with_executor(Arc::new(FixedExecutor {
            value: json!("account_access"),
        }));

        // `function_name` and `execution_time_ms` resolve on the replayed
        // side too, so these rules are checked rather than reported "absent".
        let policy = ReplayPolicy::new("p")
            .with_exact_match("function_name")
            .add_rule(ValidationRule {
                field: "execution_time_ms".to_string(),
                comparator: Comparator::MaxIncreasePercent,
                threshold: 5.0,
            });
        let result = engine.replay_with_policy(&id, &policy, None).await.unwrap();
        assert!(
            result.policy_violations.is_empty(),
            "{:?}",
            result.policy_violations
        );
        assert_eq!(result.status, ReplayStatus::Success);

        // A replay that finishes in milliseconds against a recorded minute
        // violates "no more than 1% faster", with the replayed time reported.
        let policy = ReplayPolicy::new("p").add_rule(ValidationRule {
            field: "execution_time_ms".to_string(),
            comparator: Comparator::MaxDecreasePercent,
            threshold: 1.0,
        });
        let result = engine.replay_with_policy(&id, &policy, None).await.unwrap();
        assert_eq!(result.policy_violations.len(), 1);
        assert_ne!(result.policy_violations[0].actual, "absent");
        assert_eq!(result.status, ReplayStatus::Failed);
    }

    #[tokio::test]
    async fn a_changed_answer_is_reported_as_a_mismatch() {
        let (storage, id) = stored("account_access").await;
        let engine = ReplayEngine::new(storage).with_executor(Arc::new(FixedExecutor {
            value: json!("billing"),
        }));

        let result = engine
            .replay(&id, Some(ReplayMode::Strict), None)
            .await
            .unwrap();

        assert!(
            !result.outputs_match,
            "the executor answered 'billing' where 'account_access' was recorded"
        );
        assert_eq!(result.status, ReplayStatus::Failed);
    }

    #[tokio::test]
    async fn an_unchanged_answer_still_matches() {
        let (storage, id) = stored("account_access").await;
        let engine = ReplayEngine::new(storage).with_executor(Arc::new(FixedExecutor {
            value: json!("account_access"),
        }));

        let result = engine
            .replay(&id, Some(ReplayMode::Strict), None)
            .await
            .unwrap();

        assert!(result.outputs_match);
        assert_eq!(result.status, ReplayStatus::Success);
    }

    /// Never answers within any reasonable timeout.
    struct StalledExecutor;

    #[async_trait]
    impl ModelExecutor for StalledExecutor {
        async fn execute(
            &self,
            _inputs: &[Input],
            _model_params: Option<&ModelParameters>,
            _context: &ExecutionContext,
            _config: &ExecutionConfig,
        ) -> Result<ExecutionResult, ReplayError> {
            tokio::time::sleep(std::time::Duration::from_secs(3600)).await;
            Err(ReplayError::ExecutionError("unreachable".into()))
        }
        fn supports_model(&self, _model_name: &str) -> bool {
            true
        }
        fn executor_name(&self) -> &str {
            "stalled"
        }
    }

    #[tokio::test]
    async fn an_executor_that_exceeds_timeout_ms_is_cut_off() {
        let (storage, id) = stored("account_access").await;
        let engine = ReplayEngine::new(storage)
            .with_executor(Arc::new(StalledExecutor))
            .with_execution_config(ExecutionConfig::new().with_timeout(20));

        let result = engine.replay(&id, Some(ReplayMode::Strict), None).await;

        match result {
            Err(ReplayError::ExecutionError(message)) => {
                assert!(message.contains("timed out"), "{message}")
            }
            other => panic!("expected a timeout error, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn stats_count_verified_replays_as_successful() {
        let (storage, id) = stored("account_access").await;
        let engine = ReplayEngine::new(storage).with_executor(Arc::new(FixedExecutor {
            value: json!("account_access"),
        }));

        let stats = engine.get_replay_stats(&[id]).await.unwrap();
        assert_eq!(stats.successful_replays, 1);
        assert_eq!(stats.exact_matches, 1);
        assert_eq!(stats.unverified_replays, 0);
    }

    #[tokio::test]
    async fn without_an_executor_a_replay_does_not_claim_to_have_verified_anything() {
        let (storage, id) = stored("account_access").await;
        let engine = ReplayEngine::new(storage);

        let result = engine
            .replay(&id, Some(ReplayMode::Strict), None)
            .await
            .unwrap();

        assert_eq!(
            result.status,
            ReplayStatus::Pending,
            "nothing re-executed, so the replay is incomplete rather than successful"
        );
        assert!(
            !result.outputs_match,
            "outputs_match must not read True when no comparison happened"
        );
    }

    #[tokio::test]
    async fn an_exact_match_policy_rule_fails_when_the_field_changed() {
        let (storage, id) = stored("account_access").await;
        let engine = ReplayEngine::new(storage).with_executor(Arc::new(FixedExecutor {
            value: json!("billing"),
        }));
        let policy = ReplayPolicy::new("output-consistency").with_exact_match("answer");

        let result = engine
            .replay_with_policy(&id, &policy, Some(ReplayMode::Strict))
            .await
            .unwrap();

        assert_eq!(
            result.policy_violations.len(),
            1,
            "answer changed, so the exact-match rule must report a violation"
        );
        assert_eq!(result.policy_violations[0].field, "answer");
    }

    #[tokio::test]
    async fn an_exact_match_policy_rule_passes_when_the_field_held() {
        let (storage, id) = stored("account_access").await;
        let engine = ReplayEngine::new(storage).with_executor(Arc::new(FixedExecutor {
            value: json!("account_access"),
        }));
        let policy = ReplayPolicy::new("output-consistency").with_exact_match("answer");

        let result = engine
            .replay_with_policy(&id, &policy, Some(ReplayMode::Strict))
            .await
            .unwrap();

        assert!(result.policy_violations.is_empty());
    }

    #[tokio::test]
    async fn a_policy_cannot_pass_when_nothing_re_executed() {
        let (storage, id) = stored("account_access").await;
        let engine = ReplayEngine::new(storage);
        let policy = ReplayPolicy::new("output-consistency").with_exact_match("answer");

        let result = engine
            .replay_with_policy(&id, &policy, Some(ReplayMode::Strict))
            .await
            .unwrap();

        assert_eq!(
            result.policy_violations.len(),
            1,
            "an unverifiable rule must report, not silently pass"
        );
    }
}