Skip to main content

firstpass_core/
trace.rs

1//! The audit trace (SPEC §9.1) — the tamper-evident record of one routing decision.
2//!
3//! A trace captures *why* a request went where it did and *what it cost*: the features it was
4//! routed on, every attempt and its gate verdicts, the final served outcome, and the savings
5//! versus always calling the top rung. Each record links to the previous via [`Trace::prev_hash`]
6//! (see [`crate::hashchain`]), so the log is append-only and any tampering is detectable.
7//!
8//! **The serde field names in this module are the wire/audit contract.** External auditors
9//! parse them and re-derive the hash chain; renaming one is a breaking change that requires a
10//! schema/version bump, never a silent edit.
11
12use crate::Result;
13use crate::config::Mode;
14use crate::features::Features;
15use crate::hashchain::{Chained, record_hash};
16use crate::verdict::{GateResult, Score, Verdict};
17use jiff::Timestamp;
18use serde::{Deserialize, Serialize};
19use uuid::Uuid;
20
21/// Regime classification from the k-sample visible-pass count (ADR 0008).
22///
23/// The three regimes are validated on MBPP (k=5, n=150): 0/5 pass → 0% oracle-correct (12% of
24/// traffic); 5/5 pass → 99% oracle-correct (65%); 1–4/5 → mixed (23%). Keyed on the pass
25/// *count*, not entropy — the entropy AUC (0.431) was falsified; the count AUC is decisive.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
27#[serde(rename_all = "snake_case")]
28pub enum ProbeRegime {
29    /// All k samples passed — oracle-correct ≈99% (validated on MBPP).
30    ConfidentPass,
31    /// Zero of k samples passed — oracle-correct ≈0%.
32    ConfidentFail,
33    /// 1..k-1 samples passed — mixed signal; verification information is worth its cost.
34    Ambiguous,
35}
36
37impl ProbeRegime {
38    /// Classify a pass-count into one of three regimes.
39    ///
40    /// - `0` → `ConfidentFail`
41    /// - `pass_count >= k` → `ConfidentPass`
42    /// - otherwise → `Ambiguous`
43    #[must_use]
44    pub fn classify(pass_count: u32, k: u32) -> Self {
45        if pass_count == 0 {
46            Self::ConfidentFail
47        } else if pass_count >= k {
48            Self::ConfidentPass
49        } else {
50            Self::Ambiguous
51        }
52    }
53}
54
55/// The shadow-probe signal recorded on a sampled receipt (ADR 0008 Phase 1). Records the k-sample
56/// gate-pass-count signal and its cost separately from the served cost, so savings math is clean.
57#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
58pub struct ProbeSignal {
59    /// Number of parallel probe samples drawn.
60    pub k: u32,
61    /// How many of the k samples would have been served under the route's gate/threshold rule.
62    pub gate_pass_count: u32,
63    /// Which of the three validated regimes this request falls into.
64    pub regime: ProbeRegime,
65    /// USD cost of the k shadow model calls — **separate** from `trace.final_.total_cost_usd`
66    /// so per-request savings math is not polluted by measurement cost.
67    pub probe_cost_usd: f64,
68}
69
70/// The action elastic verification (ADR 0008 Phase 3) took on the served rung.
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
72#[serde(rename_all = "snake_case")]
73pub enum ElasticAction {
74    /// Visible signal cleared λ → served **without** running the expensive gates (skip authorized
75    /// by the conformal bound). This is the un-verified serve the bound must cover.
76    ServeSkip,
77    /// Visible gates failed (signal at the floor) → escalated **without** paying for the expensive
78    /// gates on a doomed attempt.
79    EscalateNow,
80    /// Ambiguous middle → the expensive gates ran as usual; the gate decided.
81    Verified,
82}
83
84/// Why elastic verification (ADR 0008 Phase 3) skipped or ran the expensive gates on the served
85/// rung — recorded so an auditor can see *why* verification was skipped and check the conformal
86/// bound authorized it. Absent when elastic is off (the default), keeping pre-elastic traces
87/// byte-identical and hash-chain compatible.
88#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
89pub struct ElasticDecision {
90    /// Which of the three regimes fired.
91    pub action: ElasticAction,
92    /// The visible-gate score that drove the decision (`gate_score` over the cheap gates).
93    pub signal: f64,
94    /// The calibrated skip threshold λ the signal was compared against.
95    pub lambda: f64,
96    /// Target served-failure α the λ was calibrated at (provenance, from config).
97    #[serde(default, skip_serializing_if = "Option::is_none")]
98    pub alpha: Option<f64>,
99    /// Confidence (1−δ) the λ was calibrated at (provenance, from config).
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub delta: Option<f64>,
102    /// Provenance id of the calibration run that produced λ (from config).
103    #[serde(default, skip_serializing_if = "Option::is_none")]
104    pub calibration_id: Option<String>,
105}
106
107/// The rollout arm this request landed in (ADR 0009 D1), recorded so an auditor can re-derive
108/// arm membership from the receipt alone. Absent when the route has no rollout — byte-identical
109/// What Firstpass *would* have done for an observed request (ADR 0009 D2).
110///
111/// This describes a counterfactual that was never served, so it must never enter the conformal
112/// calibration set for served failures — it is a separate estimate with its own sample size.
113/// Pooling it with served outcomes would let a projection contaminate the published bound.
114#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
115pub struct ShadowSignal {
116    /// Rung that would have been served, if any gate passed.
117    #[serde(default, skip_serializing_if = "Option::is_none")]
118    pub would_serve_rung: Option<u32>,
119    /// Whether the ladder would have produced a servable answer at all.
120    pub would_pass: bool,
121    /// What the shadow evaluation cost to run.
122    pub projected_cost_usd: f64,
123    /// What the request actually cost upstream, for comparison.
124    pub actual_cost_usd: f64,
125    /// Present when shadow did not run, saying why — a skipped measurement is recorded rather
126    /// than silently absent, so a projection that has stopped tracking is visible in the record.
127    #[serde(default, skip_serializing_if = "Option::is_none")]
128    pub skipped: Option<String>,
129}
130
131/// to pre-rollout traces and hash-chain compatible.
132#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
133pub struct RolloutRecord {
134    /// Configured percent at decision time. Recorded because it changes as an operator ramps,
135    /// and a bound computed over a window spanning a ramp must be able to see that.
136    pub percent: f64,
137    /// Which identity was held constant (`session` / `request` / `tenant`).
138    pub key: String,
139    /// The bucket this request fell in, within `0..10_000`.
140    pub bucket: u32,
141    /// Whether this request enforced. The observed arm is not a failure — it is the control.
142    pub enforced: bool,
143}
144
145/// A single routing decision, start to finish.
146#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
147pub struct Trace {
148    /// Time-ordered unique id (UUIDv7).
149    pub trace_id: Uuid,
150    /// Hash of the previous record in this chain (or [`crate::hashchain::GENESIS_HASH`]).
151    pub prev_hash: String,
152    /// Tenant this trace belongs to.
153    pub tenant_id: String,
154    /// Session (e.g. an agent run) this request is part of.
155    pub session_id: String,
156    /// When the decision was made.
157    pub ts: Timestamp,
158    /// Serving mode in effect.
159    pub mode: Mode,
160    /// Which policy produced this decision.
161    pub policy: PolicyRef,
162    /// The request that was routed.
163    pub request: RequestInfo,
164    /// Every attempt made, cheapest rung first.
165    pub attempts: Vec<Attempt>,
166    /// Verdicts that arrived after serving (deferred gates, feedback API). Attach over time.
167    #[serde(default, skip_serializing_if = "Vec::is_empty")]
168    pub deferred: Vec<DeferredVerdict>,
169    /// The final served outcome and its economics.
170    #[serde(rename = "final")]
171    pub final_: FinalOutcome,
172    /// Shadow probe signal (ADR 0008 Phase 1). Absent when probe is off (the default) or when
173    /// this request was not in the configured `sample_rate` — byte-identical to pre-probe traces
174    /// and hash-chain compatible (the `skip_serializing_if` keeps absent = absent).
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub probe: Option<ProbeSignal>,
177    /// Which rollout arm this request was in (ADR 0009 D1). Absent when the route has no
178    /// rollout configured.
179    #[serde(default, skip_serializing_if = "Option::is_none")]
180    pub rollout: Option<RolloutRecord>,
181    /// Counterfactual signal from shadow scoring (ADR 0009 D2). Absent unless shadow is enabled.
182    #[serde(default, skip_serializing_if = "Option::is_none")]
183    pub shadow: Option<ShadowSignal>,
184    /// Index of the route that handled this request, so a downstream outcome arriving later can
185    /// be attributed to the route that actually produced it (ADR 0009 D3).
186    ///
187    /// Without this the guardrail has to pool every tenant's outcomes onto one route, which in a
188    /// multi-route config means a failing route can be masked by healthy siblings — the guard
189    /// would sit green while the thing it guards degrades. Absent on traces written before this
190    /// field existed; the guardrail treats absent as route 0, its prior behaviour.
191    #[serde(default, skip_serializing_if = "Option::is_none")]
192    pub route_ix: Option<u32>,
193    /// Shadow prediction of `P(gate-pass)` for the start rung (ADR 0008 Phase 2), from the
194    /// per-query predictor. Absent when the predictor is off (the default) — byte-identical to
195    /// pre-predictor traces and hash-chain compatible. Recorded but never acted on in this phase.
196    #[serde(default, skip_serializing_if = "Option::is_none")]
197    pub predicted_pass: Option<f64>,
198    /// Elastic verification decision (ADR 0008 Phase 3) on the served rung: why the expensive gates
199    /// were skipped or run, plus the λ / calibration provenance the skip was authorized under.
200    /// Absent when elastic is off (the default) — byte-identical to pre-elastic traces and
201    /// hash-chain compatible (the `skip_serializing_if` keeps absent = absent).
202    #[serde(default, skip_serializing_if = "Option::is_none")]
203    pub elastic: Option<ElasticDecision>,
204}
205
206/// Reference to the policy that produced a decision.
207#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
208pub struct PolicyRef {
209    /// Policy identity/version, e.g. `"static@v0"` or `"bandit@v3"`.
210    pub id: String,
211    /// Whether this decision was a deliberate exploration draw (bounded, §, only in enforce).
212    #[serde(default)]
213    pub explore: bool,
214    /// The probability the logging policy assigned to the start rung it chose — the
215    /// Horvitz-Thompson denominator for IPS / SNIPS off-policy evaluation.
216    ///
217    /// `None` for deterministic (non-exploring) policies. `skip_serializing_if` keeps old
218    /// trace bytes byte-identical when `None`, preserving hash-chain compatibility with
219    /// existing logs. Only populated when `[escalation.exploration]` is configured.
220    #[serde(default, skip_serializing_if = "Option::is_none")]
221    pub propensity: Option<f64>,
222    /// Resolved routing-mode profile when it was explicitly set (header / route / global env).
223    /// `None` means `Balanced` was in effect (the default, no override active). Absent from
224    /// the JSON when `None` → byte-identical serialization for all existing traces.
225    #[serde(default, skip_serializing_if = "Option::is_none")]
226    pub mode_profile: Option<String>,
227}
228
229/// The routed request, described without its raw content.
230#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
231pub struct RequestInfo {
232    /// Wire API the caller used, e.g. `"anthropic.messages"` / `"openai.chat"`.
233    pub api: String,
234    /// Salted hash of the prompt — never the prompt text itself.
235    pub prompt_hash: String,
236    /// The versioned feature vector routing keyed on.
237    pub features: Features,
238}
239
240/// One attempt at a rung: the model call plus the gates run against its output.
241#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
242pub struct Attempt {
243    /// Ladder rung (0 = cheapest).
244    pub rung: u32,
245    /// Model called, `provider/model`.
246    pub model: String,
247    /// Provider segment (denormalized for cheap querying).
248    pub provider: String,
249    /// Input tokens consumed, **uncached only**.
250    ///
251    /// When the caller uses prompt caching this is the small remainder; the bulk of the prompt is
252    /// reported separately below and billed at different rates. Read `billable_input()` rather
253    /// than this field for anything cost-shaped.
254    pub in_tokens: u64,
255    /// Prompt tokens written to the provider's cache on this call, billed at a **premium**
256    /// (Anthropic: 1.25× base input).
257    ///
258    /// Defaults to 0, so a receipt written before this field existed still deserializes and still
259    /// re-derives the same hash — the field is skipped when zero.
260    #[serde(default, skip_serializing_if = "is_zero")]
261    pub cache_write_tokens: u64,
262    /// Prompt tokens served from the provider's cache, billed at a **discount** (Anthropic: 0.1×
263    /// base input). Same zero-default reasoning as `cache_write_tokens`.
264    #[serde(default, skip_serializing_if = "is_zero")]
265    pub cache_read_tokens: u64,
266    /// Output tokens produced.
267    pub out_tokens: u64,
268    /// USD cost of this model call (excludes gate cost).
269    pub cost_usd: f64,
270    /// Wall-clock latency of the model call.
271    pub latency_ms: u64,
272    /// Gate verdicts for this attempt's output.
273    pub gates: Vec<GateResult>,
274    /// The attempt's overall verdict (the aggregate that drove escalate-or-serve).
275    pub verdict: Verdict,
276}
277
278/// `skip_serializing_if` helper: keeps zero-valued cache fields out of the canonical JSON, so a
279/// receipt written before those fields existed hashes identically to one written after.
280#[allow(clippy::trivially_copy_pass_by_ref)] // serde requires the &-taking shape
281fn is_zero(n: &u64) -> bool {
282    *n == 0
283}
284
285impl Trace {
286    /// Milliseconds this proxy added on top of the work it actually dispatched — provider calls
287    /// plus gates. The number a gateway is judged on, and the one Firstpass could not previously
288    /// state about itself.
289    ///
290    /// Returns `None` rather than a wrong figure when it cannot be computed honestly. Under
291    /// speculation, rungs run concurrently, so the summed work legitimately exceeds wall-clock and
292    /// the subtraction is meaningless; a receipt like that is excluded from an overhead
293    /// distribution instead of being floored to zero, which would silently drag a p95 down.
294    ///
295    /// Deliberately derived rather than stored: a recorded overhead field could disagree with the
296    /// timings beside it, and this way an auditor recomputes it from the same numbers we do.
297    #[must_use]
298    pub fn overhead_ms(&self) -> Option<u64> {
299        let dispatched: u64 = self
300            .attempts
301            .iter()
302            .map(|a| {
303                a.latency_ms
304                    .saturating_add(a.gates.iter().map(|g| g.ms).sum::<u64>())
305            })
306            .sum();
307        self.final_.total_latency_ms.checked_sub(dispatched)
308    }
309}
310
311impl Attempt {
312    /// Total prompt tokens this call actually consumed, cached or not.
313    ///
314    /// `in_tokens` alone is **not** the prompt size when the caller uses prompt caching: providers
315    /// report the cached portion in separate fields, and a 190k-token cached prefix shows up as an
316    /// `in_tokens` of about 20. Anything reporting prompt volume wants this, not the raw field.
317    #[must_use]
318    pub const fn billable_input(&self) -> u64 {
319        self.in_tokens
320            .saturating_add(self.cache_write_tokens)
321            .saturating_add(self.cache_read_tokens)
322    }
323}
324
325/// A verdict that arrived after the response was served (deferred gate or downstream feedback).
326#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
327pub struct DeferredVerdict {
328    /// Gate/source identity, e.g. `"tests"` or `"feedback:ci"`.
329    pub gate_id: String,
330    /// The late verdict.
331    pub verdict: Verdict,
332    /// Optional score.
333    #[serde(default, skip_serializing_if = "Option::is_none")]
334    pub score: Option<Score>,
335    /// When it arrived.
336    pub reported_at: Timestamp,
337    /// Who reported it (a deferred gate, or a feedback-API caller identity).
338    pub reporter: String,
339}
340
341/// Where the served response came from.
342#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
343#[serde(rename_all = "snake_case")]
344pub enum ServedFrom {
345    /// A passing attempt (the normal path).
346    Attempt,
347    /// The best attempt seen, served because budget/ladder was exhausted without a pass.
348    BestAttempt,
349    /// No output served; a structured error was returned.
350    Error,
351    /// Replayed from the verified cache: this exact prompt was answered before, that answer
352    /// **passed its gate**, and the receipt names the decision that proved it.
353    ///
354    /// Distinct from [`ServedFrom::Attempt`] because no model was called — a receipt that reported
355    /// this as a normal attempt would claim a verification that did not run today, and inflate
356    /// every pass-rate computed over receipts. `cache_source` carries the trace it came from, so
357    /// the proof is one lookup away rather than asserted.
358    Cache,
359}
360
361/// The final outcome and economics of a decision.
362#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
363pub struct FinalOutcome {
364    /// Rung whose output was served (`None` if `served_from = error`).
365    #[serde(default, skip_serializing_if = "Option::is_none")]
366    pub served_rung: Option<u32>,
367    /// Provenance of the served response.
368    pub served_from: ServedFrom,
369    /// Total USD spent (all model calls + all gates).
370    pub total_cost_usd: f64,
371    /// USD portion spent on gates alone.
372    pub gate_cost_usd: f64,
373    /// Total wall-clock latency the caller experienced.
374    pub total_latency_ms: u64,
375    /// Number of rung escalations taken.
376    pub escalations: u32,
377    /// What always calling the top rung would have cost (§9.1 counterfactual).
378    pub counterfactual_baseline_usd: f64,
379    /// The decision this answer was replayed from, when `served_from = cache`.
380    ///
381    /// The whole point of a verified cache: the receipt does not merely say "cached", it names the
382    /// earlier decision whose gate passed, so an auditor can follow the link and check that the
383    /// thing being replayed was actually proven. Absent otherwise, so pre-cache receipts serialize
384    /// byte-identically and re-derive the same hash.
385    #[serde(default, skip_serializing_if = "Option::is_none")]
386    pub cache_source: Option<Uuid>,
387    /// `counterfactual_baseline_usd - total_cost_usd` — the savings this decision proves.
388    pub savings_usd: f64,
389}
390
391impl Chained for Trace {
392    fn prev_hash(&self) -> &str {
393        &self.prev_hash
394    }
395}
396
397impl Trace {
398    /// This record's own hash (SHA-256 over its canonical JSON) — the value the *next*
399    /// record stores as its `prev_hash`.
400    ///
401    /// # Errors
402    /// Returns [`crate::Error::Json`] if the trace cannot be serialized.
403    pub fn hash(&self) -> Result<String> {
404        record_hash(self)
405    }
406
407    /// Compute `savings_usd = baseline - total` and store it, keeping the field consistent
408    /// with the two it is derived from. Returns the savings.
409    pub fn recompute_savings(&mut self) -> f64 {
410        let s = self.final_.counterfactual_baseline_usd - self.final_.total_cost_usd;
411        self.final_.savings_usd = s;
412        s
413    }
414}
415
416impl std::fmt::Display for Trace {
417    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
418        write!(
419            f,
420            "trace {} rung {:?} served_from {:?} cost ${:.4} saved ${:.4}",
421            self.trace_id,
422            self.final_.served_rung,
423            self.final_.served_from,
424            self.final_.total_cost_usd,
425            self.final_.savings_usd,
426        )
427    }
428}
429
430#[cfg(test)]
431mod tests {
432    use super::*;
433    use crate::features::{Features, TaskKind};
434    use crate::hashchain::{GENESIS_HASH, verify_chain};
435    use crate::verdict::Verdict;
436
437    fn sample_trace(prev_hash: &str, id: u128) -> Trace {
438        let mut t = Trace {
439            trace_id: Uuid::from_u128(id),
440            prev_hash: prev_hash.to_owned(),
441            tenant_id: "acme".into(),
442            session_id: "agent-run-4417".into(),
443            ts: "2026-07-08T15:04:05Z".parse().unwrap(),
444            mode: Mode::Enforce,
445            policy: PolicyRef {
446                id: "static@v0".into(),
447                explore: false,
448                propensity: None,
449                mode_profile: None,
450            },
451            request: RequestInfo {
452                api: "anthropic.messages".into(),
453                prompt_hash: "deadbeef".into(),
454                features: Features::new(TaskKind::CodeEdit),
455            },
456            attempts: vec![
457                Attempt {
458                    rung: 0,
459                    model: "anthropic/claude-haiku-4-5".into(),
460                    provider: "anthropic".into(),
461                    in_tokens: 2000,
462                    cache_write_tokens: 0,
463                    cache_read_tokens: 0,
464                    out_tokens: 700,
465                    cost_usd: 0.0007,
466                    latency_ms: 900,
467                    gates: vec![GateResult::deterministic("cargo-test", Verdict::Fail, 3100)],
468                    verdict: Verdict::Fail,
469                },
470                Attempt {
471                    rung: 1,
472                    model: "anthropic/claude-sonnet-5".into(),
473                    provider: "anthropic".into(),
474                    in_tokens: 2000,
475                    cache_write_tokens: 0,
476                    cache_read_tokens: 0,
477                    out_tokens: 800,
478                    cost_usd: 0.0121,
479                    latency_ms: 1200,
480                    gates: vec![GateResult::deterministic("cargo-test", Verdict::Pass, 2950)],
481                    verdict: Verdict::Pass,
482                },
483            ],
484            deferred: vec![],
485            final_: FinalOutcome {
486                served_rung: Some(1),
487                served_from: ServedFrom::Attempt,
488                total_cost_usd: 0.0128,
489                gate_cost_usd: 0.0,
490                total_latency_ms: 2100,
491                escalations: 1,
492                counterfactual_baseline_usd: 0.0630,
493                savings_usd: 0.0,
494                cache_source: None,
495            },
496            probe: None,
497            rollout: None,
498            shadow: None,
499            route_ix: None,
500            predicted_pass: None,
501            elastic: None,
502        };
503        t.recompute_savings();
504        t
505    }
506
507    #[test]
508    fn wire_field_names_are_the_contract() {
509        let t = sample_trace(GENESIS_HASH, 1);
510        let j = serde_json::to_string(&t).unwrap();
511        assert!(j.contains("\"prev_hash\":"));
512        assert!(
513            j.contains("\"final\":"),
514            "the outcome key must serialize as `final`"
515        );
516        assert!(j.contains("\"served_from\":\"attempt\""));
517        assert!(j.contains("\"verdict\":\"fail\""));
518        assert!(j.contains("\"verdict\":\"pass\""));
519        assert!(j.contains("\"counterfactual_baseline_usd\":"));
520    }
521
522    #[test]
523    fn savings_is_baseline_minus_total() {
524        let t = sample_trace(GENESIS_HASH, 1);
525        assert!((t.final_.savings_usd - (0.0630 - 0.0128)).abs() < 1e-12);
526    }
527
528    #[test]
529    fn traces_chain_and_verify() {
530        let t0 = sample_trace(GENESIS_HASH, 1);
531        let t1 = sample_trace(&t0.hash().unwrap(), 2);
532        let chain = [t0, t1];
533        assert!(verify_chain(&chain, GENESIS_HASH).is_ok());
534    }
535
536    #[test]
537    fn tampering_a_served_trace_is_detectable() {
538        let t0 = sample_trace(GENESIS_HASH, 1);
539        let t1 = sample_trace(&t0.hash().unwrap(), 2);
540        let mut chain = [t0, t1];
541        chain[0].final_.total_cost_usd = 0.0; // forge a cheaper decision after the fact
542        assert!(verify_chain(&chain, GENESIS_HASH).is_err());
543    }
544
545    #[test]
546    fn roundtrips_through_json() {
547        let t = sample_trace(GENESIS_HASH, 7);
548        let j = serde_json::to_string(&t).unwrap();
549        let back: Trace = serde_json::from_str(&j).unwrap();
550        assert_eq!(t, back);
551    }
552
553    // ── propensity backward-compat ────────────────────────────────────────────
554
555    /// Traces where propensity is None must serialize byte-identically to pre-field traces:
556    /// the field must be absent from the JSON, not serialized as `null`.
557    #[test]
558    fn propensity_none_absent_from_json() {
559        let pr = PolicyRef {
560            id: "static@v0".into(),
561            explore: false,
562            propensity: None,
563            mode_profile: None,
564        };
565        let j = serde_json::to_string(&pr).unwrap();
566        assert!(
567            !j.contains("propensity"),
568            "propensity=None must be omitted (skip_serializing_if): {j}"
569        );
570    }
571
572    /// Old JSON without a `propensity` field must deserialize to `propensity: None`
573    /// (via `#[serde(default)]`), keeping old traces readable without schema migration.
574    #[test]
575    fn old_trace_without_propensity_deserializes_to_none() {
576        let old_json = r#"{"id":"static@v0","explore":false}"#;
577        let pr: PolicyRef = serde_json::from_str(old_json).unwrap();
578        assert_eq!(pr.propensity, None);
579    }
580
581    /// New JSON with a propensity value round-trips correctly.
582    #[test]
583    fn propensity_some_roundtrips() {
584        let pr = PolicyRef {
585            id: "bandit@v1+eps".into(),
586            explore: true,
587            propensity: Some(0.3),
588            mode_profile: None,
589        };
590        let j = serde_json::to_string(&pr).unwrap();
591        assert!(
592            j.contains("\"propensity\":0.3"),
593            "expected propensity in: {j}"
594        );
595        let back: PolicyRef = serde_json::from_str(&j).unwrap();
596        assert_eq!(back, pr);
597    }
598
599    // ── mode_profile backward-compat ─────────────────────────────────────────
600
601    /// `mode_profile = None` must not appear in the serialized JSON — byte-identical for
602    /// existing traces (Balanced is the default and must be invisible).
603    #[test]
604    fn mode_profile_none_absent_from_json() {
605        let pr = PolicyRef {
606            id: "static@v0".into(),
607            explore: false,
608            propensity: None,
609            mode_profile: None,
610        };
611        let j = serde_json::to_string(&pr).unwrap();
612        assert!(
613            !j.contains("mode_profile"),
614            "mode_profile=None must be omitted (skip_serializing_if): {j}"
615        );
616    }
617
618    /// Old JSON without a `mode_profile` field deserializes to `mode_profile: None`.
619    #[test]
620    fn old_trace_without_mode_profile_deserializes_to_none() {
621        let old_json = r#"{"id":"static@v0","explore":false}"#;
622        let pr: PolicyRef = serde_json::from_str(old_json).unwrap();
623        assert_eq!(pr.mode_profile, None);
624    }
625
626    /// `mode_profile = Some(...)` round-trips correctly.
627    #[test]
628    fn mode_profile_some_roundtrips() {
629        let pr = PolicyRef {
630            id: "static@v0".into(),
631            explore: false,
632            propensity: None,
633            mode_profile: Some("quality".into()),
634        };
635        let j = serde_json::to_string(&pr).unwrap();
636        assert!(
637            j.contains("\"mode_profile\":\"quality\""),
638            "expected mode_profile in: {j}"
639        );
640        let back: PolicyRef = serde_json::from_str(&j).unwrap();
641        assert_eq!(back, pr);
642    }
643
644    // ── ProbeRegime::classify ─────────────────────────────────────────────────
645
646    #[test]
647    fn classify_zero_is_confident_fail() {
648        assert_eq!(ProbeRegime::classify(0, 5), ProbeRegime::ConfidentFail);
649    }
650
651    #[test]
652    fn classify_all_pass_is_confident_pass() {
653        assert_eq!(ProbeRegime::classify(5, 5), ProbeRegime::ConfidentPass);
654    }
655
656    #[test]
657    fn classify_above_k_is_confident_pass() {
658        // pass_count > k is technically impossible but the rule handles it gracefully.
659        assert_eq!(ProbeRegime::classify(6, 5), ProbeRegime::ConfidentPass);
660    }
661
662    #[test]
663    fn classify_mixed_is_ambiguous() {
664        assert_eq!(ProbeRegime::classify(1, 5), ProbeRegime::Ambiguous);
665        assert_eq!(ProbeRegime::classify(2, 5), ProbeRegime::Ambiguous);
666        assert_eq!(ProbeRegime::classify(4, 5), ProbeRegime::Ambiguous);
667    }
668
669    #[test]
670    fn classify_k_equals_2_boundaries() {
671        assert_eq!(ProbeRegime::classify(0, 2), ProbeRegime::ConfidentFail);
672        assert_eq!(ProbeRegime::classify(1, 2), ProbeRegime::Ambiguous);
673        assert_eq!(ProbeRegime::classify(2, 2), ProbeRegime::ConfidentPass);
674    }
675
676    // ── ProbeSignal serde backward-compat ────────────────────────────────────
677
678    /// `probe = None` must be absent from the JSON — byte-identical to pre-probe traces.
679    #[test]
680    fn probe_none_absent_from_json() {
681        let t = sample_trace(GENESIS_HASH, 1);
682        assert!(t.probe.is_none());
683        let j = serde_json::to_string(&t).unwrap();
684        assert!(
685            !j.contains("\"probe\""),
686            "probe=None must be omitted (skip_serializing_if): {j}"
687        );
688    }
689
690    /// Old JSON without a `probe` field deserializes cleanly (probe defaults to None).
691    #[test]
692    fn old_trace_without_probe_deserializes_to_none() {
693        // Use the canonical JSON of a probe-None trace as a stand-in for old traces.
694        let t = sample_trace(GENESIS_HASH, 1);
695        let j = serde_json::to_string(&t).unwrap();
696        assert!(!j.contains("probe"));
697        let back: Trace = serde_json::from_str(&j).unwrap();
698        assert_eq!(back.probe, None);
699    }
700
701    /// `probe = Some(...)` round-trips correctly.
702    #[test]
703    fn probe_signal_some_roundtrips() {
704        let mut t = sample_trace(GENESIS_HASH, 1);
705        t.probe = Some(ProbeSignal {
706            k: 5,
707            gate_pass_count: 5,
708            regime: ProbeRegime::ConfidentPass,
709            probe_cost_usd: 0.0003,
710        });
711        let j = serde_json::to_string(&t).unwrap();
712        assert!(j.contains("\"probe\""), "probe=Some must be present: {j}");
713        assert!(j.contains("\"regime\":\"confident_pass\""));
714        assert!(j.contains("\"gate_pass_count\":5"));
715        let back: Trace = serde_json::from_str(&j).unwrap();
716        assert_eq!(back.probe, t.probe);
717    }
718
719    /// Hash chain still verifies when `probe` is present — field participates in the hash.
720    #[test]
721    fn verify_chain_passes_with_probe_field_present() {
722        let mut t0 = sample_trace(GENESIS_HASH, 10);
723        t0.probe = Some(ProbeSignal {
724            k: 3,
725            gate_pass_count: 0,
726            regime: ProbeRegime::ConfidentFail,
727            probe_cost_usd: 0.0001,
728        });
729        let t1 = sample_trace(&t0.hash().unwrap(), 11);
730        let chain = [t0, t1];
731        assert!(
732            verify_chain(&chain, GENESIS_HASH).is_ok(),
733            "chain must verify when probe is present"
734        );
735    }
736
737    /// Tampering the probe field is detectable via the hash chain.
738    #[test]
739    fn tampering_probe_field_is_detectable() {
740        let mut t0 = sample_trace(GENESIS_HASH, 20);
741        t0.probe = Some(ProbeSignal {
742            k: 5,
743            gate_pass_count: 5,
744            regime: ProbeRegime::ConfidentPass,
745            probe_cost_usd: 0.0005,
746        });
747        let t1 = sample_trace(&t0.hash().unwrap(), 21);
748        let mut chain = [t0, t1];
749        // Tamper the probe field.
750        chain[0].probe.as_mut().unwrap().gate_pass_count = 0;
751        assert!(
752            verify_chain(&chain, GENESIS_HASH).is_err(),
753            "tampered probe must break the chain"
754        );
755    }
756}