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 / isolation / manifest.rs

284 lines · 9575 bytes Raw Blame History
1use serde::{Deserialize, Serialize};
2use sha2::{Digest, Sha256};
3use std::collections::{HashMap, HashSet};
4use std::fs;
5use std::os::unix::fs::PermissionsExt;
6use std::path::{Path, PathBuf};
7
8#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
9pub struct ArtifactRecord {
10 pub relative_path: String,
11 pub sha256: String,
12 pub size_bytes: u64,
13 pub is_executable: bool,
14}
15
16#[derive(Debug, Clone, Serialize, Deserialize)]
17pub struct CandidateManifest {
18 pub manifest_version: String,
19 pub candidate_id: String,
20 pub parent_commit_sha: String,
21 pub proposal_id: String,
22 pub code_tier: String,
23 pub declared_files: Vec<String>,
24 pub primary_metric: String,
25 pub expected_delta_pct: f64,
26 pub regression_budgets: HashMap<String, f64>,
27 pub protected_metric_limits: HashMap<String, f64>,
28 pub timestamp_utc: String,
29}
30
31impl CandidateManifest {
32 pub fn new(
33 candidate_id: &str,
34 parent_commit_sha: &str,
35 proposal_id: &str,
36 code_tier: &str,
37 declared_files: Vec<String>,
38 primary_metric: &str,
39 expected_delta_pct: f64,
40 ) -> Self {
41 let mut regression_budgets = HashMap::new();
42 regression_budgets.insert("latency_p95_degradation_pct".to_string(), 1.0);
43 regression_budgets.insert("latency_p99_degradation_pct".to_string(), 1.0);
44 regression_budgets.insert("rss_growth_pct".to_string(), 2.0);
45
46 let mut protected_metric_limits = HashMap::new();
47 protected_metric_limits.insert("host_memory_ceiling_mb".to_string(), 49152.0);
48
49 Self {
50 manifest_version: "1.0.0".to_string(),
51 candidate_id: candidate_id.to_string(),
52 parent_commit_sha: parent_commit_sha.to_string(),
53 proposal_id: proposal_id.to_string(),
54 code_tier: code_tier.to_string(),
55 declared_files,
56 primary_metric: primary_metric.to_string(),
57 expected_delta_pct,
58 regression_budgets,
59 protected_metric_limits,
60 timestamp_utc: chrono::Utc::now().to_rfc3339(),
61 }
62 }
63}
64
65#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
66pub struct ArtifactManifest {
67 pub manifest_version: String,
68 pub candidate_id: String,
69 pub builder_image_digest: String,
70 pub source_bundle_digest: String,
71 pub artifacts: Vec<ArtifactRecord>,
72 pub manifest_digest: String,
73 pub timestamp_utc: String,
74}
75
76impl ArtifactManifest {
77 pub fn compute_file_sha256(path: &Path) -> Result<String, String> {
78 let bytes = fs::read(path).map_err(|e| format!("Failed to read file {:?}: {}", path, e))?;
79 let mut hasher = Sha256::new();
80 hasher.update(&bytes);
81 Ok(hex::encode(hasher.finalize()))
82 }
83
84 pub fn compute_source_digest(dir: &Path) -> Result<String, String> {
85 let mut file_entries = Vec::new();
86 Self::collect_files_sorted(dir, dir, &mut file_entries)?;
87
88 let mut hasher = Sha256::new();
89 for (rel_path, abs_path) in file_entries {
90 let file_hash = Self::compute_file_sha256(&abs_path)?;
91 hasher.update(rel_path.as_bytes());
92 hasher.update(file_hash.as_bytes());
93 }
94
95 Ok(hex::encode(hasher.finalize()))
96 }
97
98 fn collect_files_sorted(
99 base: &Path,
100 current: &Path,
101 acc: &mut Vec<(String, PathBuf)>,
102 ) -> Result<(), String> {
103 if !current.exists() {
104 return Ok(());
105 }
106 let mut entries = Vec::new();
107 for entry in fs::read_dir(current).map_err(|e| e.to_string())?.flatten() {
108 entries.push(entry.path());
109 }
110 entries.sort();
111
112 for path in entries {
113 let name = path
114 .file_name()
115 .and_then(|n| n.to_str())
116 .unwrap_or_default();
117 if name == "target" || name == ".git" || name == "node_modules" {
118 continue;
119 }
120 if path.is_dir() {
121 Self::collect_files_sorted(base, &path, acc)?;
122 } else if path.is_file() {
123 let rel = path
124 .strip_prefix(base)
125 .map_err(|e| e.to_string())?
126 .to_string_lossy()
127 .to_string();
128 acc.push((rel, path));
129 }
130 }
131 Ok(())
132 }
133
134 pub fn generate_from_output_dir(
135 candidate_id: &str,
136 builder_image_digest: &str,
137 source_bundle_digest: &str,
138 output_dir: &Path,
139 ) -> Result<Self, String> {
140 let mut file_entries = Vec::new();
141 Self::collect_files_sorted(output_dir, output_dir, &mut file_entries)?;
142
143 let mut records = Vec::new();
144 let mut digest_hasher = Sha256::new();
145 digest_hasher.update(candidate_id.as_bytes());
146 digest_hasher.update(builder_image_digest.as_bytes());
147 digest_hasher.update(source_bundle_digest.as_bytes());
148
149 for (rel_path, abs_path) in file_entries {
150 let meta = fs::metadata(&abs_path).map_err(|e| e.to_string())?;
151 let sha = Self::compute_file_sha256(&abs_path)?;
152 let is_exec = (meta.permissions().mode() & 0o111) != 0;
153
154 digest_hasher.update(rel_path.as_bytes());
155 digest_hasher.update(sha.as_bytes());
156 digest_hasher.update(meta.len().to_be_bytes());
157
158 records.push(ArtifactRecord {
159 relative_path: rel_path,
160 sha256: sha,
161 size_bytes: meta.len(),
162 is_executable: is_exec,
163 });
164 }
165
166 let manifest_digest = hex::encode(digest_hasher.finalize());
167
168 Ok(Self {
169 manifest_version: "1.0.0".to_string(),
170 candidate_id: candidate_id.to_string(),
171 builder_image_digest: builder_image_digest.to_string(),
172 source_bundle_digest: source_bundle_digest.to_string(),
173 artifacts: records,
174 manifest_digest,
175 timestamp_utc: chrono::Utc::now().to_rfc3339(),
176 })
177 }
178
179 pub fn verify_integrity(&self, output_dir: &Path) -> Result<bool, String> {
180 let mut expected_paths = HashSet::new();
181 for record in &self.artifacts {
182 let full_path = output_dir.join(&record.relative_path);
183 if !full_path.exists() {
184 return Ok(false);
185 }
186 let actual_sha = Self::compute_file_sha256(&full_path)?;
187 if actual_sha != record.sha256 {
188 return Ok(false);
189 }
190 expected_paths.insert(record.relative_path.clone());
191 }
192
193 // Active scan for extra unmanifested files
194 let mut on_disk_entries = Vec::new();
195 Self::collect_files_sorted(output_dir, output_dir, &mut on_disk_entries)?;
196
197 for (rel_path, _) in on_disk_entries {
198 if !expected_paths.contains(&rel_path) {
199 return Ok(false);
200 }
201 }
202
203 Ok(true)
204 }
205}
206
207#[cfg(test)]
208mod tests {
209 use super::*;
210
211 #[test]
212 fn test_candidate_manifest_creation() {
213 let manifest = CandidateManifest::new(
214 "cand-001",
215 "6ac8ae95cf13fd618c855ca1c0c67e6f8455fc5d",
216 "hyp-001",
217 "TARGET",
218 vec!["src/observe.rs".to_string()],
219 "latency_p95_us",
220 -12.5,
221 );
222 assert_eq!(manifest.candidate_id, "cand-001");
223 assert_eq!(manifest.code_tier, "TARGET");
224 assert_eq!(manifest.expected_delta_pct, -12.5);
225 assert!(manifest
226 .regression_budgets
227 .contains_key("latency_p95_degradation_pct"));
228 assert!(manifest
229 .protected_metric_limits
230 .contains_key("host_memory_ceiling_mb"));
231 }
232
233 #[test]
234 fn test_artifact_manifest_generation_and_integrity() {
235 let tmp = tempfile::tempdir().unwrap();
236 let file1 = tmp.path().join("libsample.so");
237 let file2 = tmp.path().join("config.json");
238
239 fs::write(&file1, "mock shared library binary content").unwrap();
240 fs::write(&file2, "{\"key\":\"value\"}").unwrap();
241
242 let source_digest = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
243 let builder_img = "docker.io/library/spark-rsi-builder@sha256:abcd1234";
244
245 let manifest = ArtifactManifest::generate_from_output_dir(
246 "cand-test",
247 builder_img,
248 source_digest,
249 tmp.path(),
250 )
251 .unwrap();
252
253 assert_eq!(manifest.artifacts.len(), 2);
254 assert!(!manifest.manifest_digest.is_empty());
255 assert!(manifest.verify_integrity(tmp.path()).unwrap());
256
257 // Tamper with file
258 fs::write(&file1, "tampered content").unwrap();
259 assert!(!manifest.verify_integrity(tmp.path()).unwrap());
260 }
261
262 #[test]
263 fn test_artifact_manifest_rejects_unmanifested_extra_file() {
264 let tmp = tempfile::tempdir().unwrap();
265 let file1 = tmp.path().join("main_binary");
266 fs::write(&file1, "compiled binary bytes").unwrap();
267
268 let manifest = ArtifactManifest::generate_from_output_dir(
269 "cand-test",
270 "builder-img",
271 "source-digest",
272 tmp.path(),
273 )
274 .unwrap();
275
276 assert!(manifest.verify_integrity(tmp.path()).unwrap());
277
278 // Inject extra unauthorized file
279 let rogue = tmp.path().join("backdoor.sh");
280 fs::write(&rogue, "#!/bin/sh\nexit 0").unwrap();
281
282 assert!(!manifest.verify_integrity(tmp.path()).unwrap());
283 }
284}