firstpass-proxy 0.8.1

Drop-in, Anthropic-compatible LLM proxy that routes each request to the cheapest model that provably passes a quality gate, escalates on failure, and records a tamper-evident audit trace.
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
//! A response cache that can only ever return an answer which **passed a gate**.
//!
//! ## Why this is not the same feature everyone else ships
//!
//! A conventional semantic or exact cache stores whatever the model said and replays it. It saves
//! money by skipping the model — and skipping the model is exactly how a gateway stops knowing
//! whether the thing it just served was any good. On a cache hit rate of 40%, a product whose claim
//! is "nothing ships until a real check passes" would be shipping 40% of its traffic unchecked.
//!
//! So insertion is the gate here, not lookup: an entry is written **only** when the request it came
//! from was served on a passing verdict. A failed answer, a best-effort serve after budget
//! exhaustion, an abstain — none of them are cacheable, because replaying one would launder an
//! unverified answer into a served one and no later reader could tell.
//!
//! The receipt records `served_from: cache` and `cache_source: <trace_id>`, so a hit is not the
//! word "cached" but a link to the decision whose gate passed. That is the difference between
//! asserting a saving and being able to prove what was served.
//!
//! ## What it is keyed on
//!
//! The salted prompt hash the router already computes, plus the ladder identity. Exact-match, not
//! semantic: two prompts that merely *look* similar can want different answers, and a verification
//! product guessing that they don't is the one shortcut it cannot take. Semantic matching would
//! need its own gate over the similarity decision, which is a bigger design than a cache.
//!
//! The ladder is part of the key because the same prompt under a different ladder is a different
//! question — an answer proven against one gate configuration says nothing about another.

use std::collections::HashMap;
use std::sync::Mutex;
use std::time::{Duration, Instant};

use firstpass_core::{ServedFrom, Trace, Verdict};

use crate::provider::ModelResponse;

/// An answer that passed, kept for replay.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Entry {
    /// The response that was served.
    ///
    /// Stored as the normalized [`ModelResponse`] rather than raw wire bytes, so a replay flows
    /// back out through the same dialect-shaping the live path uses. Caching bytes would mean an
    /// answer cached from an Anthropic caller could not be replayed to an OpenAI one, and the two
    /// paths would drift.
    pub response: ModelResponse,
    /// The decision that proved it — recorded on every replay's receipt.
    pub source: uuid::Uuid,
    /// What that decision cost, so a replay can report the spend it avoided rather than guess.
    pub original_cost_usd: f64,
    /// Insert time, for the in-process store's TTL.
    ///
    /// Skipped on the wire and re-stamped on read: an `Instant` is meaningless in another process,
    /// and expiry in the shared store is Redis's own TTL rather than a timestamp we compare. Two
    /// replicas comparing monotonic clocks would disagree about what is stale.
    #[serde(skip, default = "Instant::now")]
    stored: Instant,
}

/// Whether a finished decision may be cached at all.
///
/// **The single place these rules live.** They were duplicated nowhere and must stay that way: a
/// second backend re-deriving "was this proven?" from its own reading of the receipt is how one of
/// them eventually accepts something the other would reject, and the failure is silent — an
/// unverified answer served from cache looks exactly like a verified one.
///
/// Rejects, in order:
/// 1. **Not served from a real attempt.** `BestAttempt` is the budget-exhausted fallback, served
///    *without* a passing verdict; caching it would replay an answer that never passed anything.
/// 2. **A cache hit.** Harmless in itself, but it would relocate `cache_source` onto a replay
///    rather than the decision that ran a gate, letting the provenance chain go a hop stale.
/// 3. **A verdict that is not an unambiguous Pass.** An `Abstain` is "the gate could not tell",
///    which is precisely the state that must never be frozen and replayed.
/// 4. **A deferred Fail already on the receipt.** Rarely the path that matters — deferred verdicts
///    usually arrive later via `/v1/feedback`, which is what `retract` handles — but free to check.
#[must_use]
pub fn is_cacheable(trace: &Trace) -> bool {
    if trace.final_.served_from != ServedFrom::Attempt {
        return false;
    }
    if trace.final_.cache_source.is_some() {
        return false;
    }
    let Some(served) = trace.final_.served_rung else {
        return false;
    };
    if !trace
        .attempts
        .iter()
        .any(|a| a.rung == served && a.verdict == Verdict::Pass)
    {
        return false;
    }
    !trace.deferred.iter().any(|d| d.verdict == Verdict::Fail)
}

