Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/spark-rsi-mv/blob/main/src/canary/observation.rs # spark-rsi-mv Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `spark-rsi-mv / src / canary / observation.rs` 282 lines ยท 11148 bytes Raw Blame History 1 //! Version 2 canary observation: the supervisor's verified record of one issued request and 2 //! its checked outcome. Version 1 (`crate::canary_observation`) is history and stays as it is. 3 //! 4 //! Everything in the record comes from the supervisor: it issued the request, measured the 5 //! elapsed time on its own clock, hashed the bytes it received and compared them with the 6 //! pinned workload. Nothing the worker says about itself is in here. 7 8 use super::{canonical_json, domain_digest, is_hex_digest, sha256_hex, OBSERVATION_RECORD_VERSION}; 9 use serde::{Deserialize, Serialize}; 10 11 pub const OBSERVATION_DOMAIN: &str = "spark-rsi/canary-observation/v2"; 12 pub const OBSERVATION_ID_DOMAIN: &str = "spark-rsi/canary-observation-id/v2"; 13 14 /// What the supervisor established about one issued request. 15 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] 16 #[serde(rename_all = "snake_case")] 17 pub enum VerifiedStatus { 18 /// A well-formed result for this request arrived within the deadline and its bytes equal 19 /// the pinned expected output. 20 VerifiedSuccess, 21 /// A well-formed result arrived within the deadline but did not equal the expected output. 22 WrongResult, 23 /// No well-formed result arrived before the deadline. 24 Timeout, 25 /// A frame arrived for this request but was not a valid versioned result for this 26 /// generation (wrong protocol version, wrong generation, undecodable). 27 InvalidResponse, 28 /// The authenticated connection closed before a result arrived. 29 ConnectionClosed, 30 } 31 32 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] 33 #[serde(rename_all = "snake_case")] 34 pub enum Provenance { 35 /// Produced by the supervisor from a request it issued over an authenticated connection. 36 Measured, 37 /// A rehearsal in the same shape. Never counts. 38 Synthetic, 39 } 40 41 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] 42 #[serde(deny_unknown_fields)] 43 pub struct CanaryObservationV2 { 44 pub record_version: u16, 45 /// Domain-separated hash of (generation id, request id, request digest). Duplicates and 46 /// replays collide by construction. 47 pub observation_id: String, 48 pub generation_id: String, 49 pub request_id: String, 50 pub request_digest: String, 51 pub workload_digest: String, 52 pub candidate_executable_digest: String, 53 /// SHA-256 of the exact result bytes received, or absent when no result arrived. 54 pub result_digest: Option, 55 /// Supervisor-measured time from sending the request to reading the complete result frame. 56 pub elapsed_us: u64, 57 /// Supervisor clock when the observation was recorded, milliseconds since the Unix epoch. 58 pub observed_at_ms: u64, 59 pub status: VerifiedStatus, 60 pub provenance: Provenance, 61 } 62 63 /// Observation identity: domain-separated hash of the issued request's coordinates. 64 pub fn observation_id(generation_id: &str, request_id: &str, request_digest: &str) -> String { 65 domain_digest( 66 OBSERVATION_ID_DOMAIN, 67 &[ 68 generation_id.as_bytes(), 69 request_id.as_bytes(), 70 request_digest.as_bytes(), 71 ], 72 ) 73 } 74 75 /// SHA-256 of the exact result bytes received. 76 pub fn result_digest(output: &[u8]) -> String { 77 sha256_hex(output) 78 } 79 80 /// Everything the supervisor binds into one observation, before the id is derived. 81 #[derive(Debug, Clone, PartialEq, Eq)] 82 pub struct ObservationInput<'a> { 83 pub generation_id: &'a str, 84 pub request_id: &'a str, 85 pub request_digest: &'a str, 86 pub workload_digest: &'a str, 87 pub candidate_executable_digest: &'a str, 88 pub result_digest: Option<&'a str>, 89 pub elapsed_us: u64, 90 pub observed_at_ms: u64, 91 pub status: VerifiedStatus, 92 pub provenance: Provenance, 93 } 94 95 impl CanaryObservationV2 { 96 /// Builds the record and derives its id. 97 pub fn new(input: ObservationInput<'_>) -> Self { 98 Self { 99 record_version: OBSERVATION_RECORD_VERSION, 100 observation_id: observation_id( 101 input.generation_id, 102 input.request_id, 103 input.request_digest, 104 ), 105 generation_id: input.generation_id.to_string(), 106 request_id: input.request_id.to_string(), 107 request_digest: input.request_digest.to_string(), 108 workload_digest: input.workload_digest.to_string(), 109 candidate_executable_digest: input.candidate_executable_digest.to_string(), 110 result_digest: input.result_digest.map(str::to_string), 111 elapsed_us: input.elapsed_us, 112 observed_at_ms: input.observed_at_ms, 113 status: input.status, 114 provenance: input.provenance, 115 } 116 } 117 118 pub fn canonical_bytes(&self) -> Vec { 119 canonical_json(self) 120 } 121 122 /// Domain-separated SHA-256 of the canonical bytes. Covers every field. 123 pub fn digest_hex(&self) -> String { 124 domain_digest(OBSERVATION_DOMAIN, &[&self.canonical_bytes()]) 125 } 126 127 /// Structural validity: version, non-empty ids, well-formed digests, id derivation, and a 128 /// result digest present exactly when a result was received. 129 pub fn validate(&self) -> Result<(), String> { 130 if self.record_version != OBSERVATION_RECORD_VERSION { 131 return Err(format!( 132 "observation record version {} is not supported (expected {})", 133 self.record_version, OBSERVATION_RECORD_VERSION 134 )); 135 } 136 if self.generation_id.trim().is_empty() { 137 return Err("observation generation id is required".to_string()); 138 } 139 if self.request_id.trim().is_empty() { 140 return Err("observation request id is required".to_string()); 141 } 142 for (name, value) in [ 143 ("request_digest", &self.request_digest), 144 ("workload_digest", &self.workload_digest), 145 ( 146 "candidate_executable_digest", 147 &self.candidate_executable_digest, 148 ), 149 ] { 150 if !is_hex_digest(value) { 151 return Err(format!("observation {} is not a hex SHA-256", name)); 152 } 153 } 154 match (&self.result_digest, self.status) { 155 (Some(d), _) if !is_hex_digest(d) => { 156 return Err("observation result_digest is not a hex SHA-256".to_string()); 157 } 158 (None, VerifiedStatus::VerifiedSuccess) | (None, VerifiedStatus::WrongResult) => { 159 return Err(format!( 160 "observation status {:?} requires a result digest", 161 self.status 162 )); 163 } 164 _ => {} 165 } 166 let expected = observation_id(&self.generation_id, &self.request_id, &self.request_digest); 167 if self.observation_id != expected { 168 return Err(format!( 169 "observation id {} does not derive from its generation, request and request digest", 170 self.observation_id 171 )); 172 } 173 Ok(()) 174 } 175 176 /// Counts toward the quota only when measured and verified as a success. The quota 177 /// validator applies the remaining checks (workload membership, expected result, identity). 178 pub fn is_qualifying(&self) -> bool { 179 self.provenance == Provenance::Measured 180 && self.status == VerifiedStatus::VerifiedSuccess 181 && self.result_digest.is_some() 182 } 183 } 184 185 #[cfg(test)] 186 mod tests { 187 use super::*; 188 189 pub(crate) fn sample(status: VerifiedStatus) -> CanaryObservationV2 { 190 CanaryObservationV2::new(ObservationInput { 191 generation_id: "gen-0001", 192 request_id: "req-001", 193 request_digest: &sha256_hex(b"request"), 194 workload_digest: &sha256_hex(b"workload"), 195 candidate_executable_digest: &sha256_hex(b"executable"), 196 result_digest: Some(&sha256_hex(b"pong")), 197 elapsed_us: 1234, 198 observed_at_ms: 1_700_000_000_000, 199 status, 200 provenance: Provenance::Measured, 201 }) 202 } 203 204 #[test] 205 fn id_derives_from_generation_request_and_digest_only() { 206 let a = sample(VerifiedStatus::VerifiedSuccess); 207 let mut b = sample(VerifiedStatus::WrongResult); 208 b.elapsed_us = 9; 209 assert_eq!(a.observation_id, b.observation_id); 210 assert_ne!(a.digest_hex(), b.digest_hex()); 211 let c = CanaryObservationV2::new(ObservationInput { 212 request_id: "req-002", 213 ..ObservationInput { 214 generation_id: "gen-0001", 215 request_id: "req-001", 216 request_digest: &a.request_digest, 217 workload_digest: &a.workload_digest, 218 candidate_executable_digest: &a.candidate_executable_digest, 219 result_digest: a.result_digest.as_deref(), 220 elapsed_us: a.elapsed_us, 221 observed_at_ms: a.observed_at_ms, 222 status: a.status, 223 provenance: a.provenance, 224 } 225 }); 226 assert_ne!(a.observation_id, c.observation_id); 227 } 228 229 #[test] 230 fn validation_covers_version_ids_digests_and_result_presence() { 231 assert!(sample(VerifiedStatus::VerifiedSuccess).validate().is_ok()); 232 233 let mut tampered_id = sample(VerifiedStatus::VerifiedSuccess); 234 tampered_id.request_id = "req-999".into(); 235 assert!(tampered_id 236 .validate() 237 .unwrap_err() 238 .contains("does not derive")); 239 240 let mut bad_version = sample(VerifiedStatus::VerifiedSuccess); 241 bad_version.record_version = 1; 242 assert!(bad_version.validate().is_err()); 243 244 let mut no_result = sample(VerifiedStatus::VerifiedSuccess); 245 no_result.result_digest = None; 246 assert!(no_result 247 .validate() 248 .unwrap_err() 249 .contains("requires a result digest")); 250 251 let mut timeout = sample(VerifiedStatus::Timeout); 252 timeout.result_digest = None; 253 assert!(timeout.validate().is_ok()); 254 assert!(!timeout.is_qualifying()); 255 256 let mut bad_digest = sample(VerifiedStatus::VerifiedSuccess); 257 bad_digest.workload_digest = "nope".into(); 258 assert!(bad_digest.validate().is_err()); 259 } 260 261 #[test] 262 fn only_measured_verified_success_qualifies() { 263 assert!(sample(VerifiedStatus::VerifiedSuccess).is_qualifying()); 264 assert!(!sample(VerifiedStatus::WrongResult).is_qualifying()); 265 let mut synthetic = sample(VerifiedStatus::VerifiedSuccess); 266 synthetic.provenance = Provenance::Synthetic; 267 assert!(!synthetic.is_qualifying()); 268 } 269 270 #[test] 271 fn canonical_bytes_are_sorted_and_compact() { 272 let bytes = sample(VerifiedStatus::VerifiedSuccess).canonical_bytes(); 273 let text = String::from_utf8(bytes).unwrap(); 274 assert!(text.starts_with("{\"candidate_executable_digest\":\"")); 275 assert!(text.contains("\"status\":\"verified_success\",")); 276 assert!(text.ends_with(&format!( 277 "\"workload_digest\":\"{}\"}}", 278 sha256_hex(b"workload") 279 ))); 280 assert!(!text.contains(' ')); 281 } 282 }