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 / admission.rs

368 lines · 13240 bytes Raw Blame History
1//! The hand-off from a sealed observation log to the quota validator. This is the single
2//! authority on evidence sufficiency for the version 2 path: the supervisor collects and
3//! seals, the promotion path decides whether to promote, and only this function says whether
4//! enough verified evidence exists.
5//!
6//! Everything fails closed. Only measured, supervisor-confirmed successes whose request is in
7//! the pinned workload, whose request digest matches it, whose result digest equals the
8//! workload's expected outcome, and whose elapsed time is within the request deadline count.
9//! A single non-success observation in the log refuses admission: a canary with a failed or
10//! slow request is not promotable. The old `CanaryReport` self-report path cannot produce a
11//! version 2 observation, so it can never satisfy this validator.
12
13use super::{
14 CanaryWorkloadManifest, CandidateIdentity, Provenance, SealedObservationLog, VerifiedStatus,
15};
16use std::collections::BTreeSet;
17
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct SealedQuotaDecision {
20 pub counted: u64,
21 pub target: u64,
22 pub generation_id: String,
23 pub candidate_executable_digest: String,
24 pub workload_digest: String,
25 pub log_digest: String,
26}
27
28pub fn admit_sealed_quota(
29 sealed: &SealedObservationLog,
30 identity: &CandidateIdentity,
31 workload: &CanaryWorkloadManifest,
32 target: u64,
33) -> Result<SealedQuotaDecision, String> {
34 if target == 0 {
35 return Err("production canary quota target must be at least 1".to_string());
36 }
37 identity.validate()?;
38 workload.validate()?;
39 let workload_digest = workload.digest();
40
41 let header = &sealed.header;
42 if header.generation_id != identity.generation_id {
43 return Err(format!(
44 "observation log is for generation {}, candidate is generation {}",
45 header.generation_id, identity.generation_id
46 ));
47 }
48 if header.candidate_executable_digest != identity.executable_digest {
49 return Err(format!(
50 "observation log executable digest {} does not match the candidate executable {}",
51 header.candidate_executable_digest, identity.executable_digest
52 ));
53 }
54 if header.workload_digest != workload_digest {
55 return Err(format!(
56 "observation log workload digest {} does not match the pinned workload {}",
57 header.workload_digest, workload_digest
58 ));
59 }
60
61 let mut counted = 0u64;
62 let mut seen: BTreeSet<&str> = BTreeSet::new();
63 for obs in &sealed.observations {
64 obs.validate()?;
65 if obs.generation_id != identity.generation_id
66 || obs.candidate_executable_digest != identity.executable_digest
67 || obs.workload_digest != workload_digest
68 {
69 return Err(format!(
70 "observation {} is not bound to this generation, executable and workload",
71 obs.observation_id
72 ));
73 }
74 if obs.provenance != Provenance::Measured {
75 return Err(format!(
76 "observation {} is a synthetic rehearsal; it cannot satisfy the production canary quota",
77 obs.observation_id
78 ));
79 }
80 if obs.status != VerifiedStatus::VerifiedSuccess {
81 return Err(format!(
82 "canary observed a {:?} on request {}; the candidate is not promotable",
83 obs.status, obs.request_id
84 ));
85 }
86 let spec = workload.request(&obs.request_id).ok_or_else(|| {
87 format!(
88 "observation {} answers request {} which is not in the pinned workload",
89 obs.observation_id, obs.request_id
90 )
91 })?;
92 let expected_request = spec.request_digest(&workload.workload_id);
93 if obs.request_digest != expected_request {
94 return Err(format!(
95 "observation {} carries request digest {}, workload request {} has {}",
96 obs.observation_id, obs.request_digest, spec.request_id, expected_request
97 ));
98 }
99 let expected_result = spec.expected_result_digest();
100 if obs.result_digest.as_deref() != Some(expected_result.as_str()) {
101 return Err(format!(
102 "observation {} result digest {:?} does not equal the expected outcome of request {}",
103 obs.observation_id, obs.result_digest, spec.request_id
104 ));
105 }
106 if obs.elapsed_us > spec.deadline_ms.saturating_mul(1000) {
107 return Err(format!(
108 "observation {} took {} us, over the {} ms deadline of request {}",
109 obs.observation_id, obs.elapsed_us, spec.deadline_ms, spec.request_id
110 ));
111 }
112 if seen.insert(obs.observation_id.as_str()) {
113 counted += 1;
114 }
115 }
116
117 if counted < target {
118 return Err(format!(
119 "production canary quota requires {} verified observations, received {}",
120 target, counted
121 ));
122 }
123 Ok(SealedQuotaDecision {
124 counted,
125 target,
126 generation_id: identity.generation_id.clone(),
127 candidate_executable_digest: identity.executable_digest.clone(),
128 workload_digest,
129 log_digest: sealed.seal.log_digest.clone(),
130 })
131}
132
133#[cfg(test)]
134mod tests {
135 use super::*;
136 use crate::canary::observation::ObservationInput;
137 use crate::canary::{
138 sha256_hex, CanaryObservationV2, CanaryRequestSpec, LogHeader, Nondeterminism,
139 ObservationLogWriter,
140 };
141
142 fn workload() -> CanaryWorkloadManifest {
143 CanaryWorkloadManifest {
144 workload_version: 1,
145 workload_id: "fixture-v1".into(),
146 protocol_version: 1,
147 requests: (1..=3)
148 .map(|i| CanaryRequestSpec {
149 request_id: format!("req-{:03}", i),
150 input: format!("ping {}", i),
151 expected_output: format!("pong {}", i),
152 deadline_ms: 2000,
153 nondeterminism: Nondeterminism::Exact,
154 })
155 .collect(),
156 }
157 }
158
159 fn identity() -> CandidateIdentity {
160 CandidateIdentity::new(
161 &sha256_hex(b"patch"),
162 &sha256_hex(b"tree"),
163 &sha256_hex(b"exe"),
164 "gen-0001",
165 )
166 }
167
168 fn observation(
169 w: &CanaryWorkloadManifest,
170 id: &CandidateIdentity,
171 request_id: &str,
172 output: &str,
173 elapsed_us: u64,
174 status: VerifiedStatus,
175 ) -> CanaryObservationV2 {
176 let spec = w.request(request_id).unwrap();
177 CanaryObservationV2::new(ObservationInput {
178 generation_id: &id.generation_id,
179 request_id,
180 request_digest: &spec.request_digest(&w.workload_id),
181 workload_digest: &w.digest(),
182 candidate_executable_digest: &id.executable_digest,
183 result_digest: Some(&sha256_hex(output.as_bytes())),
184 elapsed_us,
185 observed_at_ms: 1_700_000_000_000 + elapsed_us,
186 status,
187 provenance: Provenance::Measured,
188 })
189 }
190
191 fn sealed_with(obs: &[CanaryObservationV2]) -> SealedObservationLog {
192 let tmp = tempfile::tempdir().unwrap();
193 let path = tmp.path().join("gen.jsonl");
194 let id = identity();
195 let mut w = ObservationLogWriter::create(
196 &path,
197 LogHeader::new(
198 &id.generation_id,
199 &workload().digest(),
200 &id.executable_digest,
201 1,
202 ),
203 )
204 .unwrap();
205 for o in obs {
206 w.append_observation(o).unwrap();
207 }
208 w.seal(2).unwrap()
209 }
210
211 #[test]
212 fn enough_genuine_observations_pass() {
213 let w = workload();
214 let id = identity();
215 let obs: Vec<_> = (1..=3)
216 .map(|i| {
217 observation(
218 &w,
219 &id,
220 &format!("req-{:03}", i),
221 &format!("pong {}", i),
222 800,
223 VerifiedStatus::VerifiedSuccess,
224 )
225 })
226 .collect();
227 let sealed = sealed_with(&obs);
228 let decision = admit_sealed_quota(&sealed, &id, &w, 3).unwrap();
229 assert_eq!(decision.counted, 3);
230 assert_eq!(decision.log_digest, sealed.seal.log_digest);
231 assert!(admit_sealed_quota(&sealed, &id, &w, 4)
232 .unwrap_err()
233 .contains("received 3"));
234 }
235
236 #[test]
237 fn zero_observations_fail_closed() {
238 let sealed = sealed_with(&[]);
239 let err = admit_sealed_quota(&sealed, &identity(), &workload(), 1).unwrap_err();
240 assert!(err.contains("received 0"), "{}", err);
241 assert!(admit_sealed_quota(&sealed, &identity(), &workload(), 0).is_err());
242 }
243
244 #[test]
245 fn wrong_output_timeout_and_synthetic_cannot_qualify() {
246 let w = workload();
247 let id = identity();
248 let good = observation(
249 &w,
250 &id,
251 "req-001",
252 "pong 1",
253 800,
254 VerifiedStatus::VerifiedSuccess,
255 );
256
257 let wrong = observation(
258 &w,
259 &id,
260 "req-002",
261 "pong 1",
262 800,
263 VerifiedStatus::WrongResult,
264 );
265 let err = admit_sealed_quota(&sealed_with(&[good.clone(), wrong]), &id, &w, 1).unwrap_err();
266 assert!(err.contains("WrongResult"), "{}", err);
267
268 // A success claimed with the wrong bytes is refused even if the status says success.
269 let lying = observation(
270 &w,
271 &id,
272 "req-002",
273 "pong 1",
274 800,
275 VerifiedStatus::VerifiedSuccess,
276 );
277 let err = admit_sealed_quota(&sealed_with(&[lying]), &id, &w, 1).unwrap_err();
278 assert!(err.contains("expected outcome"), "{}", err);
279
280 let mut timeout = observation(&w, &id, "req-002", "", 2_000_001, VerifiedStatus::Timeout);
281 timeout.result_digest = None;
282 let err =
283 admit_sealed_quota(&sealed_with(&[good.clone(), timeout]), &id, &w, 1).unwrap_err();
284 assert!(err.contains("Timeout"), "{}", err);
285
286 let slow = observation(
287 &w,
288 &id,
289 "req-002",
290 "pong 2",
291 2_000_001,
292 VerifiedStatus::VerifiedSuccess,
293 );
294 let err = admit_sealed_quota(&sealed_with(&[slow]), &id, &w, 1).unwrap_err();
295 assert!(err.contains("deadline"), "{}", err);
296
297 let mut synthetic = good.clone();
298 synthetic.provenance = Provenance::Synthetic;
299 let err = admit_sealed_quota(&sealed_with(&[synthetic]), &id, &w, 1).unwrap_err();
300 assert!(err.contains("synthetic"), "{}", err);
301 }
302
303 #[test]
304 fn mismatched_identity_or_workload_is_refused() {
305 let w = workload();
306 let id = identity();
307 let sealed = sealed_with(&[observation(
308 &w,
309 &id,
310 "req-001",
311 "pong 1",
312 800,
313 VerifiedStatus::VerifiedSuccess,
314 )]);
315
316 let mut other_exe = identity();
317 other_exe.executable_digest = sha256_hex(b"something else that was built");
318 assert!(admit_sealed_quota(&sealed, &other_exe, &w, 1)
319 .unwrap_err()
320 .contains("executable"));
321
322 let mut other_gen = identity();
323 other_gen.generation_id = "gen-0002".into();
324 assert!(admit_sealed_quota(&sealed, &other_gen, &w, 1)
325 .unwrap_err()
326 .contains("generation"));
327
328 let mut other_workload = workload();
329 other_workload.requests[0].expected_output = "anything".into();
330 assert!(admit_sealed_quota(&sealed, &id, &other_workload, 1)
331 .unwrap_err()
332 .contains("workload"));
333 }
334
335 #[test]
336 fn unknown_request_or_tampered_request_digest_is_refused() {
337 let w = workload();
338 let id = identity();
339 let mut stranger = observation(
340 &w,
341 &id,
342 "req-001",
343 "pong 1",
344 800,
345 VerifiedStatus::VerifiedSuccess,
346 );
347 stranger.request_id = "req-777".into();
348 stranger.observation_id =
349 crate::canary::observation_id(&id.generation_id, "req-777", &stranger.request_digest);
350 let err = admit_sealed_quota(&sealed_with(&[stranger]), &id, &w, 1).unwrap_err();
351 assert!(err.contains("not in the pinned workload"), "{}", err);
352
353 let mut relabeled = observation(
354 &w,
355 &id,
356 "req-002",
357 "pong 1",
358 800,
359 VerifiedStatus::VerifiedSuccess,
360 );
361 // Keep the request id but carry the digest of another request.
362 relabeled.request_digest = w.requests[0].request_digest(&w.workload_id);
363 relabeled.observation_id =
364 crate::canary::observation_id(&id.generation_id, "req-002", &relabeled.request_digest);
365 let err = admit_sealed_quota(&sealed_with(&[relabeled]), &id, &w, 1).unwrap_err();
366 assert!(err.contains("request digest"), "{}", err);
367 }
368}