spark-rsi-mv
Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger
Brought by drakestapleton
spark-rsi-mv / src / canary / log.rs
| 1 | //! The per-generation observation log: append-only JSON lines, one canonical record per line, |
| 2 | //! opened with a header and closed with a seal that commits the digest of everything before |
| 3 | //! it. Every append is synced to disk before it is acknowledged. A partial trailing record |
| 4 | //! (a crash mid-write) is detected and excluded. The store refuses an observation id it |
| 5 | //! already holds unless the record is byte-identical, in which case the retry is idempotent; |
| 6 | //! a different record under a known id is a conflict. |
| 7 | //! |
| 8 | //! Only a sealed log can be handed to the quota validator (`SealedObservationLog`). |
| 9 | |
| 10 | use super::{ |
| 11 | canonical_json, domain_digest, is_hex_digest, CanaryObservationV2, OBSERVATION_LOG_VERSION, |
| 12 | }; |
| 13 | use serde::{Deserialize, Serialize}; |
| 14 | use std::collections::BTreeMap; |
| 15 | use std::fs::{File, OpenOptions}; |
| 16 | use std::io::Write; |
| 17 | use std::path::{Path, PathBuf}; |
| 18 | |
| 19 | pub const LOG_DOMAIN: &str = "spark-rsi/canary-observation-log/v1"; |
| 20 | |
| 21 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 22 | #[serde(deny_unknown_fields)] |
| 23 | pub struct LogHeader { |
| 24 | pub log_version: u16, |
| 25 | pub generation_id: String, |
| 26 | pub workload_digest: String, |
| 27 | pub candidate_executable_digest: String, |
| 28 | pub opened_at_ms: u64, |
| 29 | } |
| 30 | |
| 31 | impl LogHeader { |
| 32 | pub fn new( |
| 33 | generation_id: &str, |
| 34 | workload_digest: &str, |
| 35 | candidate_executable_digest: &str, |
| 36 | opened_at_ms: u64, |
| 37 | ) -> Self { |
| 38 | Self { |
| 39 | log_version: OBSERVATION_LOG_VERSION, |
| 40 | generation_id: generation_id.to_string(), |
| 41 | workload_digest: workload_digest.to_string(), |
| 42 | candidate_executable_digest: candidate_executable_digest.to_string(), |
| 43 | opened_at_ms, |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | pub fn validate(&self) -> Result<(), String> { |
| 48 | if self.log_version != OBSERVATION_LOG_VERSION { |
| 49 | return Err(format!( |
| 50 | "observation log version {} is not supported (expected {})", |
| 51 | self.log_version, OBSERVATION_LOG_VERSION |
| 52 | )); |
| 53 | } |
| 54 | if self.generation_id.trim().is_empty() { |
| 55 | return Err("observation log generation id is required".to_string()); |
| 56 | } |
| 57 | if !is_hex_digest(&self.workload_digest) { |
| 58 | return Err("observation log workload digest is not a hex SHA-256".to_string()); |
| 59 | } |
| 60 | if !is_hex_digest(&self.candidate_executable_digest) { |
| 61 | return Err( |
| 62 | "observation log candidate executable digest is not a hex SHA-256".to_string(), |
| 63 | ); |
| 64 | } |
| 65 | Ok(()) |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 70 | #[serde(deny_unknown_fields)] |
| 71 | pub struct LogObservation { |
| 72 | pub observation: CanaryObservationV2, |
| 73 | pub observation_digest: String, |
| 74 | } |
| 75 | |
| 76 | /// Something the supervisor refused: an unauthenticated or wrong-generation message, an |
| 77 | /// unsolicited or duplicate result. Informational; never counts. |
| 78 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 79 | #[serde(deny_unknown_fields)] |
| 80 | pub struct LogRejection { |
| 81 | pub reason: String, |
| 82 | pub observed_at_ms: u64, |
| 83 | } |
| 84 | |
| 85 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 86 | #[serde(deny_unknown_fields)] |
| 87 | pub struct LogSeal { |
| 88 | /// Unique observations before the seal. |
| 89 | pub observation_count: u64, |
| 90 | /// Of those, the measured verified successes. |
| 91 | pub qualifying_count: u64, |
| 92 | /// Domain-separated SHA-256 of every byte of the file before the seal line. |
| 93 | pub log_digest: String, |
| 94 | pub sealed_at_ms: u64, |
| 95 | } |
| 96 | |
| 97 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 98 | #[serde(tag = "kind", content = "record", rename_all = "snake_case")] |
| 99 | pub enum LogRecord { |
| 100 | Header(LogHeader), |
| 101 | Observation(LogObservation), |
| 102 | Rejection(LogRejection), |
| 103 | Seal(LogSeal), |
| 104 | } |
| 105 | |
| 106 | impl LogRecord { |
| 107 | /// The exact bytes of this record on disk: canonical JSON and a newline. |
| 108 | pub fn to_line(&self) -> Vec<u8> { |
| 109 | let mut line = canonical_json(self); |
| 110 | line.push(b'\n'); |
| 111 | line |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 116 | pub enum AppendOutcome { |
| 117 | Appended, |
| 118 | /// The same id with a byte-identical record was already stored. |
| 119 | Idempotent, |
| 120 | } |
| 121 | |
| 122 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 123 | pub enum LogState { |
| 124 | Missing, |
| 125 | Unsealed { |
| 126 | observations: usize, |
| 127 | partial_tail: bool, |
| 128 | }, |
| 129 | Sealed { |
| 130 | observations: usize, |
| 131 | }, |
| 132 | Invalid(String), |
| 133 | } |
| 134 | |
| 135 | /// What the parser found in a log's bytes. |
| 136 | struct Parsed { |
| 137 | header: Option<LogHeader>, |
| 138 | observations: Vec<CanaryObservationV2>, |
| 139 | rejections: Vec<LogRejection>, |
| 140 | /// The seal and the byte offset where its line starts. |
| 141 | seal: Option<(LogSeal, usize)>, |
| 142 | /// Byte offset just past the last complete line. |
| 143 | complete_end: usize, |
| 144 | partial_tail: bool, |
| 145 | } |
| 146 | |
| 147 | fn parse_log(bytes: &[u8]) -> Result<Parsed, String> { |
| 148 | let mut parsed = Parsed { |
| 149 | header: None, |
| 150 | observations: Vec::new(), |
| 151 | rejections: Vec::new(), |
| 152 | seal: None, |
| 153 | complete_end: 0, |
| 154 | partial_tail: false, |
| 155 | }; |
| 156 | let mut seen: BTreeMap<String, String> = BTreeMap::new(); |
| 157 | let mut offset = 0usize; |
| 158 | let mut line_no = 0usize; |
| 159 | while offset < bytes.len() { |
| 160 | let Some(rel) = bytes[offset..].iter().position(|&b| b == b'\n') else { |
| 161 | parsed.partial_tail = true; |
| 162 | break; |
| 163 | }; |
| 164 | let line_start = offset; |
| 165 | let line_end = offset + rel; |
| 166 | offset = line_end + 1; |
| 167 | line_no += 1; |
| 168 | if parsed.seal.is_some() { |
| 169 | return Err(format!( |
| 170 | "observation log line {} comes after the seal", |
| 171 | line_no |
| 172 | )); |
| 173 | } |
| 174 | let line = &bytes[line_start..line_end]; |
| 175 | let record: LogRecord = serde_json::from_slice(line) |
| 176 | .map_err(|e| format!("observation log line {} does not parse: {}", line_no, e))?; |
| 177 | if record.to_line() != bytes[line_start..offset] { |
| 178 | return Err(format!( |
| 179 | "observation log line {} is not in canonical encoding", |
| 180 | line_no |
| 181 | )); |
| 182 | } |
| 183 | match record { |
| 184 | LogRecord::Header(h) => { |
| 185 | if line_no != 1 { |
| 186 | return Err(format!( |
| 187 | "observation log line {} is a header; only line 1 may be", |
| 188 | line_no |
| 189 | )); |
| 190 | } |
| 191 | h.validate()?; |
| 192 | parsed.header = Some(h); |
| 193 | } |
| 194 | LogRecord::Observation(o) => { |
| 195 | let header = parsed |
| 196 | .header |
| 197 | .as_ref() |
| 198 | .ok_or("observation log has no header")?; |
| 199 | o.observation.validate()?; |
| 200 | let digest = o.observation.digest_hex(); |
| 201 | if o.observation_digest != digest { |
| 202 | return Err(format!( |
| 203 | "observation {} carries digest {} but hashes to {}", |
| 204 | o.observation.observation_id, o.observation_digest, digest |
| 205 | )); |
| 206 | } |
| 207 | check_bindings(header, &o.observation)?; |
| 208 | match seen.get(&o.observation.observation_id) { |
| 209 | Some(previous) if previous == &digest => {} |
| 210 | Some(_) => { |
| 211 | return Err(format!( |
| 212 | "observation id {} conflicts with a different record", |
| 213 | o.observation.observation_id |
| 214 | )); |
| 215 | } |
| 216 | None => { |
| 217 | seen.insert(o.observation.observation_id.clone(), digest); |
| 218 | parsed.observations.push(o.observation); |
| 219 | } |
| 220 | } |
| 221 | } |
| 222 | LogRecord::Rejection(r) => { |
| 223 | if parsed.header.is_none() { |
| 224 | return Err("observation log has no header".to_string()); |
| 225 | } |
| 226 | parsed.rejections.push(r); |
| 227 | } |
| 228 | LogRecord::Seal(s) => { |
| 229 | if parsed.header.is_none() { |
| 230 | return Err("observation log has no header".to_string()); |
| 231 | } |
| 232 | parsed.seal = Some((s, line_start)); |
| 233 | } |
| 234 | } |
| 235 | parsed.complete_end = offset; |
| 236 | } |
| 237 | if parsed.header.is_none() && parsed.complete_end > 0 { |
| 238 | return Err("observation log has no header".to_string()); |
| 239 | } |
| 240 | Ok(parsed) |
| 241 | } |
| 242 | |
| 243 | fn check_bindings(header: &LogHeader, obs: &CanaryObservationV2) -> Result<(), String> { |
| 244 | if obs.generation_id != header.generation_id { |
| 245 | return Err(format!( |
| 246 | "observation {} belongs to generation {}, log is for {}", |
| 247 | obs.observation_id, obs.generation_id, header.generation_id |
| 248 | )); |
| 249 | } |
| 250 | if obs.workload_digest != header.workload_digest { |
| 251 | return Err(format!( |
| 252 | "observation {} carries workload digest {}, log is for {}", |
| 253 | obs.observation_id, obs.workload_digest, header.workload_digest |
| 254 | )); |
| 255 | } |
| 256 | if obs.candidate_executable_digest != header.candidate_executable_digest { |
| 257 | return Err(format!( |
| 258 | "observation {} carries executable digest {}, log is for {}", |
| 259 | obs.observation_id, obs.candidate_executable_digest, header.candidate_executable_digest |
| 260 | )); |
| 261 | } |
| 262 | Ok(()) |
| 263 | } |
| 264 | |
| 265 | fn log_digest_of(bytes_before_seal: &[u8]) -> String { |
| 266 | domain_digest(LOG_DOMAIN, &[bytes_before_seal]) |
| 267 | } |
| 268 | |
| 269 | /// Reports the state of the log at `path` without requiring it to be valid. |
| 270 | pub fn inspect(path: &Path) -> LogState { |
| 271 | if !path.exists() { |
| 272 | return LogState::Missing; |
| 273 | } |
| 274 | let bytes = match std::fs::read(path) { |
| 275 | Ok(b) => b, |
| 276 | Err(e) => return LogState::Invalid(format!("cannot read {:?}: {}", path, e)), |
| 277 | }; |
| 278 | match parse_log(&bytes) { |
| 279 | Err(e) => LogState::Invalid(e), |
| 280 | Ok(p) => match p.seal { |
| 281 | Some(_) => LogState::Sealed { |
| 282 | observations: p.observations.len(), |
| 283 | }, |
| 284 | None => LogState::Unsealed { |
| 285 | observations: p.observations.len(), |
| 286 | partial_tail: p.partial_tail, |
| 287 | }, |
| 288 | }, |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | /// Appends observations and rejections for one generation, each synced before return. |
| 293 | #[derive(Debug)] |
| 294 | pub struct ObservationLogWriter { |
| 295 | path: PathBuf, |
| 296 | file: File, |
| 297 | header: LogHeader, |
| 298 | seen: BTreeMap<String, String>, |
| 299 | } |
| 300 | |
| 301 | impl ObservationLogWriter { |
| 302 | /// Creates a new log. Refuses to overwrite an existing file. |
| 303 | pub fn create(path: &Path, header: LogHeader) -> Result<Self, String> { |
| 304 | header.validate()?; |
| 305 | if let Some(parent) = path.parent() { |
| 306 | std::fs::create_dir_all(parent) |
| 307 | .map_err(|e| format!("cannot create {:?}: {}", parent, e))?; |
| 308 | } |
| 309 | let mut file = OpenOptions::new() |
| 310 | .write(true) |
| 311 | .create_new(true) |
| 312 | .open(path) |
| 313 | .map_err(|e| format!("cannot create observation log {:?}: {}", path, e))?; |
| 314 | write_synced(&mut file, &LogRecord::Header(header.clone()).to_line())?; |
| 315 | Ok(Self { |
| 316 | path: path.to_path_buf(), |
| 317 | file, |
| 318 | header, |
| 319 | seen: BTreeMap::new(), |
| 320 | }) |
| 321 | } |
| 322 | |
| 323 | /// Reopens an unsealed log after a restart. The header on disk must equal `expected`; |
| 324 | /// a partial trailing record is dropped; every stored id is remembered so replays are |
| 325 | /// refused. A sealed log cannot be reopened. |
| 326 | pub fn reopen(path: &Path, expected: &LogHeader) -> Result<Self, String> { |
| 327 | expected.validate()?; |
| 328 | let bytes = std::fs::read(path) |
| 329 | .map_err(|e| format!("cannot read observation log {:?}: {}", path, e))?; |
| 330 | let parsed = parse_log(&bytes)?; |
| 331 | let header = parsed |
| 332 | .header |
| 333 | .ok_or_else(|| format!("observation log {:?} has no header", path))?; |
| 334 | if &header != expected { |
| 335 | return Err(format!( |
| 336 | "observation log {:?} was opened for generation {} with other bindings; refusing", |
| 337 | path, header.generation_id |
| 338 | )); |
| 339 | } |
| 340 | if parsed.seal.is_some() { |
| 341 | return Err(format!( |
| 342 | "observation log {:?} is already sealed; a sealed log is never reopened", |
| 343 | path |
| 344 | )); |
| 345 | } |
| 346 | let file = OpenOptions::new() |
| 347 | .write(true) |
| 348 | .open(path) |
| 349 | .map_err(|e| format!("cannot open observation log {:?}: {}", path, e))?; |
| 350 | if parsed.partial_tail { |
| 351 | file.set_len(parsed.complete_end as u64) |
| 352 | .map_err(|e| format!("cannot drop partial record in {:?}: {}", path, e))?; |
| 353 | file.sync_all().map_err(|e| e.to_string())?; |
| 354 | } |
| 355 | let mut file = OpenOptions::new() |
| 356 | .append(true) |
| 357 | .open(path) |
| 358 | .map_err(|e| format!("cannot open observation log {:?}: {}", path, e))?; |
| 359 | file.flush().map_err(|e| e.to_string())?; |
| 360 | let seen = parsed |
| 361 | .observations |
| 362 | .iter() |
| 363 | .map(|o| (o.observation_id.clone(), o.digest_hex())) |
| 364 | .collect(); |
| 365 | Ok(Self { |
| 366 | path: path.to_path_buf(), |
| 367 | file, |
| 368 | header, |
| 369 | seen, |
| 370 | }) |
| 371 | } |
| 372 | |
| 373 | pub fn path(&self) -> &Path { |
| 374 | &self.path |
| 375 | } |
| 376 | |
| 377 | pub fn header(&self) -> &LogHeader { |
| 378 | &self.header |
| 379 | } |
| 380 | |
| 381 | pub fn contains(&self, observation_id: &str) -> bool { |
| 382 | self.seen.contains_key(observation_id) |
| 383 | } |
| 384 | |
| 385 | pub fn stored_count(&self) -> usize { |
| 386 | self.seen.len() |
| 387 | } |
| 388 | |
| 389 | /// Stores `obs`. A byte-identical retry is idempotent; a different record under a known id |
| 390 | /// is refused; a record for another generation, workload or executable is refused. |
| 391 | pub fn append_observation( |
| 392 | &mut self, |
| 393 | obs: &CanaryObservationV2, |
| 394 | ) -> Result<AppendOutcome, String> { |
| 395 | obs.validate()?; |
| 396 | check_bindings(&self.header, obs)?; |
| 397 | let digest = obs.digest_hex(); |
| 398 | if let Some(previous) = self.seen.get(&obs.observation_id) { |
| 399 | if previous == &digest { |
| 400 | return Ok(AppendOutcome::Idempotent); |
| 401 | } |
| 402 | return Err(format!( |
| 403 | "observation id {} conflicts with a different record", |
| 404 | obs.observation_id |
| 405 | )); |
| 406 | } |
| 407 | let record = LogRecord::Observation(LogObservation { |
| 408 | observation: obs.clone(), |
| 409 | observation_digest: digest.clone(), |
| 410 | }); |
| 411 | write_synced(&mut self.file, &record.to_line())?; |
| 412 | self.seen.insert(obs.observation_id.clone(), digest); |
| 413 | Ok(AppendOutcome::Appended) |
| 414 | } |
| 415 | |
| 416 | pub fn append_rejection(&mut self, reason: &str, observed_at_ms: u64) -> Result<(), String> { |
| 417 | let record = LogRecord::Rejection(LogRejection { |
| 418 | reason: reason.to_string(), |
| 419 | observed_at_ms, |
| 420 | }); |
| 421 | write_synced(&mut self.file, &record.to_line()) |
| 422 | } |
| 423 | |
| 424 | /// Re-reads the file, verifies it, commits its digest in a seal record and returns the |
| 425 | /// verified sealed log. Consumes the writer: nothing is appended after the seal. |
| 426 | pub fn seal(self, sealed_at_ms: u64) -> Result<SealedObservationLog, String> { |
| 427 | let ObservationLogWriter { path, mut file, .. } = self; |
| 428 | let bytes = std::fs::read(&path) |
| 429 | .map_err(|e| format!("cannot re-read observation log {:?}: {}", path, e))?; |
| 430 | let parsed = parse_log(&bytes)?; |
| 431 | if parsed.seal.is_some() { |
| 432 | return Err(format!("observation log {:?} is already sealed", path)); |
| 433 | } |
| 434 | if parsed.partial_tail { |
| 435 | return Err(format!( |
| 436 | "observation log {:?} ends in a partial record; refusing to seal", |
| 437 | path |
| 438 | )); |
| 439 | } |
| 440 | let seal = LogSeal { |
| 441 | observation_count: parsed.observations.len() as u64, |
| 442 | qualifying_count: parsed |
| 443 | .observations |
| 444 | .iter() |
| 445 | .filter(|o| o.is_qualifying()) |
| 446 | .count() as u64, |
| 447 | log_digest: log_digest_of(&bytes), |
| 448 | sealed_at_ms, |
| 449 | }; |
| 450 | write_synced(&mut file, &LogRecord::Seal(seal).to_line())?; |
| 451 | drop(file); |
| 452 | SealedObservationLog::load(&path) |
| 453 | } |
| 454 | } |
| 455 | |
| 456 | fn write_synced(file: &mut File, line: &[u8]) -> Result<(), String> { |
| 457 | file.write_all(line) |
| 458 | .map_err(|e| format!("cannot append to observation log: {}", e))?; |
| 459 | file.sync_all() |
| 460 | .map_err(|e| format!("cannot sync observation log: {}", e)) |
| 461 | } |
| 462 | |
| 463 | /// A log that was closed with a seal and verified: header present, every record canonical and |
| 464 | /// well-formed, every observation bound to the header, ids unique, the seal digest equal to the |
| 465 | /// digest of the bytes before it, nothing after the seal. |
| 466 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 467 | pub struct SealedObservationLog { |
| 468 | pub path: Option<PathBuf>, |
| 469 | pub header: LogHeader, |
| 470 | pub observations: Vec<CanaryObservationV2>, |
| 471 | pub rejections: Vec<LogRejection>, |
| 472 | pub seal: LogSeal, |
| 473 | } |
| 474 | |
| 475 | impl SealedObservationLog { |
| 476 | pub fn load(path: &Path) -> Result<Self, String> { |
| 477 | let bytes = std::fs::read(path) |
| 478 | .map_err(|e| format!("cannot read observation log {:?}: {}", path, e))?; |
| 479 | let mut sealed = Self::verify_bytes(&bytes)?; |
| 480 | sealed.path = Some(path.to_path_buf()); |
| 481 | Ok(sealed) |
| 482 | } |
| 483 | |
| 484 | pub fn verify_bytes(bytes: &[u8]) -> Result<Self, String> { |
| 485 | let parsed = parse_log(bytes)?; |
| 486 | let header = parsed.header.ok_or("observation log has no header")?; |
| 487 | let (seal, seal_start) = parsed.seal.ok_or("observation log is not sealed")?; |
| 488 | if parsed.partial_tail || parsed.complete_end != bytes.len() { |
| 489 | return Err("observation log has bytes after the seal".to_string()); |
| 490 | } |
| 491 | let expected = log_digest_of(&bytes[..seal_start]); |
| 492 | if seal.log_digest != expected { |
| 493 | return Err(format!( |
| 494 | "observation log seal digest {} does not match the log bytes ({})", |
| 495 | seal.log_digest, expected |
| 496 | )); |
| 497 | } |
| 498 | if seal.observation_count != parsed.observations.len() as u64 { |
| 499 | return Err(format!( |
| 500 | "observation log seal counts {} observations, log holds {}", |
| 501 | seal.observation_count, |
| 502 | parsed.observations.len() |
| 503 | )); |
| 504 | } |
| 505 | let qualifying = parsed |
| 506 | .observations |
| 507 | .iter() |
| 508 | .filter(|o| o.is_qualifying()) |
| 509 | .count() as u64; |
| 510 | if seal.qualifying_count != qualifying { |
| 511 | return Err(format!( |
| 512 | "observation log seal counts {} qualifying observations, log holds {}", |
| 513 | seal.qualifying_count, qualifying |
| 514 | )); |
| 515 | } |
| 516 | Ok(Self { |
| 517 | path: None, |
| 518 | header, |
| 519 | observations: parsed.observations, |
| 520 | rejections: parsed.rejections, |
| 521 | seal, |
| 522 | }) |
| 523 | } |
| 524 | |
| 525 | pub fn log_digest(&self) -> &str { |
| 526 | &self.seal.log_digest |
| 527 | } |
| 528 | |
| 529 | pub fn qualifying(&self) -> impl Iterator<Item = &CanaryObservationV2> { |
| 530 | self.observations.iter().filter(|o| o.is_qualifying()) |
| 531 | } |
| 532 | } |
| 533 | |
| 534 | #[cfg(test)] |
| 535 | mod tests { |
| 536 | use super::*; |
| 537 | use crate::canary::observation::{ObservationInput, Provenance, VerifiedStatus}; |
| 538 | use crate::canary::sha256_hex; |
| 539 | |
| 540 | fn header() -> LogHeader { |
| 541 | LogHeader::new( |
| 542 | "gen-0001", |
| 543 | &sha256_hex(b"workload"), |
| 544 | &sha256_hex(b"exe"), |
| 545 | 1_700_000_000_000, |
| 546 | ) |
| 547 | } |
| 548 | |
| 549 | fn obs(request_id: &str, status: VerifiedStatus) -> CanaryObservationV2 { |
| 550 | CanaryObservationV2::new(ObservationInput { |
| 551 | generation_id: "gen-0001", |
| 552 | request_id, |
| 553 | request_digest: &sha256_hex(request_id.as_bytes()), |
| 554 | workload_digest: &sha256_hex(b"workload"), |
| 555 | candidate_executable_digest: &sha256_hex(b"exe"), |
| 556 | result_digest: Some(&sha256_hex(b"pong")), |
| 557 | elapsed_us: 500, |
| 558 | observed_at_ms: 1_700_000_000_500, |
| 559 | status, |
| 560 | provenance: Provenance::Measured, |
| 561 | }) |
| 562 | } |
| 563 | |
| 564 | #[test] |
| 565 | fn write_seal_and_verify_round_trip() { |
| 566 | let tmp = tempfile::tempdir().unwrap(); |
| 567 | let path = tmp.path().join("canary").join("gen-0001.jsonl"); |
| 568 | let mut w = ObservationLogWriter::create(&path, header()).unwrap(); |
| 569 | assert_eq!( |
| 570 | w.append_observation(&obs("req-001", VerifiedStatus::VerifiedSuccess)) |
| 571 | .unwrap(), |
| 572 | AppendOutcome::Appended |
| 573 | ); |
| 574 | assert_eq!( |
| 575 | w.append_observation(&obs("req-001", VerifiedStatus::VerifiedSuccess)) |
| 576 | .unwrap(), |
| 577 | AppendOutcome::Idempotent |
| 578 | ); |
| 579 | w.append_rejection("unsolicited result for req-009", 1_700_000_000_600) |
| 580 | .unwrap(); |
| 581 | w.append_observation(&obs("req-002", VerifiedStatus::WrongResult)) |
| 582 | .unwrap(); |
| 583 | assert_eq!( |
| 584 | inspect(&path), |
| 585 | LogState::Unsealed { |
| 586 | observations: 2, |
| 587 | partial_tail: false |
| 588 | } |
| 589 | ); |
| 590 | let sealed = w.seal(1_700_000_001_000).unwrap(); |
| 591 | assert_eq!(sealed.observations.len(), 2); |
| 592 | assert_eq!(sealed.rejections.len(), 1); |
| 593 | assert_eq!(sealed.seal.observation_count, 2); |
| 594 | assert_eq!(sealed.seal.qualifying_count, 1); |
| 595 | assert_eq!(sealed.qualifying().count(), 1); |
| 596 | assert_eq!(inspect(&path), LogState::Sealed { observations: 2 }); |
| 597 | let reloaded = SealedObservationLog::load(&path).unwrap(); |
| 598 | assert_eq!(reloaded, sealed); |
| 599 | } |
| 600 | |
| 601 | #[test] |
| 602 | fn conflicting_record_under_a_known_id_is_refused() { |
| 603 | let tmp = tempfile::tempdir().unwrap(); |
| 604 | let path = tmp.path().join("gen.jsonl"); |
| 605 | let mut w = ObservationLogWriter::create(&path, header()).unwrap(); |
| 606 | w.append_observation(&obs("req-001", VerifiedStatus::VerifiedSuccess)) |
| 607 | .unwrap(); |
| 608 | let mut changed = obs("req-001", VerifiedStatus::VerifiedSuccess); |
| 609 | changed.elapsed_us = 1; |
| 610 | let err = w.append_observation(&changed).unwrap_err(); |
| 611 | assert!(err.contains("conflicts")); |
| 612 | } |
| 613 | |
| 614 | #[test] |
| 615 | fn foreign_bindings_are_refused() { |
| 616 | let tmp = tempfile::tempdir().unwrap(); |
| 617 | let path = tmp.path().join("gen.jsonl"); |
| 618 | let mut w = ObservationLogWriter::create(&path, header()).unwrap(); |
| 619 | let mut other_gen = obs("req-001", VerifiedStatus::VerifiedSuccess); |
| 620 | other_gen.generation_id = "gen-0002".into(); |
| 621 | other_gen.observation_id = |
| 622 | crate::canary::observation_id("gen-0002", "req-001", &other_gen.request_digest); |
| 623 | assert!(w |
| 624 | .append_observation(&other_gen) |
| 625 | .unwrap_err() |
| 626 | .contains("belongs to generation")); |
| 627 | let mut other_exe = obs("req-001", VerifiedStatus::VerifiedSuccess); |
| 628 | other_exe.candidate_executable_digest = sha256_hex(b"other"); |
| 629 | assert!(w |
| 630 | .append_observation(&other_exe) |
| 631 | .unwrap_err() |
| 632 | .contains("executable digest")); |
| 633 | } |
| 634 | |
| 635 | #[test] |
| 636 | fn unsealed_tampered_and_appended_logs_do_not_verify() { |
| 637 | let tmp = tempfile::tempdir().unwrap(); |
| 638 | let path = tmp.path().join("gen.jsonl"); |
| 639 | let mut w = ObservationLogWriter::create(&path, header()).unwrap(); |
| 640 | w.append_observation(&obs("req-001", VerifiedStatus::VerifiedSuccess)) |
| 641 | .unwrap(); |
| 642 | assert!(SealedObservationLog::load(&path) |
| 643 | .unwrap_err() |
| 644 | .contains("not sealed")); |
| 645 | let sealed = w.seal(1).unwrap(); |
| 646 | let bytes = std::fs::read(&path).unwrap(); |
| 647 | |
| 648 | // Flip a byte inside the observation line. |
| 649 | let mut tampered = bytes.clone(); |
| 650 | let idx = String::from_utf8_lossy(&bytes) |
| 651 | .find("\"elapsed_us\":500") |
| 652 | .unwrap(); |
| 653 | tampered[idx + "\"elapsed_us\":".len()] = b'9'; |
| 654 | let err = SealedObservationLog::verify_bytes(&tampered).unwrap_err(); |
| 655 | assert!( |
| 656 | err.contains("hashes to") || err.contains("seal digest"), |
| 657 | "{}", |
| 658 | err |
| 659 | ); |
| 660 | |
| 661 | // Append a record after the seal. |
| 662 | let mut appended = bytes.clone(); |
| 663 | appended.extend_from_slice( |
| 664 | &LogRecord::Rejection(LogRejection { |
| 665 | reason: "late".into(), |
| 666 | observed_at_ms: 2, |
| 667 | }) |
| 668 | .to_line(), |
| 669 | ); |
| 670 | assert!(SealedObservationLog::verify_bytes(&appended) |
| 671 | .unwrap_err() |
| 672 | .contains("after the seal")); |
| 673 | |
| 674 | // Partial bytes after the seal. |
| 675 | let mut partial = bytes.clone(); |
| 676 | partial.extend_from_slice(b"{\"kind\":\"rejection\""); |
| 677 | assert!(SealedObservationLog::verify_bytes(&partial) |
| 678 | .unwrap_err() |
| 679 | .contains("after the seal")); |
| 680 | |
| 681 | // Drop an observation line but keep the seal: digest mismatch. |
| 682 | let text = String::from_utf8(bytes.clone()).unwrap(); |
| 683 | let mut lines: Vec<&str> = text.lines().collect(); |
| 684 | lines.remove(1); |
| 685 | let shortened = format!("{}\n", lines.join("\n")); |
| 686 | let err = SealedObservationLog::verify_bytes(shortened.as_bytes()).unwrap_err(); |
| 687 | assert!(err.contains("seal digest"), "{}", err); |
| 688 | |
| 689 | // A sealed log is never reopened. |
| 690 | assert!(ObservationLogWriter::reopen(&path, &header()) |
| 691 | .unwrap_err() |
| 692 | .contains("already sealed")); |
| 693 | assert_eq!(sealed.observations.len(), 1); |
| 694 | } |
| 695 | |
| 696 | #[test] |
| 697 | fn reopen_drops_a_partial_tail_and_remembers_ids() { |
| 698 | let tmp = tempfile::tempdir().unwrap(); |
| 699 | let path = tmp.path().join("gen.jsonl"); |
| 700 | let mut w = ObservationLogWriter::create(&path, header()).unwrap(); |
| 701 | w.append_observation(&obs("req-001", VerifiedStatus::VerifiedSuccess)) |
| 702 | .unwrap(); |
| 703 | drop(w); |
| 704 | // Simulate a crash mid-write. |
| 705 | let mut f = OpenOptions::new().append(true).open(&path).unwrap(); |
| 706 | f.write_all(b"{\"kind\":\"observation\",\"record\":{\"obs") |
| 707 | .unwrap(); |
| 708 | drop(f); |
| 709 | assert_eq!( |
| 710 | inspect(&path), |
| 711 | LogState::Unsealed { |
| 712 | observations: 1, |
| 713 | partial_tail: true |
| 714 | } |
| 715 | ); |
| 716 | let mut w = ObservationLogWriter::reopen(&path, &header()).unwrap(); |
| 717 | assert!(w.contains(&obs("req-001", VerifiedStatus::VerifiedSuccess).observation_id)); |
| 718 | assert_eq!( |
| 719 | w.append_observation(&obs("req-001", VerifiedStatus::VerifiedSuccess)) |
| 720 | .unwrap(), |
| 721 | AppendOutcome::Idempotent |
| 722 | ); |
| 723 | w.append_observation(&obs("req-002", VerifiedStatus::Timeout).with_no_result()) |
| 724 | .unwrap(); |
| 725 | let sealed = w.seal(5).unwrap(); |
| 726 | assert_eq!(sealed.observations.len(), 2); |
| 727 | assert_eq!(sealed.seal.qualifying_count, 1); |
| 728 | |
| 729 | let mut other = header(); |
| 730 | other.generation_id = "gen-0009".into(); |
| 731 | let tmp2 = tempfile::tempdir().unwrap(); |
| 732 | let path2 = tmp2.path().join("gen.jsonl"); |
| 733 | let w2 = ObservationLogWriter::create(&path2, header()).unwrap(); |
| 734 | drop(w2); |
| 735 | assert!(ObservationLogWriter::reopen(&path2, &other) |
| 736 | .unwrap_err() |
| 737 | .contains("refusing")); |
| 738 | } |
| 739 | |
| 740 | #[test] |
| 741 | fn create_never_overwrites() { |
| 742 | let tmp = tempfile::tempdir().unwrap(); |
| 743 | let path = tmp.path().join("gen.jsonl"); |
| 744 | let _w = ObservationLogWriter::create(&path, header()).unwrap(); |
| 745 | assert!(ObservationLogWriter::create(&path, header()).is_err()); |
| 746 | } |
| 747 | |
| 748 | impl CanaryObservationV2 { |
| 749 | fn with_no_result(mut self) -> Self { |
| 750 | self.result_digest = None; |
| 751 | self |
| 752 | } |
| 753 | } |
| 754 | } |