impl Entry {
    /// Build an entry from a decision and what it served.
    ///
    /// Takes the proof off the trace rather than as a parameter, for the same reason the tenant is
    /// read off the receipt: a call site cannot then file an answer under the wrong decision.
    #[must_use]
    pub fn new(response: ModelResponse, trace: &Trace, now: Instant) -> Self {
        Self {
            response,
            source: trace.trace_id,
            original_cost_usd: trace.final_.total_cost_usd,
            stored: now,
        }
    }
}

/// Key: tenant, then the salted prompt hash, then the ladder that answered it.
///
/// **The tenant is not optional.** The prompt salt is per-deployment, not per-tenant, so two
/// tenants sending an identical prompt produce an identical hash — a key without the tenant would
/// serve one customer's paid-for, verified answer to another. That is a cross-tenant data leak in
/// a multi-tenant proxy, not merely a wrong cache hit, and it is silent: the receipt would look
/// entirely normal.
fn key(tenant: &str, prompt_hash: &str, ladder: &[String]) -> String {
    format!("{tenant}|{prompt_hash}|{}", ladder.join(">"))
}

/// Where verified entries live.
///
/// Exists so the in-process store stays exactly what it was — the version four review rounds
/// hardened — while a shared L2 can sit behind it. A single-instance deployment keeps byte-identical
/// behaviour and no Redis dependency; a multi-replica one gets entries and, critically,
/// **retractions** that cross process boundaries.
///
/// Async because an L2 is a network hop. Blocking one inside an async proxy would stall the runtime
/// on a cache lookup, which is precisely the wrong place to lose latency.
#[async_trait::async_trait]
pub trait CacheStore: Send + Sync + std::fmt::Debug {
    /// Fetch a live entry, if one exists.
    async fn get(&self, key: &str, now: Instant) -> Option<Entry>;
    /// Store an entry under `key`, proven by `source`.
    ///
    /// `source` is passed separately because a backend has to index by it: retraction arrives
    /// naming a decision, not a key, and one decision can back several keys once the same prompt
    /// is seen under more than one ladder.
    async fn put(&self, key: &str, source: uuid::Uuid, entry: Entry, now: Instant);
    /// Drop every entry proven by `source`. Returns how many went.
    async fn retract(&self, source: uuid::Uuid) -> usize;
    /// Entries currently held, for tests and `/metrics`.
    async fn entry_count(&self) -> usize;
}

/// A bounded, in-process store of verified answers.
#[derive(Debug)]
pub struct VerifiedCache {
    entries: Mutex<HashMap<String, Entry>>,
    ttl: Duration,
    max_entries: usize,
}

impl VerifiedCache {
    /// Build a cache holding at most `max_entries` for `ttl`.
    #[must_use]
    pub fn new(ttl: Duration, max_entries: usize) -> Self {
        Self {
            entries: Mutex::new(HashMap::new()),
            ttl,
            max_entries,
        }
    }

    /// Look up a proven answer for this prompt under this ladder.
    #[must_use]
    pub fn get(
        &self,
        tenant: &str,
        prompt_hash: &str,
        ladder: &[String],
        now: Instant,
    ) -> Option<Entry> {
        let Ok(map) = self.entries.lock() else {
            // A poisoned lock must not take serving down. Missing the cache is always safe: the
            // request simply runs the ladder, which is the behaviour with caching off.
            return None;
        };
        map.get(&key(tenant, prompt_hash, ladder))
            .filter(|e| now.duration_since(e.stored) < self.ttl)
            .cloned()
    }

    /// Offer a finished decision to the cache.
    ///
    /// Returns whether it was stored. Everything about the safety of this feature is in the
    /// rejection rules below, so they are checked here — in one place, against the receipt — rather
    /// than trusted to each call site to have got right.
    pub fn offer(
        &self,
        trace: &Trace,
        response: &ModelResponse,
        ladder: &[String],
        now: Instant,
    ) -> bool {
        if !is_cacheable(trace) {
            return false;
        }
        let mut entry = Entry {
            response: response.clone(),
            source: trace.trace_id,
            original_cost_usd: trace.final_.total_cost_usd,
            stored: now,
        };
        entry.stored = now;
        self.put_by_key(
            &key(&trace.tenant_id, &trace.request.prompt_hash, ladder),
            entry,
        );
        true
    }

    /// Fetch by a pre-built key. The key-level primitive behind [`CacheStore`]; the
    /// tenant/prompt/ladder composition lives in [`key`] so both stores agree on it.
    #[must_use]
    pub fn get_by_key(&self, key: &str, now: Instant) -> Option<Entry> {
        let Ok(map) = self.entries.lock() else {
            return None;
        };
        map.get(key)
            .filter(|e| now.duration_since(e.stored) < self.ttl)
            .cloned()
    }

