assay-core 2.17.0

High-performance evaluation framework for LLM agents (Core)
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
//! VCR (Video Cassette Recording) middleware for HTTP request/response recording and replay.
//!
//! SOTA implementation (Jan 2026) with:
//! - Provider-level interception (typed requests, not raw HTTP)
//! - JCS fingerprinting (RFC 8785 canonical JSON)
//! - Scrubbers for security hygiene (no secrets in cassettes)
//! - Atomic writes (temp + rename) for parallel safety
//! - Strict replay mode for hermetic CI
//!
//! # Environment Variables
//!
//! - `ASSAY_VCR_MODE`: `replay_strict` (CI default), `replay`, `record`, `auto`, `off`
//! - `ASSAY_VCR_DIR`: Path to cassette directory (default: `tests/fixtures/perf/semantic_vcr/cassettes`)
//!
//! # Matching
//!
//! Requests are matched by fingerprint: method + URL + canonical body (JCS).
//! Authorization headers and transient metadata are excluded.

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::env;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};

/// VCR mode: how to handle HTTP requests
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum VcrMode {
    /// Replay from cassettes; fail if no match (CI default, hermetic)
    #[default]
    ReplayStrict,
    /// Replay from cassettes; passthrough if no match (dangerous in CI)
    Replay,
    /// Record to cassettes; make real requests (local only)
    Record,
    /// Auto: replay if hit, record if miss (convenient for local dev)
    Auto,
    /// Pass through to live network; no recording
    Off,
}

impl VcrMode {
    /// Parse from environment variable `ASSAY_VCR_MODE`
    pub fn from_env() -> Self {
        match env::var("ASSAY_VCR_MODE")
            .unwrap_or_default()
            .to_lowercase()
            .as_str()
        {
            "record" => VcrMode::Record,
            "auto" => VcrMode::Auto,
            "replay" => VcrMode::Replay,
            "off" => VcrMode::Off,
            // Default to replay_strict for CI safety
            _ => VcrMode::ReplayStrict,
        }
    }

    /// Is this mode allowed to make network requests?
    pub fn allows_network(&self) -> bool {
        matches!(
            self,
            VcrMode::Record | VcrMode::Auto | VcrMode::Replay | VcrMode::Off
        )
    }

    /// Does this mode fail on cassette miss?
    pub fn fails_on_miss(&self) -> bool {
        matches!(self, VcrMode::ReplayStrict)
    }
}

/// Scrubber configuration for security hygiene
#[derive(Debug, Clone, Default)]
pub struct ScrubConfig {
    /// Headers to remove from recorded requests (case-insensitive)
    pub request_headers: Vec<String>,
    /// Headers to remove from recorded responses
    pub response_headers: Vec<String>,
    /// JSON paths to redact in request body (e.g., "$.api_key")
    pub request_body_paths: Vec<String>,
    /// JSON paths to redact in response body
    pub response_body_paths: Vec<String>,
}

impl ScrubConfig {
    /// Default scrubber: remove auth headers and common secrets (VCR/cassette sign-off: no prompt/response bodies by default).
    pub fn default_secure() -> Self {
        Self {
            request_headers: vec![
                "authorization".to_string(),
                "x-api-key".to_string(),
                "openai-organization".to_string(),
                "api-key".to_string(),
            ],
            response_headers: vec![
                "set-cookie".to_string(),
                "x-request-id".to_string(),
                "cf-ray".to_string(),
            ],
            request_body_paths: vec![],
            response_body_paths: vec![],
        }
    }
}

/// A recorded HTTP request/response pair (cassette entry)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CassetteEntry {
    /// Schema version for forward compatibility
    pub schema_version: u32,
    /// Fingerprint used for matching
    pub fingerprint: String,
    /// HTTP method
    pub method: String,
    /// Request URL (without query params that vary)
    pub url: String,
    /// Request body (canonical JSON)
    pub request_body: Option<serde_json::Value>,
    /// Response status code
    pub status: u16,
    /// Response body
    pub response_body: serde_json::Value,
    /// Metadata
    pub meta: CassetteMeta,
}

