//! Named filesystem and subprocess boundaries for isolated Emacs task execution. use std::{ env, fs::{self, File}, io::{Read, Write}, path::{Path, PathBuf}, process::{Child, Command, Stdio}, sync::atomic::{AtomicBool, Ordering}, thread, time::{Duration, Instant}, }; use sha2::{Digest, Sha256}; use super::{RunnerOptions, TaskBenchmarkError}; /// Maximum child diagnostic bytes retained before terminating runaway output. const MAX_DIAGNOSTIC_BYTES: u64 = 64 * 1024; /// Maximum complete fixture or result bytes accepted by the adapter. pub(super) const MAX_DOCUMENT_BYTES: u64 = 8 * 1024 * 1024; /// Stop work at an explicit cooperative boundary. pub(super) fn check_cancelled(cancelled: &AtomicBool) -> Result<(), TaskBenchmarkError> { if cancelled.load(Ordering::Acquire) { Err(TaskBenchmarkError::Cancelled) } else { Ok(()) } } /// Hash one exact byte sequence using the publication manifest's digest format. pub(super) fn digest(bytes: &[u8]) -> String { format!("{:x}", Sha256::digest(bytes)) } /// Hash a file without allocating a second complete model or executable image. pub(super) fn file_digest(path: &Path) -> Result { let mut source = File::open(path)?; let mut digest = Sha256::new(); let mut buffer = [0_u8; 32 * 1024]; loop { let read = source.read(&mut buffer)?; if read == 0 { break; } let bytes = buffer .get(..read) .ok_or(TaskBenchmarkError::Invalid("invalid file read length"))?; digest.update(bytes); } Ok(format!("{:x}", digest.finalize())) } /// Read a bounded document and reject a file growing past the byte limit. pub(super) fn read_document(path: &Path) -> Result, TaskBenchmarkError> { let mut bytes = Vec::new(); File::open(path)? .take(MAX_DOCUMENT_BYTES + 1) .read_to_end(&mut bytes)?; if u64::try_from(bytes.len()).map_err(|_| TaskBenchmarkError::OutputLimit)? > MAX_DOCUMENT_BYTES { return Err(TaskBenchmarkError::OutputLimit); } Ok(bytes) } /// Resolve one explicit executable without a shell or command-string interpretation. pub(super) fn executable(path: &Path) -> Result { if path.is_absolute() || path.components().count() > 1 { return Ok(fs::canonicalize(path)?); } if let Some(paths) = env::var_os("PATH") { for directory in env::split_paths(&paths) { let candidate = directory.join(path); if candidate.is_file() { return Ok(fs::canonicalize(candidate)?); } } } Err(TaskBenchmarkError::EmacsNotFound(path.to_path_buf())) } /// Ensure every error and cancellation path terminates and reaps the child. struct ChildGuard { /// Sole ownership of the subprocess handle. child: Child, /// A successful wait already reaped the child. finished: bool, } impl Drop for ChildGuard { fn drop(&mut self) { if !self.finished { let _ = self.child.kill(); let _ = self.child.wait(); } } } /// Reject a child that writes unbounded diagnostics or a result of excessive size. fn bounded_outputs(diagnostic: &Path, output: &Path) -> Result<(), TaskBenchmarkError> { for (path, limit) in [ (diagnostic, MAX_DIAGNOSTIC_BYTES), (output, MAX_DOCUMENT_BYTES), ] { match fs::metadata(path) { Ok(metadata) if metadata.len() > limit => { return Err(TaskBenchmarkError::OutputLimit); } Ok(_) => {} Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} Err(error) => return Err(error.into()), } } Ok(()) } /// Wait in short cancellable intervals and return a bounded diagnostic on failure. fn wait_for_runner( child: Child, options: &RunnerOptions, diagnostic: &Path, output: &Path, cancelled: &AtomicBool, ) -> Result<(), TaskBenchmarkError> { let mut child = ChildGuard { child, finished: false, }; let started = Instant::now(); loop { check_cancelled(cancelled)?; bounded_outputs(diagnostic, output)?; if let Some(status) = child.child.try_wait()? { child.finished = true; if status.success() { return Ok(()); } let mut bytes = Vec::new(); File::open(diagnostic)? .take(MAX_DIAGNOSTIC_BYTES) .read_to_end(&mut bytes)?; return Err(TaskBenchmarkError::RunnerFailed(format!( "{status}: {}", String::from_utf8_lossy(&bytes) ))); } if started.elapsed() >= Duration::from_secs(options.timeout_seconds) { return Err(TaskBenchmarkError::Timeout(options.timeout_seconds)); } thread::sleep(Duration::from_millis(20)); } } /// Run reviewed source bytes in a clean batch process and private working directory. /// /// This isolates fixture effects from the user's Emacs process. It is not an OS /// sandbox: the reviewed Lisp runner must enforce its bounded action/path rules. pub(super) fn run( executable: &Path, runner: &[u8], request: &[u8], options: &RunnerOptions, cancelled: &AtomicBool, ) -> Result, TaskBenchmarkError> { check_cancelled(cancelled)?; if options.timeout_seconds == 0 || options.timeout_seconds > 3600 { return Err(TaskBenchmarkError::Invalid( "runner timeout must be 1..=3600 seconds", )); } let scratch = tempfile::Builder::new().prefix("lispm-task-").tempdir()?; let source = scratch.path().join("runner.el"); let input = scratch.path().join("request.json"); let output = scratch.path().join("report.json"); let diagnostic = scratch.path().join("stderr.log"); fs::write(&source, runner)?; fs::write(&input, request)?; let errors = File::create(&diagnostic)?; let child = Command::new(executable) .args(["-Q", "--batch", "-l"]) .arg(&source) .args(["-f", "lispm-llm-benchmark-batch"]) .arg(&input) .arg(&output) .current_dir(scratch.path()) .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::from(errors)) .spawn()?; wait_for_runner(child, options, &diagnostic, &output, cancelled)?; check_cancelled(cancelled)?; read_document(&output) } /// Publish a report to a previously nonexistent path after complete serialization. pub fn write_report(path: &Path, value: &impl serde::Serialize) -> Result<(), TaskBenchmarkError> { let bytes = serde_json::to_vec_pretty(value)?; let parent = path .parent() .filter(|path| !path.as_os_str().is_empty()) .unwrap_or(Path::new(".")); let mut temporary = tempfile::NamedTempFile::new_in(parent)?; temporary.write_all(&bytes)?; temporary.write_all(b"\n")?; temporary.as_file().sync_all()?; temporary .persist_noclobber(path) .map_err(|error| error.error)?; Ok(()) }