    /// Store by a pre-built key, applying the same bound as `offer`.
    pub fn put_by_key(&self, key: &str, entry: Entry) {
        let Ok(mut map) = self.entries.lock() else {
            return;
        };
        let now = entry.stored;
        if map.len() >= self.max_entries {
            map.retain(|_, e| now.duration_since(e.stored) < self.ttl);
            if map.len() >= self.max_entries {
                let mut by_age: Vec<(String, Instant)> =
                    map.iter().map(|(k, e)| (k.clone(), e.stored)).collect();
                by_age.sort_by_key(|(_, t)| *t);
                for (k, _) in by_age.into_iter().take(self.max_entries.max(2) / 2) {
                    map.remove(&k);
                }
            }
        }
        map.insert(key.to_owned(), entry);
    }

    /// Compose the key both stores use, so an entry written by one is found by the other.
    #[must_use]
    pub fn compose_key(tenant: &str, prompt_hash: &str, ladder: &[String]) -> String {
        key(tenant, prompt_hash, ladder)
    }

    /// Evict every entry proven by `source`, because that proof has been retracted.
    ///
    /// Called when a deferred gate or downstream outcome reports a Fail for a decision. Without
    /// this, an answer the world has since disproven keeps being replayed until its TTL expires —
    /// and each replay carries a `cache_source` pointing at a receipt that now records a failure,
    /// so the audit trail would actively contradict what was served.
    ///
    /// Returns how many entries were dropped. A single decision can back several keys once the
    /// same prompt is seen under more than one ladder, so this scans by source rather than
    /// assuming one.
    pub fn retract(&self, source: uuid::Uuid) -> usize {
        let Ok(mut map) = self.entries.lock() else {
            return 0;
        };
        let before = map.len();
        map.retain(|_, e| e.source != source);
        before - map.len()
    }

    /// Entries currently held (tests and `/metrics`).
    #[must_use]
    pub fn len(&self) -> usize {
        self.entries.lock().map(|m| m.len()).unwrap_or(0)
    }

    /// Whether the cache holds nothing.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

#[async_trait::async_trait]
impl CacheStore for VerifiedCache {
    // Delegates to the existing synchronous methods rather than reimplementing them. The
    // in-process path is the one four review rounds hardened — a parallel async copy would be free
    // to drift on exactly the rules that keep an unproven answer out.
    async fn get(&self, key: &str, now: Instant) -> Option<Entry> {
        self.get_by_key(key, now)
    }

    async fn put(&self, key: &str, _source: uuid::Uuid, entry: Entry, _now: Instant) {
        self.put_by_key(key, entry);
    }

    async fn retract(&self, source: uuid::Uuid) -> usize {
        Self::retract(self, source)
    }

    async fn entry_count(&self) -> usize {
        Self::len(self)
    }
}

/// A Redis-backed L2, so entries and retractions cross process boundaries.
///
/// Enabled by the `redis-cache` feature and a `redis_url`. Without it the cache is per-replica:
/// behind N instances a session's answer is cached N times over and the hit rate drops roughly by
/// N. Worse, a retraction only reaches the replica that received the feedback — the other N-1 keep
/// serving an answer the world has disproven, which is the multi-instance form of the bug this
/// module already had once.
///
/// ## Keys
///
/// - `fp:vc:<key>` → the serialized entry, with a Redis TTL so expiry is the server's job rather
///   than ours. A manual sweep across replicas would race; `SETEX` does not.
/// - `fp:vc:src:<uuid>` → a SET of the entry keys that decision proved, so `retract` can find them.
///   Given the same TTL, so the index cannot outlive what it points at and leak.
///
/// ## What it deliberately does not do
///
/// No local caching of L2 reads. A stale local copy would survive a retraction issued on another
/// replica — exactly the failure this exists to prevent — and a cache that can serve a disproven
/// answer is worse than no cache in a product whose claim is that it does not.
#[cfg(feature = "redis-cache")]
pub struct RedisStore {
    client: redis::aio::ConnectionManager,
    ttl_secs: u64,
}

// Hand-written: `ConnectionManager` is not `Debug`, and printing it would risk putting a
// credential-bearing URL into a log line anyway.
#[cfg(feature = "redis-cache")]
impl std::fmt::Debug for RedisStore {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RedisStore")
            .field("ttl_secs", &self.ttl_secs)
            .finish_non_exhaustive()
    }
}

/// How long to wait for Redis at startup before giving up.
///
/// Short on purpose: this runs before the listener binds, so every second here is a second the
/// proxy is not serving. A reachable Redis answers in milliseconds; one that needs ten seconds is
/// not one to put in the request path.
#[cfg(feature = "redis-cache")]
const CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);

