briefcase-core 3.0.0

Open-source decision tracking for AI
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
//! Model execution traits for replay
//!
//! These traits define how to re-execute a model during replay.
//! Implementors connect the replay engine to actual model inference.

use super::ReplayError;
use crate::models::{ExecutionContext, Input, ModelParameters, Output};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

#[cfg(feature = "async")]
use async_trait::async_trait;

/// Result of model execution during replay
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionResult {
    pub outputs: Vec<Output>,
    pub execution_time_ms: f64,
    pub metadata: HashMap<String, serde_json::Value>,
    pub raw_response: Option<serde_json::Value>,
}

/// Configuration for how to execute during replay
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionConfig {
    /// Maximum time to wait for execution (ms)
    pub timeout_ms: u64,
    /// Whether to use cached results if available
    pub use_cache: bool,
    /// Whether to record the execution for auditing
    pub record_execution: bool,
    /// Environment overrides for execution
    pub env_overrides: HashMap<String, String>,
    /// Custom parameters passed to executor
    pub custom_params: HashMap<String, serde_json::Value>,
}

impl Default for ExecutionConfig {
    fn default() -> Self {
        Self {
            timeout_ms: 30_000,
            use_cache: false,
            record_execution: true,
            env_overrides: HashMap::new(),
            custom_params: HashMap::new(),
        }
    }
}

impl ExecutionConfig {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_timeout(mut self, timeout_ms: u64) -> Self {
        self.timeout_ms = timeout_ms;
        self
    }

    pub fn with_cache(mut self, use_cache: bool) -> Self {
        self.use_cache = use_cache;
        self
    }

    pub fn with_recording(mut self, record: bool) -> Self {
        self.record_execution = record;
        self
    }
}

