lean_ctx/shell/process_tree.rs
1// SPDX-License-Identifier: Apache-2.0
2//! Whole-tree ownership of a spawned command (#1920).
3//!
4//! A timeout or cancel has to end every process the command started, not just
5//! the shell leader. On Unix callers already isolate the child in its own
6//! process group, and `killpg` reaches every descendant. Windows has no such
7//! group: `Child::kill` ends the shell alone, and a `python -` it started keeps
8//! running detached — spinning a core for hours when its script loops.
9//!
10//! A job object is the Windows equivalent. The child is spawned suspended,
11//! assigned to a private job and only then resumed, so nothing it starts can
12//! escape. `TerminateJobObject` ends the whole tree at once, and
13//! `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE` ends it when lean-ctx itself dies before
14//! it could clean up.
15
16use std::process::{Child, Command};
17
18/// The process tree of one spawned command. Create it with `ProcessTree::start`
19/// right after spawning a command prepared by [`ProcessTree::prepare`].
20pub struct ProcessTree {
21 #[cfg(windows)]
22 job: Option<job::ProcessJob>,
23}
24
25impl ProcessTree {
26 /// Configure `cmd` so its tree can be contained. On Windows this spawns the
27 /// child suspended — `ProcessTree::start` must follow every successful
28 /// spawn. It sets the creation flags, so callers must not set their own.
29 pub fn prepare(cmd: &mut Command) {
30 #[cfg(windows)]
31 {
32 use std::os::windows::process::CommandExt;
33 cmd.creation_flags(windows_sys::Win32::System::Threading::CREATE_SUSPENDED);
34 }
35 #[cfg(not(windows))]
36 let _ = cmd;
37 }
38
39 /// Take ownership of the tree of a child spawned from a prepared command
40 /// and let it run.
41 ///
42 /// A job that cannot be created or assigned is not fatal: the command still
43 /// runs, and [`ProcessTree::kill`] falls back to `taskkill /T`. A child that
44 /// cannot be resumed is killed and reported, never left suspended.
45 // pub only for lean-ctx-engine-ext; not public API
46 #[doc(hidden)]
47 pub fn start(child: &mut Child) -> Result<Self, String> {
48 #[cfg(windows)]
49 {
50 let job = match job::ProcessJob::assign(child) {
51 Ok(job) => Some(job),
52 Err(error) => {
53 tracing::warn!("process tree not contained, falling back to taskkill: {error}");
54 None
55 }
56 };
57 if let Err(error) = job::resume(child.id()) {
58 if let Some(job) = &job {
59 job.terminate();
60 }
61 let _ = child.kill();
62 let _ = child.wait();
63 return Err(error);
64 }
65 Ok(Self { job })
66 }
67 #[cfg(not(windows))]
68 {
69 let _ = child;
70 Ok(Self {})
71 }
72 }
73
74 /// Start `command` as one contained call (B7): on Windows its tree goes
75 /// into a private kill-on-close job before its first instruction runs
76 /// (spawned suspended, assigned, resumed). The caller holds the returned
77 /// tree for the call and drops it afterwards, which ends whatever the
78 /// call left running; the tree ends as well should this process die
79 /// first. A job that cannot be created leaves the previous behaviour
80 /// (`taskkill /T` on a limit). A child that cannot be resumed was killed
81 /// without having run, and the error says so. (Unix calls start behind
82 /// their guard instead, `shell::containment::start_behind_guard`.)
83 #[cfg(not(unix))]
84 pub fn spawn_contained(command: &mut Command) -> std::io::Result<(Child, Self)> {
85 Self::prepare(command);
86 let mut child = command.spawn()?;
87 let tree = Self::start(&mut child).map_err(std::io::Error::other)?;
88 Ok((child, tree))
89 }
90
91 /// Kill the command and every descendant it started. Killing only the
92 /// leader would leave grandchildren alive and the caller's pipe readers
93 /// unable to reach EOF (#995).
94 ///
95 /// On Unix the child must lead its own process group (`setsid` or
96 /// `process_group(0)`), which makes its pid the group id.
97 // pub only for lean-ctx-engine-ext; not public API
98 #[doc(hidden)]
99 pub fn kill(&self, child: &mut Child) {
100 #[cfg(unix)]
101 {
102 if let Ok(pgid) = crate::ipc::process::group_target(child.id()) {
103 // SAFETY: killpg is a plain syscall; a stale group yields ESRCH.
104 unsafe { libc::killpg(pgid, libc::SIGKILL) };
105 }
106 }
107 #[cfg(windows)]
108 match &self.job {
109 Some(job) => job.terminate(),
110 None => {
111 let _ = std::process::Command::new("taskkill")
112 .args(["/F", "/T", "/PID", &child.id().to_string()])
113 .stdin(std::process::Stdio::null())
114 .stdout(std::process::Stdio::null())
115 .stderr(std::process::Stdio::null())
116 .status();
117 }
118 }
119 let _ = child.kill();
120 }
121
122 /// Hand the tree back after the command exited on its own.
123 ///
124 /// A process it deliberately left running (`start /b server`) survives, as
125 /// it does on Unix, where an exited leader leaves its group alone. Dropping
126 /// a `ProcessTree` without this — lean-ctx unwinding or dying mid-command —
127 /// ends the whole tree instead.
128 // pub only for lean-ctx-engine-ext; not public API
129 #[doc(hidden)]
130 pub fn release(self) {
131 #[cfg(windows)]
132 if let Some(job) = &self.job {
133 job.release();
134 }
135 }
136}
137
138/// The output of a started shell, wherever its pipes were made.
139type ShellPipe = Option<Box<dyn std::io::Read + Send>>;
140
141fn boxed(pipe: impl std::io::Read + Send + 'static) -> Box<dyn std::io::Read + Send> {
142 Box::new(pipe)
143}
144
145/// A started MCP shell: the process, its output, and what the caller has to
146/// show in front of the result, if anything.
147pub struct StartedShell {
148 pub child: ShellChild,
149 pub stdout: ShellPipe,
150 pub stderr: ShellPipe,
151 /// A fixed, content-free line (see `shell::containment`).
152 pub notice: Option<&'static str>,
153}
154
155/// The shell of one MCP shell call, whoever its parent is.
156///
157/// On Unix the parent is this process's spawn helper (`shell::containment`):
158/// it holds the shell's session and ends it should this process die. Where
159/// there is no helper — Windows, a host that is not `lean-ctx`, a helper that
160/// could not be started — this process is the parent, as it always was.
161pub enum ShellChild {
162 Direct {
163 child: Child,
164 tree: ProcessTree,
165 },
166 #[cfg(unix)]
167 Helped(crate::shell::containment::HelpedChild),
168}
169
170impl ShellChild {
171 /// Starts the shell that `cmd` describes, in a session of its own on
172 /// Unix, with its output piped. `cmd` must have been through
173 /// [`ProcessTree::prepare`] and must not set its own standard streams.
174 pub fn start(cmd: &mut Command) -> Result<StartedShell, String> {
175 #[cfg(unix)]
176 let notice = {
177 use crate::shell::containment::{HelperSpawn, spawn_shell};
178 match spawn_shell(cmd) {
179 HelperSpawn::Helped {
180 child,
181 stdout,
182 stderr,
183 } => {
184 return Ok(StartedShell {
185 child: Self::Helped(child),
186 stdout: Some(boxed(stdout)),
187 stderr: Some(boxed(stderr)),
188 notice: None,
189 });
190 }
191 HelperSpawn::Direct(notice) => notice,
192 }
193 };
194 #[cfg(not(unix))]
195 let notice = None;
196 #[cfg(unix)]
197 crate::shell::containment::lead_new_session(cmd);
198 let mut child = cmd
199 .stdout(std::process::Stdio::piped())
200 .stderr(std::process::Stdio::piped())
201 .spawn()
202 .map_err(|error| error.to_string())?;
203 let tree = ProcessTree::start(&mut child)?;
204 let stdout = child.stdout.take().map(boxed);
205 let stderr = child.stderr.take().map(boxed);
206 Ok(StartedShell {
207 child: Self::Direct { child, tree },
208 stdout,
209 stderr,
210 notice,
211 })
212 }
213
214 /// The shell's process id; on Unix also the id of the group it leads.
215 pub fn id(&self) -> u32 {
216 match self {
217 Self::Direct { child, .. } => child.id(),
218 #[cfg(unix)]
219 Self::Helped(child) => child.id(),
220 }
221 }
222
223 /// The exit status, if the shell has exited. Reaps a direct child.
224 pub fn try_wait(&mut self) -> std::io::Result<Option<std::process::ExitStatus>> {
225 match self {
226 Self::Direct { child, .. } => child.try_wait(),
227 #[cfg(unix)]
228 Self::Helped(child) => child.try_wait(),
229 }
230 }
231
232 /// Ends the shell and everything it started (`ProcessTree::kill`). The
233 /// group is signalled by the shell's parent, while the shell is unreaped.
234 pub fn kill(&mut self) {
235 match self {
236 Self::Direct { child, tree } => tree.kill(child),
237 #[cfg(unix)]
238 Self::Helped(child) => child.kill(),
239 }
240 }
241
242 /// Waits for a shell that was just killed to be reaped.
243 pub fn wait(&mut self) {
244 match self {
245 Self::Direct { child, .. } => {
246 let _ = child.wait();
247 }
248 #[cfg(unix)]
249 Self::Helped(child) => child.wait(),
250 }
251 }
252
253 /// Hands the tree back after the command exited on its own
254 /// (`ProcessTree::release`): what it left running stays.
255 ///
256 /// `Some`: the fixed notice for a release that could not be handed to
257 /// the shell's helper — whether what the command left running is still
258 /// running is then not known. The caller shows it with the result.
259 pub fn release(self) -> Option<&'static str> {
260 match self {
261 Self::Direct { tree, .. } => {
262 tree.release();
263 None
264 }
265 #[cfg(unix)]
266 Self::Helped(child) => {
267 (!child.release()).then_some(crate::shell::containment::RELEASE_NOTICE)
268 }
269 }
270 }
271
272 /// The fixed notice for a shell whose helper went away — before it said
273 /// whether the command was started, or before the shell's exit was
274 /// known. The call's outcome is then not known in full. Never the case
275 /// for a direct child.
276 pub fn lost_notice(&self) -> Option<&'static str> {
277 match self {
278 Self::Direct { .. } => None,
279 #[cfg(unix)]
280 Self::Helped(child) => child.notice(),
281 }
282 }
283}
284
285/// Session containment on Windows (Q13/B7), the counterpart of the Unix
286/// session starter (`shell::containment`).
287///
288/// An SDK asks for it with `LEAN_CTX_SESSION_CONTAINMENT=1` on an `engine …`
289/// start. There is no starter process here: the Engine puts itself into a
290/// kill-on-close job before it does anything else. From then on everything it
291/// starts belongs to that job, and all of it ends when the Engine process
292/// ends — on its own, because the SDK ended it, or because its input closed
293/// after the SDK went away. Only then is the acknowledgement written, the
294/// same first line as on Unix, so an SDK reports containment exactly when it
295/// exists. A job that cannot be created or joined (a host job that forbids
296/// nesting) writes nothing: the Engine runs as before and the SDK reports
297/// `unavailable`.
298///
299/// The request is taken out of the environment first, as the starter does, so
300/// no process the Engine starts sees or repeats it.
301#[cfg(windows)]
302pub fn contain_requested_session() {
303 use std::io::Write;
304 const SESSION_ENV: &str = "LEAN_CTX_SESSION_CONTAINMENT";
305 const SESSION_ACK: &[u8] = b"{\"leanctx_session_containment\":1}\n";
306
307 let mut args = std::env::args_os();
308 let _program = args.next();
309 if args.next().is_none_or(|first| first != "engine")
310 || std::env::var_os(SESSION_ENV).is_none_or(|value| value != "1")
311 {
312 return;
313 }
314 // SAFETY: called first thing in `run`, before any other thread exists.
315 unsafe { std::env::remove_var(SESSION_ENV) };
316 let Ok(session) = job::ProcessJob::assign_current_process() else {
317 return;
318 };
319 // The handle must live exactly as long as the process: it is never
320 // dropped, and the system closes it when the process ends.
321 std::mem::forget(session);
322 let mut stdout = std::io::stdout().lock();
323 let _ = stdout.write_all(SESSION_ACK).and_then(|()| stdout.flush());
324}
325
326#[cfg(windows)]
327pub(crate) mod job {
328 use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
329 use windows_sys::Win32::System::JobObjects::{
330 JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
331 JobObjectExtendedLimitInformation, SetInformationJobObject,
332 };
333
334 /// A private job object whose processes die when its last handle closes.
335 pub(crate) struct ProcessJob(HANDLE);
336
337 impl ProcessJob {
338 /// Create a kill-on-close job and assign `child` to it. The child should
339 /// still be suspended so nothing it starts can escape the job.
340 pub(crate) fn assign(child: &std::process::Child) -> Result<Self, String> {
341 use std::os::windows::io::AsRawHandle;
342 use windows_sys::Win32::System::JobObjects::{
343 AssignProcessToJobObject, CreateJobObjectW,
344 };
345
346 // SAFETY: null attributes/name create a private job owned by Self.
347 let handle = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
348 if handle.is_null() {
349 return Err(format!(
350 "failed to create job object: {}",
351 std::io::Error::last_os_error()
352 ));
353 }
354 let job = Self(handle);
355 job.set_limit_flags(JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE)
356 .map_err(|error| format!("failed to configure job object: {error}"))?;
357 // SAFETY: Child owns a live process handle for the spawned process.
358 let assigned = unsafe { AssignProcessToJobObject(job.0, child.as_raw_handle()) };
359 if assigned == 0 {
360 return Err(format!(
361 "failed to assign process {} to its job: {}",
362 child.id(),
363 std::io::Error::last_os_error()
364 ));
365 }
366 Ok(job)
367 }
368
369 /// Create a kill-on-close job and put THIS process into it. Every
370 /// process it starts from now on is a member (a per-call job of
371 /// [`ProcessJob::assign`] nests inside), and all of them end when the
372 /// last handle closes — which is when this process ends, since the
373 /// handle is private and not inheritable.
374 pub(crate) fn assign_current_process() -> Result<Self, String> {
375 use windows_sys::Win32::System::JobObjects::{
376 AssignProcessToJobObject, CreateJobObjectW,
377 };
378 use windows_sys::Win32::System::Threading::GetCurrentProcess;
379
380 // SAFETY: null attributes/name create a private job owned by Self.
381 let handle = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
382 if handle.is_null() {
383 return Err(format!(
384 "failed to create job object: {}",
385 std::io::Error::last_os_error()
386 ));
387 }
388 let job = Self(handle);
389 job.set_limit_flags(JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE)
390 .map_err(|error| format!("failed to configure job object: {error}"))?;
391 // SAFETY: the pseudo-handle of the current process is always valid.
392 let assigned = unsafe { AssignProcessToJobObject(job.0, GetCurrentProcess()) };
393 if assigned == 0 {
394 return Err(format!(
395 "failed to assign this process to its session job: {}",
396 std::io::Error::last_os_error()
397 ));
398 }
399 Ok(job)
400 }
401
402 /// End every process in the job.
403 pub(crate) fn terminate(&self) {
404 // SAFETY: self.0 is a live job handle owned by this instance.
405 unsafe {
406 windows_sys::Win32::System::JobObjects::TerminateJobObject(self.0, 1);
407 }
408 }
409
410 /// Stop killing the job's processes when the handle closes.
411 pub(crate) fn release(&self) {
412 if let Err(error) = self.set_limit_flags(0) {
413 tracing::warn!("failed to release job object: {error}");
414 }
415 }
416
417 fn set_limit_flags(&self, flags: u32) -> std::io::Result<()> {
418 let mut limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
419 limits.BasicLimitInformation.LimitFlags = flags;
420 // SAFETY: limits has the exact structure and size this info class requires.
421 let configured = unsafe {
422 SetInformationJobObject(
423 self.0,
424 JobObjectExtendedLimitInformation,
425 std::ptr::from_ref(&limits).cast(),
426 std::mem::size_of_val(&limits) as u32,
427 )
428 };
429 if configured == 0 {
430 return Err(std::io::Error::last_os_error());
431 }
432 Ok(())
433 }
434 }
435
436 impl Drop for ProcessJob {
437 fn drop(&mut self) {
438 // SAFETY: this instance exclusively owns the CreateJobObjectW handle.
439 unsafe {
440 CloseHandle(self.0);
441 }
442 }
443 }
444
445 /// Resume every thread of a process spawned with `CREATE_SUSPENDED`.
446 pub(crate) fn resume(process_id: u32) -> Result<(), String> {
447 use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
448 use windows_sys::Win32::System::Diagnostics::ToolHelp::{
449 CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next,
450 };
451 use windows_sys::Win32::System::Threading::{
452 OpenThread, ResumeThread, THREAD_SUSPEND_RESUME,
453 };
454
455 // SAFETY: snapshot handle is closed on every return path below.
456 let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) };
457 if snapshot == INVALID_HANDLE_VALUE {
458 return Err(format!(
459 "failed to inspect suspended process {process_id} threads: {}",
460 std::io::Error::last_os_error()
461 ));
462 }
463 let mut entry = THREADENTRY32 {
464 dwSize: std::mem::size_of::<THREADENTRY32>() as u32,
465 ..THREADENTRY32::default()
466 };
467 // SAFETY: snapshot and entry are valid for ToolHelp thread enumeration.
468 let mut has_entry = unsafe { Thread32First(snapshot, &raw mut entry) } != 0;
469 let mut resumed = false;
470 let result = loop {
471 if !has_entry {
472 break if resumed {
473 Ok(())
474 } else {
475 Err(format!(
476 "suspended process {process_id} exposed no resumable thread"
477 ))
478 };
479 }
480 if entry.th32OwnerProcessID == process_id {
481 // SAFETY: entry names a thread owned by the suspended child process.
482 let thread = unsafe { OpenThread(THREAD_SUSPEND_RESUME, 0, entry.th32ThreadID) };
483 if thread.is_null() {
484 break Err(format!(
485 "failed to open suspended process {process_id} thread: {}",
486 std::io::Error::last_os_error()
487 ));
488 }
489 // SAFETY: thread is a live handle with THREAD_SUSPEND_RESUME access.
490 let resume_result = unsafe { ResumeThread(thread) };
491 // SAFETY: this scope owns the OpenThread handle.
492 unsafe { CloseHandle(thread) };
493 if resume_result == u32::MAX {
494 break Err(format!(
495 "failed to resume process {process_id} thread: {}",
496 std::io::Error::last_os_error()
497 ));
498 }
499 resumed = true;
500 }
501 // SAFETY: snapshot and entry remain valid until CloseHandle below.
502 has_entry = unsafe { Thread32Next(snapshot, &raw mut entry) } != 0;
503 };
504 // SAFETY: this scope owns the ToolHelp snapshot handle.
505 unsafe { CloseHandle(snapshot) };
506 result
507 }
508}
509
510#[cfg(all(test, unix))]
511mod tests {
512 use super::ProcessTree;
513 use std::os::unix::process::CommandExt;
514 use std::process::{Command, Stdio};
515 use std::time::{Duration, Instant};
516
517 fn alive(pid: i32) -> bool {
518 // SAFETY: signal 0 only probes whether the pid exists.
519 unsafe { libc::kill(pid, 0) == 0 }
520 }
521
522 #[test]
523 fn kill_ends_grandchildren_not_just_the_shell() {
524 let mut cmd = Command::new("sh");
525 cmd.args(["-c", "sleep 30 & echo $!; wait"])
526 .stdin(Stdio::null())
527 .stdout(Stdio::piped())
528 .process_group(0);
529 ProcessTree::prepare(&mut cmd);
530 let mut child = cmd.spawn().expect("spawn sh");
531 let tree = ProcessTree::start(&mut child).expect("start tree");
532
533 let mut line = String::new();
534 std::io::BufRead::read_line(
535 &mut std::io::BufReader::new(child.stdout.take().expect("stdout")),
536 &mut line,
537 )
538 .expect("read grandchild pid");
539 let grandchild: i32 = line.trim().parse().expect("grandchild pid");
540 assert!(
541 alive(grandchild),
542 "grandchild must be running before the kill"
543 );
544
545 tree.kill(&mut child);
546 let _ = child.wait();
547 let deadline = Instant::now() + Duration::from_secs(5);
548 while alive(grandchild) && Instant::now() < deadline {
549 std::thread::sleep(Duration::from_millis(20));
550 }
551 assert!(!alive(grandchild), "kill must reach the shell's grandchild");
552 }
553
554 #[test]
555 fn release_after_normal_exit_is_a_no_op() {
556 let mut cmd = Command::new("sh");
557 cmd.args(["-c", "exit 3"]).process_group(0);
558 ProcessTree::prepare(&mut cmd);
559 let mut child = cmd.spawn().expect("spawn sh");
560 let tree = ProcessTree::start(&mut child).expect("start tree");
561 let status = child.wait().expect("wait");
562 tree.release();
563 assert_eq!(status.code(), Some(3));
564 }
565}