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 / supervisor / mod.rs

600 lines · 21524 bytes Raw Blame History
1pub mod canary_exec;
2pub mod daemon;
3
4pub mod ipc;
5
6use crate::evaluator::metrics::system_page_size_kb;
7use crate::isolation::{cargo_sandbox::bounded_bwrap, SandboxLimits};
8use serde::{Deserialize, Serialize};
9use std::fs;
10use std::path::{Path, PathBuf};
11use std::time::{Duration, Instant};
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
14pub enum GenerationState {
15 Staged,
16 Starting,
17 Ready,
18 CanaryActive,
19 Durable,
20 Reverting,
21 Reverted,
22}
23
24#[derive(Debug, Clone, Serialize, Deserialize)]
25pub struct GenerationInfo {
26 pub generation_id: String,
27 pub installed_path: PathBuf,
28 pub manifest_digest: String,
29 pub state: GenerationState,
30 pub pid: Option<u32>,
31 pub socket_path: Option<PathBuf>,
32 pub canary_transactions: u64,
33 pub canary_errors: u64,
34 pub max_latency_us: u64,
35 pub total_latency_us: u64,
36 pub staged_timestamp: String,
37}
38
39pub struct HostSupervisor {
40 pub active_symlink: PathBuf,
41 pub generations_root: PathBuf,
42 pub memory_limit_mb: u64,
43}
44
45impl HostSupervisor {
46 pub const DEFAULT_CANARY_QUOTA: u64 = 5_000;
47
48 pub fn new(rsi_root: &Path, memory_limit_mb: u64) -> Self {
49 Self {
50 active_symlink: rsi_root.join("active"),
51 generations_root: rsi_root.join("generations"),
52 memory_limit_mb,
53 }
54 }
55
56 pub fn stage_generation(
57 &self,
58 generation_id: &str,
59 source_dir: &Path,
60 manifest_digest: &str,
61 ) -> Result<GenerationInfo, String> {
62 let dest = self.generations_root.join(generation_id);
63 if dest.exists() {
64 fs::remove_dir_all(&dest).map_err(|e| e.to_string())?;
65 }
66 fs::create_dir_all(&dest).map_err(|e| e.to_string())?;
67
68 copy_dir_all(source_dir, &dest)?;
69
70 Ok(GenerationInfo {
71 generation_id: generation_id.to_string(),
72 installed_path: dest,
73 manifest_digest: manifest_digest.to_string(),
74 state: GenerationState::Staged,
75 pid: None,
76 socket_path: None,
77 canary_transactions: 0,
78 canary_errors: 0,
79 max_latency_us: 0,
80 total_latency_us: 0,
81 staged_timestamp: chrono::Utc::now().to_rfc3339(),
82 })
83 }
84
85 pub fn atomic_symlink_swap(&self, generation_id: &str) -> Result<(), String> {
86 let target_dir = self.generations_root.join(generation_id);
87 if !target_dir.exists() {
88 return Err(format!(
89 "Target generation directory does not exist: {:?}",
90 target_dir
91 ));
92 }
93
94 let parent = self
95 .active_symlink
96 .parent()
97 .ok_or_else(|| "No parent dir for active symlink".to_string())?;
98 fs::create_dir_all(parent).map_err(|e| e.to_string())?;
99
100 let tmp_link = parent.join(format!(".active.tmp.{}", uuid::Uuid::new_v4().simple()));
101 if tmp_link.exists() {
102 let _ = fs::remove_file(&tmp_link);
103 }
104
105 #[cfg(unix)]
106 std::os::unix::fs::symlink(&target_dir, &tmp_link)
107 .map_err(|e| format!("Failed to create temporary symlink: {}", e))?;
108
109 fs::rename(&tmp_link, &self.active_symlink)
110 .map_err(|e| format!("Failed atomic symlink swap: {}", e))?;
111
112 Ok(())
113 }
114
115 /// Launches the worker and returns its pid. The child handle is dropped, so the caller
116 /// cannot stop it; the canary executor uses [`Self::spawn_worker_process`] instead.
117 pub fn spawn_worker(
118 &self,
119 gen_info: &mut GenerationInfo,
120 executable: &Path,
121 args: &[&str],
122 socket_path: &Path,
123 ) -> Result<u32, String> {
124 self.spawn_worker_process(gen_info, executable, args, socket_path, &[])
125 .map(|child| child.id())
126 }
127
128 /// Launches the worker inside a fail-closed user, mount, PID and network namespace.
129 /// Only its executable, system runtime, private scratch and this one IPC socket are visible.
130 /// Readiness still requires the authenticated versioned handshake.
131 pub fn spawn_worker_process(
132 &self,
133 gen_info: &mut GenerationInfo,
134 executable: &Path,
135 args: &[&str],
136 socket_path: &Path,
137 env: &[(&str, &str)],
138 ) -> Result<std::process::Child, String> {
139 let executable = executable
140 .canonicalize()
141 .map_err(|e| format!("Cannot resolve worker executable: {}", e))?;
142 let socket = socket_path
143 .canonicalize()
144 .map_err(|e| format!("Cannot resolve worker socket: {}", e))?;
145 let worker_socket = Path::new("/ipc").join(
146 socket
147 .file_name()
148 .ok_or_else(|| "Worker socket has no filename".to_string())?,
149 );
150 let limits = SandboxLimits {
151 max_memory_mb: self.memory_limit_mb,
152 ..SandboxLimits::default()
153 };
154 let mut cmd = bounded_bwrap(&limits, None);
155 cmd.args([
156 "--unshare-user",
157 "--disable-userns",
158 "--assert-userns-disabled",
159 "--unshare-ipc",
160 "--unshare-pid",
161 "--unshare-net",
162 "--unshare-uts",
163 "--uid",
164 "65534",
165 "--gid",
166 "65534",
167 "--cap-drop",
168 "ALL",
169 "--new-session",
170 "--die-with-parent",
171 "--clearenv",
172 "--proc",
173 "/proc",
174 "--dev",
175 "/dev",
176 "--tmpfs",
177 "/tmp",
178 "--tmpfs",
179 "/scratch",
180 "--chdir",
181 "/scratch",
182 ]);
183 for runtime in ["/usr", "/lib", "/lib64", "/bin"] {
184 if Path::new(runtime).exists() {
185 cmd.args(["--ro-bind", runtime, runtime]);
186 }
187 }
188 cmd.arg("--ro-bind").arg(&executable).arg("/worker");
189 // Bind the endpoint, never its parent directory containing other supervisor sockets.
190 cmd.arg("--ro-bind").arg(&socket).arg(&worker_socket);
191 cmd.args(["--remount-ro", "/"]);
192 for (key, value) in worker_environment(env) {
193 cmd.args(["--setenv", &key, &value]);
194 }
195 cmd.arg("--")
196 .arg("/worker")
197 .args(args)
198 .arg("--socket")
199 .arg(&worker_socket);
200 cmd.stdin(std::process::Stdio::null());
201
202 let child = cmd
203 .spawn()
204 .map_err(|e| format!("Failed to spawn worker executable {:?}: {}", executable, e))?;
205
206 gen_info.pid = Some(child.id());
207 gen_info.socket_path = Some(socket_path.to_path_buf());
208 gen_info.state = GenerationState::Starting;
209
210 Ok(child)
211 }
212
213 pub fn switch_active_socket(
214 &self,
215 active_socket_link: &Path,
216 target_socket: &Path,
217 ) -> Result<(), String> {
218 let parent = active_socket_link
219 .parent()
220 .ok_or_else(|| "No parent directory for active socket link".to_string())?;
221 fs::create_dir_all(parent).map_err(|e| e.to_string())?;
222
223 let tmp_link = parent.join(format!(
224 ".active_sock.tmp.{}",
225 uuid::Uuid::new_v4().simple()
226 ));
227 if tmp_link.exists() {
228 let _ = fs::remove_file(&tmp_link);
229 }
230
231 #[cfg(unix)]
232 std::os::unix::fs::symlink(target_socket, &tmp_link)
233 .map_err(|e| format!("Failed to create temporary socket symlink: {}", e))?;
234
235 fs::rename(&tmp_link, active_socket_link)
236 .map_err(|e| format!("Failed atomic socket swap: {}", e))?;
237
238 Ok(())
239 }
240
241 pub fn drain_parent(&self, parent_pid: u32, timeout: Duration) -> Result<(), String> {
242 #[cfg(unix)]
243 unsafe {
244 // Signal graceful drain via SIGQUIT
245 libc::kill(parent_pid as i32, libc::SIGQUIT);
246 }
247
248 let start = Instant::now();
249 let poll_interval = Duration::from_millis(50);
250
251 while start.elapsed() < timeout {
252 #[cfg(unix)]
253 unsafe {
254 if libc::kill(parent_pid as i32, 0) != 0 {
255 return Ok(()); // Process exited cleanly
256 }
257 }
258 std::thread::sleep(poll_interval);
259 }
260
261 // Force kill if graceful drain exceeded timeout window
262 #[cfg(unix)]
263 unsafe {
264 libc::kill(parent_pid as i32, libc::SIGKILL);
265 }
266
267 Ok(())
268 }
269
270 /// Applies the early safety budgets to one worker self-report. The counters it keeps are
271 /// diagnostics: this function never returns `Durable`, however many reports arrive.
272 /// Whether a canary has enough evidence is decided only by the quota validator over a
273 /// sealed observation log.
274 pub fn record_canary_transaction(
275 &self,
276 gen_info: &mut GenerationInfo,
277 success: bool,
278 latency_us: u64,
279 max_latency_us: u64,
280 max_error_rate: f64,
281 ) -> Result<GenerationState, String> {
282 gen_info.canary_transactions += 1;
283 if !success {
284 gen_info.canary_errors += 1;
285 }
286 if latency_us > gen_info.max_latency_us {
287 gen_info.max_latency_us = latency_us;
288 }
289 gen_info.total_latency_us += latency_us;
290
291 // 1. Latency budget check
292 if max_latency_us > 0 && latency_us > max_latency_us {
293 gen_info.state = GenerationState::Reverting;
294 return Err(format!(
295 "Latency budget exceeded: {} us > {} us limit (transaction {})",
296 latency_us, max_latency_us, gen_info.canary_transactions
297 ));
298 }
299
300 // 2. Error budget check
301 let error_rate = gen_info.canary_errors as f64 / gen_info.canary_transactions as f64;
302 if error_rate > max_error_rate {
303 gen_info.state = GenerationState::Reverting;
304 return Err(format!(
305 "Error budget exceeded: {:.2}% errors ({}/{}) > {:.2}% limit",
306 error_rate * 100.0,
307 gen_info.canary_errors,
308 gen_info.canary_transactions,
309 max_error_rate * 100.0
310 ));
311 }
312
313 // 3. Resource budget check
314 // A failed read is not proof that memory is within budget: it reverts.
315 if let Some(pid) = gen_info.pid {
316 match self.is_memory_within_budget(pid) {
317 Ok(true) => {}
318 Ok(false) => {
319 gen_info.state = GenerationState::Reverting;
320 return Err(format!(
321 "Resource budget exceeded: PID {} exceeded {} MB limit",
322 pid, self.memory_limit_mb
323 ));
324 }
325 Err(read_err) => {
326 gen_info.state = GenerationState::Reverting;
327 return Err(format!(
328 "Resource budget unreadable for PID {}, reverting: {}",
329 pid, read_err
330 ));
331 }
332 }
333 }
334
335 gen_info.state = GenerationState::CanaryActive;
336 Ok(gen_info.state)
337 }
338
339 pub fn rollback_to_parent(
340 &self,
341 parent_generation_id: &str,
342 active_socket_link: Option<&Path>,
343 parent_socket: Option<&Path>,
344 ) -> Result<(), String> {
345 self.atomic_symlink_swap(parent_generation_id)?;
346
347 if let (Some(active_sock), Some(parent_sock)) = (active_socket_link, parent_socket) {
348 self.switch_active_socket(active_sock, parent_sock)?;
349 }
350
351 Ok(())
352 }
353
354 pub fn check_unified_memory_mb(pid: u32) -> Result<u64, String> {
355 let statm_path = format!("/proc/{}/statm", pid);
356 let content = fs::read_to_string(&statm_path)
357 .map_err(|e| format!("Failed to read statm for pid {}: {}", pid, e))?;
358
359 let parts: Vec<&str> = content.split_whitespace().collect();
360 if parts.len() < 2 {
361 return Err("Malformed statm output".to_string());
362 }
363
364 let resident_pages: u64 = parts[1]
365 .parse()
366 .map_err(|e| format!("Failed to parse resident pages: {}", e))?;
367
368 let page_size_kb = system_page_size_kb();
369 let rss_mb = (resident_pages * page_size_kb) / 1024;
370 Ok(rss_mb)
371 }
372
373 pub fn is_memory_within_budget(&self, pid: u32) -> Result<bool, String> {
374 // The tracked pid is the bubblewrap monitor. Account for the entire worker tree,
375 // including children forked by non-main threads, not just that small monitor.
376 let mut pending = vec![pid];
377 let mut total_mb = 0u64;
378 while let Some(current) = pending.pop() {
379 total_mb = total_mb
380 .checked_add(Self::check_unified_memory_mb(current)?)
381 .ok_or_else(|| "Worker memory accounting overflow".to_string())?;
382 if total_mb > self.memory_limit_mb {
383 return Ok(false);
384 }
385 let tasks = fs::read_dir(format!("/proc/{}/task", current))
386 .map_err(|e| format!("Cannot read worker tasks: {}", e))?;
387 for task in tasks {
388 let task = task.map_err(|e| e.to_string())?;
389 let children = fs::read_to_string(task.path().join("children"))
390 .map_err(|e| format!("Cannot read worker descendants: {}", e))?;
391 for child in children.split_whitespace() {
392 pending.push(
393 child
394 .parse::<u32>()
395 .map_err(|e| format!("Invalid worker child pid: {}", e))?,
396 );
397 }
398 }
399 }
400 Ok(true)
401 }
402}
403
404/// Locale and diagnostic variables a worker may inherit. Home and executable search paths
405/// are private sandbox values, never operator-controlled host directories.
406pub const WORKER_ENV_PASSTHROUGH: &[&str] = &["LANG", "LC_ALL", "RUST_BACKTRACE"];
407/// The variable namespace reserved for canary workers (fixture behaviour switches live here).
408pub const WORKER_ENV_PREFIX: &str = "RSI_CANARY_";
409
410/// The environment a worker is launched with: the passthrough allowlist and the canary
411/// namespace from this process, then `extra`. A later entry overrides an earlier one.
412pub fn worker_environment(extra: &[(&str, &str)]) -> Vec<(String, String)> {
413 let mut env: Vec<(String, String)> = std::env::vars()
414 .filter(|(key, _)| {
415 WORKER_ENV_PASSTHROUGH.contains(&key.as_str()) || key.starts_with(WORKER_ENV_PREFIX)
416 })
417 .collect();
418 for (key, value) in extra {
419 env.push((key.to_string(), value.to_string()));
420 }
421 for (key, value) in [
422 ("PATH", "/usr/bin:/bin"),
423 ("HOME", "/tmp"),
424 ("TMPDIR", "/tmp"),
425 ] {
426 env.push((key.to_string(), value.to_string()));
427 }
428 env
429}
430
431fn copy_dir_all(src: &Path, dst: &Path) -> Result<(), String> {
432 if !dst.exists() {
433 fs::create_dir_all(dst).map_err(|e| e.to_string())?;
434 }
435 for entry in fs::read_dir(src).map_err(|e| e.to_string())?.flatten() {
436 let path = entry.path();
437 let dest = dst.join(entry.file_name());
438 if path.is_dir() {
439 copy_dir_all(&path, &dest)?;
440 } else {
441 fs::copy(&path, &dest).map_err(|e| e.to_string())?;
442 }
443 }
444 Ok(())
445}
446
447#[cfg(test)]
448mod tests {
449 use super::*;
450
451 #[test]
452 fn test_stage_and_atomic_symlink_swap() {
453 let tmp = tempfile::tempdir().unwrap();
454 let rsi_root = tmp.path().join(".rsi");
455 let src = tmp.path().join("src_art");
456 fs::create_dir_all(&src).unwrap();
457 fs::write(src.join("bin"), "generation binary v1").unwrap();
458
459 let supervisor = HostSupervisor::new(&rsi_root, 49152);
460 let gen_info = supervisor
461 .stage_generation("gen-001", &src, "manifest-sha-001")
462 .unwrap();
463
464 assert_eq!(gen_info.state, GenerationState::Staged);
465 assert!(gen_info.installed_path.exists());
466
467 supervisor.atomic_symlink_swap("gen-001").unwrap();
468 assert!(supervisor.active_symlink.exists());
469
470 let content = fs::read_to_string(supervisor.active_symlink.join("bin")).unwrap();
471 assert_eq!(content, "generation binary v1");
472
473 // Stage and swap to gen-002
474 let src2 = tmp.path().join("src_art2");
475 fs::create_dir_all(&src2).unwrap();
476 fs::write(src2.join("bin"), "generation binary v2").unwrap();
477
478 supervisor
479 .stage_generation("gen-002", &src2, "manifest-sha-002")
480 .unwrap();
481 supervisor.atomic_symlink_swap("gen-002").unwrap();
482
483 let content2 = fs::read_to_string(supervisor.active_symlink.join("bin")).unwrap();
484 assert_eq!(content2, "generation binary v2");
485
486 // Rollback swap to gen-001
487 supervisor.atomic_symlink_swap("gen-001").unwrap();
488 let content_rollback = fs::read_to_string(supervisor.active_symlink.join("bin")).unwrap();
489 assert_eq!(content_rollback, "generation binary v1");
490 }
491
492 #[test]
493 fn test_memory_budget_check_own_pid() {
494 let pid = std::process::id();
495 let tmp = tempfile::tempdir().unwrap();
496 let supervisor = HostSupervisor::new(tmp.path(), 49152);
497
498 let within_budget = supervisor.is_memory_within_budget(pid).unwrap();
499 assert!(within_budget);
500 }
501
502 #[test]
503 fn test_socket_switch_and_self_reports_never_promote() {
504 let tmp = tempfile::tempdir().unwrap();
505 let rsi_root = tmp.path().join(".rsi");
506 let supervisor = HostSupervisor::new(&rsi_root, 49152);
507
508 let active_sock = tmp.path().join("active.sock");
509 let target_sock = tmp.path().join("gen2.sock");
510 fs::write(&target_sock, "socket stub").unwrap();
511
512 supervisor
513 .switch_active_socket(&active_sock, &target_sock)
514 .unwrap();
515 assert!(active_sock.exists());
516
517 let src = tmp.path().join("src_art");
518 fs::create_dir_all(&src).unwrap();
519 let mut gen = supervisor
520 .stage_generation("gen-canary", &src, "digest")
521 .unwrap();
522 gen.state = GenerationState::Ready;
523
524 // Any number of clean self-reports leaves the generation on probation. Counters never
525 // promote: only a sealed observation log through the quota validator can.
526 for _ in 0..50 {
527 let state = supervisor
528 .record_canary_transaction(&mut gen, true, 1000, 1_000_000, 0.0)
529 .unwrap();
530 assert_eq!(state, GenerationState::CanaryActive);
531 }
532 assert_eq!(gen.state, GenerationState::CanaryActive);
533 assert_eq!(gen.canary_transactions, 50);
534
535 // Failure during canary triggers Reverting
536 assert!(supervisor
537 .record_canary_transaction(&mut gen, false, 1000, 1_000_000, 0.0)
538 .is_err());
539 assert_eq!(gen.state, GenerationState::Reverting);
540 }
541
542 #[test]
543 fn worker_environment_passes_only_the_allowlist_and_the_canary_namespace() {
544 std::env::set_var("RSI_CANARY_TEST_MODE", "probe");
545 std::env::set_var("RSI_SECRET_FOR_TEST", "must-not-cross");
546 let env = worker_environment(&[("SUPERVISOR_SECRET", "run-secret")]);
547 std::env::remove_var("RSI_CANARY_TEST_MODE");
548 std::env::remove_var("RSI_SECRET_FOR_TEST");
549 let get = |k: &str| {
550 env.iter()
551 .rev()
552 .find(|(key, _)| key == k)
553 .map(|(_, v)| v.clone())
554 };
555 assert_eq!(get("RSI_CANARY_TEST_MODE").as_deref(), Some("probe"));
556 assert_eq!(get("SUPERVISOR_SECRET").as_deref(), Some("run-secret"));
557 assert!(get("RSI_SECRET_FOR_TEST").is_none());
558 assert!(env.iter().all(|(k, _)| {
559 WORKER_ENV_PASSTHROUGH.contains(&k.as_str())
560 || k.starts_with(WORKER_ENV_PREFIX)
561 || ["SUPERVISOR_SECRET", "PATH", "HOME", "TMPDIR"].contains(&k.as_str())
562 }));
563 }
564
565 #[test]
566 fn test_unreadable_memory_budget_reverts_instead_of_passing() {
567 let tmp = tempfile::tempdir().unwrap();
568 let supervisor = HostSupervisor::new(&tmp.path().join(".rsi"), 49152);
569 let src = tmp.path().join("src_art");
570 fs::create_dir_all(&src).unwrap();
571 let mut gen = supervisor
572 .stage_generation("gen-canary", &src, "digest")
573 .unwrap();
574 // No process has this pid, so the resource read fails.
575 gen.pid = Some(u32::MAX - 1);
576 let err = supervisor
577 .record_canary_transaction(&mut gen, true, 1000, 1_000_000, 0.0)
578 .unwrap_err();
579 assert!(err.contains("unreadable"), "{}", err);
580 assert_eq!(gen.state, GenerationState::Reverting);
581 }
582
583 #[test]
584 fn test_memory_over_limit_reverts() {
585 let tmp = tempfile::tempdir().unwrap();
586 // A one MB limit is below any live process.
587 let supervisor = HostSupervisor::new(&tmp.path().join(".rsi"), 1);
588 let src = tmp.path().join("src_art");
589 fs::create_dir_all(&src).unwrap();
590 let mut gen = supervisor
591 .stage_generation("gen-canary", &src, "digest")
592 .unwrap();
593 gen.pid = Some(std::process::id());
594 let err = supervisor
595 .record_canary_transaction(&mut gen, true, 1000, 1_000_000, 0.0)
596 .unwrap_err();
597 assert!(err.contains("Resource budget exceeded"), "{}", err);
598 assert_eq!(gen.state, GenerationState::Reverting);
599 }
600}