interplane.Get Omega
Read in your language

spark-rsi-mv

Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger

Brought by drakestapleton

branch main Branches Tags History

spark-rsi-mv / src / canary_observation.rs

167 lines · 5458 bytes Raw Blame History
1//! Production canary evidence.
2//!
3//! A qualifying observation is a measured result. A synthetic rehearsal can use
4//! the same shape and cannot increment the production quota. The same
5//! observation id with the same canonical record is an idempotent success.
6//! The same id with a different record is a conflict.
7
8use sha2::{Digest, Sha256};
9use std::collections::BTreeMap;
10
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum ObservationProvenance {
13 Measured,
14 Synthetic,
15}
16
17#[derive(Clone, Debug, PartialEq, Eq)]
18pub struct CanaryObservation {
19 pub observation_id: String,
20 pub observed_at_ms: u64,
21 pub candidate_digest: String,
22 pub latency_us: u64,
23 pub status: String,
24 pub provenance: ObservationProvenance,
25}
26
27#[derive(Clone, Debug, PartialEq, Eq)]
28pub struct QuotaDecision {
29 pub counted: u64,
30}
31
32impl CanaryObservation {
33 /// One JSON object, keys in alphabetical order, no insignificant whitespace.
34 pub fn canonical_bytes(&self) -> Vec<u8> {
35 let provenance = match self.provenance {
36 ObservationProvenance::Measured => "measured",
37 ObservationProvenance::Synthetic => "synthetic",
38 };
39 format!(
40 "{{\"candidate_digest\":\"{}\",\"latency_us\":{},\"observation_id\":\"{}\",\"observed_at_ms\":{},\"provenance\":\"{}\",\"status\":\"{}\"}}",
41 json_string(&self.candidate_digest),
42 self.latency_us,
43 json_string(&self.observation_id),
44 self.observed_at_ms,
45 provenance,
46 json_string(&self.status),
47 )
48 .into_bytes()
49 }
50
51 pub fn digest_hex(&self) -> String {
52 hex::encode(Sha256::digest(self.canonical_bytes()))
53 }
54}
55
56pub fn admit_production_quota(
57 observations: &[CanaryObservation],
58 candidate_digest: &str,
59 target: u64,
60) -> Result<QuotaDecision, String> {
61 if target == 0 {
62 return Err("production canary quota target must be at least 1".to_string());
63 }
64 let mut seen: BTreeMap<String, String> = BTreeMap::new();
65 let mut counted = 0u64;
66 for obs in observations {
67 if obs.observation_id.trim().is_empty() {
68 return Err("observation id is required".to_string());
69 }
70 if obs.status.trim().is_empty() {
71 return Err("execution status is required".to_string());
72 }
73 if obs.candidate_digest != candidate_digest {
74 return Err("observation candidate digest does not match the candidate".to_string());
75 }
76 if obs.provenance != ObservationProvenance::Measured {
77 return Err(
78 "synthetic rehearsal cannot satisfy the production canary quota".to_string(),
79 );
80 }
81 let digest = obs.digest_hex();
82 if let Some(previous) = seen.get(&obs.observation_id) {
83 if previous != &digest {
84 return Err(format!(
85 "observation id {} conflicts with a different record",
86 obs.observation_id
87 ));
88 }
89 continue;
90 }
91 seen.insert(obs.observation_id.clone(), digest);
92 counted += 1;
93 }
94 if counted < target {
95 return Err(format!(
96 "production canary quota requires {} measured observations, received {}",
97 target, counted
98 ));
99 }
100 Ok(QuotaDecision { counted })
101}
102
103fn json_string(value: &str) -> String {
104 let mut out = String::with_capacity(value.len());
105 for c in value.chars() {
106 match c {
107 '\\' => out.push_str("\\\\"),
108 '"' => out.push_str("\\\""),
109 c if c.is_control() => out.push_str(&format!("\\u{:04x}", c as u32)),
110 c => out.push(c),
111 }
112 }
113 out
114}
115
116#[cfg(test)]
117mod tests {
118 use super::*;
119
120 fn measured(id: &str, latency: u64, status: &str) -> CanaryObservation {
121 CanaryObservation {
122 observation_id: id.to_string(),
123 observed_at_ms: 1_700_000_000_000,
124 candidate_digest: "abc".to_string(),
125 latency_us: latency,
126 status: status.to_string(),
127 provenance: ObservationProvenance::Measured,
128 }
129 }
130
131 #[test]
132 fn empty_quota_fails_closed() {
133 let err = admit_production_quota(&[], "abc", 3).unwrap_err();
134 assert!(err.contains("received 0"));
135 }
136
137 #[test]
138 fn synthetic_rehearsal_cannot_fill_the_quota() {
139 let mut obs = measured("obs-1", 1500, "ok");
140 obs.provenance = ObservationProvenance::Synthetic;
141 let err = admit_production_quota(&[obs], "abc", 1).unwrap_err();
142 assert!(err.contains("synthetic rehearsal"));
143 }
144
145 #[test]
146 fn identical_retry_counts_once_and_changed_payload_conflicts() {
147 let first = measured("obs-1", 1800, "ok");
148 let retry = first.clone();
149 let decision = admit_production_quota(&[first.clone(), retry], "abc", 1).unwrap();
150 assert_eq!(decision.counted, 1);
151
152 let mut changed = first.clone();
153 changed.latency_us = 9999;
154 let err = admit_production_quota(&[first, changed], "abc", 1).unwrap_err();
155 assert!(err.contains("conflicts"));
156 }
157
158 #[test]
159 fn canonical_digest_covers_the_whole_record() {
160 let mut other = measured("obs-1", 1800, "ok");
161 other.status = "error".to_string();
162 assert_ne!(
163 measured("obs-1", 1800, "ok").digest_hex(),
164 other.digest_hex()
165 );
166 }
167}