/// Cassette metadata for debugging and versioning
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CassetteMeta {
    /// When this cassette was recorded
    pub recorded_at: String,
    /// Model used (if applicable)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    /// Provider (openai, anthropic, etc.)
    pub provider: String,
    /// Kind (embeddings, judge, chat)
    pub kind: String,
}

/// VCR client for HTTP request interception
pub struct VcrClient {
    mode: VcrMode,
    cassette_dir: PathBuf,
    scrub_config: ScrubConfig,
    /// In-memory cassette cache (fingerprint -> entry)
    cache: HashMap<String, CassetteEntry>,
    inner: reqwest::Client,
}

impl VcrClient {
    /// Create a new VCR client with mode and directory from environment
    pub fn from_env() -> Self {
        let mode = VcrMode::from_env();
        let cassette_dir = env::var("ASSAY_VCR_DIR")
            .map(PathBuf::from)
            .unwrap_or_else(|_| PathBuf::from("tests/fixtures/perf/semantic_vcr/cassettes"));

        Self::new(mode, cassette_dir)
    }

    /// Create a new VCR client with explicit mode and directory
    pub fn new(mode: VcrMode, cassette_dir: PathBuf) -> Self {
        let mut client = Self {
            mode,
            cassette_dir,
            scrub_config: ScrubConfig::default_secure(),
            cache: HashMap::new(),
            inner: reqwest::Client::new(),
        };

        // Load existing cassettes in replay modes
        if matches!(
            mode,
            VcrMode::ReplayStrict | VcrMode::Replay | VcrMode::Auto
        ) {
            client.load_cassettes();
        }

        client
    }

    /// Set custom scrub configuration
    pub fn with_scrub_config(mut self, config: ScrubConfig) -> Self {
        self.scrub_config = config;
        self
    }

    /// Compute fingerprint for request matching using JCS (RFC 8785)
    ///
    /// Fingerprint includes: method + URL + canonical body (excluding auth)
    pub fn fingerprint(method: &str, url: &str, body: Option<&serde_json::Value>) -> String {
        let mut hasher = Sha256::new();
        hasher.update(method.as_bytes());
        hasher.update(b"|");

        // Normalize URL (remove trailing slashes, lowercase)
        let normalized_url = url.trim_end_matches('/').to_lowercase();
        hasher.update(normalized_url.as_bytes());
        hasher.update(b"|");

        if let Some(b) = body {
            // Use JCS for canonical JSON (RFC 8785)
            let canonical = serde_jcs::to_string(b).unwrap_or_else(|_| b.to_string());
            hasher.update(canonical.as_bytes());
        }

        format!("{:x}", hasher.finalize())
    }