/// Strip credentials from a Redis URL so it can appear in a log line.
///
/// `redis://user:hunter2@cache:6379/0` → `redis://cache:6379/0`. A connect failure has to name the
/// server or the message is useless for fixing it, and the userinfo is the one part that must not
/// be named. This module's own `Debug` impl avoids printing the URL for exactly this reason; the
/// error paths were interpolating it raw, which made that care pointless.
#[cfg(feature = "redis-cache")]
#[must_use]
pub fn redact_redis_url(url: &str) -> String {
    // Split on the LAST `@` before any path: a password may itself contain `@`, and splitting on
    // the first would leak the tail of it.
    let Some((scheme, rest)) = url.split_once("://") else {
        return "<malformed redis url>".to_owned();
    };
    let host_part = match rest.rfind('@') {
        Some(i) => &rest[i + 1..],
        None => rest,
    };
    format!("{scheme}://{host_part}")
}

#[cfg(feature = "redis-cache")]
impl RedisStore {
    /// Connect to `url`.
    ///
    /// # Errors
    /// A malformed URL or an unreachable server. Surfaced at startup rather than swallowed: a
    /// cache that silently degrades to "always miss" looks like the feature is off, and an operator
    /// who configured Redis should be told it is not working.
    pub async fn connect(url: &str, ttl_secs: u64) -> Result<Self, String> {
        let safe = redact_redis_url(url);
        let client = redis::Client::open(url).map_err(|e| format!("redis url {safe}: {e}"))?;
        // Bounded, because `ConnectionManager::new` retries a dead server indefinitely by default
        // — the proxy simply never finishes starting, with no error and no listening socket. A
        // hang is the worst of the three outcomes here: an operator can act on a refusal and can
        // live with a degraded cache, but "startup never returns" looks like a deploy that stalled
        // for unrelated reasons.
        let mgr = tokio::time::timeout(CONNECT_TIMEOUT, redis::aio::ConnectionManager::new(client))
            .await
            .map_err(|_| {
                format!(
                    "redis at {safe} did not answer within {}s. The proxy refuses to start rather \
                 than run with a cache that silently stays per-replica — check the server is \
                 reachable, or remove redis_url to use the in-process cache.",
                    CONNECT_TIMEOUT.as_secs()
                )
            })?
            .map_err(|e| format!("redis connect {safe}: {e}"))?;

        // `ConnectionManager::new` connects LAZILY: it returns Ok against a server that is not
        // running, the proxy logs "shared via redis", binds, and serves with a cache that never
        // works. That is worse than degrading to per-replica — it is non-functional while
        // announcing success, which is the exact failure this fail-fast exists to prevent.
        //
        // So prove the connection with a real round trip before claiming it.
        let mut probe = mgr.clone();
        let pong: Result<String, _> = tokio::time::timeout(
            CONNECT_TIMEOUT,
            redis::cmd("PING").query_async(&mut probe),
        )
        .await
        .map_err(|_| {
            format!(
                "redis at {safe} did not answer PING within {}s. Refusing to start rather than \
                 run with a cache that reports itself as shared and never works — check the \
                 server is reachable, or remove redis_url to use the in-process cache.",
                CONNECT_TIMEOUT.as_secs()
            )
        })?;
        pong.map_err(|e| format!("redis at {safe} rejected PING: {e}"))?;

        Ok(Self {
            client: mgr,
            ttl_secs,
        })
    }

    fn entry_key(key: &str) -> String {
        format!("fp:vc:{key}")
    }

    fn source_key(source: uuid::Uuid) -> String {
        format!("fp:vc:src:{source}")
    }
}

#[cfg(feature = "redis-cache")]
#[async_trait::async_trait]
impl CacheStore for RedisStore {
    async fn get(&self, key: &str, _now: Instant) -> Option<Entry> {
        let mut c = self.client.clone();
        let raw: Option<String> = redis::cmd("GET")
            .arg(Self::entry_key(key))
            .query_async(&mut c)
            .await
            .ok()?;
        // A malformed value is treated as a miss rather than an error: the request simply runs the
        // ladder, which is always safe. Failing the request because a cache entry did not
        // deserialize would turn an optimisation into an outage.
        serde_json::from_str(&raw?).ok()
    }

    async fn put(&self, key: &str, source: uuid::Uuid, entry: Entry, _now: Instant) {
        let Ok(body) = serde_json::to_string(&entry) else {
            return;
        };
        let mut c = self.client.clone();
        let ek = Self::entry_key(key);
        // Pipelined, not transactional: if the index write is lost the entry becomes unretractable
        // until TTL, so the TTL is the backstop that bounds that window. A MULTI would remove the
        // race but not the failure mode, and the entry TTL already caps the exposure.
        let _: Result<(), _> = redis::pipe()
            .cmd("SETEX")
            .arg(&ek)
            .arg(self.ttl_secs)
            .arg(body)
            .ignore()
            .cmd("SADD")
            .arg(Self::source_key(source))
            .arg(&ek)
            .ignore()
            .cmd("EXPIRE")
            .arg(Self::source_key(source))
            .arg(self.ttl_secs)
            .ignore()
            .query_async::<()>(&mut c)
            .await;
    }

