Skip to main content

vtcode_core/exec/
async_command.rs

1use hashbrown::HashMap;
2use std::ffi::OsString;
3use std::path::PathBuf;
4use std::pin::Pin;
5use std::time::{Duration, Instant};
6
7use anyhow::{Context, Result, anyhow};
8use std::process::{ExitStatus, Stdio};
9use tokio::io::AsyncReadExt;
10use tokio::process::{Child, Command};
11use tokio::time::{Sleep, sleep, timeout};
12use tokio_util::sync::{CancellationToken, WaitForCancellationFutureOwned};
13
14use crate::telemetry::perf;
15use crate::utils::gatekeeper;
16
17const DEFAULT_CAPTURE_LIMIT: usize = 256 * 1024; // 256 KiB
18
19/// Upper bound on how long `run` will wait, after killing the direct child on
20/// the `TimedOut`/`Cancelled` paths, for (a) the child to be reaped and (b) the
21/// stdout/stderr pipes to drain.
22///
23/// The timeout/cancellation kill targets the child's whole process group, so
24/// descendants that inherited the group die with it. Two rare cases still
25/// justify the bound: a grandchild that called `setsid()` escapes the group and
26/// can keep the stdout/stderr pipe write ends open, and a wedged reap could
27/// stall indefinitely. Bounding the wait ensures `run` always returns; whatever
28/// bytes were already captured before the bound elapses are returned as-is,
29/// and any data written afterward is accepted as lost since the process has
30/// already been killed.
31const POST_KILL_DRAIN_TIMEOUT: Duration = Duration::from_secs(2);
32
33/// Configuration for capturing a process stream (stdout or stderr).
34#[derive(Debug, Clone)]
35pub struct StreamCaptureConfig {
36    /// Whether to capture this stream.
37    pub capture: bool,
38    /// Maximum number of bytes to capture before truncating.
39    pub max_bytes: usize,
40}
41
42impl Default for StreamCaptureConfig {
43    fn default() -> Self {
44        Self { capture: true, max_bytes: DEFAULT_CAPTURE_LIMIT }
45    }
46}
47
48/// Options for spawning an asynchronous process.
49#[derive(Debug, Clone, Default)]
50pub struct ProcessOptions {
51    /// The program to execute.
52    pub program: String,
53    /// Arguments to pass to the program.
54    pub args: Vec<String>,
55    /// Environment variables for the process.
56    pub env: HashMap<OsString, OsString>,
57    /// Working directory for the process.
58    pub current_dir: Option<PathBuf>,
59    /// Maximum time the process is allowed to run before being killed.
60    pub timeout: Option<Duration>,
61    /// Token to externally cancel the process.
62    pub cancellation_token: Option<CancellationToken>,
63    /// Configuration for stdout capture.
64    pub stdout: StreamCaptureConfig,
65    /// Configuration for stderr capture.
66    pub stderr: StreamCaptureConfig,
67}
68
69/// Output from a completed asynchronous process.
70#[derive(Debug)]
71pub struct ProcessOutput {
72    /// The exit status of the process.
73    pub exit_status: ExitStatus,
74    /// Captured stdout bytes.
75    pub stdout: Vec<u8>,
76    /// Captured stderr bytes.
77    pub stderr: Vec<u8>,
78    /// Whether the process was killed due to a timeout.
79    pub timed_out: bool,
80    /// Whether the process was cancelled via its cancellation token.
81    pub cancelled: bool,
82    /// Wall-clock duration from spawn to completion.
83    pub duration: Duration,
84}
85
86/// Runs a child process asynchronously with timeout and cancellation support.
87pub struct AsyncProcessRunner;
88
89impl AsyncProcessRunner {
90    /// Spawn and await a child process with the given options.
91    ///
92    /// On Unix the child starts in its own process group, so the timeout and
93    /// cancellation kills terminate the child *and* any descendant that
94    /// inherited the group (see `kill_child_process_group`). The post-kill
95    /// stream drain and process reap stay bounded by `POST_KILL_DRAIN_TIMEOUT`
96    /// so this function can never hang.
97    pub async fn run(options: ProcessOptions) -> Result<ProcessOutput> {
98        if options.program.is_empty() {
99            return Err(anyhow!("program cannot be empty"));
100        }
101
102        let mut tags = HashMap::new();
103        tags.insert("subsystem".to_string(), "async_command".to_string());
104        tags.insert("program".to_string(), options.program.clone());
105        perf::record_value("vtcode.perf.spawn_count", 1.0, tags);
106
107        gatekeeper::check_quarantine_for_program(&options.program);
108
109        let start = Instant::now();
110        let mut command = Command::new(&options.program);
111        command.args(&options.args);
112        if let Some(dir) = &options.current_dir {
113            command.current_dir(dir);
114        }
115        if !options.env.is_empty() {
116            command.envs(&options.env);
117        }
118        // Own process group (PGID == PID) on Unix: the kill path can then reach
119        // descendants via killpg instead of only the direct child.
120        #[cfg(unix)]
121        command.process_group(0);
122        command.stdout(Stdio::piped());
123        command.stderr(Stdio::piped());
124
125        let mut child = command
126            .spawn()
127            .with_context(|| format!("failed to spawn '{}' with args {:?}", options.program, options.args))?;
128
129        let child_pid = child.id();
130        let stdout_handle = child.stdout.take();
131        let stderr_handle = child.stderr.take();
132
133        let mut stdout_future = Box::pin(read_stream(stdout_handle, options.stdout));
134        let mut stderr_future = Box::pin(read_stream(stderr_handle, options.stderr));
135        let mut timeout_future = options.timeout.map(|dur| Box::pin(sleep(dur)) as Pin<Box<Sleep>>);
136        let mut cancellation_future = options
137            .cancellation_token
138            .as_ref()
139            .map(|token| Box::pin(token.clone().cancelled_owned()) as Pin<Box<WaitForCancellationFutureOwned>>);
140
141        #[derive(Clone, Copy, PartialEq, Eq)]
142        enum Completion {
143            Finished,
144            TimedOut,
145            Cancelled,
146        }
147
148        let mut exit_status: Option<ExitStatus> = None;
149        let mut stdout_result: Option<Result<Vec<u8>>> = None;
150        let mut stderr_result: Option<Result<Vec<u8>>> = None;
151
152        let completion = loop {
153            tokio::select! {
154                res = child.wait(), if exit_status.is_none() => {
155                    exit_status = Some(res?);
156                    // Continue to drain streams
157                }
158                res = &mut stdout_future, if stdout_result.is_none() => {
159                    stdout_result = Some(res);
160                }
161                res = &mut stderr_future, if stderr_result.is_none() => {
162                    stderr_result = Some(res);
163                }
164                _ = async {
165                    if let Some(fut) = timeout_future.as_mut() {
166                        fut.as_mut().await;
167                    } else {
168                        futures::future::pending::<()>().await;
169                    }
170                }, if timeout_future.is_some() => {
171                    break Completion::TimedOut;
172                }
173                _ = async {
174                    if let Some(fut) = cancellation_future.as_mut() {
175                        fut.as_mut().await;
176                    } else {
177                        futures::future::pending::<()>().await;
178                    }
179                }, if cancellation_future.is_some() => {
180                    break Completion::Cancelled;
181                }
182            }
183
184            // Check if everything is done
185            if exit_status.is_some() && stdout_result.is_some() && stderr_result.is_some() {
186                break Completion::Finished;
187            }
188        };
189
190        // Once the process has been killed on the TimedOut/Cancelled paths,
191        // reaping the child and draining its stdout/stderr pipes must be
192        // bounded (see POST_KILL_DRAIN_TIMEOUT). The Finished path keeps its
193        // original, unbounded behavior because EOF and exit status are
194        // guaranteed once the process has exited normally.
195        let bounded_drain = matches!(completion, Completion::TimedOut | Completion::Cancelled);
196
197        let (timed_out, cancelled, status) = match completion {
198            Completion::Finished => {
199                let status = match exit_status {
200                    Some(status) => status,
201                    None => child.wait().await?,
202                };
203                (false, false, status)
204            }
205            Completion::TimedOut => {
206                // Skip the kill entirely when the child already exited: the
207                // PID may have been reaped (or even reused), so signaling it
208                // is both unnecessary and unsafe.
209                if exit_status.is_none() {
210                    kill_child_process_group(child_pid, &mut child)
211                        .await
212                        .with_context(|| format!("failed to kill timed-out process '{}'", options.program))?;
213                }
214                let status = match exit_status {
215                    Some(status) => status,
216                    None => match timeout(POST_KILL_DRAIN_TIMEOUT, child.wait()).await {
217                        Ok(res) => res?,
218                        Err(_) => {
219                            return Err(anyhow!(
220                                "process timed out and was killed, but could not be reaped within {POST_KILL_DRAIN_TIMEOUT:?}"
221                            ));
222                        }
223                    },
224                };
225                (true, false, status)
226            }
227            Completion::Cancelled => {
228                // Same skip rationale as the timeout path above.
229                if exit_status.is_none() {
230                    kill_child_process_group(child_pid, &mut child)
231                        .await
232                        .with_context(|| format!("failed to kill cancelled process '{}'", options.program))?;
233                }
234                let status = match exit_status {
235                    Some(status) => status,
236                    None => match timeout(POST_KILL_DRAIN_TIMEOUT, child.wait()).await {
237                        Ok(res) => res?,
238                        Err(_) => {
239                            return Err(anyhow!(
240                                "process was cancelled and killed, but could not be reaped within {POST_KILL_DRAIN_TIMEOUT:?}"
241                            ));
242                        }
243                    },
244                };
245                (false, true, status)
246            }
247        };
248
249        // Ensure streams are fully read. On timeout/cancellation the drain of any
250        // still-pending stream is bounded: a setsid-escaping descendant may still
251        // hold the pipe's write end open, so we accept whatever was captured so
252        // far rather than blocking forever.
253        let stdout = match stdout_result {
254            Some(Ok(data)) => data,
255            Some(Err(e)) => return Err(e),
256            None if bounded_drain => match timeout(POST_KILL_DRAIN_TIMEOUT, stdout_future.as_mut()).await {
257                Ok(res) => res?,
258                Err(_) => Vec::new(),
259            },
260            None => stdout_future.await?,
261        };
262        let stderr = match stderr_result {
263            Some(Ok(data)) => data,
264            Some(Err(e)) => return Err(e),
265            None if bounded_drain => match timeout(POST_KILL_DRAIN_TIMEOUT, stderr_future.as_mut()).await {
266                Ok(res) => res?,
267                Err(_) => Vec::new(),
268            },
269            None => stderr_future.await?,
270        };
271
272        Ok(ProcessOutput {
273            exit_status: status,
274            stdout,
275            stderr,
276            timed_out,
277            cancelled,
278            duration: start.elapsed(),
279        })
280    }
281}
282
283async fn read_stream<R>(reader: Option<R>, config: StreamCaptureConfig) -> Result<Vec<u8>>
284where
285    R: tokio::io::AsyncRead + Unpin,
286{
287    if !config.capture {
288        return Ok(Vec::new());
289    }
290
291    let mut reader = match reader {
292        Some(r) => r,
293        None => return Ok(Vec::new()),
294    };
295
296    let mut output = Vec::new();
297    // Reserve a bounded amount of capacity based on the configured capture
298    // limit. We cap the reservation to DEFAULT_CAPTURE_LIMIT to avoid
299    // reserving an unbounded or attacker-controlled amount while still
300    // improving performance for typical capture sizes.
301    let reserve_cap = config.max_bytes.min(DEFAULT_CAPTURE_LIMIT);
302    if reserve_cap > 0 {
303        output.reserve(reserve_cap);
304    }
305
306    let mut buffer = [0u8; 4096];
307    loop {
308        let read = reader.read(&mut buffer).await?;
309        if read == 0 {
310            break;
311        }
312        let remaining = config.max_bytes.saturating_sub(output.len());
313        if remaining > 0 {
314            let to_copy = remaining.min(read);
315            output.extend_from_slice(&buffer[..to_copy]);
316        }
317    }
318
319    Ok(output)
320}
321
322/// Kill the spawned child on the timeout/cancellation path.
323///
324/// On Unix the child was created in its own process group, so the
325/// `vtcode-bash-runner` group kill terminates descendants too; the helper
326/// SIGKILLs the direct child as a fallback and treats an already-exited child
327/// as success. Other platforms kill the direct child only, matching the
328/// previous behavior.
329async fn kill_child_process_group(child_pid: Option<u32>, child: &mut Child) -> Result<()> {
330    #[cfg(unix)]
331    if let Some(pid) = child_pid {
332        return vtcode_bash_runner::process_group::kill_process_group_by_pid(pid)
333            .context("failed to kill process group");
334    }
335    let _ = child_pid;
336    child.kill().await.context("failed to kill child process")
337}
338
339#[cfg(test)]
340mod tests {
341    use super::*;
342
343    /// A timed-out run must return promptly with `timed_out == true` instead
344    /// of hanging on the post-kill stream drain. The whole call is wrapped in
345    /// a generous outer `tokio::time::timeout` so a regression to the old,
346    /// unbounded-drain behavior fails the test instead of hanging the suite.
347    #[tokio::test]
348    async fn run_returns_promptly_after_timeout_kill() {
349        let options = ProcessOptions {
350            program: "sleep".to_string(),
351            args: vec!["30".to_string()],
352            timeout: Some(Duration::from_millis(100)),
353            ..Default::default()
354        };
355
356        let outcome = timeout(Duration::from_secs(10), AsyncProcessRunner::run(options))
357            .await
358            .expect("run() must return well within the outer bound instead of hanging")
359            .expect("timed-out run should still yield a ProcessOutput, not an error");
360
361        assert!(outcome.timed_out, "expected timed_out to be true");
362        assert!(!outcome.cancelled, "cancelled must remain false on timeout");
363    }
364
365    /// Same guarantee as above, but for the cancellation path: a caller
366    /// cancelling a long-running process must get a prompt return with
367    /// `cancelled == true` rather than an indefinite hang.
368    #[tokio::test]
369    async fn run_returns_promptly_after_cancellation_kill() {
370        let token = CancellationToken::new();
371        let cancel_token = token.clone();
372        tokio::spawn(async move {
373            sleep(Duration::from_millis(100)).await;
374            cancel_token.cancel();
375        });
376
377        let options = ProcessOptions {
378            program: "sleep".to_string(),
379            args: vec!["30".to_string()],
380            cancellation_token: Some(token),
381            ..Default::default()
382        };
383
384        let outcome = timeout(Duration::from_secs(10), AsyncProcessRunner::run(options))
385            .await
386            .expect("run() must return well within the outer bound instead of hanging")
387            .expect("cancelled run should still yield a ProcessOutput, not an error");
388
389        assert!(outcome.cancelled, "expected cancelled to be true");
390        assert!(!outcome.timed_out, "timed_out must remain false on cancellation");
391    }
392
393    /// A grandchild process that inherits the stdout pipe and outlives the
394    /// direct child (killed on timeout) must not block `run` forever. On Unix
395    /// the group kill now terminates the grandchild itself, so the drain
396    /// completes normally; on platforms without process groups the bounded
397    /// drain lets the call return with a partial capture. Either way the call
398    /// must return promptly with `timed_out == true`.
399    #[tokio::test]
400    async fn run_bounds_drain_when_grandchild_holds_pipe_open() {
401        let options = ProcessOptions {
402            program: "sh".to_string(),
403            args: vec![
404                "-c".to_string(),
405                // The backgrounded `sleep` inherits stdout and keeps the pipe's
406                // write end open well past the parent shell's own timeout-driven
407                // death, simulating a surviving grandchild.
408                "sleep 30 & exit 0".to_string(),
409            ],
410            timeout: Some(Duration::from_millis(100)),
411            ..Default::default()
412        };
413
414        let outcome = timeout(Duration::from_secs(10), AsyncProcessRunner::run(options))
415            .await
416            .expect("run() must return well within the outer bound instead of hanging")
417            .expect("run should still yield a ProcessOutput even with a surviving grandchild");
418
419        assert!(outcome.timed_out, "expected timed_out to be true");
420    }
421}