    /// Determine provider from URL
    fn provider_from_url(url: &str) -> &'static str {
        if url.contains("openai.com") {
            "openai"
        } else if url.contains("anthropic.com") {
            "anthropic"
        } else {
            "unknown"
        }
    }

    /// Determine kind (embeddings/judge/chat) from URL
    fn kind_from_url(url: &str) -> &'static str {
        if url.contains("/embeddings") {
            "embeddings"
        } else if url.contains("/chat/completions") {
            "judge"
        } else if url.contains("/completions") {
            "completions"
        } else {
            "other"
        }
    }

    /// Extract model from request body if present
    fn extract_model(body: Option<&serde_json::Value>) -> Option<String> {
        body.and_then(|b| b.get("model"))
            .and_then(|m| m.as_str())
            .map(|s| s.to_string())
    }

    /// Load all cassettes from disk into memory
    fn load_cassettes(&mut self) {
        let cassette_dir = self.cassette_dir.clone();
        if !cassette_dir.exists() {
            return;
        }

        // Load from provider/kind subdirs
        for provider in &["openai", "anthropic", "unknown"] {
            for kind in &["embeddings", "judge", "completions", "other"] {
                let dir = cassette_dir.join(provider).join(kind);
                if dir.exists() {
                    self.load_cassettes_from_dir(&dir);
                }
            }
        }

        // Also load from legacy structure (embeddings/, judge/ at root)
        for subdir in &["embeddings", "judge"] {
            let dir = cassette_dir.join(subdir);
            if dir.exists() {
                self.load_cassettes_from_dir(&dir);
            }
        }

        // Load from root cassette dir
        self.load_cassettes_from_dir(&cassette_dir);
    }

    fn load_cassettes_from_dir(&mut self, dir: &Path) {
        let Ok(entries) = fs::read_dir(dir) else {
            return;
        };

        for entry in entries.flatten() {
            let path = entry.path();
            if path.extension().map(|e| e == "json").unwrap_or(false) {
                if let Ok(content) = fs::read_to_string(&path) {
                    if let Ok(cassette) = serde_json::from_str::<CassetteEntry>(&content) {
                        self.cache.insert(cassette.fingerprint.clone(), cassette);
                    }
                }
            }
        }
    }

    /// Save a cassette entry to disk (atomic: temp + rename)
    fn save_cassette(&self, entry: &CassetteEntry) -> anyhow::Result<()> {
        let provider = Self::provider_from_url(&entry.url);
        let kind = Self::kind_from_url(&entry.url);

        // Create directory: cassettes/<provider>/<kind>/
        let dir = self.cassette_dir.join(provider).join(kind);
        fs::create_dir_all(&dir)?;

        // Use first 16 chars of fingerprint for filename
        let fp_prefix = if entry.fingerprint.len() >= 16 {
            &entry.fingerprint[..16]
        } else {
            &entry.fingerprint
        };
        let filename = format!("{}.json", fp_prefix);
        let final_path = dir.join(&filename);

        // Atomic write: temp file + rename
        let temp_path = dir.join(format!(".{}.tmp", fp_prefix));
        let content = serde_json::to_string_pretty(entry)?;

        {
            let mut file = fs::File::create(&temp_path)?;
            file.write_all(content.as_bytes())?;
            file.sync_all()?;
        }

        fs::rename(&temp_path, &final_path)?;

        Ok(())
    }

    /// Make a POST request with VCR handling
    pub async fn post_json(
        &mut self,
        url: &str,
        body: &serde_json::Value,
        auth_header: Option<&str>,
    ) -> anyhow::Result<VcrResponse> {
        let fingerprint = Self::fingerprint("POST", url, Some(body));

        match self.mode {
            VcrMode::ReplayStrict => {
                // Strict replay: must find cassette
                if let Some(entry) = self.cache.get(&fingerprint) {
                    Ok(VcrResponse {
                        status: entry.status,
                        body: entry.response_body.clone(),
                        from_cache: true,
                    })
                } else {
                    anyhow::bail!(
                        "VCR replay_strict: no cassette found for POST {} (fingerprint: {}).\n\
                        Run with ASSAY_VCR_MODE=record to record responses.\n\
                        Cassette dir: {}",
                        url,
                        &fingerprint[..16.min(fingerprint.len())],
                        self.cassette_dir.display()
                    )
                }
            }
            VcrMode::Replay => {
                // Soft replay: try cache, passthrough on miss
                if let Some(entry) = self.cache.get(&fingerprint) {
                    Ok(VcrResponse {
                        status: entry.status,
                        body: entry.response_body.clone(),
                        from_cache: true,
                    })
                } else {
                    // Passthrough (dangerous in CI!)
                    tracing::warn!(
                        "VCR replay: cache miss for POST {}, passing through to network",
                        url
                    );
                    self.make_request_and_record(url, body, auth_header, &fingerprint, false)
                        .await
                }
            }
            VcrMode::Auto => {
                // Auto: replay if hit, record if miss
                if let Some(entry) = self.cache.get(&fingerprint) {
                    Ok(VcrResponse {
                        status: entry.status,
                        body: entry.response_body.clone(),
                        from_cache: true,
                    })
                } else {
                    self.make_request_and_record(url, body, auth_header, &fingerprint, true)
                        .await
                }
            }
            VcrMode::Record => {
                // Always record (overwrite existing)
                self.make_request_and_record(url, body, auth_header, &fingerprint, true)
                    .await
            }
            VcrMode::Off => {
                // Pass through, no recording
                crate::providers::network::check_outbound(url)?;
                let mut req = self.inner.post(url).json(body);
                if let Some(auth) = auth_header {
                    req = req.header("Authorization", auth);
                }
                let resp = req.send().await?;
                let status = resp.status().as_u16();
                let response_body: serde_json::Value = resp.json().await?;

                Ok(VcrResponse {
                    status,
                    body: response_body,
                    from_cache: false,
                })
            }
        }
    }

    /// Make real HTTP request and optionally record to cassette
    async fn make_request_and_record(
        &mut self,
        url: &str,
        body: &serde_json::Value,
        auth_header: Option<&str>,
        fingerprint: &str,
        should_record: bool,
    ) -> anyhow::Result<VcrResponse> {
        crate::providers::network::check_outbound(url)?;
        let mut req = self.inner.post(url).json(body);
        if let Some(auth) = auth_header {
            req = req.header("Authorization", auth);
        }
        let resp = req.send().await?;

        let status = resp.status().as_u16();
        let response_body: serde_json::Value = resp.json().await?;

        if should_record {
            let entry = CassetteEntry {
                schema_version: 2,
                fingerprint: fingerprint.to_string(),
                method: "POST".to_string(),
                url: url.to_string(),
                request_body: Some(body.clone()),
                status,
                response_body: response_body.clone(),
                meta: CassetteMeta {
                    recorded_at: chrono::Utc::now().to_rfc3339(),
                    model: Self::extract_model(Some(body)),
                    provider: Self::provider_from_url(url).to_string(),
                    kind: Self::kind_from_url(url).to_string(),
                },
            };

            if let Err(e) = self.save_cassette(&entry) {
                tracing::warn!("VCR: failed to save cassette: {}", e);
            }

            // Add to cache
            self.cache.insert(fingerprint.to_string(), entry);
        }

        Ok(VcrResponse {
            status,
            body: response_body,
            from_cache: false,
        })
    }

    /// Get the current VCR mode
    pub fn mode(&self) -> VcrMode {
        self.mode
    }

    /// Get cassette count (for diagnostics)
    pub fn cassette_count(&self) -> usize {
        self.cache.len()
    }
}