    async fn retract(&self, source: uuid::Uuid) -> usize {
        let mut c = self.client.clone();
        let sk = Self::source_key(source);
        let keys: Vec<String> = redis::cmd("SMEMBERS")
            .arg(&sk)
            .query_async(&mut c)
            .await
            .unwrap_or_default();
        if keys.is_empty() {
            return 0;
        }
        let n: usize = redis::cmd("DEL")
            .arg(&keys)
            .query_async(&mut c)
            .await
            .unwrap_or(0);
        let _: Result<(), _> = redis::cmd("DEL").arg(&sk).query_async(&mut c).await;
        n
    }

    async fn entry_count(&self) -> usize {
        let mut c = self.client.clone();
        let keys: Vec<String> = redis::cmd("KEYS")
            .arg("fp:vc:*")
            .query_async(&mut c)
            .await
            .unwrap_or_default();
        // ponytail: KEYS is O(n) and blocks Redis; acceptable because this is only read by
        // /metrics and tests, never on the request path. Switch to SCAN if it is ever called
        // per-request.
        keys.iter().filter(|k| !k.starts_with("fp:vc:src:")).count()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use firstpass_core::{
        Attempt, DeferredVerdict, Features, FinalOutcome, GENESIS_HASH, GateResult, Mode,
        PolicyRef, RequestInfo, TaskKind,
    };

    fn resp(text: &str) -> ModelResponse {
        ModelResponse {
            model: "anthropic/claude-haiku-4-5".to_owned(),
            text: text.to_owned(),
            in_tokens: 10,
            cache_write_tokens: 0,
            cache_read_tokens: 0,
            out_tokens: 5,
            raw: serde_json::Value::Null,
        }
    }

    fn ladder() -> Vec<String> {
        vec!["anthropic/claude-haiku-4-5".to_owned()]
    }

    fn trace(served_from: ServedFrom, verdict: Verdict) -> Trace {
        Trace {
            trace_id: uuid::Uuid::now_v7(),
            prev_hash: GENESIS_HASH.to_owned(),
            tenant_id: "t".to_owned(),
            session_id: "s".to_owned(),
            ts: jiff::Timestamp::UNIX_EPOCH,
            mode: Mode::Enforce,
            policy: PolicyRef {
                id: "static-ladder@v0".to_owned(),
                explore: false,
                propensity: None,
                mode_profile: None,
            },
            request: RequestInfo {
                api: "anthropic.messages".to_owned(),
                prompt_hash: "hash-abc".to_owned(),
                features: Features::new(TaskKind::CodeEdit),
            },
            attempts: vec![Attempt {
                rung: 0,
                model: "anthropic/claude-haiku-4-5".to_owned(),
                provider: "anthropic".to_owned(),
                in_tokens: 10,
                cache_write_tokens: 0,
                cache_read_tokens: 0,
                out_tokens: 5,
                cost_usd: 0.01,
                latency_ms: 100,
                gates: vec![GateResult::deterministic("non-empty", verdict, 1)],
                verdict,
            }],
            final_: FinalOutcome {
                served_rung: Some(0),
                served_from,
                total_cost_usd: 0.01,
                gate_cost_usd: 0.0,
                total_latency_ms: 120,
                escalations: 0,
                counterfactual_baseline_usd: 0.05,
                savings_usd: 0.04,
                cache_source: None,
            },
            deferred: vec![],
            predicted_pass: None,
            probe: None,
            elastic: None,
            rollout: None,
            shadow: None,
            route_ix: None,
        }
    }

    #[test]
    fn a_passing_answer_is_stored_and_replayed_with_its_proof() {
        let c = VerifiedCache::new(Duration::from_secs(60), 100);
        let now = Instant::now();
        let t = trace(ServedFrom::Attempt, Verdict::Pass);

        assert!(c.offer(&t, &resp("the answer"), &ladder(), now));

        let hit = c.get("t", "hash-abc", &ladder(), now).expect("hit");
        assert_eq!(hit.response.text, "the answer");
        // Not merely "cached" — the decision whose gate passed, so the proof is one lookup away.
        assert_eq!(hit.source, t.trace_id);
        assert!((hit.original_cost_usd - 0.01).abs() < f64::EPSILON);
    }

    #[test]
    fn a_failed_answer_is_never_cached() {
        let c = VerifiedCache::new(Duration::from_secs(60), 100);
        let now = Instant::now();

        assert!(!c.offer(
            &trace(ServedFrom::Attempt, Verdict::Fail),
            &resp("bad"),
            &ladder(),
            now
        ));

        assert!(
            c.get("t", "hash-abc", &ladder(), now).is_none(),
            "must not be replayable"
        );
    }

    #[test]
    fn an_abstain_is_never_cached() {
        // "The gate could not tell" is exactly the state that must not be frozen and replayed —
        // every later hit would inherit an uncertainty nobody re-examines.
        let c = VerifiedCache::new(Duration::from_secs(60), 100);
        let now = Instant::now();
        assert!(!c.offer(
            &trace(ServedFrom::Attempt, Verdict::Abstain),
            &resp("?"),
            &ladder(),
            now
        ));
        assert!(c.get("t", "hash-abc", &ladder(), now).is_none());
    }

    #[test]
    fn a_budget_exhausted_best_effort_serve_is_never_cached() {
        // BestAttempt is served WITHOUT a passing verdict. Caching it would launder an unverified
        // answer into a served one, and no later reader could tell the difference.
        let c = VerifiedCache::new(Duration::from_secs(60), 100);
        let now = Instant::now();
        assert!(!c.offer(
            &trace(ServedFrom::BestAttempt, Verdict::Pass),
            &resp("x"),
            &ladder(),
            now
        ));
        assert!(c.get("t", "hash-abc", &ladder(), now).is_none());
    }

    #[test]
    fn a_later_failing_verdict_retracts_the_proof() {
        // A deferred gate (tests in CI, downstream feedback) that comes back Fail means the answer
        // was not good after all. It must not be sitting in the cache waiting to be served again.
        let c = VerifiedCache::new(Duration::from_secs(60), 100);
        let now = Instant::now();
        let mut t = trace(ServedFrom::Attempt, Verdict::Pass);
        t.deferred.push(DeferredVerdict {
            gate_id: "tests".to_owned(),
            verdict: Verdict::Fail,
            score: None,
            reported_at: jiff::Timestamp::UNIX_EPOCH,
            reporter: "ci".to_owned(),
        });

        assert!(!c.offer(&t, &resp("looked fine"), &ladder(), now));
    }

    #[cfg(feature = "redis-cache")]
    #[test]
    fn a_redis_url_never_reaches_a_log_line_with_its_password() {
        // The module's own Debug impl avoids printing the URL for this reason; the error paths
        // were interpolating it raw, which made that care pointless.
        assert_eq!(
            redact_redis_url("redis://user:hunter2@cache:6379/0"),
            "redis://cache:6379/0"
        );
        // A password containing '@' must not leak its tail — split on the LAST '@', not the first.
        assert_eq!(
            redact_redis_url("redis://user:p@ss@cache:6379/0"),
            "redis://cache:6379/0"
        );
        assert_eq!(
            redact_redis_url("redis://cache:6379/0"),
            "redis://cache:6379/0"
        );
        assert_eq!(redact_redis_url("rediss://u:p@h:6380"), "rediss://h:6380");
        assert_eq!(redact_redis_url("nonsense"), "<malformed redis url>");

        for u in [
            "redis://user:hunter2@cache:6379/0",
            "redis://user:p@ss@cache:6379/0",
        ] {
            let out = redact_redis_url(u);
            assert!(!out.contains("hunter2"), "{out}");
            assert!(!out.contains("p@ss"), "{out}");
            assert!(!out.contains("user"), "{out}");
        }
    }

    /// Exercise the real Redis backend.
    ///
    /// Requires a reachable server at `FIRSTPASS_TEST_REDIS`. **Absent, this fails rather than
    /// skipping**: a suite that quietly passes when its subject is unavailable reports green while
    /// testing nothing, which is how this repo's `provider-smoke` job once read as verified.
    #[cfg(feature = "redis-cache")]
    #[tokio::test]
    async fn redis_store_round_trips_and_retracts() {
        let url = std::env::var("FIRSTPASS_TEST_REDIS").unwrap_or_else(|_| {
            panic!(
                "set FIRSTPASS_TEST_REDIS (e.g. redis://127.0.0.1:6379/15) to run the redis-cache \
                 tests. Not skipped on purpose: a green suite that tested nothing is worse than a \
                 red one."
            )
        });
        let store = RedisStore::connect(&url, 60).await.expect("connect");

        let t = trace(ServedFrom::Attempt, Verdict::Pass);
        let k = VerifiedCache::compose_key("t", &format!("h-{}", t.trace_id), &ladder());
        let now = Instant::now();
        let entry = Entry::new(resp("shared answer"), &t, now);

        store.put(&k, t.trace_id, entry, now).await;
        let got = store
            .get(&k, now)
            .await
            .expect("entry crossed the boundary");
        assert_eq!(got.response.text, "shared answer");
        // The PROOF is what has to survive; a replay's receipt is built from it.
        assert_eq!(got.source, t.trace_id);

        // Retraction must work through the source index, since feedback names a decision, not a key.
        assert_eq!(store.retract(t.trace_id).await, 1);
        assert!(
            store.get(&k, now).await.is_none(),
            "a retracted answer must stop being replayable in the SHARED store too"
        );
    }

    #[cfg(feature = "redis-cache")]
    #[tokio::test]
    async fn redis_store_isolates_tenants() {
        // The cross-tenant leak found in review must not reappear through the shared surface.
        let url = std::env::var("FIRSTPASS_TEST_REDIS")
            .expect("set FIRSTPASS_TEST_REDIS to run the redis-cache tests");
        let store = RedisStore::connect(&url, 60).await.expect("connect");

        let mut t = trace(ServedFrom::Attempt, Verdict::Pass);
        t.tenant_id = "tenant-a".to_owned();
        let hash = format!("iso-{}", t.trace_id);
        let ka = VerifiedCache::compose_key("tenant-a", &hash, &ladder());
        let kb = VerifiedCache::compose_key("tenant-b", &hash, &ladder());
        let now = Instant::now();

        store
            .put(&ka, t.trace_id, Entry::new(resp("a"), &t, now), now)
            .await;

        assert!(
            store.get(&kb, now).await.is_none(),
            "cross-tenant replay is a data leak"
        );
        assert!(store.get(&ka, now).await.is_some());
        store.retract(t.trace_id).await;
    }

    #[tokio::test]
    async fn the_trait_and_the_concrete_api_agree_on_keys() {
        // The two stores must compose the key identically or a multi-replica deployment silently
        // never hits: one writes under a key the other never looks up, and the only symptom is a
        // hit rate that quietly stays at zero.
        let c = VerifiedCache::new(Duration::from_secs(60), 100);
        let now = Instant::now();
        let t = trace(ServedFrom::Attempt, Verdict::Pass);
        assert!(c.offer(&t, &resp("via offer"), &ladder(), now));

        let k = VerifiedCache::compose_key("t", "hash-abc", &ladder());
        let via_trait = CacheStore::get(&c, &k, now)
            .await
            .expect("trait sees offer's entry");
        assert_eq!(via_trait.response.text, "via offer");
    }

    #[tokio::test]
    async fn the_trait_path_still_isolates_tenants() {
        // The leak found in review must not reappear through the new surface: `compose_key` is the
        // single place the tenant enters, and both stores go through it.
        let a = VerifiedCache::compose_key("tenant-a", "h", &ladder());
        let b = VerifiedCache::compose_key("tenant-b", "h", &ladder());
        assert_ne!(a, b, "tenant must be part of the key on the trait path too");
        assert!(a.starts_with("tenant-a|"), "{a}");
    }

    #[tokio::test]
    async fn an_entry_survives_a_serde_round_trip_without_its_local_clock() {
        // Redis carries entries between processes, where an Instant is meaningless. The proof
        // (source) and the answer must survive; `stored` is re-stamped, and expiry there is
        // Redis's TTL rather than a comparison of two machines' monotonic clocks.
        let e = Entry {
            response: resp("answer"),
            source: uuid::Uuid::now_v7(),
            original_cost_usd: 0.01,
            stored: Instant::now(),
        };
        let wire = serde_json::to_string(&e).expect("serializes");
        assert!(
            !wire.contains("stored"),
            "a local Instant must not go on the wire: {wire}"
        );

        let back: Entry = serde_json::from_str(&wire).expect("deserializes");
        assert_eq!(back.response.text, "answer");
        assert_eq!(back.source, e.source, "the PROOF must survive the crossing");
        assert!((back.original_cost_usd - 0.01).abs() < f64::EPSILON);
    }

    #[test]
    fn a_retraction_evicts_the_answer_it_disproved() {
        // Found in review: rule 4 only inspects the receipt at INSERT time, and deferred verdicts
        // arrive later via /v1/feedback — so on its own it is a no-op in production and a
        // disproven answer keeps being served until TTL. This is the half that actually runs.
        let c = VerifiedCache::new(Duration::from_secs(600), 100);
        let now = Instant::now();
        let t = trace(ServedFrom::Attempt, Verdict::Pass);
        assert!(c.offer(&t, &resp("looked fine"), &ladder(), now));
        assert!(c.get("t", "hash-abc", &ladder(), now).is_some());

        assert_eq!(c.retract(t.trace_id), 1);

        assert!(
            c.get("t", "hash-abc", &ladder(), now).is_none(),
            "an answer whose proof was retracted must stop being replayed immediately"
        );
    }

    #[test]
    fn retracting_an_unrelated_decision_evicts_nothing() {
        let c = VerifiedCache::new(Duration::from_secs(600), 100);
        let now = Instant::now();
        c.offer(
            &trace(ServedFrom::Attempt, Verdict::Pass),
            &resp("a"),
            &ladder(),
            now,
        );

        assert_eq!(c.retract(uuid::Uuid::now_v7()), 0);
        assert!(c.get("t", "hash-abc", &ladder(), now).is_some());
    }

    #[test]
    fn a_cache_hit_is_not_itself_re_cached() {
        // Otherwise `cache_source` would point at a replay instead of the decision that actually
        // ran a gate, and the provenance chain — the whole feature — would go one hop stale.
        let c = VerifiedCache::new(Duration::from_secs(60), 100);
        let now = Instant::now();
        let mut t = trace(ServedFrom::Attempt, Verdict::Pass);
        t.final_.cache_source = Some(uuid::Uuid::now_v7());
        assert!(!c.offer(&t, &resp("replayed"), &ladder(), now));
    }

    #[test]
    fn one_tenant_can_never_replay_anothers_answer() {
        // Caught in review, and the worst bug in this feature: the key was
        // `prompt_hash | ladder`, with no tenant. The prompt salt is per-DEPLOYMENT, so two
        // tenants sending an identical prompt hash identically — tenant B would have been served
        // tenant A's paid-for, verified answer, with a receipt that looked entirely normal.
        let c = VerifiedCache::new(Duration::from_secs(60), 100);
        let now = Instant::now();
        let mut t = trace(ServedFrom::Attempt, Verdict::Pass);
        t.tenant_id = "tenant-a".to_owned();
        assert!(c.offer(&t, &resp("a's private answer"), &ladder(), now));

        assert!(
            c.get("tenant-b", "hash-abc", &ladder(), now).is_none(),
            "cross-tenant replay — this is a data leak, not a cache miss"
        );
        assert!(
            c.get("tenant-a", "hash-abc", &ladder(), now).is_some(),
            "the owning tenant must still hit"
        );
    }

    #[test]
    fn the_cached_tenant_comes_from_the_receipt_not_the_caller() {
        // Reading it off the receipt means a call site cannot pass the wrong tenant and quietly
        // file an answer under someone else's key.
        let c = VerifiedCache::new(Duration::from_secs(60), 100);
        let now = Instant::now();
        let mut t = trace(ServedFrom::Attempt, Verdict::Pass);
        t.tenant_id = "owner".to_owned();
        c.offer(&t, &resp("x"), &ladder(), now);

        assert!(c.get("owner", "hash-abc", &ladder(), now).is_some());
        assert!(c.get("t", "hash-abc", &ladder(), now).is_none());
    }

    #[test]
    fn a_different_ladder_is_a_different_question() {
        // An answer proven against one gate/ladder configuration says nothing about another.
        let c = VerifiedCache::new(Duration::from_secs(60), 100);
        let now = Instant::now();
        c.offer(
            &trace(ServedFrom::Attempt, Verdict::Pass),
            &resp("a"),
            &ladder(),
            now,
        );

        let other = vec!["openai/gpt-5.5".to_owned()];
        assert!(c.get("t", "hash-abc", &other, now).is_none());
        assert!(c.get("t", "hash-abc", &ladder(), now).is_some());
    }

    #[test]
    fn an_entry_expires() {
        let c = VerifiedCache::new(Duration::from_secs(1), 100);
        let t0 = Instant::now();
        c.offer(
            &trace(ServedFrom::Attempt, Verdict::Pass),
            &resp("a"),
            &ladder(),
            t0,
        );

        assert!(c.get("t", "hash-abc", &ladder(), t0).is_some());
        assert!(
            c.get("t", "hash-abc", &ladder(), t0 + Duration::from_secs(2))
                .is_none(),
            "a stale proof is not a proof"
        );
    }

    #[test]
    fn the_cache_cannot_grow_without_bound() {
        let c = VerifiedCache::new(Duration::from_secs(600), 10);
        let now = Instant::now();
        for i in 0..100 {
            let mut t = trace(ServedFrom::Attempt, Verdict::Pass);
            t.request.prompt_hash = format!("h{i}");
            c.offer(&t, &resp("a"), &ladder(), now);
        }
        assert!(c.len() <= 10, "expected <= 10 entries, got {}", c.len());
    }
}