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 Attempt {
286 /// Total prompt tokens this call actually consumed, cached or not.
287 ///
288 /// `in_tokens` alone is **not** the prompt size when the caller uses prompt caching: providers
289 /// report the cached portion in separate fields, and a 190k-token cached prefix shows up as an
290 /// `in_tokens` of about 20. Anything reporting prompt volume wants this, not the raw field.
291 #[must_use]
292 pub const fn billable_input(&self) -> u64 {
293 self.in_tokens
294 .saturating_add(self.cache_write_tokens)
295 .saturating_add(self.cache_read_tokens)
296 }
297}
298
299/// A verdict that arrived after the response was served (deferred gate or downstream feedback).
300#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
301pub struct DeferredVerdict {
302 /// Gate/source identity, e.g. `"tests"` or `"feedback:ci"`.
303 pub gate_id: String,
304 /// The late verdict.
305 pub verdict: Verdict,
306 /// Optional score.
307 #[serde(default, skip_serializing_if = "Option::is_none")]
308 pub score: Option<Score>,
309 /// When it arrived.
310 pub reported_at: Timestamp,
311 /// Who reported it (a deferred gate, or a feedback-API caller identity).
312 pub reporter: String,
313}
314
315/// Where the served response came from.
316#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
317#[serde(rename_all = "snake_case")]
318pub enum ServedFrom {
319 /// A passing attempt (the normal path).
320 Attempt,
321 /// The best attempt seen, served because budget/ladder was exhausted without a pass.
322 BestAttempt,
323 /// No output served; a structured error was returned.
324 Error,
325}
326
327/// The final outcome and economics of a decision.
328#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
329pub struct FinalOutcome {
330 /// Rung whose output was served (`None` if `served_from = error`).
331 #[serde(default, skip_serializing_if = "Option::is_none")]
332 pub served_rung: Option<u32>,
333 /// Provenance of the served response.
334 pub served_from: ServedFrom,
335 /// Total USD spent (all model calls + all gates).
336 pub total_cost_usd: f64,
337 /// USD portion spent on gates alone.
338 pub gate_cost_usd: f64,
339 /// Total wall-clock latency the caller experienced.
340 pub total_latency_ms: u64,
341 /// Number of rung escalations taken.
342 pub escalations: u32,
343 /// What always calling the top rung would have cost (§9.1 counterfactual).
344 pub counterfactual_baseline_usd: f64,
345 /// `counterfactual_baseline_usd - total_cost_usd` — the savings this decision proves.
346 pub savings_usd: f64,
347}
348
349impl Chained for Trace {
350 fn prev_hash(&self) -> &str {
351 &self.prev_hash
352 }
353}
354
355impl Trace {
356 /// This record's own hash (SHA-256 over its canonical JSON) — the value the *next*
357 /// record stores as its `prev_hash`.
358 ///
359 /// # Errors
360 /// Returns [`crate::Error::Json`] if the trace cannot be serialized.
361 pub fn hash(&self) -> Result<String> {
362 record_hash(self)
363 }
364
365 /// Compute `savings_usd = baseline - total` and store it, keeping the field consistent
366 /// with the two it is derived from. Returns the savings.
367 pub fn recompute_savings(&mut self) -> f64 {
368 let s = self.final_.counterfactual_baseline_usd - self.final_.total_cost_usd;
369 self.final_.savings_usd = s;
370 s
371 }
372}
373
374impl std::fmt::Display for Trace {
375 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
376 write!(
377 f,
378 "trace {} rung {:?} served_from {:?} cost ${:.4} saved ${:.4}",
379 self.trace_id,
380 self.final_.served_rung,
381 self.final_.served_from,
382 self.final_.total_cost_usd,
383 self.final_.savings_usd,
384 )
385 }
386}
387
388#[cfg(test)]
389mod tests {
390 use super::*;
391 use crate::features::{Features, TaskKind};
392 use crate::hashchain::{GENESIS_HASH, verify_chain};
393 use crate::verdict::Verdict;
394
395 fn sample_trace(prev_hash: &str, id: u128) -> Trace {
396 let mut t = Trace {
397 trace_id: Uuid::from_u128(id),
398 prev_hash: prev_hash.to_owned(),
399 tenant_id: "acme".into(),
400 session_id: "agent-run-4417".into(),
401 ts: "2026-07-08T15:04:05Z".parse().unwrap(),
402 mode: Mode::Enforce,
403 policy: PolicyRef {
404 id: "static@v0".into(),
405 explore: false,
406 propensity: None,
407 mode_profile: None,
408 },
409 request: RequestInfo {
410 api: "anthropic.messages".into(),
411 prompt_hash: "deadbeef".into(),
412 features: Features::new(TaskKind::CodeEdit),
413 },
414 attempts: vec![
415 Attempt {
416 rung: 0,
417 model: "anthropic/claude-haiku-4-5".into(),
418 provider: "anthropic".into(),
419 in_tokens: 2000,
420 cache_write_tokens: 0,
421 cache_read_tokens: 0,
422 out_tokens: 700,
423 cost_usd: 0.0007,
424 latency_ms: 900,
425 gates: vec![GateResult::deterministic("cargo-test", Verdict::Fail, 3100)],
426 verdict: Verdict::Fail,
427 },
428 Attempt {
429 rung: 1,
430 model: "anthropic/claude-sonnet-5".into(),
431 provider: "anthropic".into(),
432 in_tokens: 2000,
433 cache_write_tokens: 0,
434 cache_read_tokens: 0,
435 out_tokens: 800,
436 cost_usd: 0.0121,
437 latency_ms: 1200,
438 gates: vec![GateResult::deterministic("cargo-test", Verdict::Pass, 2950)],
439 verdict: Verdict::Pass,
440 },
441 ],
442 deferred: vec![],
443 final_: FinalOutcome {
444 served_rung: Some(1),
445 served_from: ServedFrom::Attempt,
446 total_cost_usd: 0.0128,
447 gate_cost_usd: 0.0,
448 total_latency_ms: 2100,
449 escalations: 1,
450 counterfactual_baseline_usd: 0.0630,
451 savings_usd: 0.0,
452 },
453 probe: None,
454 rollout: None,
455 shadow: None,
456 route_ix: None,
457 predicted_pass: None,
458 elastic: None,
459 };
460 t.recompute_savings();
461 t
462 }
463
464 #[test]
465 fn wire_field_names_are_the_contract() {
466 let t = sample_trace(GENESIS_HASH, 1);
467 let j = serde_json::to_string(&t).unwrap();
468 assert!(j.contains("\"prev_hash\":"));
469 assert!(
470 j.contains("\"final\":"),
471 "the outcome key must serialize as `final`"
472 );
473 assert!(j.contains("\"served_from\":\"attempt\""));
474 assert!(j.contains("\"verdict\":\"fail\""));
475 assert!(j.contains("\"verdict\":\"pass\""));
476 assert!(j.contains("\"counterfactual_baseline_usd\":"));
477 }
478
479 #[test]
480 fn savings_is_baseline_minus_total() {
481 let t = sample_trace(GENESIS_HASH, 1);
482 assert!((t.final_.savings_usd - (0.0630 - 0.0128)).abs() < 1e-12);
483 }
484
485 #[test]
486 fn traces_chain_and_verify() {
487 let t0 = sample_trace(GENESIS_HASH, 1);
488 let t1 = sample_trace(&t0.hash().unwrap(), 2);
489 let chain = [t0, t1];
490 assert!(verify_chain(&chain, GENESIS_HASH).is_ok());
491 }
492
493 #[test]
494 fn tampering_a_served_trace_is_detectable() {
495 let t0 = sample_trace(GENESIS_HASH, 1);
496 let t1 = sample_trace(&t0.hash().unwrap(), 2);
497 let mut chain = [t0, t1];
498 chain[0].final_.total_cost_usd = 0.0; // forge a cheaper decision after the fact
499 assert!(verify_chain(&chain, GENESIS_HASH).is_err());
500 }
501
502 #[test]
503 fn roundtrips_through_json() {
504 let t = sample_trace(GENESIS_HASH, 7);
505 let j = serde_json::to_string(&t).unwrap();
506 let back: Trace = serde_json::from_str(&j).unwrap();
507 assert_eq!(t, back);
508 }
509
510 // ── propensity backward-compat ────────────────────────────────────────────
511
512 /// Traces where propensity is None must serialize byte-identically to pre-field traces:
513 /// the field must be absent from the JSON, not serialized as `null`.
514 #[test]
515 fn propensity_none_absent_from_json() {
516 let pr = PolicyRef {
517 id: "static@v0".into(),
518 explore: false,
519 propensity: None,
520 mode_profile: None,
521 };
522 let j = serde_json::to_string(&pr).unwrap();
523 assert!(
524 !j.contains("propensity"),
525 "propensity=None must be omitted (skip_serializing_if): {j}"
526 );
527 }
528
529 /// Old JSON without a `propensity` field must deserialize to `propensity: None`
530 /// (via `#[serde(default)]`), keeping old traces readable without schema migration.
531 #[test]
532 fn old_trace_without_propensity_deserializes_to_none() {
533 let old_json = r#"{"id":"static@v0","explore":false}"#;
534 let pr: PolicyRef = serde_json::from_str(old_json).unwrap();
535 assert_eq!(pr.propensity, None);
536 }
537
538 /// New JSON with a propensity value round-trips correctly.
539 #[test]
540 fn propensity_some_roundtrips() {
541 let pr = PolicyRef {
542 id: "bandit@v1+eps".into(),
543 explore: true,
544 propensity: Some(0.3),
545 mode_profile: None,
546 };
547 let j = serde_json::to_string(&pr).unwrap();
548 assert!(
549 j.contains("\"propensity\":0.3"),
550 "expected propensity in: {j}"
551 );
552 let back: PolicyRef = serde_json::from_str(&j).unwrap();
553 assert_eq!(back, pr);
554 }
555
556 // ── mode_profile backward-compat ─────────────────────────────────────────
557
558 /// `mode_profile = None` must not appear in the serialized JSON — byte-identical for
559 /// existing traces (Balanced is the default and must be invisible).
560 #[test]
561 fn mode_profile_none_absent_from_json() {
562 let pr = PolicyRef {
563 id: "static@v0".into(),
564 explore: false,
565 propensity: None,
566 mode_profile: None,
567 };
568 let j = serde_json::to_string(&pr).unwrap();
569 assert!(
570 !j.contains("mode_profile"),
571 "mode_profile=None must be omitted (skip_serializing_if): {j}"
572 );
573 }
574
575 /// Old JSON without a `mode_profile` field deserializes to `mode_profile: None`.
576 #[test]
577 fn old_trace_without_mode_profile_deserializes_to_none() {
578 let old_json = r#"{"id":"static@v0","explore":false}"#;
579 let pr: PolicyRef = serde_json::from_str(old_json).unwrap();
580 assert_eq!(pr.mode_profile, None);
581 }
582
583 /// `mode_profile = Some(...)` round-trips correctly.
584 #[test]
585 fn mode_profile_some_roundtrips() {
586 let pr = PolicyRef {
587 id: "static@v0".into(),
588 explore: false,
589 propensity: None,
590 mode_profile: Some("quality".into()),
591 };
592 let j = serde_json::to_string(&pr).unwrap();
593 assert!(
594 j.contains("\"mode_profile\":\"quality\""),
595 "expected mode_profile in: {j}"
596 );
597 let back: PolicyRef = serde_json::from_str(&j).unwrap();
598 assert_eq!(back, pr);
599 }
600
601 // ── ProbeRegime::classify ─────────────────────────────────────────────────
602
603 #[test]
604 fn classify_zero_is_confident_fail() {
605 assert_eq!(ProbeRegime::classify(0, 5), ProbeRegime::ConfidentFail);
606 }
607
608 #[test]
609 fn classify_all_pass_is_confident_pass() {
610 assert_eq!(ProbeRegime::classify(5, 5), ProbeRegime::ConfidentPass);
611 }
612
613 #[test]
614 fn classify_above_k_is_confident_pass() {
615 // pass_count > k is technically impossible but the rule handles it gracefully.
616 assert_eq!(ProbeRegime::classify(6, 5), ProbeRegime::ConfidentPass);
617 }
618
619 #[test]
620 fn classify_mixed_is_ambiguous() {
621 assert_eq!(ProbeRegime::classify(1, 5), ProbeRegime::Ambiguous);
622 assert_eq!(ProbeRegime::classify(2, 5), ProbeRegime::Ambiguous);
623 assert_eq!(ProbeRegime::classify(4, 5), ProbeRegime::Ambiguous);
624 }
625
626 #[test]
627 fn classify_k_equals_2_boundaries() {
628 assert_eq!(ProbeRegime::classify(0, 2), ProbeRegime::ConfidentFail);
629 assert_eq!(ProbeRegime::classify(1, 2), ProbeRegime::Ambiguous);
630 assert_eq!(ProbeRegime::classify(2, 2), ProbeRegime::ConfidentPass);
631 }
632
633 // ── ProbeSignal serde backward-compat ────────────────────────────────────
634
635 /// `probe = None` must be absent from the JSON — byte-identical to pre-probe traces.
636 #[test]
637 fn probe_none_absent_from_json() {
638 let t = sample_trace(GENESIS_HASH, 1);
639 assert!(t.probe.is_none());
640 let j = serde_json::to_string(&t).unwrap();
641 assert!(
642 !j.contains("\"probe\""),
643 "probe=None must be omitted (skip_serializing_if): {j}"
644 );
645 }
646
647 /// Old JSON without a `probe` field deserializes cleanly (probe defaults to None).
648 #[test]
649 fn old_trace_without_probe_deserializes_to_none() {
650 // Use the canonical JSON of a probe-None trace as a stand-in for old traces.
651 let t = sample_trace(GENESIS_HASH, 1);
652 let j = serde_json::to_string(&t).unwrap();
653 assert!(!j.contains("probe"));
654 let back: Trace = serde_json::from_str(&j).unwrap();
655 assert_eq!(back.probe, None);
656 }
657
658 /// `probe = Some(...)` round-trips correctly.
659 #[test]
660 fn probe_signal_some_roundtrips() {
661 let mut t = sample_trace(GENESIS_HASH, 1);
662 t.probe = Some(ProbeSignal {
663 k: 5,
664 gate_pass_count: 5,
665 regime: ProbeRegime::ConfidentPass,
666 probe_cost_usd: 0.0003,
667 });
668 let j = serde_json::to_string(&t).unwrap();
669 assert!(j.contains("\"probe\""), "probe=Some must be present: {j}");
670 assert!(j.contains("\"regime\":\"confident_pass\""));
671 assert!(j.contains("\"gate_pass_count\":5"));
672 let back: Trace = serde_json::from_str(&j).unwrap();
673 assert_eq!(back.probe, t.probe);
674 }
675
676 /// Hash chain still verifies when `probe` is present — field participates in the hash.
677 #[test]
678 fn verify_chain_passes_with_probe_field_present() {
679 let mut t0 = sample_trace(GENESIS_HASH, 10);
680 t0.probe = Some(ProbeSignal {
681 k: 3,
682 gate_pass_count: 0,
683 regime: ProbeRegime::ConfidentFail,
684 probe_cost_usd: 0.0001,
685 });
686 let t1 = sample_trace(&t0.hash().unwrap(), 11);
687 let chain = [t0, t1];
688 assert!(
689 verify_chain(&chain, GENESIS_HASH).is_ok(),
690 "chain must verify when probe is present"
691 );
692 }
693
694 /// Tampering the probe field is detectable via the hash chain.
695 #[test]
696 fn tampering_probe_field_is_detectable() {
697 let mut t0 = sample_trace(GENESIS_HASH, 20);
698 t0.probe = Some(ProbeSignal {
699 k: 5,
700 gate_pass_count: 5,
701 regime: ProbeRegime::ConfidentPass,
702 probe_cost_usd: 0.0005,
703 });
704 let t1 = sample_trace(&t0.hash().unwrap(), 21);
705 let mut chain = [t0, t1];
706 // Tamper the probe field.
707 chain[0].probe.as_mut().unwrap().gate_pass_count = 0;
708 assert!(
709 verify_chain(&chain, GENESIS_HASH).is_err(),
710 "tampered probe must break the chain"
711 );
712 }
713}