From 083e6c10e434abc9f0f913a1731d31f9c2f8359b Mon Sep 17 00:00:00 2001 From: Daniel Rispler Date: Tue, 1 Dec 2026 10:52:49 +0200 Subject: [PATCH 1/4] Studio: the runner's tree rows run on every platform, with a Rust fake helper (#940) The rows fail on Windows until the runner kills the whole tree there. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + test-support/Cargo.toml | 4 + test-support/src/fake.rs | 101 ++++++++++++++++ test-support/src/lib.rs | 2 +- workbench/tests/run.rs | 243 +++++++++++++++++++++++++++------------ 5 files changed, 278 insertions(+), 73 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a5a39b7c3..20779e5ad 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -638,6 +638,7 @@ dependencies = [ "libc", "serde_json", "tempfile", + "windows-sys 0.61.2", ] [[package]] diff --git a/test-support/Cargo.toml b/test-support/Cargo.toml index 0b87bdfde..357ccd4ff 100644 --- a/test-support/Cargo.toml +++ b/test-support/Cargo.toml @@ -11,5 +11,9 @@ libc = "0.2" serde_json = "1" tempfile = "3" +# The fake's helper: whether a process still runs, and the fake's own output kept from a helper given none (#940). +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_Threading"] } + [lints] workspace = true diff --git a/test-support/src/fake.rs b/test-support/src/fake.rs index bafeae324..1d3dcae2e 100644 --- a/test-support/src/fake.rs +++ b/test-support/src/fake.rs @@ -23,6 +23,17 @@ pub struct Behaviour { pub wait: Duration, /// Whether it appends the call to its record, read back with [`calls`]. pub record: bool, + /// A program it starts before printing and leaves running, with no input: a credential helper or a daemon that + /// outlives the command. Its id is read back with [`helper_pid`]. + pub helper: Option, +} + +/// A fake's [`Behaviour::helper`]. +#[derive(Clone, Debug)] +pub struct Helper { + pub program: PathBuf, + /// Whether it gets the fake's own stdout and stderr, and so holds them open while it runs. + pub holds_output: bool, } /// One recorded call of a fake. @@ -48,6 +59,10 @@ fn record_file(fake: &Path) -> PathBuf { beside(fake, ".record.json") } +fn helper_pid_file(fake: &Path) -> PathBuf { + beside(fake, ".helper.pid") +} + /// A name for a temporary file beside `file`, unique to this process, thread and call. fn temp_beside(file: &Path) -> PathBuf { static NEXT: AtomicU64 = AtomicU64::new(0); @@ -108,11 +123,94 @@ pub fn fake(dir: &Path, name: &str, behaviour: &Behaviour) -> PathBuf { "code": behaviour.code, "wait_ms": behaviour.wait.as_millis() as u64, "record": behaviour.record, + "helper": behaviour.helper.as_ref().map(|h| json!({ + "program": h.program.display().to_string(), + "holds_output": h.holds_output, + })), }); write_whole(&behaviour_file(&file), &spec.to_string()); file } +/// The id of the helper the fake at `fake` started last, once it has started one. +pub fn helper_pid(fake: &Path) -> Option { + fs::read_to_string(helper_pid_file(fake)).ok()?.parse().ok() +} + +/// Whether process `pid` is still running. A killed process counts as gone once it has exited, though nobody has +/// reaped it yet on Windows; on Unix only once its parent reaps it, `launchd` or `init` for an orphan, in a moment. +#[cfg(unix)] +pub fn running(pid: u32) -> bool { + let Ok(pid) = libc::pid_t::try_from(pid) else { + return false; + }; + // SAFETY: signal 0 only checks, and `kill` takes no pointers. + unsafe { libc::kill(pid, 0) == 0 } +} + +/// Whether process `pid` is still running. A killed process counts as gone once it has exited, though nobody has +/// reaped it yet on Windows; on Unix only once its parent reaps it, `launchd` or `init` for an orphan, in a moment. +#[cfg(windows)] +pub fn running(pid: u32) -> bool { + use windows_sys::Win32::{ + Foundation::{CloseHandle, WAIT_TIMEOUT}, + System::Threading::{OpenProcess, PROCESS_SYNCHRONIZE, WaitForSingleObject}, + }; + // SAFETY: `OpenProcess` takes plain values; a null handle means no such process. + let handle = unsafe { OpenProcess(PROCESS_SYNCHRONIZE, 0, pid) }; + if handle.is_null() { + return false; + } + // SAFETY: `handle` was opened above with `SYNCHRONIZE`, and is closed once, here. + unsafe { + let still = WaitForSingleObject(handle, 0) == WAIT_TIMEOUT; + CloseHandle(handle); + still + } +} + +/// Starts the helper `spec` names, and writes its id beside `exe`. +fn start_helper(exe: &Path, spec: &Value) { + let holds = spec["holds_output"].as_bool() == Some(true); + if !holds { + keep_output_from_children(); + } + let output = || { + if holds { + std::process::Stdio::inherit() + } else { + std::process::Stdio::null() + } + }; + let helper = std::process::Command::new(spec["program"].as_str().unwrap()) + .stdin(std::process::Stdio::null()) + .stdout(output()) + .stderr(output()) + .spawn() + .unwrap(); + write_whole(&helper_pid_file(exe), &helper.id().to_string()); +} + +/// Unix: a child's stdout and stderr are only the ones it is given, so there is nothing to do. +#[cfg(unix)] +fn keep_output_from_children() {} + +/// Windows: std starts every child with all inheritable handles (its opt-out is unstable), so a child given no output +/// would still hold the fake's own stdout and stderr open; they stop being inheritable. +#[cfg(windows)] +fn keep_output_from_children() { + use std::os::windows::io::AsRawHandle; + use windows_sys::Win32::Foundation::{HANDLE_FLAG_INHERIT, SetHandleInformation}; + for handle in [ + std::io::stdout().as_raw_handle(), + std::io::stderr().as_raw_handle(), + ] { + // SAFETY: `handle` is this process's own stdout or stderr, open for its lifetime; only its inherit flag changes. + // A stream with no handle fails here, and then has nothing to hold. + unsafe { SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0) }; + } +} + /// The calls a fake recorded, oldest first. pub fn calls(fake: &Path) -> Vec { let Ok(text) = fs::read_to_string(record_file(fake)) else { @@ -167,6 +265,9 @@ fn act_as_a_fake_when_started_as_one() { write_whole(&file, &serde_json::to_string(&all).unwrap()); drop(lock); } + if spec["helper"].is_object() { + start_helper(&exe, &spec["helper"]); + } std::io::stdout() .write_all(spec["stdout"].as_str().unwrap().as_bytes()) .ok(); diff --git a/test-support/src/lib.rs b/test-support/src/lib.rs index 62c267614..7c57985e2 100644 --- a/test-support/src/lib.rs +++ b/test-support/src/lib.rs @@ -4,7 +4,7 @@ //! one. pub mod fake; -pub use fake::{Behaviour, Call, calls, fake}; +pub use fake::{Behaviour, Call, Helper, calls, fake, helper_pid, running}; #[cfg(unix)] use std::time::{Duration, Instant}; diff --git a/workbench/tests/run.rs b/workbench/tests/run.rs index e3666cede..b36312a1e 100644 --- a/workbench/tests/run.rs +++ b/workbench/tests/run.rs @@ -1,17 +1,24 @@ //! Seam 4 (#548, Testing Decisions): the process runner, with real children. A fake `git` on `PATH` records what it was -//! started with; `sh` scripts stand in for a command that hangs, fails or leaves a helper behind. - -#[cfg(unix)] -use std::time::Instant; -use std::{path::Path, process::Command, time::Duration}; -use studio_workbench::run::{RunError, gh_at, git, run_logged, run_until, run_until_with_input}; +//! started with; the Rust fake stands in for a command that hangs, fails or leaves a helper behind, on every platform +//! (#940). The logged runs, refused on Windows, still start `sh` scripts. + +use std::{ + path::{Path, PathBuf}, + process::Command, + time::{Duration, Instant}, +}; +use studio_test_support::{Behaviour, Helper, helper_pid, running}; #[cfg(unix)] -use studio_workbench::run::{run_logged_telling, run_until_unless}; +use studio_workbench::run::run_logged_telling; +use studio_workbench::run::{ + RunError, gh_at, git, run_logged, run_until, run_until_unless, run_until_with_input, +}; -/// Long enough for a loaded machine to start a script; far short of the scripts' own sleeps. -#[cfg(unix)] +/// Long enough for a loaded machine to start a fake; far short of [`LONG`]. const SOON: Duration = Duration::from_secs(2); const AMPLE: Duration = Duration::from_secs(30); +/// Far past every deadline here: a command or helper that waits this long ends in time only when it is killed. +const LONG: Duration = Duration::from_secs(20); /// A program `name` in `dir` that records its arguments, folder, environment and stdin. fn fake(dir: &Path, name: &str) -> std::path::PathBuf { @@ -31,18 +38,53 @@ fn only_call(fake: &Path) -> studio_test_support::Call { calls.remove(0) } -#[cfg(unix)] -fn sh(script: &str) -> Command { - let mut command = Command::new("sh"); - command.args(["-c", script]); - command +/// A program `name` in `dir` that acts out `behaviour`. +fn acting(dir: &Path, name: &str, behaviour: &Behaviour) -> PathBuf { + studio_test_support::fake(dir, name, behaviour) } -/// Whether process `pid` is still there. -#[cfg(unix)] -fn alive(pid: &str) -> bool { - let probe = Command::new("kill").args(["-0", pid]).output().unwrap(); - probe.status.success() +/// A command in `dir` that starts a helper waiting `helper_waits`, which holds the command's output or not, then waits +/// `waits` itself and exits 0. +fn leaving_a_helper( + dir: &Path, + holds_output: bool, + helper_waits: Duration, + waits: Duration, +) -> PathBuf { + let helper = acting( + dir, + "helper", + &Behaviour { + wait: helper_waits, + ..Default::default() + }, + ); + acting( + dir, + "command", + &Behaviour { + wait: waits, + helper: Some(Helper { + program: helper, + holds_output, + }), + ..Default::default() + }, + ) +} + +/// The id of the helper `command` started, which it writes down right after starting it. +fn helper_of(command: &Path) -> u32 { + helper_pid(command).expect("the command started no helper") +} + +/// Whether process `pid` is gone within two seconds: a killed process is gone once it has exited, or on Unix once its +/// parent reaps it. +fn goes(pid: u32) -> bool { + (0..200).any(|_| { + std::thread::sleep(Duration::from_millis(10)); + !running(pid) + }) } #[test] @@ -98,70 +140,88 @@ fn input_reaches_the_commands_stdin() { assert_eq!(only_call(&gh).stdin, "the body\n"); } -// Unix only: an `sh` script stands in for the command (#940 twins it with the Rust fake). -#[cfg(unix)] #[test] -fn a_deadline_kills_the_whole_process_group() { +fn a_deadline_kills_the_whole_process_tree() { let dir = tempfile::tempdir().unwrap(); - let pid_file = dir.path().join("helper.pid"); // The helper holds the command's output open, as a credential helper or a filter would. - let script = format!("sleep 20 & echo $! > {}; sleep 20", pid_file.display()); + let command = leaving_a_helper(dir.path(), true, LONG, LONG); let started = Instant::now(); - let ended = run_until(&mut sh(&script), SOON); + let ended = run_until(&mut Command::new(&command), SOON); assert!( matches!(ended, Err(RunError::TimedOut(limit)) if limit == SOON), "{ended:?}" ); assert!(started.elapsed() < Duration::from_secs(10)); - let helper = std::fs::read_to_string(&pid_file).unwrap(); - let helper = helper.trim(); - assert!(!helper.is_empty()); - // A killed process is gone once its parent reaps it: `launchd` or `init` here, in a moment. - let gone = (0..200).any(|_| { - std::thread::sleep(Duration::from_millis(10)); - !alive(helper) - }); - assert!(gone, "the helper {helper} outlived the deadline"); + let helper = helper_of(&command); + assert!(goes(helper), "the helper {helper} outlived the deadline"); } -// Unix only: an `sh` script stands in for the command (#940 twins it with the Rust fake). -#[cfg(unix)] #[test] fn a_helper_that_outlives_the_command_cannot_hold_the_run_past_its_deadline() { + let dir = tempfile::tempdir().unwrap(); + let command = leaving_a_helper(dir.path(), true, LONG, Duration::ZERO); let started = Instant::now(); - let ended = run_until(&mut sh("sleep 20 & exit 0"), SOON); + let ended = run_until(&mut Command::new(&command), SOON); assert!(matches!(ended, Err(RunError::TimedOut(_))), "{ended:?}"); assert!(started.elapsed() < Duration::from_secs(10)); + let helper = helper_of(&command); + assert!(goes(helper), "the helper {helper} outlived the deadline"); +} + +#[test] +fn a_helper_left_behind_by_a_clean_exit_is_left_alone() { + let dir = tempfile::tempdir().unwrap(); + // Long enough to outlive the run on a loaded machine; short, since nothing kills it. + let command = leaving_a_helper(dir.path(), false, Duration::from_secs(5), Duration::ZERO); + + let ended = run_until(&mut Command::new(&command), AMPLE); + + assert!(ended.is_ok(), "{ended:?}"); + let helper = helper_of(&command); + // Watched as long as a killed one takes to go: until reaped, a killed one still counts as running. + assert!( + !goes(helper), + "the helper {helper} was killed after a clean exit" + ); } -// Unix only: an `sh` script stands in for the command (#940 twins it with the Rust fake). -#[cfg(unix)] #[test] fn a_run_given_up_ends_at_once_as_timed_out() { + let dir = tempfile::tempdir().unwrap(); + let command = acting( + dir.path(), + "command", + &Behaviour { + wait: LONG, + ..Default::default() + }, + ); let started = Instant::now(); - let ended = run_until_unless(&mut sh("sleep 20"), AMPLE, &|| true); + let ended = run_until_unless(&mut Command::new(command), AMPLE, &|| true); assert!(matches!(ended, Err(RunError::TimedOut(_))), "{ended:?}"); assert!(started.elapsed() < Duration::from_secs(10)); } -// Unix only: an `sh` script stands in for the command (#940 twins it with the Rust fake). -#[cfg(unix)] #[test] fn a_run_given_up_while_a_helper_holds_its_output_ends_before_its_deadline() { - let started = Instant::now(); + let dir = tempfile::tempdir().unwrap(); // The command exits at once; its helper holds the pipes until it is killed. + let command = leaving_a_helper(dir.path(), true, LONG, Duration::ZERO); + let started = Instant::now(); let given_up = || started.elapsed() > Duration::from_millis(300); - let ended = run_until_unless(&mut sh("sleep 20 & exit 0"), AMPLE, &given_up); + let ended = run_until_unless(&mut Command::new(&command), AMPLE, &given_up); assert!(matches!(ended, Err(RunError::TimedOut(_))), "{ended:?}"); assert!(started.elapsed() < Duration::from_secs(10)); + let helper = helper_of(&command); + assert!(goes(helper), "the helper {helper} outlived the run"); } #[test] @@ -176,13 +236,20 @@ fn a_program_that_is_not_there_failed_to_start() { assert!(said.starts_with("did not start: "), "{said}"); } -// Unix only: an `sh` script stands in for the command (#940 twins it with the Rust fake). -#[cfg(unix)] #[test] fn a_run_past_its_deadline_timed_out() { + let dir = tempfile::tempdir().unwrap(); + let command = acting( + dir.path(), + "command", + &Behaviour { + wait: LONG, + ..Default::default() + }, + ); let limit = Duration::from_millis(200); - let ended = run_until(&mut sh("sleep 20"), limit); + let ended = run_until(&mut Command::new(command), limit); assert!( matches!(ended, Err(RunError::TimedOut(l)) if l == limit), @@ -191,15 +258,22 @@ fn a_run_past_its_deadline_timed_out() { assert_eq!(ended.unwrap_err().to_string(), "ran past 200ms"); } -// Unix only: an `sh` script stands in for the command (#940 twins it with the Rust fake). -#[cfg(unix)] #[test] fn a_non_zero_exit_failed_with_its_status_and_what_it_printed() { - let ended = run_until( - &mut sh("echo partial; echo ' the reason ' >&2; exit 3"), - AMPLE, + let dir = tempfile::tempdir().unwrap(); + let command = acting( + dir.path(), + "command", + &Behaviour { + stdout: "partial\n".into(), + stderr: " the reason \n".into(), + code: 3, + ..Default::default() + }, ); + let ended = run_until(&mut Command::new(command), AMPLE); + let Err(RunError::Failed(output)) = &ended else { panic!("{ended:?}"); }; @@ -209,27 +283,55 @@ fn a_non_zero_exit_failed_with_its_status_and_what_it_printed() { assert_eq!(ended.unwrap_err().to_string(), "the reason"); } -// Unix only: an `sh` script stands in for the command (#940 twins it with the Rust fake). -#[cfg(unix)] #[test] fn a_silent_non_zero_exit_says_its_status() { - let ended = run_until(&mut sh("exit 3"), AMPLE); + let dir = tempfile::tempdir().unwrap(); + let command = acting( + dir.path(), + "command", + &Behaviour { + code: 3, + ..Default::default() + }, + ); + + let ended = run_until(&mut Command::new(command), AMPLE); - assert_eq!(ended.unwrap_err().to_string(), "exit status: 3"); + // std's own words for the status on each platform. + let status = if cfg!(windows) { + "exit code: 3" + } else { + "exit status: 3" + }; + assert_eq!(ended.unwrap_err().to_string(), status); } -// Unix only: an `sh` script stands in for the command (#940 twins it with the Rust fake). -#[cfg(unix)] #[test] fn a_zero_exit_gives_both_streams_however_much_they_hold() { + let dir = tempfile::tempdir().unwrap(); // More than a pipe holds on each stream: neither stalls the other. - let script = "head -c 300000 /dev/zero; head -c 300000 /dev/zero >&2"; + let command = acting( + dir.path(), + "command", + &Behaviour { + stdout: "o".repeat(300_000), + stderr: "e".repeat(300_000), + ..Default::default() + }, + ); - let out = run_until(&mut sh(script), AMPLE).unwrap(); + let out = run_until(&mut Command::new(command), AMPLE).unwrap(); assert_eq!((out.stdout.len(), out.stderr.len()), (300_000, 300_000)); } +#[cfg(unix)] +fn sh(script: &str) -> Command { + let mut command = Command::new("sh"); + command.args(["-c", script]); + command +} + /// `sh -c script` with both streams in `log`. #[cfg(unix)] fn logged(script: &str, log: &Path) -> Command { @@ -239,15 +341,6 @@ fn logged(script: &str, log: &Path) -> Command { command } -/// Whether process `pid` is gone within two seconds: a killed process is gone once its parent reaps it. -#[cfg(unix)] -fn goes(pid: &str) -> bool { - (0..200).any(|_| { - std::thread::sleep(Duration::from_millis(10)); - !alive(pid) - }) -} - // Unix only: logged runs are refused on Windows (#936), and it starts `sh`. #[cfg(unix)] #[test] @@ -285,7 +378,7 @@ fn a_logged_run_past_its_deadline_leaves_no_process_behind() { assert!(started.elapsed() < Duration::from_secs(10)); let helper = std::fs::read_to_string(&pid_file).unwrap(); assert!( - goes(helper.trim()), + goes(helper.trim().parse().unwrap()), "the helper {helper} outlived the deadline" ); } @@ -309,7 +402,10 @@ fn a_logged_run_given_up_ends_at_once_and_leaves_no_process_behind() { assert!(matches!(ended, Err(RunError::TimedOut(_))), "{ended:?}"); assert!(started.elapsed() < Duration::from_secs(10)); let helper = std::fs::read_to_string(&pid_file).unwrap(); - assert!(goes(helper.trim()), "the helper {helper} outlived the run"); + assert!( + goes(helper.trim().parse().unwrap()), + "the helper {helper} outlived the run" + ); } // Unix only: logged runs are refused on Windows (#936), and it starts `sh`. @@ -330,7 +426,10 @@ fn a_helper_a_logged_run_left_behind_is_killed_when_it_exits() { assert!(status.unwrap().success()); assert!(started.elapsed() < Duration::from_secs(10)); let helper = std::fs::read_to_string(&pid_file).unwrap(); - assert!(goes(helper.trim()), "the helper {helper} outlived the run"); + assert!( + goes(helper.trim().parse().unwrap()), + "the helper {helper} outlived the run" + ); } /// A logged run's caller is told the child's id at its start, while it runs as the leader of its own group, so a caller From 5dcb1acf7677eeee9781d98bcdb6beca8e0e4cbf Mon Sep 17 00:00:00 2001 From: Daniel Rispler Date: Tue, 1 Dec 2026 10:58:59 +0200 Subject: [PATCH 2/4] Studio: on Windows a run's deadline kills its whole process tree, through a Job Object (#940) Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 139 +++++++++++++++++++++++++++++++++++++-- system-map.json | 2 +- test-support/src/fake.rs | 4 ++ workbench/Cargo.toml | 4 ++ workbench/src/run.rs | 109 ++++++++++++++++++++++-------- 5 files changed, 225 insertions(+), 33 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 20779e5ad..119541f62 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -108,7 +108,7 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.9", ] [[package]] @@ -407,6 +407,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "process-wrap" +version = "11.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3655b18489c90df24f2c401ac65f908b17210e59cf676127f79890f67f3e30e" +dependencies = [ + "indexmap", + "nix", + "windows", +] + [[package]] name = "quick-xml" version = "0.42.0" @@ -520,7 +531,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.9", ] [[package]] @@ -671,6 +682,7 @@ name = "studio-workbench" version = "0.0.0" dependencies = [ "libc", + "process-wrap", "serde", "serde_json", "studio-test-support", @@ -683,6 +695,17 @@ version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "syn" version = "3.0.9" @@ -702,7 +725,7 @@ checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.9", ] [[package]] @@ -857,12 +880,107 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + [[package]] name = "windows-sys" version = "0.52.0" @@ -897,6 +1015,15 @@ dependencies = [ "windows_x86_64_msvc", ] +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" @@ -976,7 +1103,7 @@ checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.9", "synstructure", ] @@ -997,7 +1124,7 @@ checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.9", "synstructure", ] @@ -1037,7 +1164,7 @@ checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.9", ] [[package]] diff --git a/system-map.json b/system-map.json index 2d74a96cd..f8586de67 100644 --- a/system-map.json +++ b/system-map.json @@ -129,7 +129,7 @@ "id": "workbench", "name": "Workbench", "caption": "Worktrees and PRs", "purpose": "The one runner of `git` and `gh`, git worktrees and fetches, agy's plugin, and the atomic write every store saves a whole file with. A black box: it never fogs.", "holds": [ - { "name": "The runner", "text": "Builds every `git` and `gh` with prompts off and no input, and runs commands to a deadline that kills their process group.", "paths": ["workbench/src/run.rs"] }, + { "name": "The runner", "text": "Builds every `git` and `gh` with prompts off and no input, and runs commands to a deadline that kills their whole process tree.", "paths": ["workbench/src/run.rs"] }, { "name": "Git", "text": "A folder's main checkout, `origin`'s fetch and what removing a worktree would lose, never with force.", "paths": ["workbench/src/lib.rs"] }, { "name": "The atomic write", "text": "Saves a whole JSON file by a synced temporary file beside it, renamed over it, for the server's and the understanding layer's stores.", "paths": ["workbench/src/lib.rs"] } ], diff --git a/test-support/src/fake.rs b/test-support/src/fake.rs index 1d3dcae2e..a0f1557a1 100644 --- a/test-support/src/fake.rs +++ b/test-support/src/fake.rs @@ -170,6 +170,10 @@ pub fn running(pid: u32) -> bool { } /// Starts the helper `spec` names, and writes its id beside `exe`. +#[expect( + clippy::zombie_processes, + reason = "the helper is left running, as a credential helper or daemon is; the fake exits without waiting on it" +)] fn start_helper(exe: &Path, spec: &Value) { let holds = spec["holds_output"].as_bool() == Some(true); if !holds { diff --git a/workbench/Cargo.toml b/workbench/Cargo.toml index 83c2e2292..bd8ed34a4 100644 --- a/workbench/Cargo.toml +++ b/workbench/Cargo.toml @@ -14,6 +14,10 @@ serde_json = "1" # The atomic write's temporary file beside its target. tempfile = "3" +[target.'cfg(windows)'.dependencies] +# The runner kills a command's tree through a Job Object. +process-wrap = { version = "11", default-features = false, features = ["std", "job-object"] } + [dev-dependencies] studio-test-support = { path = "../test-support" } diff --git a/workbench/src/run.rs b/workbench/src/run.rs index df12084c9..f546ab2c3 100644 --- a/workbench/src/run.rs +++ b/workbench/src/run.rs @@ -10,7 +10,7 @@ use std::{ fmt, io::{self, Read, Write}, path::Path, - process::{Child, Command, ExitStatus, Output, Stdio}, + process::{ChildStderr, ChildStdin, ChildStdout, Command, ExitStatus, Output, Stdio}, sync::mpsc, thread, time::{Duration, Instant}, @@ -21,7 +21,7 @@ use std::{ pub enum RunError { /// The program did not start, or its exit could not be read. Start(io::Error), - /// It ran past this deadline, and its process group was killed. + /// It ran past this deadline, and it was killed with whatever it started. TimedOut(Duration), /// It exited non-zero: its status, and what it printed. Failed(Output), @@ -72,7 +72,8 @@ fn quiet(mut command: Command, dir: &Path) -> Command { } /// Runs `command` with no input and returns its output when it exits 0 within `deadline`. It runs in a process group -/// of its own, and past the deadline the whole group is killed: the command and whatever it started. +/// of its own (on Windows a Job Object), and past the deadline the whole group is killed: the command and whatever it +/// started. pub fn run_until(command: &mut Command, deadline: Duration) -> Result { run(command, None, deadline, &|| false) } @@ -111,18 +112,19 @@ fn run( }) .stdout(Stdio::piped()) .stderr(Stdio::piped()); - let mut child = in_own_group(command).spawn().map_err(RunError::Start)?; + let mut child = Tree::start(command).map_err(RunError::Start)?; + let (stdin, stdout, stderr) = child.take_stdio(); // Threads, so a command that reads no input cannot hold back the deadline, and one that fills one pipe while the // other is read cannot stall. - if let (Some(input), Some(mut stdin)) = (input, child.stdin.take()) { + if let (Some(input), Some(mut stdin)) = (input, stdin) { let input = input.to_vec(); // A command that exits without reading its input closes the pipe: its exit status says what happened. thread::spawn(move || stdin.write_all(&input).ok()); } let (send, read) = mpsc::channel(); let pipes: [(bool, Option>); 2] = [ - (true, child.stdout.take().map(|p| Box::new(p) as _)), - (false, child.stderr.take().map(|p| Box::new(p) as _)), + (true, stdout.map(|p| Box::new(p) as _)), + (false, stderr.map(|p| Box::new(p) as _)), ]; for (is_stdout, pipe) in pipes { let send = send.clone(); @@ -142,12 +144,12 @@ fn run( Ok(Some(status)) => break status, Ok(None) => {} Err(error) => { - kill_tree(&mut child); + child.kill(); return Err(RunError::Start(error)); } } if Instant::now() >= end || given_up() { - kill_tree(&mut child); + child.kill(); // Reaped, so it is no zombie; a killed child's wait cannot fail in a way to act on. child.wait().ok(); return Err(RunError::TimedOut(deadline)); @@ -168,7 +170,7 @@ fn run( Ok((false, bytes)) => stderr = bytes, Err(_) if Instant::now() < end && !given_up() => continue, Err(_) => { - kill_tree(&mut child); + child.kill(); return Err(RunError::TimedOut(deadline)); } } @@ -186,35 +188,90 @@ fn run( } } -/// `command` set to start in a process group of its own, so [`kill_tree`] reaches whatever it starts. +/// `command` set to start in a process group of its own, so killing the group reaches whatever it starts. #[cfg(unix)] fn in_own_group(command: &mut Command) -> &mut Command { use std::os::unix::process::CommandExt; command.process_group(0) } -/// On Windows the command starts as it is: the interim arm (#938) has no Job Object yet, so [`kill_tree`] stops only -/// the command itself (#940 gives it one). +/// A started command together with whatever it starts, to be killed as one: on Unix its process group, on Windows its +/// Job Object. Waiting is on the command alone, so a helper it leaves behind after a clean exit keeps running. +#[cfg(unix)] +struct Tree(std::process::Child); + +/// A started command together with whatever it starts, to be killed as one: on Unix its process group, on Windows its +/// Job Object. Waiting is on the command alone, so a helper it leaves behind after a clean exit keeps running. #[cfg(windows)] -fn in_own_group(command: &mut Command) -> &mut Command { - command -} +struct Tree(Box); -/// Kills `child`'s process group: the command and whatever it started. #[cfg(unix)] -fn kill_tree(child: &mut Child) { - if let Ok(group) = libc::pid_t::try_from(child.id()) { - // SAFETY: `kill` takes no pointers. The group is the one [`in_own_group`] made for this child; its id stays - // taken while the unreaped child or a process holding its output lives, so this signals no one else. - unsafe { libc::kill(-group, libc::SIGKILL) }; +impl Tree { + fn start(command: &mut Command) -> io::Result { + in_own_group(command).spawn().map(Tree) + } + + fn take_stdio(&mut self) -> (Option, Option, Option) { + ( + self.0.stdin.take(), + self.0.stdout.take(), + self.0.stderr.take(), + ) + } + + fn try_wait(&mut self) -> io::Result> { + self.0.try_wait() + } + + fn wait(&mut self) -> io::Result { + self.0.wait() + } + + /// Kills the process group: the command and whatever it started. + fn kill(&mut self) { + if let Ok(group) = libc::pid_t::try_from(self.0.id()) { + // SAFETY: `kill` takes no pointers. The group is the one [`in_own_group`] made for this child; its id stays + // taken while the unreaped child or a process holding its output lives, so this signals no one else. + unsafe { libc::kill(-group, libc::SIGKILL) }; + } } } -/// Kills `child` itself, the interim Windows arm (#938): what it started keeps running until #940's Job Object. #[cfg(windows)] -fn kill_tree(child: &mut Child) { - // A child that has already exited has nothing to kill. - child.kill().ok(); +impl Tree { + /// Starts `command` in a Job Object of its own, which whatever it starts joins too. The job is not killed when + /// its handle closes, so a helper left behind after a clean exit keeps running, as on Unix. + fn start(command: &mut Command) -> io::Result { + use process_wrap::std::{CommandWrap, JobObject}; + let mut wrap = CommandWrap::from(std::mem::replace(command, Command::new(""))); + let started = wrap.wrap(JobObject).spawn(); + *command = wrap.into_command(); + started.map(Tree) + } + + fn take_stdio(&mut self) -> (Option, Option, Option) { + ( + self.0.stdin().take(), + self.0.stdout().take(), + self.0.stderr().take(), + ) + } + + /// The command's own exit: the wrapper's `try_wait` would wait for the whole job. + fn try_wait(&mut self) -> io::Result> { + self.0.inner_mut().try_wait() + } + + /// The command's own exit: the wrapper's `wait` would wait for the whole job. + fn wait(&mut self) -> io::Result { + self.0.inner_mut().wait() + } + + /// Terminates the Job Object: the command and whatever it started. + fn kill(&mut self) { + // A job whose processes have all exited has nothing to kill. + self.0.start_kill().ok(); + } } /// Runs `command`, with no input and its output wherever the caller set it (a file), until it exits within `deadline`: From 73d4280685d706181e06b463c5dafeea22728b33 Mon Sep 17 00:00:00 2001 From: Daniel Rispler Date: Tue, 1 Dec 2026 11:01:40 +0200 Subject: [PATCH 3/4] Studio: the given-up row waits for its helper, and the development doc tells the Job Object (#940) Co-Authored-By: Claude Opus 5.5 --- docs/studio/development.md | 2 +- workbench/tests/run.rs | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/studio/development.md b/docs/studio/development.md index a85979a1a..57b3f3d4e 100644 --- a/docs/studio/development.md +++ b/docs/studio/development.md @@ -12,7 +12,7 @@ - `core/`: the studio core, plain Rust whose only I/O is reading the sessions' transcripts (`src/transcript.rs`, `.jsonl` files only), and `scrub`, which turns event log lines into test fixtures. At start the app takes the state its last start saved, `studio-state.json` beside the log, and replays only the log from where that state stopped, then feeds it each new line live; a pruned log, a state of another format or one that does not read means a replay from the start. It keeps the step ledger (`ledger`), the checks (`checks`: the statement parser, a run's worktree and exit code, running checks and checks sent to the background, the feed's checks, and the typical durations with the 2-minute rule: their recording, median and lookup, which `lib.rs` calls), each turn's files (`turn_files`) and the facts Ask shows (`ask`). The `Studio` type is in `src/studio.rs`, its methods by responsibility in `src/studio/`: `take` (one hook event), `roots` (worktree roots and fingerprints), `replay` (a log line applied or replayed), `turn_files` (the turns the shell diffs), `tasks` (what the shell found about each task and its PR) and `selection` (the session list, the selection and the subagent logs). - Only live lines request cards and notifications. - `understanding/`: the understanding layer's I/O: the writer interface (turn summaries, goals, "Design so far", Ask, names and risk notes), the `claude -p` writer and the other CLI writers (agy, Codex, Copilot, Cursor) in `writer.rs`, the API-key writers' HTTP calls (`http_writer.rs`: Anthropic's API and an OpenAI-compatible one) and a fake, the worktree fingerprint, the card store with the briefs, the turn summaries, Turn writing (`turn_writing.rs`: what a turn's end and a worker's return write, on a queue for each session), which files are logic and which are tests (`logic_file.rs`), Claude Code's version kept beside the event log, and `weekly`, the command that prints the drift: unrecognised wake-ups and version changes. -- `workbench/`: workbench git (danielrispler/Falinks#328, module 7): a folder's main checkout, `fetch` and what removing a task's worktree would lose; the `gh` to run; and agy's plugin. Its `run` module (`src/run.rs`, #548) is the one process runner: `git(dir)` and `gh(dir)` build every `git` and `gh` the workspace starts, with `--no-optional-locks`, `GIT_TERMINAL_PROMPT=0`, `GH_PROMPT_DISABLED=1` and no input, and a caller adds its own arguments; `run_until(command, deadline)` runs a command in a process group of its own and kills the group at the deadline, and its `RunError` tells apart a command that did not start, one that timed out and one that exited non-zero; `run_logged(command, deadline, given_up)` does the same for a command whose output goes to a file, gives its exit status, and also kills what it left in its group when it exits (#568). On Windows, until #940 gives it a Job Object, `run_until` kills only the command itself, and `run_logged` starts nothing and returns `RunError::Start`, as its callers are refused there. A new `git` or `gh` call uses both, with its deadline a named constant beside it: 30 s for a lookup or a read, 120 s for a fetch. Every wait on a child with a deadline goes through the runner: the launcher's check, setup and harness and the micro-world checks too (#568). A command streamed into another program (the hook's untracked-file listing, `git archive` into `tar`) is built by the runner and waited on by its caller. What only its own tests used is in `archive/workbench/` (#415). +- `workbench/`: workbench git (danielrispler/Falinks#328, module 7): a folder's main checkout, `fetch` and what removing a task's worktree would lose; the `gh` to run; and agy's plugin. Its `run` module (`src/run.rs`, #548) is the one process runner: `git(dir)` and `gh(dir)` build every `git` and `gh` the workspace starts, with `--no-optional-locks`, `GIT_TERMINAL_PROMPT=0`, `GH_PROMPT_DISABLED=1` and no input, and a caller adds its own arguments; `run_until(command, deadline)` runs a command in a process group of its own (on Windows a Job Object) and kills the group at the deadline, leaving alone what it left running after a clean exit, and its `RunError` tells apart a command that did not start, one that timed out and one that exited non-zero; `run_logged(command, deadline, given_up)` does the same for a command whose output goes to a file, gives its exit status, and also kills what it left in its group when it exits (#568). On Windows `run_logged` starts nothing and returns `RunError::Start`, as its callers are refused there. A new `git` or `gh` call uses both, with its deadline a named constant beside it: 30 s for a lookup or a read, 120 s for a fetch. Every wait on a child with a deadline goes through the runner: the launcher's check, setup and harness and the micro-world checks too (#568). A command streamed into another program (the hook's untracked-file listing, `git archive` into `tar`) is built by the runner and waited on by its caller. What only its own tests used is in `archive/workbench/` (#415). - `system-map/`: `studio-system-map`, a library and the `system-map` binary that check `system-map.json` against the repository, say which parts a change touches and count how well the parts follow the imports (`imports`) (`docs/studio/behaviour/map.md`). Its `scan` module is First map's free scan (#753: the parts proposed from folders and manifests, the loose files and tests, the reference-copy candidates and the placeholder parts and ids), and `cli` its command line, which `plotkeeper map check` and `map scan` share. `npm run check` runs `system-map check` after the tests. - `server/`: `studio-server`, the state and the logic behind the page's commands, and the `plotkeeper` program that serves it (`src/bin/plotkeeper.rs`, the local page in `src/web.rs`, one function for each command in `src/api.rs`). Its modules include the read loop (`read_loop.rs`), the Map view's (spec #306: `map.rs` the payload, Daniel's positions and tiers and the guarded `git fetch`; `fog.rs` the commits since Daniel last caught up, kept per part, and what reading a brief clears; `history.rs` a part's history, the map at a past commit, a commit's files and a PR's; `ci_laws.rs` the default branch's last finished CI run, the law tests that failed in it and the words for a failed check; `stop_rules.rs` the usage log and the one-time review's counts) and the PR briefs' (spec #334: `prs.rs` which PRs are ready, `pr_briefs.rs` writing, keeping and rewriting the briefs, `ratify.rs` what Daniel accepted or overturned), `settings.rs` (with the API keys' stores: the Keychain on macOS, the Secret Service through `secret-tool` on Linux), `install.rs` (`plotkeeper install` and `uninstall`: the harnesses' plugins and hook files, and what it records to undo them; [install](plugin.md)), `hook_copies.rs` (the hook binaries' copies in the data folder's `bin/`, #356), `statusline.rs` (`plotkeeper statusline`, Claude Code's status line: a link to the page for the session on its stdin, #884) and `runner.rs` (the [background runs](behaviour/background-runs.md), spec #378: the queue and its batches, the ends told to the modules that listen, the `claude` command with its sandbox block and allow list, a run's lock, status and outcome, Cancel, and the logic of the launcher, the crate's second program `plotkeeper-run`, `src/bin/plotkeeper-run.rs`), `back_a_law.rs` (Back a law, #398–#401: the clone, plotkeeper's own proof of a run's patches in `srt`, the kept patches, Open draft PR, and a new law drafted from a PR's brief) `micro_worlds.rs` (micro-worlds, #399: the run, the host checks under the network guard `micro_world_guard.mjs`, the kept pages) and `map_review.rs` (the map text review, #642: the items a PR's map text changed, the read-only run on its head, when it starts, the verdicts kept), `map_scan.rs` (First map's scan screen, #753: the skeleton's lines and its Ignore, Home, Merge and Split) and `map_draft.rs` (the Map draft, #753: the writers' and reviewers' runs, retry, redraft and Discard, Accept's Write and Open a draft PR, and following that PR). `ui/`: its TypeScript page. - `archive/`: retired code, never built, tested, linted or formatted (#415; its `README.md`): the Tauri desktop app (`src-tauri/`) and the daemon that owned its terminals (`terminal-daemon/`, danielrispler/plotkeeper#334, #332; each folder's `README.md`), the spikes, `real-calls.sh`, and the code and tests that only their own tests used. diff --git a/workbench/tests/run.rs b/workbench/tests/run.rs index b36312a1e..ae3c80a42 100644 --- a/workbench/tests/run.rs +++ b/workbench/tests/run.rs @@ -214,7 +214,9 @@ fn a_run_given_up_while_a_helper_holds_its_output_ends_before_its_deadline() { // The command exits at once; its helper holds the pipes until it is killed. let command = leaving_a_helper(dir.path(), true, LONG, Duration::ZERO); let started = Instant::now(); - let given_up = || started.elapsed() > Duration::from_millis(300); + // Given up only once the helper has started, so a slow start cannot end the run before it. + let given_up = + || helper_pid(&command).is_some() && started.elapsed() > Duration::from_millis(300); let ended = run_until_unless(&mut Command::new(&command), AMPLE, &given_up); From f249909a2a8609a909739e4eda444dd1d7e5d953 Mon Sep 17 00:00:00 2001 From: Daniel Rispler Date: Tue, 1 Dec 2026 11:14:51 +0200 Subject: [PATCH 4/4] Studio: the left-alone row's helper outlives a slow run (#940) A 5 s helper ran out on CI's macOS while the run was still ending. Co-Authored-By: Claude Opus 5.5 --- workbench/tests/run.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/workbench/tests/run.rs b/workbench/tests/run.rs index ae3c80a42..9e6e8420e 100644 --- a/workbench/tests/run.rs +++ b/workbench/tests/run.rs @@ -175,8 +175,9 @@ fn a_helper_that_outlives_the_command_cannot_hold_the_run_past_its_deadline() { #[test] fn a_helper_left_behind_by_a_clean_exit_is_left_alone() { let dir = tempfile::tempdir().unwrap(); - // Long enough to outlive the run on a loaded machine; short, since nothing kills it. - let command = leaving_a_helper(dir.path(), false, Duration::from_secs(5), Duration::ZERO); + // Long enough to outlive the run and the watch on a loaded machine: a 5 s helper ran out on CI's macOS while + // the run was still ending. Nothing kills it; it holds no output, so it exits on its own later. + let command = leaving_a_helper(dir.path(), false, LONG, Duration::ZERO); let ended = run_until(&mut Command::new(&command), AMPLE);