/// Comparison result between original and replayed outputs
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComparisonResult {
    pub is_match: bool,
    pub similarity_score: f64, // 0.0 - 1.0
    pub field_comparisons: Vec<FieldComparison>,
    pub summary: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FieldComparison {
    pub field_name: String,
    pub original_value: serde_json::Value,
    pub replayed_value: serde_json::Value,
    pub is_match: bool,
    pub similarity: f64,
}

/// Async trait for model re-execution during replay.
///
/// Implementors provide the bridge between the replay engine and actual
/// model inference (OpenAI, Anthropic, local models, etc.).
///
/// # Example
///
/// ```rust,ignore
/// struct OpenAIExecutor { client: OpenAIClient }
///
/// #[async_trait]
/// impl ModelExecutor for OpenAIExecutor {
///     async fn execute(
///         &self, inputs: &[Input], model_params: Option<&ModelParameters>,
///         context: &ExecutionContext, config: &ExecutionConfig,
///     ) -> Result<ExecutionResult, ReplayError> {
///         let response = self.client.chat(inputs, model_params).await?;
///         Ok(ExecutionResult { outputs: vec![...], ... })
///     }
/// }
/// ```
#[cfg(feature = "async")]
#[async_trait]
pub trait ModelExecutor: Send + Sync {
    /// Execute a model with the given inputs and parameters
    async fn execute(
        &self,
        inputs: &[Input],
        model_params: Option<&ModelParameters>,
        context: &ExecutionContext,
        config: &ExecutionConfig,
    ) -> Result<ExecutionResult, ReplayError>;

    /// Check if this executor supports the given model
    fn supports_model(&self, model_name: &str) -> bool;

    /// Get executor name for logging/auditing
    fn executor_name(&self) -> &str;

    /// Compare original outputs with replayed outputs
    fn compare_outputs(
        &self,
        original: &[Output],
        replayed: &[Output],
        tolerance: f64,
    ) -> ComparisonResult {
        default_compare_outputs(original, replayed, tolerance)
    }
}

/// Sync version of ModelExecutor for non-async contexts
pub trait SyncModelExecutor: Send + Sync {
    fn execute(
        &self,
        inputs: &[Input],
        model_params: Option<&ModelParameters>,
        context: &ExecutionContext,
        config: &ExecutionConfig,
    ) -> Result<ExecutionResult, ReplayError>;

    fn supports_model(&self, model_name: &str) -> bool;

    fn executor_name(&self) -> &str;

    fn compare_outputs(
        &self,
        original: &[Output],
        replayed: &[Output],
        tolerance: f64,
    ) -> ComparisonResult {
        default_compare_outputs(original, replayed, tolerance)
    }
}

/// No-op executor that returns empty outputs.
/// Used when no real model execution is available.
pub struct NoOpExecutor;

#[cfg(feature = "async")]
#[async_trait]
impl ModelExecutor for NoOpExecutor {
    async fn execute(
        &self,
        _inputs: &[Input],
        _model_params: Option<&ModelParameters>,
        _context: &ExecutionContext,
        _config: &ExecutionConfig,
    ) -> Result<ExecutionResult, ReplayError> {
        Ok(ExecutionResult {
            outputs: vec![],
            execution_time_ms: 0.0,
            metadata: HashMap::new(),
            raw_response: None,
        })
    }

    fn supports_model(&self, _model_name: &str) -> bool {
        true
    }

    fn executor_name(&self) -> &str {
        "noop"
    }
}

impl SyncModelExecutor for NoOpExecutor {
    fn execute(
        &self,
        _inputs: &[Input],
        _model_params: Option<&ModelParameters>,
        _context: &ExecutionContext,
        _config: &ExecutionConfig,
    ) -> Result<ExecutionResult, ReplayError> {
        Ok(ExecutionResult {
            outputs: vec![],
            execution_time_ms: 0.0,
            metadata: HashMap::new(),
            raw_response: None,
        })
    }

    fn supports_model(&self, _model_name: &str) -> bool {
        true
    }

    fn executor_name(&self) -> &str {
        "noop"
    }
}

/// Echo executor that returns the original snapshot outputs.
/// Useful for testing the replay pipeline without a real model.
pub struct EchoExecutor;

#[cfg(feature = "async")]
#[async_trait]
impl ModelExecutor for EchoExecutor {
    async fn execute(
        &self,
        _inputs: &[Input],
        _model_params: Option<&ModelParameters>,
        _context: &ExecutionContext,
        _config: &ExecutionConfig,
    ) -> Result<ExecutionResult, ReplayError> {
        // Echo executor returns empty outputs - should be overridden with snapshot outputs
        Ok(ExecutionResult {
            outputs: vec![],
            execution_time_ms: 0.0,
            metadata: HashMap::new(),
            raw_response: None,
        })
    }

    fn supports_model(&self, _model_name: &str) -> bool {
        true
    }

    fn executor_name(&self) -> &str {
        "echo"
    }
}

impl SyncModelExecutor for EchoExecutor {
    fn execute(
        &self,
        _inputs: &[Input],
        _model_params: Option<&ModelParameters>,
        _context: &ExecutionContext,
        _config: &ExecutionConfig,
    ) -> Result<ExecutionResult, ReplayError> {
        Ok(ExecutionResult {
            outputs: vec![],
            execution_time_ms: 0.0,
            metadata: HashMap::new(),
            raw_response: None,
        })
    }

    fn supports_model(&self, _model_name: &str) -> bool {
        true
    }

    fn executor_name(&self) -> &str {
        "echo"
    }
}

/// Default comparison implementation using string similarity
fn default_compare_outputs(
    original: &[Output],
    replayed: &[Output],
    tolerance: f64,
) -> ComparisonResult {
    if original.len() != replayed.len() {
        return ComparisonResult {
            is_match: false,
            similarity_score: 0.0,
            field_comparisons: vec![],
            summary: format!(
                "Output count mismatch: {} vs {}",
                original.len(),
                replayed.len()
            ),
        };
    }

    let mut comparisons = Vec::new();
    let mut total_similarity = 0.0;

    for (orig, replay) in original.iter().zip(replayed.iter()) {
        let is_exact = orig.value == replay.value;
        let similarity = if is_exact {
            1.0
        } else {
            // Compute string similarity for string values
            match (&orig.value, &replay.value) {
                (serde_json::Value::String(a), serde_json::Value::String(b)) => {
                    strsim::normalized_levenshtein(a, b)
                }
                (serde_json::Value::Number(a), serde_json::Value::Number(b)) => {
                    // Numeric comparison with tolerance
                    let a_f = a.as_f64().unwrap_or(0.0);
                    let b_f = b.as_f64().unwrap_or(0.0);
                    if a_f == 0.0 && b_f == 0.0 {
                        1.0
                    } else {
                        let max = a_f.abs().max(b_f.abs());
                        if max == 0.0 {
                            1.0
                        } else {
                            1.0 - ((a_f - b_f).abs() / max).min(1.0)
                        }
                    }
                }
                _ => {
                    if is_exact {
                        1.0
                    } else {
                        0.0
                    }
                }
            }
        };

        total_similarity += similarity;
        comparisons.push(FieldComparison {
            field_name: orig.name.clone(),
            original_value: orig.value.clone(),
            replayed_value: replay.value.clone(),
            is_match: similarity >= tolerance,
            similarity,
        });
    }

    let avg_similarity = if comparisons.is_empty() {
        1.0
    } else {
        total_similarity / comparisons.len() as f64
    };
    let all_match = comparisons.iter().all(|c| c.is_match);

    ComparisonResult {
        is_match: all_match,
        similarity_score: avg_similarity,
        field_comparisons: comparisons.clone(),
        summary: if all_match {
            format!(
                "All outputs match (similarity: {:.2}%)",
                avg_similarity * 100.0
            )
        } else {
            let mismatched: Vec<_> = comparisons
                .iter()
                .filter(|c| !c.is_match)
                .map(|c| c.field_name.as_str())
                .collect();
            format!("Mismatched fields: {}", mismatched.join(", "))
        },
    }
}

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

    #[test]
    fn test_execution_config_default() {
        let config = ExecutionConfig::default();
        assert_eq!(config.timeout_ms, 30_000);
        assert!(!config.use_cache);
        assert!(config.record_execution);
    }

    #[test]
    fn test_execution_config_builder() {
        let config = ExecutionConfig::new()
            .with_timeout(60_000)
            .with_cache(true)
            .with_recording(false);

        assert_eq!(config.timeout_ms, 60_000);
        assert!(config.use_cache);
        assert!(!config.record_execution);
    }

    #[test]
    fn test_noop_executor_sync() {
        let executor = NoOpExecutor;
        assert!(SyncModelExecutor::supports_model(&executor, "any-model"));
        assert_eq!(SyncModelExecutor::executor_name(&executor), "noop");

        let result = SyncModelExecutor::execute(
            &executor,
            &[],
            None,
            &ExecutionContext::new(),
            &ExecutionConfig::default(),
        )
        .unwrap();
        assert!(result.outputs.is_empty());
    }

    #[test]
    fn test_echo_executor_sync() {
        let executor = EchoExecutor;
        assert!(SyncModelExecutor::supports_model(&executor, "any-model"));
        assert_eq!(SyncModelExecutor::executor_name(&executor), "echo");

        let result = SyncModelExecutor::execute(
            &executor,
            &[],
            None,
            &ExecutionContext::new(),
            &ExecutionConfig::default(),
        )
        .unwrap();
        assert!(result.outputs.is_empty());
    }

    #[test]
    fn test_default_compare_outputs_exact_match() {
        let original = vec![Output::new("output", json!("hello"), "string")];
        let replayed = vec![Output::new("output", json!("hello"), "string")];

        let result = default_compare_outputs(&original, &replayed, 0.9);

        assert!(result.is_match);
        assert!(result.similarity_score >= 0.99);
        assert_eq!(result.field_comparisons.len(), 1);
    }

    #[test]
    fn test_default_compare_outputs_mismatch() {
        let original = vec![Output::new("output", json!("hello"), "string")];
        let replayed = vec![Output::new("output", json!("world"), "string")];

        let result = default_compare_outputs(&original, &replayed, 0.95);

        assert!(!result.is_match);
        assert!(result.similarity_score < 1.0);
    }

    #[test]
    fn test_default_compare_outputs_count_mismatch() {
        let original = vec![
            Output::new("output1", json!("hello"), "string"),
            Output::new("output2", json!("world"), "string"),
        ];
        let replayed = vec![Output::new("output1", json!("hello"), "string")];

        let result = default_compare_outputs(&original, &replayed, 0.9);

        assert!(!result.is_match);
        assert_eq!(result.similarity_score, 0.0);
    }

    #[test]
    fn test_default_compare_outputs_numeric() {
        let original = vec![Output::new("number", json!(100), "number")];
        let replayed = vec![Output::new("number", json!(101), "number")];

        let result = default_compare_outputs(&original, &replayed, 0.95);

        assert!(result.is_match); // Should be > 0.95 similarity
        assert!(result.similarity_score > 0.99);
    }
}