Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(host-core): identify runner descendants before terminating them

agentc57933847cf5
diff --git a/crates/host-core/src/background_tasks.rs b/crates/host-core/src/background_tasks.rs
index 0e1803aef..178662d24 100644
--- a/crates/host-core/src/background_tasks.rs
+++ b/crates/host-core/src/background_tasks.rs
@@ -526,6 +526,9 @@ impl BackgroundTaskRegistry {
}
}
+#[cfg(all(windows, test))]
+mod windows_tests;
+
#[cfg(test)]
mod tests {
use super::*;
@@ -533,7 +536,7 @@ mod tests {
/// A real session row, because a background spawn now refuses to start for
/// a session that no longer exists.
- fn new_session(st: &crate::state::AppState) -> String {
+ pub(super) fn new_session(st: &crate::state::AppState) -> String {
crate::sessions::create_session(&st.db, Some("test".into()), None, None, None, None)
.unwrap()
.id
@@ -887,223 +890,4 @@ mod tests {
let st = state.lock().await;
assert_eq!(st.background_tasks.running_count(), 0);
}
-
- /// On Windows, stopping a background task must terminate any child processes
- /// spawned by the shell runner, not only the top-level shell, including
- /// multi-level descendant trees.
- #[cfg(windows)]
- #[tokio::test]
- async fn stop_terminates_descendant_processes_on_windows() {
- let dir = tempfile::tempdir().unwrap();
- let child_pid_file = dir.path().join("child_pid.txt");
- let grandchild_pid_file = dir.path().join("grandchild_pid.txt");
- let child_pid_file_str = child_pid_file.to_str().unwrap().replace('\\', "/");
- let grandchild_pid_file_str = grandchild_pid_file.to_str().unwrap().replace('\\', "/");
-
- let child_script = dir.path().join("child.ps1");
- let grandchild_script = dir.path().join("grandchild.ps1");
-
- // Grandchild script: writes grandchild PID and sleeps
- std::fs::write(
- &grandchild_script,
- format!(
- "[System.IO.File]::WriteAllText('{grandchild_pid_file_str}', $PID); Start-Sleep -Seconds 60"
- ),
- )
- .unwrap();
-
- // Child script: writes child PID, spawns grandchild script, and sleeps
- let grandchild_script_str = grandchild_script.to_str().unwrap().replace('\\', "/");
- std::fs::write(
- &child_script,
- format!(
- "[System.IO.File]::WriteAllText('{child_pid_file_str}', $PID); \
- Start-Process powershell -ArgumentList '-NoProfile','-ExecutionPolicy','Bypass','-File','{grandchild_script_str}'; \
- Start-Sleep -Seconds 60"
- ),
- )
- .unwrap();
-
- // Top-level command executed by the runner shell: spawns child script and sleeps
- let child_script_str = child_script.to_str().unwrap().replace('\\', "/");
- let command = format!(
- "Start-Process powershell -ArgumentList '-NoProfile','-ExecutionPolicy','Bypass','-File','{child_script_str}'; Start-Sleep -Seconds 60"
- );
-
- let state = tokio::sync::Mutex::new(crate::state::AppState::open(dir.path()).unwrap());
- let session_id = {
- let st = state.lock().await;
- new_session(&st)
- };
- let id = spawn_background_task_detached(
- &state,
- &session_id,
- &command,
- crate::tools::shell::default_shell_id(),
- dir.path(),
- None,
- )
- .await
- .unwrap();
-
- // Wait for both child and grandchild PIDs to be recorded
- let mut child_pid = None;
- let mut grandchild_pid = None;
- for _ in 0..100 {
- tokio::time::sleep(Duration::from_millis(50)).await;
- if child_pid.is_none() {
- if let Ok(content) = std::fs::read_to_string(&child_pid_file) {
- if let Ok(pid) = content.trim().parse::<u32>() {
- child_pid = Some(pid);
- }
- }
- }
- if grandchild_pid.is_none() {
- if let Ok(content) = std::fs::read_to_string(&grandchild_pid_file) {
- if let Ok(pid) = content.trim().parse::<u32>() {
- grandchild_pid = Some(pid);
- }
- }
- }
- if child_pid.is_some() && grandchild_pid.is_some() {
- break;
- }
- }
- let child_pid = child_pid.expect("descendant child powershell process must write its PID");
- let grandchild_pid =
- grandchild_pid.expect("descendant grandchild powershell process must write its PID");
-
- // Verify descendant processes are alive
- use windows_sys::Win32::Foundation::{CloseHandle, STILL_ACTIVE};
- use windows_sys::Win32::System::Threading::{
- GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
- };
- for pid in [child_pid, grandchild_pid] {
- let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
- assert!(
- !handle.is_null(),
- "descendant process {pid} should be running before stop"
- );
- let mut exit_code = 0u32;
- unsafe {
- GetExitCodeProcess(handle, &mut exit_code);
- CloseHandle(handle);
- }
- assert_eq!(exit_code, STILL_ACTIVE as u32);
- }
-
- // Now stop the task
- {
- let st = state.lock().await;
- assert!(stop_task(&st.background_tasks, &id).await.unwrap());
- }
-
- // Wait for task to settle to Stopped
- let mut settled = false;
- for _ in 0..100 {
- tokio::time::sleep(Duration::from_millis(50)).await;
- let st = state.lock().await;
- if st.background_tasks.running_count() == 0 {
- settled = true;
- break;
- }
- }
- assert!(settled, "background task settled");
-
- // Both child and grandchild must be dead
- for pid in [child_pid, grandchild_pid] {
- let mut alive = true;
- for _ in 0..60 {
- let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
- if handle.is_null() {
- alive = false;
- break;
- }
- let mut exit_code = 0u32;
- let queried = unsafe { GetExitCodeProcess(handle, &mut exit_code) };
- unsafe {
- CloseHandle(handle);
- }
- if queried == 0 || exit_code != STILL_ACTIVE as u32 {
- alive = false;
- break;
- }
- tokio::time::sleep(Duration::from_millis(50)).await;
- }
- assert!(
- !alive,
- "descendant process {pid} must be terminated when background task stops"
- );
- }
- }
-
- /// When a descendant process cannot be terminated (e.g. system service or
- /// denied access while still alive), stop/cleanup must propagate the failure
- /// rather than reporting false success with an escaped live process.
- #[cfg(windows)]
- #[tokio::test]
- async fn stop_propagates_access_denied_when_descendant_remains_alive() {
- // Find a live system or elevated process that ordinary user processes
- // cannot open with PROCESS_TERMINATE (returning ERROR_ACCESS_DENIED).
- use windows_sys::Win32::Foundation::{GetLastError, ERROR_ACCESS_DENIED};
- use windows_sys::Win32::System::Diagnostics::ToolHelp::{
- CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W,
- TH32CS_SNAPPROCESS,
- };
- use windows_sys::Win32::System::Threading::{OpenProcess, PROCESS_TERMINATE};
-
- let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) };
- assert!(snapshot != windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE);
-
- let mut entry: PROCESSENTRY32W = unsafe { std::mem::zeroed() };
- entry.dwSize = std::mem::size_of::<PROCESSENTRY32W>() as u32;
-
- let mut denied_pid = None;
- if unsafe { Process32FirstW(snapshot, &mut entry) } != 0 {
- loop {
- let pid = entry.th32ProcessID;
- if pid > 4 {
- let handle = unsafe { OpenProcess(PROCESS_TERMINATE, 0, pid) };
- if handle.is_null() {
- let err = unsafe { GetLastError() };
- if err == ERROR_ACCESS_DENIED {
- denied_pid = Some(pid);
- break;
- }
- } else {
- unsafe {
- windows_sys::Win32::Foundation::CloseHandle(handle);
- }
- }
- }
- if unsafe { Process32NextW(snapshot, &mut entry) } == 0 {
- break;
- }
- }
- }
- unsafe {
- windows_sys::Win32::Foundation::CloseHandle(snapshot);
- }
-
- let Some(target_pid) = denied_pid else {
- // In an environment where all processes can be terminated (unlikely), skip.
- return;
- };
-
- // Verifying terminate_windows_process_tree directly for root_pid of the denied process:
- // A synthetic parent PID that owns target_pid, or calling terminate_windows_process_tree
- // on the parent of target_pid will attempt to terminate target_pid and fail.
- // Even simpler: test that terminating a tree containing target_pid propagates Err.
- let result = crate::tools::terminate_windows_process_tree_for_test(target_pid);
- assert!(
- result.is_err(),
- "tree termination must fail when a live descendant cannot be terminated: {:?}",
- result
- );
- let err_msg = result.unwrap_err();
- assert!(
- err_msg.contains("OpenProcess failed") || err_msg.contains("TerminateProcess failed"),
- "unexpected error message: {err_msg}"
- );
- }
}
diff --git a/crates/host-core/src/background_tasks/windows_tests.rs b/crates/host-core/src/background_tasks/windows_tests.rs
new file mode 100644
index 000000000..18cf87cbf
--- /dev/null
+++ b/crates/host-core/src/background_tasks/windows_tests.rs
@@ -0,0 +1,141 @@
+//! Windows-only regression coverage for issue #1805: stopping a background task
+//! must terminate the command the runner launched, not only the runner itself.
+
+use super::tests::new_session;
+use super::*;
+use std::time::Duration;
+
+/// The reported symptom: a stop took the runner shell but left the command
+/// it launched — and that command's own child — running (#1805).
+///
+/// The production chain is exercised end to end: the host binary starts in
+/// hidden runner mode, reads its config frame, then starts the shell. A test
+/// that spawns the shell directly would not cover the ordering the race
+/// depends on.
+#[cfg(windows)]
+#[tokio::test]
+async fn stop_terminates_the_command_the_runner_launched() {
+ let dir = tempfile::tempdir().unwrap();
+ let command_pid_file = dir.path().join("command-pid.txt");
+ let nested_pid_file = dir.path().join("nested-pid.txt");
+ let ps_path = |path: &std::path::Path| path.display().to_string().replace('\\', "/");
+
+ let nested_script = dir.path().join("nested.ps1");
+ std::fs::write(
+ &nested_script,
+ format!(
+ "[System.IO.File]::WriteAllText('{}', $PID); Start-Sleep -Seconds 120",
+ ps_path(&nested_pid_file)
+ ),
+ )
+ .unwrap();
+
+ let command_script = dir.path().join("command.ps1");
+ std::fs::write(
+ &command_script,
+ format!(
+ "[System.IO.File]::WriteAllText('{own}', $PID); \
+ Start-Process powershell -ArgumentList '-NoProfile','-ExecutionPolicy','Bypass','-File','{nested}'; \
+ Start-Sleep -Seconds 120",
+ own = ps_path(&command_pid_file),
+ nested = ps_path(&nested_script),
+ ),
+ )
+ .unwrap();
+
+ let state = tokio::sync::Mutex::new(crate::state::AppState::open(dir.path()).unwrap());
+ let session_id = {
+ let st = state.lock().await;
+ new_session(&st)
+ };
+ let command = format!(
+ "powershell -NoProfile -ExecutionPolicy Bypass -File '{}'",
+ command_script.display()
+ );
+ let id = spawn_background_task_detached(
+ &state,
+ &session_id,
+ &command,
+ crate::tools::shell::default_shell_id(),
+ dir.path(),
+ None,
+ )
+ .await
+ .unwrap();
+
+ // Both levels have to be running first, otherwise the assertions below
+ // would pass on a fixture that never launched anything.
+ let mut command_pid = None;
+ let mut nested_pid = None;
+ for _ in 0..200 {
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ command_pid = command_pid.or_else(|| read_pid(&command_pid_file));
+ nested_pid = nested_pid.or_else(|| read_pid(&nested_pid_file));
+ if command_pid.is_some() && nested_pid.is_some() {
+ break;
+ }
+ }
+ let command_pid = command_pid.expect("the shell must launch the command");
+ let nested_pid = nested_pid.expect("the command must launch its own child");
+ assert!(process_running(command_pid), "command runs before the stop");
+ assert!(
+ process_running(nested_pid),
+ "nested child runs before the stop"
+ );
+
+ {
+ let st = state.lock().await;
+ assert!(stop_task(&st.background_tasks, &id).await.unwrap());
+ }
+
+ assert!(
+ wait_for_exit(nested_pid),
+ "the command's own child must not survive stopping the task (#1805)"
+ );
+ assert!(
+ wait_for_exit(command_pid),
+ "the launched command must not survive stopping the task (#1805)"
+ );
+
+ let mut st = state.lock().await;
+ st.shutdown();
+}
+
+#[cfg(windows)]
+fn read_pid(path: &std::path::Path) -> Option<u32> {
+ std::fs::read_to_string(path)
+ .ok()
+ .and_then(|text| text.trim().parse().ok())
+}
+
+/// A process the test cannot query is a fixture failure, not "exited": the
+/// assertions above would otherwise pass for the wrong reason.
+#[cfg(windows)]
+fn process_running(pid: u32) -> bool {
+ use windows_sys::Win32::Foundation::{CloseHandle, STILL_ACTIVE};
+ use windows_sys::Win32::System::Threading::{
+ GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
+ };
+
+ let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
+ if handle.is_null() {
+ return false;
+ }
+ let mut exit_code = 0u32;
+ let queried = unsafe { GetExitCodeProcess(handle, &mut exit_code) };
+ unsafe {
+ CloseHandle(handle);
+ }
+ queried != 0 && exit_code == STILL_ACTIVE as u32
+}
+
+#[cfg(windows)]
+fn wait_for_exit(pid: u32) -> bool {
+ for _ in 0..120 {
+ if !process_running(pid) {
+ return true;
+ }
+ std::thread::sleep(Duration::from_millis(50));
+ }
+ false
+}
diff --git a/crates/host-core/src/tools/mod.rs b/crates/host-core/src/tools/mod.rs
index 6a2d47150..d77f9760a 100644
--- a/crates/host-core/src/tools/mod.rs
+++ b/crates/host-core/src/tools/mod.rs
@@ -28,6 +28,8 @@ pub mod hashline;
pub mod ignore_rules;
mod image_dimensions;
pub mod shell;
+#[cfg(windows)]
+mod windows_process_tree;
pub use hashline::{HashlineContext, HashlineStore};
@@ -112,25 +114,13 @@ const RUNNER_SPAWN_BACKOFFS_MS: [u64; 3] = [50, 100, 250];
const INTERNAL_RUNNER_ERROR_PREFIX: &str = "PI_DESKTOP_RUNNER_ERROR\t";
#[cfg(windows)]
-use windows_sys::Win32::Foundation::{
- CloseHandle, GetLastError, ERROR_ACCESS_DENIED, ERROR_INVALID_PARAMETER, ERROR_NO_MORE_FILES,
- HANDLE, INVALID_HANDLE_VALUE, STILL_ACTIVE,
-};
-#[cfg(windows)]
-use windows_sys::Win32::System::Diagnostics::ToolHelp::{
- CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W, TH32CS_SNAPPROCESS,
-};
+use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
#[cfg(windows)]
use windows_sys::Win32::System::JobObjects::{
AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation,
SetInformationJobObject, TerminateJobObject, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
};
-#[cfg(windows)]
-use windows_sys::Win32::System::Threading::{
- GetExitCodeProcess, OpenProcess, TerminateProcess, PROCESS_QUERY_LIMITED_INFORMATION,
- PROCESS_TERMINATE,
-};
#[cfg(windows)]
#[derive(Debug, Default)]
@@ -296,128 +286,7 @@ impl Drop for ProcessOwnership {
#[cfg(windows)]
fn terminate_windows_process_tree(root_pid: u32) -> Result<(), String> {
- let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) };
- if snapshot == INVALID_HANDLE_VALUE {
- let err = std::io::Error::last_os_error();
- return Err(format!("CreateToolhelp32Snapshot failed: {err}"));
- }
-
- let mut parent_to_children: std::collections::HashMap<u32, Vec<u32>> =
- std::collections::HashMap::new();
- let mut entry: PROCESSENTRY32W = unsafe { std::mem::zeroed() };
- entry.dwSize = std::mem::size_of::<PROCESSENTRY32W>() as u32;
-
- if unsafe { Process32FirstW(snapshot, &mut entry) } != 0 {
- loop {
- let pid = entry.th32ProcessID;
- let parent_pid = entry.th32ParentProcessID;
- if pid != 0 && pid != parent_pid {
- parent_to_children.entry(parent_pid).or_default().push(pid);
- }
- if unsafe { Process32NextW(snapshot, &mut entry) } == 0 {
- let err = unsafe { GetLastError() };
- if err != ERROR_NO_MORE_FILES {
- unsafe {
- CloseHandle(snapshot);
- }
- let os_err = std::io::Error::from_raw_os_error(err as i32);
- return Err(format!("Process32NextW failed: {os_err}"));
- }
- break;
- }
- }
- } else {
- let err = std::io::Error::last_os_error();
- unsafe {
- CloseHandle(snapshot);
- }
- return Err(format!("Process32FirstW failed: {err}"));
- }
- unsafe {
- CloseHandle(snapshot);
- }
-
- // Traverse the descendants breadth-first / post-order to collect all child PIDs.
- let mut queue = std::collections::VecDeque::new();
- let mut descendants = Vec::new();
- queue.push_back(root_pid);
- descendants.push(root_pid);
-
- while let Some(current) = queue.pop_front() {
- if let Some(children) = parent_to_children.get(&current) {
- for &child in children {
- descendants.push(child);
- queue.push_back(child);
- }
- }
- }
-
- let mut first_error: Option<String> = None;
-
- // Helper to verify if a process has already exited when OpenProcess/TerminateProcess
- // encounters ERROR_ACCESS_DENIED or other unexpected errors.
- let is_process_exited = |pid: u32| -> bool {
- let query_handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
- if query_handle.is_null() {
- let err = unsafe { GetLastError() };
- // If query open fails with invalid parameter, the PID does not exist (already exited).
- return err == ERROR_INVALID_PARAMETER;
- }
- let mut exit_code = 0u32;
- let queried = unsafe { GetExitCodeProcess(query_handle, &mut exit_code) };
- unsafe {
- CloseHandle(query_handle);
- }
- queried != 0 && exit_code != STILL_ACTIVE as u32
- };
-
- // Terminate leaf/descendant processes in reverse order so children are terminated before parents.
- // Continue cleanup across the remaining descendant tree, recording the first failure.
- for &pid in descendants.iter().rev() {
- let process = unsafe { OpenProcess(PROCESS_TERMINATE, 0, pid) };
- if process.is_null() {
- let err = unsafe { GetLastError() };
- if err == ERROR_INVALID_PARAMETER {
- // The process already exited.
- continue;
- }
- if err == ERROR_ACCESS_DENIED && is_process_exited(pid) {
- // Verified already exited race despite access denied on terminate open.
- continue;
- }
- let os_err = std::io::Error::from_raw_os_error(err as i32);
- if first_error.is_none() {
- first_error = Some(format!("OpenProcess failed for PID {pid}: {os_err}"));
- }
- continue;
- }
- let term_res = unsafe { TerminateProcess(process, 1) };
- if term_res == 0 {
- let err = unsafe { GetLastError() };
- if err == ERROR_INVALID_PARAMETER {
- // The process already exited.
- } else if err == ERROR_ACCESS_DENIED && is_process_exited(pid) {
- // Verified already exited race.
- } else if first_error.is_none() {
- let os_err = std::io::Error::from_raw_os_error(err as i32);
- first_error = Some(format!("TerminateProcess failed for PID {pid}: {os_err}"));
- }
- }
- unsafe {
- CloseHandle(process);
- }
- }
-
- if let Some(err) = first_error {
- Err(err)
- } else {
- Ok(())
- }
-}
-
-#[cfg(all(windows, test))]
-pub(crate) fn terminate_windows_process_tree_for_test(root_pid: u32) -> Result<(), String> {
- terminate_windows_process_tree(root_pid)
+ windows_process_tree::terminate_tree(root_pid)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
diff --git a/crates/host-core/src/tools/windows_process_tree.rs b/crates/host-core/src/tools/windows_process_tree.rs
new file mode 100644
index 000000000..89ca3da54
--- /dev/null
+++ b/crates/host-core/src/tools/windows_process_tree.rs
@@ -0,0 +1,293 @@
+//! Windows descendant termination for a tool runner (issue #1805).
+//!
+//! `AssignProcessToJobObject` does not reach processes the shell already
+//! spawned, so a command launched at shell startup can sit outside the job and
+//! survive `TerminateJobObject`. This module terminates the runner's descendant
+//! tree through the process snapshot, and it refuses to act on a PID whose
+//! identity it cannot tie back to the snapshot: a PID is only meaningful while
+//! the process that owned it is still the same process.
+
+use std::collections::{HashMap, HashSet, VecDeque};
+
+use windows_sys::Win32::Foundation::{
+ CloseHandle, GetLastError, ERROR_ACCESS_DENIED, ERROR_INVALID_PARAMETER, ERROR_NO_MORE_FILES,
+ FILETIME, HANDLE, INVALID_HANDLE_VALUE, STILL_ACTIVE,
+};
+use windows_sys::Win32::System::Diagnostics::ToolHelp::{
+ CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W, TH32CS_SNAPPROCESS,
+};
+use windows_sys::Win32::System::Threading::{
+ GetExitCodeProcess, GetProcessTimes, OpenProcess, TerminateProcess,
+ PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_TERMINATE,
+};
+
+/// Terminate every live descendant of `root_pid`, deepest first, then the root.
+///
+/// Cleanup continues across the whole tree after a failure so one stuck process
+/// never hides the rest; the first failure is reported afterwards. That keeps
+/// the caller from recording "stopped" while a descendant is still running.
+pub(super) fn terminate_tree(root_pid: u32) -> Result<(), String> {
+ if root_pid == 0 {
+ return Ok(());
+ }
+ let snapshot = Snapshot::capture()?;
+ // A process created after the snapshot cannot be one the snapshot
+ // described, so its creation time is the watermark that makes a recycled
+ // PID distinguishable from the real descendant.
+ let watermark = ProcessTimes::now()?;
+
+ let mut errors: Vec<String> = Vec::new();
+ for pid in snapshot.descendants_deepest_first(root_pid) {
+ if let Err(error) = terminate_member(pid, &watermark) {
+ errors.push(error);
+ }
+ }
+ match errors.split_first() {
+ None => Ok(()),
+ Some((first, [])) => Err(first.clone()),
+ Some((first, rest)) => Err(format!("{first} (and {} more)", rest.len())),
+ }
+}
+
+/// Parent → children edges captured from `TH32CS_SNAPPROCESS`.
+struct Snapshot {
+ edges: HashMap<u32, Vec<u32>>,
+}
+
+impl Snapshot {
+ fn capture() -> Result<Self, String> {
+ let handle = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) };
+ if handle == INVALID_HANDLE_VALUE {
+ return Err(format!(
+ "CreateToolhelp32Snapshot failed: {}",
+ std::io::Error::last_os_error()
+ ));
+ }
+ let mut entry: PROCESSENTRY32W = unsafe { std::mem::zeroed() };
+ entry.dwSize = std::mem::size_of::<PROCESSENTRY32W>() as u32;
+ let mut edges: HashMap<u32, Vec<u32>> = HashMap::new();
+ if unsafe { Process32FirstW(handle, &mut entry) } == 0 {
+ let error = std::io::Error::last_os_error();
+ unsafe {
+ CloseHandle(handle);
+ }
+ return Err(format!("Process32FirstW failed: {error}"));
+ }
+ loop {
+ if entry.th32ProcessID != 0 && entry.th32ProcessID != entry.th32ParentProcessID {
+ edges
+ .entry(entry.th32ParentProcessID)
+ .or_default()
+ .push(entry.th32ProcessID);
+ }
+ if unsafe { Process32NextW(handle, &mut entry) } == 0 {
+ break;
+ }
+ }
+ // A zero result means either "no more files" or a real enumeration
+ // failure; only the first is a completed snapshot.
+ let error = unsafe { GetLastError() };
+ unsafe {
+ CloseHandle(handle);
+ }
+ if error != ERROR_NO_MORE_FILES {
+ return Err(format!(
+ "Process32NextW failed: {}",
+ std::io::Error::from_raw_os_error(error as i32)
+ ));
+ }
+ Ok(Self { edges })
+ }
+
+ fn descendants_deepest_first(&self, root: u32) -> Vec<u32> {
+ // Breadth-first from the root, then reversed: children are terminated
+ // before the parent that could still spawn more of them.
+ let mut order = Vec::new();
+ let mut seen = HashSet::from([root]);
+ let mut queue = VecDeque::from([root]);
+ while let Some(current) = queue.pop_front() {
+ if let Some(children) = self.edges.get(&current) {
+ for &child in children {
+ // A recycled parent PID can make the edge list cyclic;
+ // each PID is terminated at most once.
+ if seen.insert(child) {
+ order.push(child);
+ queue.push_back(child);
+ }
+ }
+ }
+ }
+ order.reverse();
+ order.push(root);
+ order
+ }
+}
+
+/// Terminate one snapshot entry after proving it is still that process.
+fn terminate_member(pid: u32, watermark: &ProcessTimes) -> Result<(), String> {
+ let handle = unsafe {
+ OpenProcess(
+ PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION,
+ 0,
+ pid,
+ )
+ };
+ if handle.is_null() {
+ let error = unsafe { GetLastError() };
+ if error == ERROR_INVALID_PARAMETER {
+ // The PID is gone, which is the outcome stopping wants.
+ return Ok(());
+ }
+ // Access denied here is a live process this runner cannot open; it is
+ // not proof of exit, so it must surface rather than pass as stopped.
+ return Err(format!(
+ "OpenProcess failed for runner process {pid}: {}",
+ std::io::Error::from_raw_os_error(error as i32)
+ ));
+ }
+ let result = terminate_handle(pid, handle, watermark);
+ unsafe {
+ CloseHandle(handle);
+ }
+ result
+}
+
+fn terminate_handle(pid: u32, handle: HANDLE, watermark: &ProcessTimes) -> Result<(), String> {
+ let mut exit_code = 0u32;
+ if unsafe { GetExitCodeProcess(handle, &mut exit_code) } == 0 {
+ return Err(format!(
+ "GetExitCodeProcess failed for runner process {pid}: {}",
+ std::io::Error::last_os_error()
+ ));
+ }
+ if exit_code != STILL_ACTIVE as u32 {
+ return Ok(());
+ }
+ // The handle is bound to one process, so a recycled PID cannot be hit
+ // through it. The creation time is still checked because a snapshot entry
+ // may name a process that exited while a new one took its PID.
+ let created = ProcessTimes::of(handle)
+ .map_err(|error| format!("GetProcessTimes failed for runner process {pid}: {error}"))?;
+ if created.created_after(watermark) {
+ return Ok(());
+ }
+ if unsafe { TerminateProcess(handle, 1) } == 0 {
+ let error = unsafe { GetLastError() };
+ if error == ERROR_INVALID_PARAMETER {
+ return Ok(());
+ }
+ let mut after = 0u32;
+ let queried = unsafe { GetExitCodeProcess(handle, &mut after) };
+ if queried != 0 && after != STILL_ACTIVE as u32 {
+ // It exited while the call was in flight.
+ return Ok(());
+ }
+ if error == ERROR_ACCESS_DENIED {
+ return Err(format!(
+ "TerminateProcess denied for live runner process {pid}; it may still be running"
+ ));
+ }
+ return Err(format!(
+ "TerminateProcess failed for runner process {pid}: {}",
+ std::io::Error::from_raw_os_error(error as i32)
+ ));
+ }
+ Ok(())
+}
+
+/// Process creation times in 100ns intervals since 1601.
+///
+/// Comparable without converting either side to `SystemTime`, and every value
+/// comes from the same clock the snapshot entries are created under.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+pub(super) struct ProcessTimes {
+ created: u64,
+}
+
+impl ProcessTimes {
+ fn of(handle: HANDLE) -> std::io::Result<Self> {
+ let mut created = FILETIME {
+ dwLowDateTime: 0,
+ dwHighDateTime: 0,
+ };
+ let mut exited = created;
+ let mut kernel = created;
+ let mut user = created;
+ if unsafe { GetProcessTimes(handle, &mut created, &mut exited, &mut kernel, &mut user) }
+ == 0
+ {
+ return Err(std::io::Error::last_os_error());
+ }
+ Ok(Self {
+ created: (u64::from(created.dwHighDateTime) << 32) | u64::from(created.dwLowDateTime),
+ })
+ }
+
+ /// Creation time of the current process, used as the snapshot watermark.
+ fn now() -> Result<Self, String> {
+ let current = unsafe { windows_sys::Win32::System::Threading::GetCurrentProcess() };
+ Self::of(current)
+ .map_err(|error| format!("GetProcessTimes failed for the current process: {error}"))
+ }
+
+ fn created_after(&self, watermark: &Self) -> bool {
+ self.created > watermark.created
+ }
+
+ #[cfg(test)]
+ pub(super) fn from_raw(created: u64) -> Self {
+ Self { created }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn children_are_terminated_before_their_parents() {
+ let edges = HashMap::from([
+ (10, vec![11]),
+ (11, vec![12]),
+ (12, vec![13]),
+ (11, vec![14]),
+ ]);
+ let order = Snapshot { edges }.descendants_deepest_first(10);
+ let position = |pid: u32| order.iter().position(|entry| *entry == pid).unwrap();
+ assert!(position(13) < position(12));
+ assert!(position(12) < position(11));
+ assert!(position(14) < position(11));
+ assert!(
+ position(10) > position(11),
+ "the runner itself is terminated last"
+ );
+ assert_eq!(order.len(), 5, "root plus four descendants");
+ }
+
+ #[test]
+ fn unrelated_processes_are_not_in_the_tree() {
+ let edges = HashMap::from([(1, vec![2]), (2, vec![3]), (7, vec![8])]);
+ let order = Snapshot { edges }.descendants_deepest_first(1);
+ assert_eq!(order, vec![3, 2, 1]);
+ }
+
+ #[test]
+ fn a_cyclic_snapshot_lists_each_pid_once() {
+ // A recycled parent PID can make the edge list point back at the root.
+ let edges = HashMap::from([(5, vec![6]), (6, vec![7]), (7, vec![5])]);
+ let order = Snapshot { edges }.descendants_deepest_first(5);
+ let mut unique = order.clone();
+ unique.sort_unstable();
+ unique.dedup();
+ assert_eq!(unique.len(), order.len());
+ assert_eq!(order.iter().filter(|pid| **pid == 5).count(), 1);
+ }
+
+ #[test]
+ fn a_process_created_after_the_snapshot_is_a_recycled_pid() {
+ let watermark = ProcessTimes::from_raw(1_000);
+ assert!(ProcessTimes::from_raw(1_001).created_after(&watermark));
+ assert!(!ProcessTimes::from_raw(1_000).created_after(&watermark));
+ assert!(!ProcessTimes::from_raw(999).created_after(&watermark));
+ }
+}