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

277 lines · 9886 bytes Raw Blame History
1//! The canary workload: the digest-pinned set of requests, expected outcomes, deadlines and
2//! permitted nondeterminism the supervisor issues. It lives under the RSI state directory and
3//! is owned by the operator. The candidate never rewrites it and never sets its own passing
4//! criteria.
5
6use super::{canonical_json, domain_digest, sha256_hex, CANARY_PROTOCOL_VERSION, WORKLOAD_VERSION};
7use serde::{Deserialize, Serialize};
8use std::collections::BTreeSet;
9use std::path::{Path, PathBuf};
10
11pub const WORKLOAD_DOMAIN: &str = "spark-rsi/canary-workload/v1";
12pub const REQUEST_DOMAIN: &str = "spark-rsi/canary-request/v1";
13
14/// How much the observed output may differ from `expected_output`. Version 1 permits none.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
16#[serde(rename_all = "snake_case")]
17pub enum Nondeterminism {
18 Exact,
19}
20
21impl Nondeterminism {
22 pub fn as_str(&self) -> &'static str {
23 match self {
24 Nondeterminism::Exact => "exact",
25 }
26 }
27}
28
29/// One challenge the supervisor sends. The worker only ever sees `input`.
30#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
31#[serde(deny_unknown_fields)]
32pub struct CanaryRequestSpec {
33 pub request_id: String,
34 pub input: String,
35 pub expected_output: String,
36 pub deadline_ms: u64,
37 pub nondeterminism: Nondeterminism,
38}
39
40impl CanaryRequestSpec {
41 /// Binds the request to its workload, input, expected outcome and deadline.
42 pub fn request_digest(&self, workload_id: &str) -> String {
43 domain_digest(
44 REQUEST_DOMAIN,
45 &[
46 workload_id.as_bytes(),
47 self.request_id.as_bytes(),
48 self.input.as_bytes(),
49 self.expected_output.as_bytes(),
50 &self.deadline_ms.to_le_bytes(),
51 self.nondeterminism.as_str().as_bytes(),
52 ],
53 )
54 }
55
56 /// The result digest a correct answer produces: SHA-256 of the expected output bytes.
57 pub fn expected_result_digest(&self) -> String {
58 sha256_hex(self.expected_output.as_bytes())
59 }
60
61 /// Whether `output` satisfies this request under its permitted nondeterminism.
62 pub fn matches_output(&self, output: &str) -> bool {
63 match self.nondeterminism {
64 Nondeterminism::Exact => output == self.expected_output,
65 }
66 }
67
68 pub fn validate(&self) -> Result<(), String> {
69 if self.request_id.trim().is_empty() {
70 return Err("canary request id is required".to_string());
71 }
72 if self.request_id.chars().any(char::is_control) {
73 return Err(format!(
74 "canary request id {:?} contains a control character",
75 self.request_id
76 ));
77 }
78 if self.deadline_ms == 0 {
79 return Err(format!(
80 "canary request {} has a zero deadline",
81 self.request_id
82 ));
83 }
84 Ok(())
85 }
86}
87
88#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
89#[serde(deny_unknown_fields)]
90pub struct CanaryWorkloadManifest {
91 pub workload_version: u16,
92 pub workload_id: String,
93 pub protocol_version: u16,
94 pub requests: Vec<CanaryRequestSpec>,
95}
96
97/// A workload read from disk together with the digest it was verified against.
98#[derive(Debug, Clone, PartialEq, Eq)]
99pub struct PinnedWorkload {
100 pub manifest: CanaryWorkloadManifest,
101 pub digest: String,
102 pub path: PathBuf,
103}
104
105impl CanaryWorkloadManifest {
106 pub fn parse(bytes: &[u8]) -> Result<Self, String> {
107 let manifest: Self = serde_json::from_slice(bytes)
108 .map_err(|e| format!("canary workload does not parse: {}", e))?;
109 manifest.validate()?;
110 Ok(manifest)
111 }
112
113 pub fn validate(&self) -> Result<(), String> {
114 if self.workload_version != WORKLOAD_VERSION {
115 return Err(format!(
116 "canary workload version {} is not supported (expected {})",
117 self.workload_version, WORKLOAD_VERSION
118 ));
119 }
120 if self.protocol_version != CANARY_PROTOCOL_VERSION {
121 return Err(format!(
122 "canary workload protocol version {} is not supported (expected {})",
123 self.protocol_version, CANARY_PROTOCOL_VERSION
124 ));
125 }
126 if self.workload_id.trim().is_empty() || self.workload_id.chars().any(char::is_control) {
127 return Err("canary workload id is required and must be printable".to_string());
128 }
129 if self.requests.is_empty() {
130 return Err("canary workload has no requests".to_string());
131 }
132 let mut ids = BTreeSet::new();
133 for req in &self.requests {
134 req.validate()?;
135 if !ids.insert(req.request_id.as_str()) {
136 return Err(format!(
137 "canary workload repeats request id {}",
138 req.request_id
139 ));
140 }
141 }
142 Ok(())
143 }
144
145 pub fn canonical_bytes(&self) -> Vec<u8> {
146 canonical_json(self)
147 }
148
149 /// Workload digest: domain-separated SHA-256 of the canonical bytes. Reformatting the file
150 /// on disk does not change it; changing any request, outcome or deadline does.
151 pub fn digest(&self) -> String {
152 domain_digest(WORKLOAD_DOMAIN, &[&self.canonical_bytes()])
153 }
154
155 pub fn request(&self, request_id: &str) -> Option<&CanaryRequestSpec> {
156 self.requests.iter().find(|r| r.request_id == request_id)
157 }
158
159 /// Reads and validates the workload at `path`.
160 pub fn load(path: &Path) -> Result<PinnedWorkload, String> {
161 let bytes = std::fs::read(path)
162 .map_err(|e| format!("cannot read canary workload {:?}: {}", path, e))?;
163 let manifest = Self::parse(&bytes)?;
164 let digest = manifest.digest();
165 Ok(PinnedWorkload {
166 manifest,
167 digest,
168 path: path.to_path_buf(),
169 })
170 }
171
172 /// Reads the workload at `path` and refuses it unless its digest equals the operator's
173 /// pinned `expected_digest`.
174 pub fn load_pinned(path: &Path, expected_digest: &str) -> Result<PinnedWorkload, String> {
175 let loaded = Self::load(path)?;
176 if loaded.digest != expected_digest {
177 return Err(format!(
178 "canary workload {:?} has digest {}, pinned digest is {}",
179 path, loaded.digest, expected_digest
180 ));
181 }
182 Ok(loaded)
183 }
184}
185
186#[cfg(test)]
187mod tests {
188 use super::*;
189
190 fn sample() -> CanaryWorkloadManifest {
191 CanaryWorkloadManifest {
192 workload_version: 1,
193 workload_id: "fixture-v1".into(),
194 protocol_version: 1,
195 requests: vec![
196 CanaryRequestSpec {
197 request_id: "req-001".into(),
198 input: "ping".into(),
199 expected_output: "pong".into(),
200 deadline_ms: 2000,
201 nondeterminism: Nondeterminism::Exact,
202 },
203 CanaryRequestSpec {
204 request_id: "req-002".into(),
205 input: "add 2 3".into(),
206 expected_output: "5".into(),
207 deadline_ms: 2000,
208 nondeterminism: Nondeterminism::Exact,
209 },
210 ],
211 }
212 }
213
214 #[test]
215 fn digest_ignores_formatting_but_not_content() {
216 let a = sample();
217 let pretty = serde_json::to_vec_pretty(&a).unwrap();
218 let reparsed = CanaryWorkloadManifest::parse(&pretty).unwrap();
219 assert_eq!(reparsed.digest(), a.digest());
220
221 let mut b = sample();
222 b.requests[0].expected_output = "PONG".into();
223 assert_ne!(b.digest(), a.digest());
224 assert_ne!(
225 b.requests[0].request_digest(&b.workload_id),
226 a.requests[0].request_digest(&a.workload_id)
227 );
228
229 let mut c = sample();
230 c.requests[0].deadline_ms = 1999;
231 assert_ne!(c.digest(), a.digest());
232 }
233
234 #[test]
235 fn validation_fails_closed() {
236 let mut dup = sample();
237 dup.requests[1].request_id = "req-001".into();
238 assert!(dup.validate().unwrap_err().contains("repeats"));
239
240 let mut empty = sample();
241 empty.requests.clear();
242 assert!(empty.validate().unwrap_err().contains("no requests"));
243
244 let mut version = sample();
245 version.protocol_version = 2;
246 assert!(version.validate().unwrap_err().contains("protocol version"));
247
248 let mut deadline = sample();
249 deadline.requests[0].deadline_ms = 0;
250 assert!(deadline.validate().unwrap_err().contains("zero deadline"));
251
252 let unknown_field = br#"{"workload_version":1,"workload_id":"w","protocol_version":1,"requests":[],"passing_criteria":"any"}"#;
253 assert!(CanaryWorkloadManifest::parse(unknown_field).is_err());
254 }
255
256 #[test]
257 fn exact_matching_and_expected_digest() {
258 let w = sample();
259 let r = w.request("req-001").unwrap();
260 assert!(r.matches_output("pong"));
261 assert!(!r.matches_output("pong\n"));
262 assert_eq!(r.expected_result_digest(), sha256_hex(b"pong"));
263 assert!(w.request("req-404").is_none());
264 }
265
266 #[test]
267 fn pinned_load_refuses_a_different_digest() {
268 let tmp = tempfile::tempdir().unwrap();
269 let path = tmp.path().join("workload.json");
270 std::fs::write(&path, serde_json::to_vec(&sample()).unwrap()).unwrap();
271 let loaded = CanaryWorkloadManifest::load(&path).unwrap();
272 assert_eq!(loaded.digest, sample().digest());
273 assert!(CanaryWorkloadManifest::load_pinned(&path, &loaded.digest).is_ok());
274 let err = CanaryWorkloadManifest::load_pinned(&path, &sha256_hex(b"other")).unwrap_err();
275 assert!(err.contains("pinned digest"));
276 }
277}