Skip to main content

stackless_core/
helper_command.rs

1//! Privileged CLI calls whose deadline and capture survive the calling controller.
2
3use std::collections::BTreeMap;
4use std::ffi::{OsStr, OsString};
5use std::io::{BufRead, Read, Write};
6use std::os::unix::ffi::{OsStrExt, OsStringExt};
7use std::os::unix::process::{CommandExt, ExitStatusExt};
8use std::path::{Path, PathBuf};
9use std::process::{Command, Output, Stdio};
10use std::time::{Duration, Instant};
11
12use base64::Engine;
13use serde::{Deserialize, Serialize};
14
15use crate::process::{CaptureFailure, TimedCommand};
16
17const INPUT_LIMIT: u64 = 1024 * 1024;
18// Base64 for 4 MiB stdout + 256 KiB stderr, plus the result envelope.
19const WIRE_LIMIT: usize = 6 * 1024 * 1024;
20const LAUNCH_BUDGET: Duration = Duration::from_secs(5);
21const CLEANUP_BUDGET: Duration = Duration::from_secs(8);
22const PROTOCOL: u32 = 1;
23
24/// Explicit command inputs. Environment inheritance is captured at construction;
25/// `env_clear` and later overrides are preserved when crossing the helper boundary.
26#[derive(Clone)]
27pub struct HelperCommand {
28    program: OsString,
29    args: Vec<OsString>,
30    directory: Option<PathBuf>,
31    environment: BTreeMap<OsString, OsString>,
32    lock: Option<LockInput>,
33}
34
35impl std::fmt::Debug for HelperCommand {
36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37        f.debug_struct("HelperCommand")
38            .field("program", &self.program)
39            .finish_non_exhaustive()
40    }
41}
42
43impl HelperCommand {
44    pub fn new(program: impl AsRef<OsStr>) -> Self {
45        Self {
46            program: program.as_ref().into(),
47            args: Vec::new(),
48            directory: None,
49            environment: std::env::vars_os().collect(),
50            lock: None,
51        }
52    }
53    pub fn arg(&mut self, value: impl AsRef<OsStr>) -> &mut Self {
54        self.args.push(value.as_ref().into());
55        self
56    }
57    pub fn args<I, S>(&mut self, values: I) -> &mut Self
58    where
59        I: IntoIterator<Item = S>,
60        S: AsRef<OsStr>,
61    {
62        self.args
63            .extend(values.into_iter().map(|value| value.as_ref().into()));
64        self
65    }
66    pub fn current_dir(&mut self, directory: impl AsRef<Path>) -> &mut Self {
67        self.directory = Some(directory.as_ref().into());
68        self
69    }
70    pub fn env_clear(&mut self) -> &mut Self {
71        self.environment.clear();
72        self
73    }
74    pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Self {
75        self.environment
76            .insert(key.as_ref().into(), value.as_ref().into());
77        self
78    }
79    pub fn env_remove(&mut self, key: impl AsRef<OsStr>) -> &mut Self {
80        self.environment.remove(key.as_ref());
81        self
82    }
83
84    /// The helper acquires this lock before acknowledging its launch gate.
85    /// It retains the lock through command termination and output capture.
86    pub fn lock(&mut self, path: &Path, budget: Duration) -> &mut Self {
87        self.lock = Some(LockInput {
88            path: path.as_os_str().as_bytes().into(),
89            budget_ms: budget.as_millis().min(86_400_000) as u64,
90        });
91        self
92    }
93
94    pub fn run(&self, budget: Duration) -> TimedCommand {
95        #[cfg(test)]
96        let program = std::env::current_exe();
97        #[cfg(not(test))]
98        let program = if crate::cli_binary::is_cli_process() {
99            std::env::current_exe()
100        } else {
101            crate::cli_binary::resolve_cli()
102                .map(|(path, _)| path)
103                .map_err(std::io::Error::other)
104        };
105        let program = match program {
106            Ok(path) => path,
107            Err(error) => return TimedCommand::Spawn(error),
108        };
109        #[cfg(test)]
110        let args = [
111            "--exact",
112            "helper_command::tests::helper_entrypoint",
113            "--nocapture",
114        ]
115        .as_slice();
116        #[cfg(not(test))]
117        let args = ["daemon", "helper"].as_slice();
118        self.run_using(&program, args, budget, cfg!(test))
119    }
120
121    /// Supply the CLI explicitly when embedding this library without an installed CLI.
122    pub fn run_with_cli(&self, executable: &Path, budget: Duration) -> TimedCommand {
123        self.run_using(executable, &["daemon", "helper"], budget, false)
124    }
125
126    fn run_using(
127        &self,
128        program: &Path,
129        args: &[&str],
130        budget: Duration,
131        wire_stderr: bool,
132    ) -> TimedCommand {
133        let budget_ms = match u64::try_from(budget.as_millis()) {
134            Ok(value) if (1..=86_400_000).contains(&value) => value,
135            _ => {
136                return TimedCommand::Spawn(std::io::Error::other(
137                    "helper budget must be between 1 ms and one day",
138                ));
139            }
140        };
141        let input = Launch {
142            protocol: PROTOCOL,
143            budget_ms,
144            program: self.program.as_bytes().into(),
145            args: self.args.iter().map(|arg| arg.as_bytes().into()).collect(),
146            lock: self.lock.clone(),
147        };
148        let mut input = match serde_json::to_vec(&input) {
149            Ok(bytes) => bytes,
150            Err(error) => return TimedCommand::Spawn(error.into()),
151        };
152        input.push(b'\n');
153        if input.len() as u64 > INPUT_LIMIT {
154            return TimedCommand::Spawn(std::io::Error::other("helper input exceeds 1 MiB"));
155        }
156        let cookie = uuid::Uuid::new_v4().to_string();
157        let mut command = Command::new(program);
158        command
159            .args(args)
160            .env_clear()
161            .envs(&self.environment)
162            .env("STACKLESS_SPAWN", &cookie)
163            .stdin(Stdio::piped())
164            .stdout(Stdio::piped())
165            .stderr(Stdio::piped())
166            .process_group(0);
167        if let Some(directory) = &self.directory {
168            command.current_dir(directory);
169        }
170        let mut child = match command.spawn() {
171            Ok(child) => child,
172            Err(error) => return TimedCommand::Spawn(error),
173        };
174        let launch = || -> std::io::Result<()> {
175            let mut gate = child
176                .stdin
177                .take()
178                .ok_or_else(|| std::io::Error::other("helper gate missing"))?;
179            write_gate(&mut gate, &input)?;
180            let wait = LAUNCH_BUDGET
181                + Duration::from_millis(self.lock.as_ref().map_or(0, |lock| lock.budget_ms));
182            let ready = if wire_stderr {
183                read_ready(
184                    child
185                        .stderr
186                        .as_mut()
187                        .ok_or_else(|| std::io::Error::other("helper response missing"))?,
188                    wait,
189                )?
190            } else {
191                read_ready(
192                    child
193                        .stdout
194                        .as_mut()
195                        .ok_or_else(|| std::io::Error::other("helper response missing"))?,
196                    wait,
197                )?
198            };
199            if ready {
200                write_gate(&mut gate, b"run\n")?;
201            }
202            Ok(())
203        };
204        let mut launch = launch;
205        if let Err(error) = launch() {
206            let _ = child.kill();
207            let _ = child.wait();
208            return TimedCommand::Spawn(error);
209        }
210        match crate::process::collect_child(
211            child,
212            &cookie,
213            budget + CLEANUP_BUDGET,
214            if wire_stderr { 64 * 1024 } else { WIRE_LIMIT },
215            if wire_stderr { WIRE_LIMIT } else { 64 * 1024 },
216        ) {
217            TimedCommand::Finished(output) if output.status.success() => decode(if wire_stderr {
218                &output.stderr
219            } else {
220                &output.stdout
221            }),
222            TimedCommand::Finished(_) => TimedCommand::Spawn(std::io::Error::other(
223                "helper exited without a complete result",
224            )),
225            other => other,
226        }
227    }
228}
229
230fn write_gate(
231    pipe: &mut (impl Write + std::os::fd::AsFd),
232    mut bytes: &[u8],
233) -> std::io::Result<()> {
234    let flags = rustix::fs::fcntl_getfl(&pipe)?;
235    rustix::fs::fcntl_setfl(&pipe, flags | rustix::fs::OFlags::NONBLOCK)?;
236    let deadline = Instant::now() + LAUNCH_BUDGET;
237    while !bytes.is_empty() {
238        match pipe.write(bytes) {
239            Ok(0) => return Err(std::io::Error::other("helper gate closed")),
240            Ok(count) => bytes = &bytes[count..],
241            Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
242            Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
243                if Instant::now() >= deadline {
244                    return Err(std::io::Error::other("helper launch timed out"));
245                }
246                std::thread::sleep(Duration::from_millis(5));
247            }
248            Err(error) => return Err(error),
249        }
250    }
251    Ok(())
252}
253
254fn read_ready(
255    pipe: &mut (impl Read + std::os::fd::AsFd),
256    budget: Duration,
257) -> std::io::Result<bool> {
258    let flags = rustix::fs::fcntl_getfl(&pipe)?;
259    rustix::fs::fcntl_setfl(&pipe, flags | rustix::fs::OFlags::NONBLOCK)?;
260    let deadline = Instant::now() + budget;
261    let mut byte = [0];
262    loop {
263        match pipe.read(&mut byte) {
264            Ok(1) if byte[0] == b'R' => return Ok(true),
265            Ok(1) if byte[0] == b'F' => return Ok(false),
266            Ok(_) => {
267                return Err(std::io::Error::other(
268                    "invalid helper launch acknowledgement",
269                ));
270            }
271            Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
272            Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
273                if Instant::now() >= deadline {
274                    return Err(std::io::Error::other("helper acknowledgement timed out"));
275                }
276                std::thread::sleep(Duration::from_millis(5));
277            }
278            Err(error) => return Err(error),
279        }
280    }
281}
282
283#[derive(Clone, Serialize, Deserialize)]
284#[serde(deny_unknown_fields)]
285struct LockInput {
286    path: Vec<u8>,
287    budget_ms: u64,
288}
289
290#[derive(Serialize, Deserialize)]
291#[serde(deny_unknown_fields)]
292struct Launch {
293    lock: Option<LockInput>,
294    protocol: u32,
295    budget_ms: u64,
296    program: Vec<u8>,
297    args: Vec<Vec<u8>>,
298}
299
300#[derive(Serialize, Deserialize)]
301#[serde(deny_unknown_fields)]
302struct Reply {
303    protocol: u32,
304    result: ResultWire,
305}
306
307#[derive(Serialize, Deserialize)]
308#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
309enum ResultWire {
310    LockFailed {
311        path: Vec<u8>,
312        detail: String,
313    },
314    Finished {
315        status: i32,
316        stdout: String,
317        stderr: String,
318    },
319    TimedOut {
320        pid: u32,
321    },
322    Spawn {
323        detail: String,
324    },
325    Limit {
326        stream: Stream,
327        limit: usize,
328    },
329    Incomplete {
330        stream: Stream,
331    },
332    Read {
333        stream: Stream,
334        detail: String,
335    },
336    CleanupFailed {
337        pid: u32,
338    },
339}
340
341#[derive(Serialize, Deserialize)]
342#[serde(rename_all = "snake_case")]
343enum Stream {
344    Stdout,
345    Stderr,
346    Output,
347}
348impl Stream {
349    fn from_name(name: &str) -> Self {
350        match name {
351            "stdout" => Self::Stdout,
352            "stderr" => Self::Stderr,
353            _ => Self::Output,
354        }
355    }
356    fn name(&self) -> &'static str {
357        match self {
358            Self::Stdout => "stdout",
359            Self::Stderr => "stderr",
360            Self::Output => "output",
361        }
362    }
363}
364
365fn encode(result: TimedCommand) -> Reply {
366    let result = match result {
367        TimedCommand::LockFailed { path, detail } => ResultWire::LockFailed {
368            path: path.as_os_str().as_bytes().into(),
369            detail,
370        },
371        TimedCommand::Finished(output) => ResultWire::Finished {
372            status: output.status.into_raw(),
373            stdout: base64::prelude::BASE64_STANDARD.encode(output.stdout),
374            stderr: base64::prelude::BASE64_STANDARD.encode(output.stderr),
375        },
376        TimedCommand::TimedOut { pid } => ResultWire::TimedOut { pid },
377        TimedCommand::Spawn(error) => ResultWire::Spawn {
378            detail: error.to_string(),
379        },
380        TimedCommand::CleanupFailed { pid } => ResultWire::CleanupFailed { pid },
381        TimedCommand::CaptureFailed(CaptureFailure::Limit { stream, limit }) => ResultWire::Limit {
382            stream: Stream::from_name(stream),
383            limit,
384        },
385        TimedCommand::CaptureFailed(CaptureFailure::Incomplete { stream }) => {
386            ResultWire::Incomplete {
387                stream: Stream::from_name(stream),
388            }
389        }
390        TimedCommand::CaptureFailed(CaptureFailure::Read { stream, source }) => ResultWire::Read {
391            stream: Stream::from_name(stream),
392            detail: source.to_string(),
393        },
394    };
395    Reply {
396        protocol: PROTOCOL,
397        result,
398    }
399}
400
401fn decode(bytes: &[u8]) -> TimedCommand {
402    let invalid =
403        || TimedCommand::Spawn(std::io::Error::other("invalid or incomplete helper result"));
404    let reply: Reply = match serde_json::from_slice(bytes) {
405        Ok(reply) => reply,
406        Err(_) => return invalid(),
407    };
408    if reply.protocol != PROTOCOL {
409        return invalid();
410    }
411    match reply.result {
412        ResultWire::LockFailed { path, detail } => TimedCommand::LockFailed {
413            path: PathBuf::from(OsString::from_vec(path)),
414            detail,
415        },
416        ResultWire::Finished {
417            status,
418            stdout,
419            stderr,
420        } => {
421            let (Ok(stdout), Ok(stderr)) = (
422                base64::prelude::BASE64_STANDARD.decode(stdout),
423                base64::prelude::BASE64_STANDARD.decode(stderr),
424            ) else {
425                return invalid();
426            };
427            if stdout.len() > crate::process::COMMAND_STDOUT_LIMIT
428                || stderr.len() > crate::process::COMMAND_STDERR_LIMIT
429            {
430                return invalid();
431            }
432            TimedCommand::Finished(Output {
433                status: std::process::ExitStatus::from_raw(status),
434                stdout,
435                stderr,
436            })
437        }
438        ResultWire::TimedOut { pid } => TimedCommand::TimedOut { pid },
439        ResultWire::Spawn { detail } => TimedCommand::Spawn(std::io::Error::other(detail)),
440        ResultWire::CleanupFailed { pid } => TimedCommand::CleanupFailed { pid },
441        ResultWire::Limit { stream, limit } => TimedCommand::CaptureFailed(CaptureFailure::Limit {
442            stream: stream.name(),
443            limit,
444        }),
445        ResultWire::Incomplete { stream } => {
446            TimedCommand::CaptureFailed(CaptureFailure::Incomplete {
447                stream: stream.name(),
448            })
449        }
450        ResultWire::Read { stream, detail } => TimedCommand::CaptureFailed(CaptureFailure::Read {
451            stream: stream.name(),
452            source: std::io::Error::other(detail),
453        }),
454    }
455}
456
457/// Internal CLI entrypoint. The helper owns the actual command's timeout and capture.
458pub fn serve() -> std::io::Result<()> {
459    serve_to(std::io::stdout().lock())
460}
461
462fn serve_to(mut output: impl Write) -> std::io::Result<()> {
463    let mut input = Vec::new();
464    let mut gate = std::io::stdin().lock();
465    (&mut gate)
466        .take(INPUT_LIMIT + 1)
467        .read_until(b'\n', &mut input)?;
468    if input.len() as u64 > INPUT_LIMIT || input.last() != Some(&b'\n') {
469        return Err(std::io::Error::other(
470            "helper gate closed or input exceeded limit",
471        ));
472    }
473    let input: Launch = serde_json::from_slice(&input)?;
474    if input.protocol != PROTOCOL || !(1..=86_400_000).contains(&input.budget_ms) {
475        return Err(std::io::Error::other(
476            "invalid helper launch protocol or budget",
477        ));
478    }
479    let _lock = if let Some(lock) = input.lock {
480        if lock.budget_ms > 86_400_000 {
481            return Err(std::io::Error::other("invalid helper lock budget"));
482        }
483        let path = PathBuf::from(OsString::from_vec(lock.path));
484        match crate::lockfile::FileLock::acquire_with_wait(
485            &path,
486            Duration::from_millis(lock.budget_ms),
487        ) {
488            Ok(lock) => Some(lock),
489            Err(error) => {
490                output.write_all(b"F")?;
491                return output.write_all(&serde_json::to_vec(&encode(TimedCommand::LockFailed {
492                    path,
493                    detail: error.to_string(),
494                }))?);
495            }
496        }
497    } else {
498        None
499    };
500    output.write_all(b"R")?;
501    output.flush()?;
502    let mut release = [0; 4];
503    gate.read_exact(&mut release)?;
504    if &release != b"run\n" {
505        return Err(std::io::Error::other("helper gate was not released"));
506    }
507    let mut command = Command::new(OsString::from_vec(input.program));
508    command.args(input.args.into_iter().map(OsString::from_vec));
509    let result =
510        crate::process::run_with_timeout(&mut command, Duration::from_millis(input.budget_ms));
511    let bytes = serde_json::to_vec(&encode(result))?;
512    output.write_all(&bytes)
513}
514
515#[cfg(test)]
516#[allow(clippy::unwrap_used, clippy::panic)]
517mod tests {
518    use super::*;
519
520    #[test]
521    fn helper_entrypoint() {
522        if rustix::process::getpgrp() == rustix::process::getpid()
523            && serve_to(std::io::stderr().lock()).is_ok()
524        {
525            // The test harness writes to stdout; the test transport reads stderr.
526            std::process::exit(0);
527        }
528    }
529
530    #[test]
531    fn helper_preserves_exit_status_and_both_output_streams() {
532        let mut command = HelperCommand::new("/bin/sh");
533        command.args(["-c", "printf stdout; printf stderr >&2; exit 17"]);
534        match command.run(Duration::from_secs(2)) {
535            TimedCommand::Finished(output) => {
536                assert_eq!(output.status.code(), Some(17));
537                assert_eq!(output.stdout, b"stdout");
538                assert_eq!(output.stderr, b"stderr");
539            }
540            other => panic!("unexpected result: {other:?}"),
541        }
542    }
543    #[test]
544    fn helper_keeps_environment_clear_and_preserves_raw_arguments() {
545        let mut command = HelperCommand::new("/usr/bin/env");
546        command
547            .env("REMOVED_CANARY", "private")
548            .env_clear()
549            .env("KEPT_CANARY", "value");
550        let TimedCommand::Finished(output) = command.run(Duration::from_secs(2)) else {
551            panic!("env command failed")
552        };
553        let output = String::from_utf8(output.stdout).unwrap();
554        assert!(output.contains("KEPT_CANARY=value\n"));
555        assert!(!output.contains("REMOVED_CANARY="));
556        assert!(!output.contains("HOME="));
557        assert!(!output.contains("PATH="));
558        let root = tempfile::tempdir().unwrap();
559        let path = root.path().join("unicode-雪");
560        std::fs::create_dir(&path).unwrap();
561        let path = path.canonicalize().unwrap();
562        let mut command = HelperCommand::new("python3");
563        command
564            .current_dir(&path)
565            .args([
566                "-c",
567                "import os,sys; os.write(1, os.fsencode(sys.argv[1])); os.write(2, os.getcwdb())",
568            ])
569            .arg(OsString::from_vec(b"argument-\xfe".to_vec()));
570        let TimedCommand::Finished(output) = command.run(Duration::from_secs(2)) else {
571            panic!("binary argument command failed")
572        };
573        assert_eq!(output.stdout, b"argument-\xfe");
574        assert_eq!(output.stderr, path.as_os_str().as_bytes());
575    }
576
577    #[test]
578    fn helper_transports_full_limits_and_rejects_partial_overflow_output() {
579        let mut command = HelperCommand::new("python3");
580        command.args(["-c", &format!("import sys; sys.stdout.buffer.write(b'x' * {}); sys.stderr.buffer.write(b'y' * {})",
581            crate::process::COMMAND_STDOUT_LIMIT, crate::process::COMMAND_STDERR_LIMIT)]);
582        match command.run(Duration::from_secs(5)) {
583            TimedCommand::Finished(output) => {
584                assert!(output.status.success());
585                assert_eq!(output.stdout.len(), crate::process::COMMAND_STDOUT_LIMIT);
586                assert_eq!(output.stderr.len(), crate::process::COMMAND_STDERR_LIMIT);
587            }
588            other => panic!("full output failed: {other:?}"),
589        }
590        let mut command = HelperCommand::new("python3");
591        command.args(["-c", &format!(r#"import sys; sys.stdout.write('{{"ok":true,"data":{{"environments":[]}}}}' + ' ' * {})"#,
592            crate::process::COMMAND_STDOUT_LIMIT)]);
593        assert!(matches!(
594            command.run(Duration::from_secs(5)),
595            TimedCommand::CaptureFailed(CaptureFailure::Limit {
596                stream: "stdout",
597                ..
598            })
599        ));
600    }
601
602    #[test]
603    fn helper_lock_failure_never_launches_the_command() {
604        let root = tempfile::tempdir().unwrap();
605        let path = root.path().join("command.lock");
606        let _lock = crate::lockfile::FileLock::try_acquire(&path).unwrap();
607        let marker = root.path().join("executed");
608        let mut command = HelperCommand::new("/usr/bin/touch");
609        command.arg(&marker).lock(&path, Duration::from_millis(50));
610        assert!(matches!(
611            command.run(Duration::from_secs(2)),
612            TimedCommand::LockFailed { .. }
613        ));
614        assert!(!marker.exists());
615    }
616
617    #[test]
618    fn closing_the_acknowledged_gate_releases_lock_without_running_code() {
619        let root = tempfile::tempdir().unwrap();
620        let lock = root.path().join("command.lock");
621        let marker = root.path().join("executed");
622        let mut child = Command::new(std::env::current_exe().unwrap())
623            .args([
624                "--exact",
625                "helper_command::tests::helper_entrypoint",
626                "--nocapture",
627            ])
628            .stdin(Stdio::piped())
629            .stdout(Stdio::null())
630            .stderr(Stdio::piped())
631            .process_group(0)
632            .spawn()
633            .unwrap();
634        let mut gate = child.stdin.take().unwrap();
635        let launch = Launch {
636            protocol: PROTOCOL,
637            budget_ms: 1000,
638            program: b"/usr/bin/touch".to_vec(),
639            args: vec![marker.as_os_str().as_bytes().to_vec()],
640            lock: Some(LockInput {
641                path: lock.as_os_str().as_bytes().to_vec(),
642                budget_ms: 1000,
643            }),
644        };
645        let mut bytes = serde_json::to_vec(&launch).unwrap();
646        bytes.push(b'\n');
647        write_gate(&mut gate, &bytes).unwrap();
648        assert!(read_ready(child.stderr.as_mut().unwrap(), Duration::from_secs(2)).unwrap());
649        assert!(crate::lockfile::FileLock::try_acquire(&lock).is_err());
650        drop(gate);
651        child.wait().unwrap();
652        assert!(!marker.exists());
653        assert!(crate::lockfile::FileLock::try_acquire(&lock).is_ok());
654    }
655
656    #[test]
657    fn caller_crash_entrypoint() {
658        let Some(root) = std::env::var_os("STACKLESS_TEST_HELPER_CRASH_DIR") else {
659            return;
660        };
661        let root = PathBuf::from(root);
662        let mut command = HelperCommand::new("python3");
663        command.current_dir(&root).args(["-c", r#"
664import json, os, pathlib, time
665child = os.fork()
666if child == 0:
667    os.setsid()
668    os.close(1)
669    os.close(2)
670    time.sleep(30)
671    pathlib.Path('escaped-late').touch()
672    os._exit(0)
673pathlib.Path('ready.tmp').write_text(json.dumps({'pid': os.getpid(), 'helper': os.getppid(), 'cookie': os.environ['STACKLESS_SPAWN']}))
674os.replace('ready.tmp', 'ready')
675time.sleep(30)
676pathlib.Path('late').touch()
677"#]).lock(&root.join("command.lock"), Duration::from_secs(2));
678        let _ = command.run(Duration::from_secs(2));
679    }
680
681    #[test]
682    fn caller_sigkill_leaves_deadline_cleanup_and_lock_in_the_helper() {
683        let root = tempfile::tempdir().unwrap();
684        let mut caller = Command::new(std::env::current_exe().unwrap())
685            .args([
686                "--exact",
687                "helper_command::tests::caller_crash_entrypoint",
688                "--nocapture",
689            ])
690            .env("STACKLESS_TEST_HELPER_CRASH_DIR", root.path())
691            .stdin(Stdio::null())
692            .stdout(Stdio::null())
693            .stderr(Stdio::null())
694            .spawn()
695            .unwrap();
696        let deadline = Instant::now() + Duration::from_secs(5);
697        let ready: serde_json::Value = loop {
698            if let Ok(bytes) = std::fs::read(root.path().join("ready")) {
699                break serde_json::from_slice(&bytes).unwrap();
700            }
701            assert!(Instant::now() < deadline, "helper did not launch");
702            std::thread::sleep(Duration::from_millis(10));
703        };
704        let process =
705            crate::process::ProcessStamp::of(ready["pid"].as_u64().unwrap() as u32).unwrap();
706        let helper =
707            crate::process::ProcessStamp::of(ready["helper"].as_u64().unwrap() as u32).unwrap();
708        let command = crate::durable_command::CommandStamp {
709            pid: process.pid,
710            start_time: process.start_time,
711            cookie: ready["cookie"].as_str().unwrap().into(),
712        };
713        caller.kill().unwrap();
714        caller.wait().unwrap();
715        assert!(helper.is_alive());
716        assert!(crate::lockfile::FileLock::try_acquire(&root.path().join("command.lock")).is_err());
717        let deadline = Instant::now() + Duration::from_secs(6);
718        while (!command.is_stopped() || helper.is_alive()) && Instant::now() < deadline {
719            std::thread::sleep(Duration::from_millis(20));
720        }
721        let stopped = command.is_stopped();
722        command.stop().unwrap();
723        assert!(stopped && !helper.is_alive());
724        assert!(!root.path().join("late").exists());
725        assert!(!root.path().join("escaped-late").exists());
726        assert!(crate::lockfile::FileLock::try_acquire(&root.path().join("command.lock")).is_ok());
727    }
728    #[test]
729    fn malformed_helper_result_cannot_become_command_output() {
730        use std::os::unix::fs::PermissionsExt;
731        let root = tempfile::tempdir().unwrap();
732        let fake = root.path().join("fake-cli");
733        std::fs::write(&fake, b"#!/bin/sh\nIFS= read -r input\nprintf R\nIFS= read -r gate\nprintf '{invalid-result'\n").unwrap();
734        std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o700)).unwrap();
735        let marker = root.path().join("executed");
736        let mut command = HelperCommand::new("/usr/bin/touch");
737        command.arg(&marker);
738        assert!(matches!(
739            command.run_with_cli(&fake, Duration::from_secs(1)),
740            TimedCommand::Spawn(_)
741        ));
742        assert!(!marker.exists());
743    }
744}