/// Response from VCR client
#[derive(Debug)]
pub struct VcrResponse {
    pub status: u16,
    pub body: serde_json::Value,
    /// True if response came from cache (replay)
    pub from_cache: bool,
}

impl VcrResponse {
    pub fn is_success(&self) -> bool {
        (200..300).contains(&self.status)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    /// Sign-off: default_secure() must scrub auth and common secret headers so cassettes don't leak.
    #[test]
    fn test_default_secure_scrub_paths() {
        let cfg = ScrubConfig::default_secure();
        assert!(
            cfg.request_headers
                .iter()
                .any(|h| h.eq_ignore_ascii_case("authorization")),
            "Must scrub Authorization"
        );
        assert!(
            cfg.request_headers
                .iter()
                .any(|h| h.eq_ignore_ascii_case("x-api-key")),
            "Must scrub x-api-key"
        );
        assert!(
            cfg.request_headers
                .iter()
                .any(|h| h.eq_ignore_ascii_case("api-key")),
            "Must scrub api-key"
        );
        assert!(
            cfg.response_headers
                .iter()
                .any(|h| h.eq_ignore_ascii_case("set-cookie")),
            "Must scrub set-cookie"
        );
        assert!(
            cfg.request_body_paths.is_empty(),
            "Default: no body paths (audit: explicit if needed)"
        );
        assert!(
            cfg.response_body_paths.is_empty(),
            "Default: no response body paths"
        );
    }

    #[test]
    fn test_fingerprint_stability() {
        let body = serde_json::json!({"input": "hello", "model": "text-embedding-3-small"});
        let fp1 =
            VcrClient::fingerprint("POST", "https://api.openai.com/v1/embeddings", Some(&body));
        let fp2 =
            VcrClient::fingerprint("POST", "https://api.openai.com/v1/embeddings", Some(&body));
        assert_eq!(fp1, fp2);

        // Different body = different fingerprint
        let body2 = serde_json::json!({"input": "world", "model": "text-embedding-3-small"});
        let fp3 =
            VcrClient::fingerprint("POST", "https://api.openai.com/v1/embeddings", Some(&body2));
        assert_ne!(fp1, fp3);
    }

    #[test]
    fn test_fingerprint_key_order_invariant() {
        // JCS ensures key order doesn't matter
        let body1 = serde_json::json!({"model": "gpt-4", "input": "hello"});
        let body2 = serde_json::json!({"input": "hello", "model": "gpt-4"});
        let fp1 =
            VcrClient::fingerprint("POST", "https://api.openai.com/v1/embeddings", Some(&body1));
        let fp2 =
            VcrClient::fingerprint("POST", "https://api.openai.com/v1/embeddings", Some(&body2));
        assert_eq!(fp1, fp2, "JCS should normalize key order");
    }

    #[test]
    fn test_vcr_mode_from_env() {
        env::remove_var("ASSAY_VCR_MODE");
        assert_eq!(VcrMode::from_env(), VcrMode::ReplayStrict);

        env::set_var("ASSAY_VCR_MODE", "record");
        assert_eq!(VcrMode::from_env(), VcrMode::Record);

        env::set_var("ASSAY_VCR_MODE", "auto");
        assert_eq!(VcrMode::from_env(), VcrMode::Auto);

        env::set_var("ASSAY_VCR_MODE", "replay");
        assert_eq!(VcrMode::from_env(), VcrMode::Replay);

        env::set_var("ASSAY_VCR_MODE", "off");
        assert_eq!(VcrMode::from_env(), VcrMode::Off);

        env::set_var("ASSAY_VCR_MODE", "replay_strict");
        assert_eq!(VcrMode::from_env(), VcrMode::ReplayStrict);

        env::remove_var("ASSAY_VCR_MODE");
    }

    #[test]
    fn test_cassette_save_load_atomic() {
        let tmp = TempDir::new().unwrap();
        let client = VcrClient::new(VcrMode::Record, tmp.path().to_path_buf());

        let body = serde_json::json!({"input": "test", "model": "text-embedding-3-small"});
        let fingerprint =
            VcrClient::fingerprint("POST", "https://api.openai.com/v1/embeddings", Some(&body));

        let entry = CassetteEntry {
            schema_version: 2,
            fingerprint: fingerprint.clone(),
            method: "POST".to_string(),
            url: "https://api.openai.com/v1/embeddings".to_string(),
            request_body: Some(body),
            status: 200,
            response_body: serde_json::json!({"data": [{"embedding": [0.1, 0.2]}]}),
            meta: CassetteMeta {
                recorded_at: "2026-01-30T12:00:00Z".to_string(),
                model: Some("text-embedding-3-small".to_string()),
                provider: "openai".to_string(),
                kind: "embeddings".to_string(),
            },
        };

        client.save_cassette(&entry).unwrap();

        // Verify file exists in correct location
        let expected_path = tmp
            .path()
            .join("openai")
            .join("embeddings")
            .join(format!("{}.json", &fingerprint[..16]));
        assert!(expected_path.exists(), "Cassette file should exist");

        // Reload and verify
        let mut client2 = VcrClient::new(VcrMode::ReplayStrict, tmp.path().to_path_buf());
        client2.load_cassettes();

        assert!(client2.cache.contains_key(&fingerprint));
        assert_eq!(client2.cache.get(&fingerprint).unwrap().status, 200);
    }

    #[test]
    fn test_provider_and_kind_detection() {
        assert_eq!(
            VcrClient::provider_from_url("https://api.openai.com/v1/embeddings"),
            "openai"
        );
        assert_eq!(
            VcrClient::kind_from_url("https://api.openai.com/v1/embeddings"),
            "embeddings"
        );
        assert_eq!(
            VcrClient::kind_from_url("https://api.openai.com/v1/chat/completions"),
            "judge"
        );
    }

    #[tokio::test]
    async fn test_network_policy_blocks_passthrough_modes() {
        let _serial = crate::providers::network::lock_test_serial_async().await;
        let tmp = TempDir::new().unwrap();
        let mut client = VcrClient::new(VcrMode::Off, tmp.path().to_path_buf());
        let _guard = crate::providers::network::NetworkPolicyGuard::deny("unit test");
        let body = serde_json::json!({"input": "test", "model": "gpt-4o-mini"});
        let err = client
            .post_json("https://api.openai.com/v1/chat/completions", &body, None)
            .await
            .expect_err("deny policy must block passthrough network");
        assert!(err
            .to_string()
            .contains("outbound network blocked by policy"));
    }
}