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

567 lines · 20186 bytes Raw Blame History
1use std::path::{Path, PathBuf};
2use std::process::Command;
3
4use super::cargo_sandbox::{bounded_bwrap, Toolchain};
5
6/// The jail PATH after the toolchain bin directories.
7const JAIL_PATH_TAIL: &[&str] = &["/usr/local/cuda/bin", "/usr/local/bin", "/usr/bin", "/bin"];
8
9/// Binds the host toolchain read-only at its own path and points `RUSTUP_HOME` / `CARGO_HOME`
10/// at it, wherever it lives (see [`Toolchain`]).
11fn push_toolchain(args: &mut Vec<String>, toolchain: &Toolchain) {
12 for d in toolchain.bind_dirs() {
13 let d = d.display().to_string();
14 args.push("--ro-bind".to_string());
15 args.push(d.clone());
16 args.push(d);
17 }
18 for (k, d) in toolchain.env() {
19 args.push("--setenv".to_string());
20 args.push(k.to_string());
21 args.push(d.display().to_string());
22 }
23}
24
25#[derive(Debug, Clone)]
26pub struct SandboxLimits {
27 pub max_memory_mb: u64,
28 pub max_cpu_percent: u32,
29 pub max_pids: u32,
30 pub timeout_seconds: u64,
31}
32
33impl Default for SandboxLimits {
34 fn default() -> Self {
35 Self {
36 max_memory_mb: 16384,
37 max_cpu_percent: 800,
38 max_pids: 256,
39 timeout_seconds: 180,
40 }
41 }
42}
43
44impl SandboxLimits {
45 pub fn new(
46 max_memory_mb: u64,
47 max_cpu_percent: u32,
48 max_pids: u32,
49 timeout_seconds: u64,
50 ) -> Self {
51 Self {
52 max_memory_mb,
53 max_cpu_percent,
54 max_pids,
55 timeout_seconds,
56 }
57 }
58}
59
60fn execute_with_timeout(
61 mut cmd: Command,
62 timeout_secs: u64,
63) -> Result<(bool, String, String), String> {
64 use std::io::Read;
65 use std::time::{Duration, Instant};
66
67 let mut child = cmd
68 .stdout(std::process::Stdio::piped())
69 .stderr(std::process::Stdio::piped())
70 .spawn()
71 .map_err(|e| format!("Failed to spawn process: {}", e))?;
72
73 let start = Instant::now();
74 let timeout = Duration::from_secs(timeout_secs);
75 let mut poll_interval = Duration::from_micros(100);
76
77 loop {
78 match child.try_wait() {
79 Ok(Some(status)) => {
80 let mut stdout = String::new();
81 let mut stderr = String::new();
82 if let Some(mut out) = child.stdout.take() {
83 let _ = out.read_to_string(&mut stdout);
84 }
85 if let Some(mut err) = child.stderr.take() {
86 let _ = err.read_to_string(&mut stderr);
87 }
88 return Ok((status.success(), stdout, stderr));
89 }
90 Ok(None) => {
91 let elapsed = start.elapsed();
92 if elapsed >= timeout {
93 let _ = child.kill();
94 let _ = child.wait();
95 return Err(format!("Process timed out after {} seconds", timeout_secs));
96 }
97 if elapsed > Duration::from_millis(50) && poll_interval < Duration::from_millis(1) {
98 poll_interval = Duration::from_millis(1);
99 } else if elapsed > Duration::from_millis(500) {
100 poll_interval = Duration::from_millis(5);
101 }
102 std::thread::sleep(poll_interval);
103 }
104 Err(e) => {
105 let _ = child.kill();
106 return Err(format!("Error waiting on child process: {}", e));
107 }
108 }
109 }
110}
111
112#[derive(Debug, Clone)]
113pub struct BuildJail {
114 pub builder_image: String,
115 pub host_source_dir: PathBuf,
116 pub host_output_dir: PathBuf,
117 pub limits: SandboxLimits,
118}
119
120impl BuildJail {
121 pub fn new(builder_image: &str, host_source: &Path, host_output: &Path) -> Self {
122 Self {
123 builder_image: builder_image.to_string(),
124 host_source_dir: host_source.to_path_buf(),
125 host_output_dir: host_output.to_path_buf(),
126 limits: SandboxLimits::default(),
127 }
128 }
129
130 pub fn build_docker_args(&self, command: &[&str]) -> Vec<String> {
131 let uid = unsafe { libc::getuid() }.to_string();
132 let gid = unsafe { libc::getgid() }.to_string();
133
134 let mut args = vec![
135 "run".to_string(),
136 "--rm".to_string(),
137 "--network".to_string(),
138 "none".to_string(),
139 "--read-only".to_string(),
140 "--cap-drop".to_string(),
141 "ALL".to_string(),
142 "--security-opt".to_string(),
143 "no-new-privileges".to_string(),
144 "--memory".to_string(),
145 format!("{}m", self.limits.max_memory_mb),
146 "--cpus".to_string(),
147 format!("{:.2}", self.limits.max_cpu_percent as f64 / 100.0),
148 "--pids-limit".to_string(),
149 self.limits.max_pids.to_string(),
150 "-u".to_string(),
151 format!("{}:{}", uid, gid),
152 "-v".to_string(),
153 format!("{}:/workspace/src:ro", self.host_source_dir.display()),
154 "-v".to_string(),
155 format!("{}:/output:rw", self.host_output_dir.display()),
156 "--tmpfs".to_string(),
157 "/tmp:rw,size=4G,mode=1777".to_string(),
158 "--tmpfs".to_string(),
159 "/build:rw,size=8G,mode=1777".to_string(),
160 "-w".to_string(),
161 "/build".to_string(),
162 self.builder_image.clone(),
163 ];
164
165 for c in command {
166 args.push(c.to_string());
167 }
168
169 args
170 }
171
172 pub fn build_bwrap_args(&self, command: &[&str]) -> Vec<String> {
173 let mut args = vec![
174 "--unshare-user".to_string(),
175 "--unshare-ipc".to_string(),
176 "--unshare-pid".to_string(),
177 "--unshare-net".to_string(),
178 "--unshare-uts".to_string(),
179 "--die-with-parent".to_string(),
180 "--clearenv".to_string(),
181 "--ro-bind".to_string(),
182 "/usr".to_string(),
183 "/usr".to_string(),
184 "--ro-bind".to_string(),
185 "/lib".to_string(),
186 "/lib".to_string(),
187 "--proc".to_string(),
188 "/proc".to_string(),
189 "--dev".to_string(),
190 "/dev".to_string(),
191 "--tmpfs".to_string(),
192 "/tmp".to_string(),
193 "--ro-bind".to_string(),
194 self.host_source_dir.display().to_string(),
195 "/workspace/src".to_string(),
196 "--bind".to_string(),
197 self.host_output_dir.display().to_string(),
198 "/output".to_string(),
199 "--chdir".to_string(),
200 "/workspace/src".to_string(),
201 ];
202
203 if Path::new("/lib64").exists() {
204 args.push("--ro-bind".to_string());
205 args.push("/lib64".to_string());
206 args.push("/lib64".to_string());
207 }
208 if Path::new("/bin").exists() {
209 args.push("--ro-bind".to_string());
210 args.push("/bin".to_string());
211 args.push("/bin".to_string());
212 }
213 if Path::new("/etc").exists() {
214 args.push("--ro-bind".to_string());
215 args.push("/etc".to_string());
216 args.push("/etc".to_string());
217 }
218 // Resolve the host toolchain before the launcher drops its inherited environment.
219 // The only writable build output is this jail's caller-provided output directory.
220 let toolchain = Toolchain::from_env();
221 push_toolchain(&mut args, &toolchain);
222 args.push("--setenv".to_string());
223 args.push("CARGO_TARGET_DIR".to_string());
224 args.push("/output/target".to_string());
225
226 args.push("--setenv".to_string());
227 args.push("PATH".to_string());
228 args.push(toolchain.jail_path(JAIL_PATH_TAIL));
229 args.push("--setenv".to_string());
230 args.push("HOME".to_string());
231 args.push("/tmp".to_string());
232 args.push("--setenv".to_string());
233 args.push("CARGO_BUILD_JOBS".to_string());
234 args.push("2".to_string());
235
236 for c in command {
237 args.push(c.to_string());
238 }
239
240 args
241 }
242
243 pub fn execute(&self, command: &[&str]) -> Result<(bool, String, String), String> {
244 let args = self.build_docker_args(command);
245 let mut cmd = Command::new("docker");
246 cmd.args(&args);
247 execute_with_timeout(cmd, self.limits.timeout_seconds)
248 }
249
250 pub fn execute_bwrap(&self, command: &[&str]) -> Result<(bool, String, String), String> {
251 // A writable alias of the source would defeat its read-only bind.
252 let source = self
253 .host_source_dir
254 .canonicalize()
255 .map_err(|e| format!("cannot resolve build source: {e}"))?;
256 let output = self
257 .host_output_dir
258 .canonicalize()
259 .map_err(|e| format!("cannot resolve build output: {e}"))?;
260 if source.starts_with(&output) || output.starts_with(&source) {
261 return Err("build source and output must be separate directories".to_string());
262 }
263 let args = self.build_bwrap_args(command);
264 let mut cmd = bounded_bwrap(&self.limits, Some(self.limits.timeout_seconds));
265 cmd.args(&args);
266 // No retry without the network namespace: the jailed program controls its own stderr, so
267 // an error-string fallback would let it ask for the network.
268 execute_with_timeout(cmd, self.limits.timeout_seconds)
269 }
270}
271
272#[derive(Debug, Clone)]
273pub struct GpuEvaluationJail {
274 pub eval_image: String,
275 pub host_artifact_dir: PathBuf,
276 pub cdi_device: String,
277 pub limits: SandboxLimits,
278}
279
280impl GpuEvaluationJail {
281 pub fn new(eval_image: &str, artifact_dir: &Path) -> Self {
282 Self {
283 eval_image: eval_image.to_string(),
284 host_artifact_dir: artifact_dir.to_path_buf(),
285 cdi_device: "nvidia.com/gpu=0".to_string(),
286 limits: SandboxLimits::new(49152, 800, 256, 300), // 48 GB limit, 300s timeout
287 }
288 }
289
290 pub fn build_docker_args(&self, command: &[&str]) -> Vec<String> {
291 let uid = unsafe { libc::getuid() }.to_string();
292 let gid = unsafe { libc::getgid() }.to_string();
293
294 let mut args = vec![
295 "run".to_string(),
296 "--rm".to_string(),
297 "--network".to_string(),
298 "none".to_string(),
299 "--device".to_string(),
300 self.cdi_device.clone(),
301 "--read-only".to_string(),
302 "--cap-drop".to_string(),
303 "ALL".to_string(),
304 "--security-opt".to_string(),
305 "no-new-privileges".to_string(),
306 "--memory".to_string(),
307 format!("{}m", self.limits.max_memory_mb),
308 "--cpus".to_string(),
309 format!("{:.2}", self.limits.max_cpu_percent as f64 / 100.0),
310 "--pids-limit".to_string(),
311 self.limits.max_pids.to_string(),
312 "-u".to_string(),
313 format!("{}:{}", uid, gid),
314 "-v".to_string(),
315 format!("{}:/artifacts:ro", self.host_artifact_dir.display()),
316 "--tmpfs".to_string(),
317 "/tmp:rw,size=4G,mode=1777".to_string(),
318 "-w".to_string(),
319 "/artifacts".to_string(),
320 self.eval_image.clone(),
321 ];
322
323 for c in command {
324 args.push(c.to_string());
325 }
326
327 args
328 }
329
330 pub fn execute(&self, command: &[&str]) -> Result<(bool, String, String), String> {
331 let args = self.build_docker_args(command);
332 let mut cmd = Command::new("docker");
333 cmd.args(&args);
334 execute_with_timeout(cmd, self.limits.timeout_seconds)
335 }
336}
337
338#[derive(Debug, Clone)]
339pub struct CandidateJailRunner {
340 pub candidate_bin: PathBuf,
341 pub working_dir: Option<PathBuf>,
342 pub limits: SandboxLimits,
343}
344
345impl CandidateJailRunner {
346 pub fn new(candidate_bin: &Path) -> Self {
347 Self {
348 candidate_bin: candidate_bin.to_path_buf(),
349 working_dir: None,
350 limits: SandboxLimits::new(49152, 800, 256, 30),
351 }
352 }
353
354 pub fn with_working_dir(mut self, dir: &Path) -> Self {
355 self.working_dir = Some(dir.to_path_buf());
356 self
357 }
358
359 pub fn with_timeout_seconds(mut self, timeout_seconds: u64) -> Self {
360 self.limits.timeout_seconds = timeout_seconds;
361 self
362 }
363
364 pub fn build_bwrap_args(&self, command_args: &[&str]) -> Vec<String> {
365 let mut args = vec![
366 "--unshare-user".to_string(),
367 "--unshare-ipc".to_string(),
368 "--unshare-pid".to_string(),
369 "--unshare-net".to_string(),
370 "--unshare-uts".to_string(),
371 "--die-with-parent".to_string(),
372 // The candidate never sees the judge's environment (a key passed by variable included).
373 "--clearenv".to_string(),
374 "--ro-bind".to_string(),
375 "/usr".to_string(),
376 "/usr".to_string(),
377 "--ro-bind".to_string(),
378 "/lib".to_string(),
379 "/lib".to_string(),
380 "--proc".to_string(),
381 "/proc".to_string(),
382 "--dev".to_string(),
383 "/dev".to_string(),
384 "--tmpfs".to_string(),
385 "/tmp".to_string(),
386 ];
387
388 if Path::new("/lib64").exists() {
389 args.push("--ro-bind".to_string());
390 args.push("/lib64".to_string());
391 args.push("/lib64".to_string());
392 }
393 if Path::new("/bin").exists() {
394 args.push("--ro-bind".to_string());
395 args.push("/bin".to_string());
396 args.push("/bin".to_string());
397 }
398 if Path::new("/etc").exists() {
399 args.push("--ro-bind".to_string());
400 args.push("/etc".to_string());
401 args.push("/etc".to_string());
402 }
403 let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string());
404 let toolchain = Toolchain::from_env();
405 push_toolchain(&mut args, &toolchain);
406
407 let bin_dir = self
408 .candidate_bin
409 .parent()
410 .unwrap_or_else(|| Path::new("/"));
411 args.push("--ro-bind".to_string());
412 args.push(bin_dir.display().to_string());
413 args.push("/app".to_string());
414
415 let bin_name = self
416 .candidate_bin
417 .file_name()
418 .and_then(|n| n.to_str())
419 .unwrap_or("candidate");
420 let in_jail_bin = format!("/app/{}", bin_name);
421
422 if let Some(ref work) = self.working_dir {
423 args.push("--bind".to_string());
424 args.push(work.display().to_string());
425 args.push("/workspace".to_string());
426 args.push("--chdir".to_string());
427 args.push("/workspace".to_string());
428 } else {
429 args.push("--chdir".to_string());
430 args.push("/tmp".to_string());
431 }
432
433 args.push("--setenv".to_string());
434 args.push("PATH".to_string());
435 args.push(toolchain.jail_path(JAIL_PATH_TAIL));
436 args.push("--setenv".to_string());
437 args.push("HOME".to_string());
438 args.push(home.clone());
439
440 args.push(in_jail_bin);
441 for arg in command_args {
442 args.push(arg.to_string());
443 }
444
445 args
446 }
447
448 pub fn execute(&self, command_args: &[&str]) -> Result<(bool, String, String), String> {
449 let args = self.build_bwrap_args(command_args);
450 let mut cmd = Command::new("bwrap");
451 cmd.args(&args);
452 // No retry without the network namespace: the jailed program controls its own stderr, so
453 // an error-string fallback would let it ask for the network.
454 execute_with_timeout(cmd, self.limits.timeout_seconds)
455 }
456}
457
458#[cfg(test)]
459mod tests {
460 use super::*;
461
462 #[test]
463 fn test_build_jail_docker_args() {
464 let jail = BuildJail::new(
465 "spark-rsi-builder@sha256:123456",
466 Path::new("/tmp/src"),
467 Path::new("/tmp/out"),
468 );
469 let args = jail.build_docker_args(&["cargo", "build", "--offline"]);
470
471 assert!(args.contains(&"--network".to_string()));
472 assert!(args.contains(&"none".to_string()));
473 assert!(args.contains(&"--read-only".to_string()));
474 assert!(args.contains(&"--cap-drop".to_string()));
475 assert!(args.contains(&"ALL".to_string()));
476 assert!(args.contains(&"--pids-limit".to_string()));
477 assert!(args.contains(&"/tmp/src:/workspace/src:ro".to_string()));
478 assert!(args.contains(&"/tmp/out:/output:rw".to_string()));
479 assert!(args.contains(&"cargo".to_string()));
480 }
481
482 #[test]
483 fn test_build_jail_bwrap_args() {
484 let jail = BuildJail::new(
485 "spark-rsi-builder@sha256:123456",
486 Path::new("/tmp/src"),
487 Path::new("/tmp/out"),
488 );
489 let args = jail.build_bwrap_args(&["cargo", "build"]);
490
491 assert!(args.contains(&"--unshare-net".to_string()));
492 assert!(args.contains(&"--die-with-parent".to_string()));
493 assert!(args.contains(&"/output".to_string()));
494 assert!(args.contains(&"cargo".to_string()));
495 assert!(args.contains(&"--clearenv".to_string()));
496 let clear = args.iter().position(|arg| arg == "--clearenv").unwrap();
497 let set = args.iter().position(|arg| arg == "--setenv").unwrap();
498 assert!(clear < set);
499 assert!(args
500 .windows(3)
501 .any(|w| w == ["--ro-bind", "/tmp/src", "/workspace/src"]));
502 assert!(args
503 .windows(3)
504 .any(|w| w == ["--bind", "/tmp/out", "/output"]));
505 assert!(args.windows(2).any(|w| w == ["--chdir", "/workspace/src"]));
506 assert!(args.windows(3).any(|w| w == ["--setenv", "HOME", "/tmp"]));
507 assert!(args
508 .windows(3)
509 .any(|w| w == ["--setenv", "CARGO_TARGET_DIR", "/output/target"]));
510 assert!(args
511 .windows(3)
512 .any(|w| w == ["--setenv", "CARGO_BUILD_JOBS", "2"]));
513 assert!(!args.iter().any(|arg| arg.contains("/tmp/spark-rsi-target")));
514 // The toolchain the host resolves is bound read-only at its own path and named by its
515 // variables, wherever it lives.
516 let toolchain = Toolchain::from_env();
517 for d in toolchain.bind_dirs() {
518 let d = d.display().to_string();
519 assert!(
520 args.windows(3)
521 .any(|w| w[0] == "--ro-bind" && w[1] == d && w[2] == d),
522 "toolchain dir {} not bound",
523 d
524 );
525 }
526 for (k, d) in toolchain.env() {
527 let d = d.display().to_string();
528 assert!(args
529 .windows(3)
530 .any(|w| w[0] == "--setenv" && w[1] == k && w[2] == d));
531 }
532 }
533
534 #[test]
535 fn test_build_jail_refuses_writable_source_alias() {
536 let root = tempfile::tempdir().unwrap();
537 let source = root.path().join("source");
538 let output = source.join("output");
539 std::fs::create_dir_all(&output).unwrap();
540 let jail = BuildJail::new("unused", &source, &output);
541 let refusal = jail.execute_bwrap(&["cargo", "build"]).unwrap_err();
542 assert!(refusal.contains("separate directories"));
543 }
544
545 #[test]
546 fn test_gpu_eval_jail_args_network_none_and_no_holdouts() {
547 let jail = GpuEvaluationJail::new("spark-rsi-eval@sha256:abcdef", Path::new("/tmp/art"));
548 let args = jail.build_docker_args(&["./bench_suite", "--iterations", "30"]);
549
550 assert!(args.contains(&"--network".to_string()));
551 assert!(args.contains(&"none".to_string()));
552 assert!(args.contains(&"--device".to_string()));
553 assert!(args.contains(&"nvidia.com/gpu=0".to_string()));
554 assert!(args.contains(&"--pids-limit".to_string()));
555 assert!(args.contains(&"256".to_string()));
556 assert!(args.contains(&"/tmp/art:/artifacts:ro".to_string()));
557 // CRITICAL INVARIANT: Candidate jail must NEVER mount holdouts
558 for arg in &args {
559 assert!(
560 !arg.contains("holdout"),
561 "Candidate jail mounted holdout path: {}",
562 arg
563 );
564 }
565 assert!(args.contains(&"30".to_string()));
566 }
567}