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 /// Shadow prediction of `P(gate-pass)` for the start rung (ADR 0008 Phase 2), from the
185 /// per-query predictor. Absent when the predictor is off (the default) — byte-identical to
186 /// pre-predictor traces and hash-chain compatible. Recorded but never acted on in this phase.
187 #[serde(default, skip_serializing_if = "Option::is_none")]
188 pub predicted_pass: Option<f64>,
189 /// Elastic verification decision (ADR 0008 Phase 3) on the served rung: why the expensive gates
190 /// were skipped or run, plus the λ / calibration provenance the skip was authorized under.
191 /// Absent when elastic is off (the default) — byte-identical to pre-elastic traces and
192 /// hash-chain compatible (the `skip_serializing_if` keeps absent = absent).
193 #[serde(default, skip_serializing_if = "Option::is_none")]
194 pub elastic: Option<ElasticDecision>,
195}
196
197/// Reference to the policy that produced a decision.
198#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
199pub struct PolicyRef {
200 /// Policy identity/version, e.g. `"static@v0"` or `"bandit@v3"`.
201 pub id: String,
202 /// Whether this decision was a deliberate exploration draw (bounded, §, only in enforce).
203 #[serde(default)]
204 pub explore: bool,
205 /// The probability the logging policy assigned to the start rung it chose — the
206 /// Horvitz-Thompson denominator for IPS / SNIPS off-policy evaluation.
207 ///
208 /// `None` for deterministic (non-exploring) policies. `skip_serializing_if` keeps old
209 /// trace bytes byte-identical when `None`, preserving hash-chain compatibility with
210 /// existing logs. Only populated when `[escalation.exploration]` is configured.
211 #[serde(default, skip_serializing_if = "Option::is_none")]
212 pub propensity: Option<f64>,
213 /// Resolved routing-mode profile when it was explicitly set (header / route / global env).
214 /// `None` means `Balanced` was in effect (the default, no override active). Absent from
215 /// the JSON when `None` → byte-identical serialization for all existing traces.
216 #[serde(default, skip_serializing_if = "Option::is_none")]
217 pub mode_profile: Option<String>,
218}
219
220/// The routed request, described without its raw content.
221#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
222pub struct RequestInfo {
223 /// Wire API the caller used, e.g. `"anthropic.messages"` / `"openai.chat"`.
224 pub api: String,
225 /// Salted hash of the prompt — never the prompt text itself.
226 pub prompt_hash: String,
227 /// The versioned feature vector routing keyed on.
228 pub features: Features,
229}
230
231/// One attempt at a rung: the model call plus the gates run against its output.
232#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
233pub struct Attempt {
234 /// Ladder rung (0 = cheapest).
235 pub rung: u32,
236 /// Model called, `provider/model`.
237 pub model: String,
238 /// Provider segment (denormalized for cheap querying).
239 pub provider: String,
240 /// Input tokens consumed.
241 pub in_tokens: u64,
242 /// Output tokens produced.
243 pub out_tokens: u64,
244 /// USD cost of this model call (excludes gate cost).
245 pub cost_usd: f64,
246 /// Wall-clock latency of the model call.
247 pub latency_ms: u64,
248 /// Gate verdicts for this attempt's output.
249 pub gates: Vec<GateResult>,
250 /// The attempt's overall verdict (the aggregate that drove escalate-or-serve).
251 pub verdict: Verdict,
252}
253
254/// A verdict that arrived after the response was served (deferred gate or downstream feedback).
255#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
256pub struct DeferredVerdict {
257 /// Gate/source identity, e.g. `"tests"` or `"feedback:ci"`.
258 pub gate_id: String,
259 /// The late verdict.
260 pub verdict: Verdict,
261 /// Optional score.
262 #[serde(default, skip_serializing_if = "Option::is_none")]
263 pub score: Option<Score>,
264 /// When it arrived.
265 pub reported_at: Timestamp,
266 /// Who reported it (a deferred gate, or a feedback-API caller identity).
267 pub reporter: String,
268}
269
270/// Where the served response came from.
271#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
272#[serde(rename_all = "snake_case")]
273pub enum ServedFrom {
274 /// A passing attempt (the normal path).
275 Attempt,
276 /// The best attempt seen, served because budget/ladder was exhausted without a pass.
277 BestAttempt,
278 /// No output served; a structured error was returned.
279 Error,
280}
281
282/// The final outcome and economics of a decision.
283#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
284pub struct FinalOutcome {
285 /// Rung whose output was served (`None` if `served_from = error`).
286 #[serde(default, skip_serializing_if = "Option::is_none")]
287 pub served_rung: Option<u32>,
288 /// Provenance of the served response.
289 pub served_from: ServedFrom,
290 /// Total USD spent (all model calls + all gates).
291 pub total_cost_usd: f64,
292 /// USD portion spent on gates alone.
293 pub gate_cost_usd: f64,
294 /// Total wall-clock latency the caller experienced.
295 pub total_latency_ms: u64,
296 /// Number of rung escalations taken.
297 pub escalations: u32,
298 /// What always calling the top rung would have cost (§9.1 counterfactual).
299 pub counterfactual_baseline_usd: f64,
300 /// `counterfactual_baseline_usd - total_cost_usd` — the savings this decision proves.
301 pub savings_usd: f64,
302}
303
304impl Chained for Trace {
305 fn prev_hash(&self) -> &str {
306 &self.prev_hash
307 }
308}
309
310impl Trace {
311 /// This record's own hash (SHA-256 over its canonical JSON) — the value the *next*
312 /// record stores as its `prev_hash`.
313 ///
314 /// # Errors
315 /// Returns [`crate::Error::Json`] if the trace cannot be serialized.
316 pub fn hash(&self) -> Result<String> {
317 record_hash(self)
318 }
319
320 /// Compute `savings_usd = baseline - total` and store it, keeping the field consistent
321 /// with the two it is derived from. Returns the savings.
322 pub fn recompute_savings(&mut self) -> f64 {
323 let s = self.final_.counterfactual_baseline_usd - self.final_.total_cost_usd;
324 self.final_.savings_usd = s;
325 s
326 }
327}
328
329impl std::fmt::Display for Trace {
330 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
331 write!(
332 f,
333 "trace {} rung {:?} served_from {:?} cost ${:.4} saved ${:.4}",
334 self.trace_id,
335 self.final_.served_rung,
336 self.final_.served_from,
337 self.final_.total_cost_usd,
338 self.final_.savings_usd,
339 )
340 }
341}
342
343#[cfg(test)]
344mod tests {
345 use super::*;
346 use crate::features::{Features, TaskKind};
347 use crate::hashchain::{GENESIS_HASH, verify_chain};
348 use crate::verdict::Verdict;
349
350 fn sample_trace(prev_hash: &str, id: u128) -> Trace {
351 let mut t = Trace {
352 trace_id: Uuid::from_u128(id),
353 prev_hash: prev_hash.to_owned(),
354 tenant_id: "acme".into(),
355 session_id: "agent-run-4417".into(),
356 ts: "2026-07-08T15:04:05Z".parse().unwrap(),
357 mode: Mode::Enforce,
358 policy: PolicyRef {
359 id: "static@v0".into(),
360 explore: false,
361 propensity: None,
362 mode_profile: None,
363 },
364 request: RequestInfo {
365 api: "anthropic.messages".into(),
366 prompt_hash: "deadbeef".into(),
367 features: Features::new(TaskKind::CodeEdit),
368 },
369 attempts: vec![
370 Attempt {
371 rung: 0,
372 model: "anthropic/claude-haiku-4-5".into(),
373 provider: "anthropic".into(),
374 in_tokens: 2000,
375 out_tokens: 700,
376 cost_usd: 0.0007,
377 latency_ms: 900,
378 gates: vec![GateResult::deterministic("cargo-test", Verdict::Fail, 3100)],
379 verdict: Verdict::Fail,
380 },
381 Attempt {
382 rung: 1,
383 model: "anthropic/claude-sonnet-5".into(),
384 provider: "anthropic".into(),
385 in_tokens: 2000,
386 out_tokens: 800,
387 cost_usd: 0.0121,
388 latency_ms: 1200,
389 gates: vec![GateResult::deterministic("cargo-test", Verdict::Pass, 2950)],
390 verdict: Verdict::Pass,
391 },
392 ],
393 deferred: vec![],
394 final_: FinalOutcome {
395 served_rung: Some(1),
396 served_from: ServedFrom::Attempt,
397 total_cost_usd: 0.0128,
398 gate_cost_usd: 0.0,
399 total_latency_ms: 2100,
400 escalations: 1,
401 counterfactual_baseline_usd: 0.0630,
402 savings_usd: 0.0,
403 },
404 probe: None,
405 rollout: None,
406 shadow: None,
407 predicted_pass: None,
408 elastic: None,
409 };
410 t.recompute_savings();
411 t
412 }
413
414 #[test]
415 fn wire_field_names_are_the_contract() {
416 let t = sample_trace(GENESIS_HASH, 1);
417 let j = serde_json::to_string(&t).unwrap();
418 assert!(j.contains("\"prev_hash\":"));
419 assert!(
420 j.contains("\"final\":"),
421 "the outcome key must serialize as `final`"
422 );
423 assert!(j.contains("\"served_from\":\"attempt\""));
424 assert!(j.contains("\"verdict\":\"fail\""));
425 assert!(j.contains("\"verdict\":\"pass\""));
426 assert!(j.contains("\"counterfactual_baseline_usd\":"));
427 }
428
429 #[test]
430 fn savings_is_baseline_minus_total() {
431 let t = sample_trace(GENESIS_HASH, 1);
432 assert!((t.final_.savings_usd - (0.0630 - 0.0128)).abs() < 1e-12);
433 }
434
435 #[test]
436 fn traces_chain_and_verify() {
437 let t0 = sample_trace(GENESIS_HASH, 1);
438 let t1 = sample_trace(&t0.hash().unwrap(), 2);
439 let chain = [t0, t1];
440 assert!(verify_chain(&chain, GENESIS_HASH).is_ok());
441 }
442
443 #[test]
444 fn tampering_a_served_trace_is_detectable() {
445 let t0 = sample_trace(GENESIS_HASH, 1);
446 let t1 = sample_trace(&t0.hash().unwrap(), 2);
447 let mut chain = [t0, t1];
448 chain[0].final_.total_cost_usd = 0.0; // forge a cheaper decision after the fact
449 assert!(verify_chain(&chain, GENESIS_HASH).is_err());
450 }
451
452 #[test]
453 fn roundtrips_through_json() {
454 let t = sample_trace(GENESIS_HASH, 7);
455 let j = serde_json::to_string(&t).unwrap();
456 let back: Trace = serde_json::from_str(&j).unwrap();
457 assert_eq!(t, back);
458 }
459
460 // ── propensity backward-compat ────────────────────────────────────────────
461
462 /// Traces where propensity is None must serialize byte-identically to pre-field traces:
463 /// the field must be absent from the JSON, not serialized as `null`.
464 #[test]
465 fn propensity_none_absent_from_json() {
466 let pr = PolicyRef {
467 id: "static@v0".into(),
468 explore: false,
469 propensity: None,
470 mode_profile: None,
471 };
472 let j = serde_json::to_string(&pr).unwrap();
473 assert!(
474 !j.contains("propensity"),
475 "propensity=None must be omitted (skip_serializing_if): {j}"
476 );
477 }
478
479 /// Old JSON without a `propensity` field must deserialize to `propensity: None`
480 /// (via `#[serde(default)]`), keeping old traces readable without schema migration.
481 #[test]
482 fn old_trace_without_propensity_deserializes_to_none() {
483 let old_json = r#"{"id":"static@v0","explore":false}"#;
484 let pr: PolicyRef = serde_json::from_str(old_json).unwrap();
485 assert_eq!(pr.propensity, None);
486 }
487
488 /// New JSON with a propensity value round-trips correctly.
489 #[test]
490 fn propensity_some_roundtrips() {
491 let pr = PolicyRef {
492 id: "bandit@v1+eps".into(),
493 explore: true,
494 propensity: Some(0.3),
495 mode_profile: None,
496 };
497 let j = serde_json::to_string(&pr).unwrap();
498 assert!(
499 j.contains("\"propensity\":0.3"),
500 "expected propensity in: {j}"
501 );
502 let back: PolicyRef = serde_json::from_str(&j).unwrap();
503 assert_eq!(back, pr);
504 }
505
506 // ── mode_profile backward-compat ─────────────────────────────────────────
507
508 /// `mode_profile = None` must not appear in the serialized JSON — byte-identical for
509 /// existing traces (Balanced is the default and must be invisible).
510 #[test]
511 fn mode_profile_none_absent_from_json() {
512 let pr = PolicyRef {
513 id: "static@v0".into(),
514 explore: false,
515 propensity: None,
516 mode_profile: None,
517 };
518 let j = serde_json::to_string(&pr).unwrap();
519 assert!(
520 !j.contains("mode_profile"),
521 "mode_profile=None must be omitted (skip_serializing_if): {j}"
522 );
523 }
524
525 /// Old JSON without a `mode_profile` field deserializes to `mode_profile: None`.
526 #[test]
527 fn old_trace_without_mode_profile_deserializes_to_none() {
528 let old_json = r#"{"id":"static@v0","explore":false}"#;
529 let pr: PolicyRef = serde_json::from_str(old_json).unwrap();
530 assert_eq!(pr.mode_profile, None);
531 }
532
533 /// `mode_profile = Some(...)` round-trips correctly.
534 #[test]
535 fn mode_profile_some_roundtrips() {
536 let pr = PolicyRef {
537 id: "static@v0".into(),
538 explore: false,
539 propensity: None,
540 mode_profile: Some("quality".into()),
541 };
542 let j = serde_json::to_string(&pr).unwrap();
543 assert!(
544 j.contains("\"mode_profile\":\"quality\""),
545 "expected mode_profile in: {j}"
546 );
547 let back: PolicyRef = serde_json::from_str(&j).unwrap();
548 assert_eq!(back, pr);
549 }
550
551 // ── ProbeRegime::classify ─────────────────────────────────────────────────
552
553 #[test]
554 fn classify_zero_is_confident_fail() {
555 assert_eq!(ProbeRegime::classify(0, 5), ProbeRegime::ConfidentFail);
556 }
557
558 #[test]
559 fn classify_all_pass_is_confident_pass() {
560 assert_eq!(ProbeRegime::classify(5, 5), ProbeRegime::ConfidentPass);
561 }
562
563 #[test]
564 fn classify_above_k_is_confident_pass() {
565 // pass_count > k is technically impossible but the rule handles it gracefully.
566 assert_eq!(ProbeRegime::classify(6, 5), ProbeRegime::ConfidentPass);
567 }
568
569 #[test]
570 fn classify_mixed_is_ambiguous() {
571 assert_eq!(ProbeRegime::classify(1, 5), ProbeRegime::Ambiguous);
572 assert_eq!(ProbeRegime::classify(2, 5), ProbeRegime::Ambiguous);
573 assert_eq!(ProbeRegime::classify(4, 5), ProbeRegime::Ambiguous);
574 }
575
576 #[test]
577 fn classify_k_equals_2_boundaries() {
578 assert_eq!(ProbeRegime::classify(0, 2), ProbeRegime::ConfidentFail);
579 assert_eq!(ProbeRegime::classify(1, 2), ProbeRegime::Ambiguous);
580 assert_eq!(ProbeRegime::classify(2, 2), ProbeRegime::ConfidentPass);
581 }
582
583 // ── ProbeSignal serde backward-compat ────────────────────────────────────
584
585 /// `probe = None` must be absent from the JSON — byte-identical to pre-probe traces.
586 #[test]
587 fn probe_none_absent_from_json() {
588 let t = sample_trace(GENESIS_HASH, 1);
589 assert!(t.probe.is_none());
590 let j = serde_json::to_string(&t).unwrap();
591 assert!(
592 !j.contains("\"probe\""),
593 "probe=None must be omitted (skip_serializing_if): {j}"
594 );
595 }
596
597 /// Old JSON without a `probe` field deserializes cleanly (probe defaults to None).
598 #[test]
599 fn old_trace_without_probe_deserializes_to_none() {
600 // Use the canonical JSON of a probe-None trace as a stand-in for old traces.
601 let t = sample_trace(GENESIS_HASH, 1);
602 let j = serde_json::to_string(&t).unwrap();
603 assert!(!j.contains("probe"));
604 let back: Trace = serde_json::from_str(&j).unwrap();
605 assert_eq!(back.probe, None);
606 }
607
608 /// `probe = Some(...)` round-trips correctly.
609 #[test]
610 fn probe_signal_some_roundtrips() {
611 let mut t = sample_trace(GENESIS_HASH, 1);
612 t.probe = Some(ProbeSignal {
613 k: 5,
614 gate_pass_count: 5,
615 regime: ProbeRegime::ConfidentPass,
616 probe_cost_usd: 0.0003,
617 });
618 let j = serde_json::to_string(&t).unwrap();
619 assert!(j.contains("\"probe\""), "probe=Some must be present: {j}");
620 assert!(j.contains("\"regime\":\"confident_pass\""));
621 assert!(j.contains("\"gate_pass_count\":5"));
622 let back: Trace = serde_json::from_str(&j).unwrap();
623 assert_eq!(back.probe, t.probe);
624 }
625
626 /// Hash chain still verifies when `probe` is present — field participates in the hash.
627 #[test]
628 fn verify_chain_passes_with_probe_field_present() {
629 let mut t0 = sample_trace(GENESIS_HASH, 10);
630 t0.probe = Some(ProbeSignal {
631 k: 3,
632 gate_pass_count: 0,
633 regime: ProbeRegime::ConfidentFail,
634 probe_cost_usd: 0.0001,
635 });
636 let t1 = sample_trace(&t0.hash().unwrap(), 11);
637 let chain = [t0, t1];
638 assert!(
639 verify_chain(&chain, GENESIS_HASH).is_ok(),
640 "chain must verify when probe is present"
641 );
642 }
643
644 /// Tampering the probe field is detectable via the hash chain.
645 #[test]
646 fn tampering_probe_field_is_detectable() {
647 let mut t0 = sample_trace(GENESIS_HASH, 20);
648 t0.probe = Some(ProbeSignal {
649 k: 5,
650 gate_pass_count: 5,
651 regime: ProbeRegime::ConfidentPass,
652 probe_cost_usd: 0.0005,
653 });
654 let t1 = sample_trace(&t0.hash().unwrap(), 21);
655 let mut chain = [t0, t1];
656 // Tamper the probe field.
657 chain[0].probe.as_mut().unwrap().gate_pass_count = 0;
658 assert!(
659 verify_chain(&chain, GENESIS_HASH).is_err(),
660 "tampered probe must break the chain"
661 );
662 }
663}