Craft Anything: understand how any software works, and craft your own.
Rust
Test watched descendant shutdown on every system (#1030)
Tomáš Doubek74176f2cbe69
diff --git a/crates/platform/src/process.rs b/crates/platform/src/process.rsindex 32420758..c8f09bbd 100644--- a/crates/platform/src/process.rs+++ b/crates/platform/src/process.rs@@ -1294,15 +1294,154 @@ mod launch_tests {assert!(l.ended().unwrap().after < Duration::from_secs(20));}- #[cfg(unix)]+ /// Verify that stopping a watched launch stops its descendant on Unix and Windows.+ ///+ /// Wait for the child's startup and heartbeat files, then stop even if they are absent. The+ /// descendant holds an exclusive lock on `descendant-alive` for its whole life, and the system+ /// releases it only when the process exits: taking that lock after `stop()` is the exit probe,+ /// with no timing guess. A descendant that outlived the stop instead finishes its bounded loop+ /// and writes `descendant-survived` before its lock is released.#[test]- fn stopping_a_watched_program_stops_its_process_group() {+ fn stopping_a_watched_program_stops_its_descendant() {+ let dir = tempfile::Builder::new().prefix("watched descendant ").tempdir().unwrap();+ let l = start_descendant_fixture(dir.path(), true);+ let (started, heartbeat) = stop_after_descendant_startup(&l, dir.path(), Duration::from_secs(5));+ assert!(started, "descendant never signalled that it started");+ assert!(heartbeat, "descendant never produced a heartbeat");+ // Exclusive locks may need write access (e.g. on NFS), so open for reading and writing.+ let alive = std::fs::OpenOptions::new().read(true).write(true).open(dir.path().join("descendant-alive")).unwrap();+ let deadline = Instant::now() + Duration::from_secs(20);+ loop {+ match alive.try_lock() {+ Ok(()) => break,+ Err(std::fs::TryLockError::WouldBlock) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(20)),+ Err(e) => panic!("descendant still holds its lock after the watched program stopped: {e}"),+ }+ }+ assert!(!dir.path().join("descendant-survived").exists(), "descendant ran to completion after the watched program stopped");+ }++ /// Wait for bounded startup, snapshot its markers, and stop before callers assert on them.+ fn stop_after_descendant_startup(launch: &Launched, dir: &std::path::Path, timeout: Duration) -> (bool, bool) {+ let started = dir.join("descendant-started");+ let heartbeat = dir.join("descendant-heartbeat");+ let deadline = Instant::now() + timeout;+ while (!started.exists() || !heartbeat.exists()) && Instant::now() < deadline {+ std::thread::sleep(Duration::from_millis(20));+ }+ let markers = (started.exists(), heartbeat.exists());+ assert!(launch.stop(), "could not stop the watched launch");+ markers+ }++ /// Missing startup markers must still stop a live fixture before reporting startup failure.+ ///+ /// Wait (bounded) for the parent to say it is waiting, so the stop is proven to end a live+ /// process; stop before asserting, then require that it never finished on its own.+ #[test]+ fn a_descendant_startup_timeout_stops_the_watched_launch() {let dir = tempfile::tempdir().unwrap();- let l = shell("sleep 2; echo survived > descendant & wait").cwd(dir.path()).start_watched().unwrap();- assert!(l.wait_timeout(Duration::from_millis(300)).is_none(), "it should still be running");- assert!(l.stop());- std::thread::sleep(Duration::from_secs(3));- assert!(!dir.path().join("descendant").exists(), "a descendant outlived the watched program");+ let l = start_descendant_fixture(dir.path(), false);+ let ready = dir.path().join("parent-waiting");+ let deadline = Instant::now() + Duration::from_secs(20);+ while !ready.exists() && Instant::now() < deadline {+ std::thread::sleep(Duration::from_millis(20));+ }+ let parent_ready = ready.exists();+ let markers = stop_after_descendant_startup(&l, dir.path(), Duration::from_millis(100));+ assert!(parent_ready, "the waiting parent never signalled that it was ready");+ assert_eq!(markers, (false, false));+ assert!(!l.is_running(), "startup failure left the watched launch running");+ assert!(!dir.path().join("parent-completed").exists(), "the waiting parent finished on its own instead of being stopped");+ }++ /// Enable the guarded parent in an isolated directory, with or without child startup.+ fn start_descendant_fixture(dir: &std::path::Path, start_descendant: bool) -> Launched {+ std::fs::write(dir.join("descendant-fixture"), if start_descendant { "start" } else { "wait" }).unwrap();+ Launch::new(std::env::current_exe().unwrap())+ .args(["--ignored", "--exact", "process::launch_tests::watched_parent_stand_in"])+ .cwd(dir)+ .hide_console()+ .start_watched()+ .unwrap()+ }++ /// Start the bounded child in the watched parent's process group and wait for it.+ ///+ /// An exact directory-local guard enables this fixture. The `wait` mode simulates a+ /// parent that stays alive without starting its child, exercising timeout cleanup: it+ /// writes `parent-waiting` once running and `parent-completed` only if its wait runs out.+ #[test]+ #[ignore = "stand-in invoked by watched descendant tests"]+ fn watched_parent_stand_in() {+ match std::fs::read("descendant-fixture").ok().as_deref() {+ Some(b"start") => {}+ Some(b"wait") => {+ std::fs::write("parent-waiting", b"ready").unwrap();+ std::thread::sleep(Duration::from_secs(5));+ std::fs::write("parent-completed", b"yes").unwrap();+ return;+ }+ _ => return,+ }+ // This process-layer fixture must inherit the parent's group/job. Process and+ // Launch deliberately create new Unix groups, which would invalidate the test.+ let mut command = std::process::Command::new(std::env::current_exe().unwrap());+ command+ .args(["--ignored", "--exact", "process::launch_tests::watched_descendant_stand_in"])+ .env("CRAFT_ANYTHING_TEST_DESCENDANT", "1")+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null());+ #[cfg(windows)]+ {+ use std::os::windows::process::CommandExt;+ command.creation_flags(0x0800_0000);+ }+ // The child's heartbeat loop exits after five seconds even if no stop arrives.+ let mut child = spawn_retrying(|| command.spawn()).unwrap();+ assert!(child.wait().unwrap().success());+ }++ /// Provide a child process whose marker files expose whether it survives shutdown.+ ///+ /// Return without writing unless `CRAFT_ANYTHING_TEST_DESCENDANT` is exactly `1`, as+ /// set by the parent test. When enabled, hold an exclusive lock on `descendant-alive` until+ /// the process exits, write startup and periodic heartbeat files in the working directory,+ /// then a survival marker (before the lock is released) if the loop reaches its end.+ #[test]+ #[ignore = "stand-in invoked by stopping_a_watched_program_stops_its_descendant"]+ fn watched_descendant_stand_in() {+ if std::env::var_os("CRAFT_ANYTHING_TEST_DESCENDANT").as_deref() != Some(OsStr::new("1")) {+ return;+ }+ let alive = std::fs::File::create("descendant-alive").unwrap();+ alive.lock().unwrap();+ std::fs::write("descendant-started", b"ready").unwrap();+ for n in 0..100 {+ std::fs::write("descendant-heartbeat", n.to_string()).unwrap();+ std::thread::sleep(Duration::from_millis(50));+ }+ std::fs::write("descendant-survived", b"yes").unwrap();+ }++ /// Verify that directly running the ignored fixture without its guard writes no files.+ ///+ /// Start the test executable in an empty temporary directory with the guard removed,+ /// then require a successful exit and an unchanged directory.+ #[test]+ fn a_direct_descendant_stand_in_run_writes_nothing() {+ let dir = tempfile::tempdir().unwrap();+ for fixture in ["watched_parent_stand_in", "watched_descendant_stand_in"] {+ let out = Process::new(std::env::current_exe().unwrap())+ .args(["--ignored", "--exact", &format!("process::launch_tests::{fixture}")])+ .env_remove("CRAFT_ANYTHING_TEST_DESCENDANT")+ .cwd(dir.path())+ .run()+ .unwrap();+ assert!(out.success, "{fixture}: {}", out.stderr_text());+ assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0, "the unguarded {fixture} wrote files");+ }}fn exits_with(code: u8) -> Process {diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex f937ac91..4ac74b64 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -167,6 +167,20 @@ cheapest help we can give anyone, so nothing below should hold it up for long.### R5.2 Keeping contributions movingOwner: maintainers · Status: in progress+- [x] Fix PR #1030's Windows descendant fixture startup and stop the watched launch before+ startup assertions can fail; cover the failure cleanup path+ — claimed: Codex, branch bugfix/r5.2-watched-launch-tests+- [ ] Run PR #1030's shell-free parent/descendant fixture and startup-timeout cleanup test+ on Windows; the contributor reproduced startup failure and leaked processes on 07671fe+- [x] Clarify PR #1030's test Rustdoc: post-stop heartbeat sampling, child-fixture guard,+ and the direct-run no-write check+ — claimed: Codex, branch bugfix/r5.2-watched-launch-tests+- [x] Address PR #1030 review: take the heartbeat baseline after stopping, guard the descendant+ stand-in against direct ignored-test runs, and document the test helpers+ — claimed: Codex, branch bugfix/r5.2-watched-launch-tests+- [ ] `regression_preview_limits_connections_and_releases_listener` (platform) fails on macOS+ with `Invalid argument` in its socket fixture, also reported before PR #1030's review fixes.+ Investigate the fixture separately from the watched descendant shutdown testReview comes before new work while the queue is long, smallest and clean PRs first. A PR is mergedonly when it's green and a maintainer has fully reviewed it, code as well as wording.- [ ] Maintainers: protect `main` (PRs required, squash only); the only ruleset covers `release`diff --git a/docs/STATUS.md b/docs/STATUS.mdindex 4fba3585..676ea723 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -8,6 +8,7 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi| Area | State | Verified by ||---|---|---|+| Watched descendant regression | A guarded Rust parent starts the heartbeat child in its inherited process group/job. No shell quoting is involved. The watched launch is stopped before missing startup markers can fail an assertion | macOS regressions pass for descendant shutdown, startup-timeout cleanup and direct ignored-fixture runs without guards. Windows execution of this replacement remains pending; the prior shell fixture failed there. The platform suite still has the separately tracked preview-connection fixture failure || Disabled chat backends | Naming a backend that is off refuses chat and either side of compare with a settings error and guidance, before API or coding-agent setup | Isolated hub regressions for disabled API and agent backends, both compare positions, and enabled/automatic controls. Invalid tunnel settings detect API setup before the guard. No live provider or agent was used || Runner-owned app windows | Runtime capture tries the launched process and its descendants; the captured window owner's PID is also used for the UI tree. Unrelated processes with matching names are excluded. Process discovery has a deadline, output cap and candidate limit | Hermetic regressions cover runner/child/grandchild ownership, unrelated windows, direct launches, cycles, malformed rows, caps and errors. A macOS process snapshot finds an owned child without opening a window. Windows and real Go GUI capture have not been run || New-project toolchains | New Python, Go, .NET, Maven, Gradle and Make projects use the same build catalogue as existing projects (`engine/src/toolchains.toml`). Shared launch recipes let screenshots, self-tests and Play start Python `main.py`, `app.py` or `__main__.py`, Go with a root `main.go`, and one root `.csproj`. Python uses a project-local virtual environment when present, resolves its executable to an absolute path even for relative project folders, and forces fresh syntax compilation; .NET passes app options after `--`. Manifest markers take priority over standalone Python files. Runtime window-capture requests normalize relative project and runner paths to absolute paths. Existing packaged programs, Rust, Electron and Godot keep launch priority. Multiple `.csproj` matches or a capped scan do not choose a project. Other layouts still need a packaged program or another launch recipe | Catalogue and launch regressions cover argv boundaries, ambiguous entrypoints, scan limits and Windows/local interpreter selection, including relative project folders and unchanged argument boundaries. Capture-request tests cover relative placements and PATH results, local interpreters and optional UI-tree output without opening a window. An owned interpreter stand-in runs the full new-project build/screenshot path, rejects failed builds, and verifies a failed screenshot cannot reuse an old PNG. An opt-in real Python 3.15.2 fixture on macOS passes build/screenshot checks, ignores invalid virtualenv code, and rejects a syntax error even when its mtime matches the cached version. Without `compileall -f` that same syntax-error probe incorrectly exits zero. Real Go/.NET/Maven/Gradle runs, Windows and GUI apps have not been verified for this change |diff --git a/docs/pitfalls.md b/docs/pitfalls.mdindex 39ffe96a..67808e28 100644--- a/docs/pitfalls.md+++ b/docs/pitfalls.md@@ -81,6 +81,16 @@ names (`git merge-base --is-ancestor <fix> <release tag>`), and check the messag## Tests+**A heartbeat sampled before shutdown raced a successful stop.** A child could write between+the baseline read and `stop()`, failing the descendant cleanup test even when cleanup worked.+Probe for exit instead of timing writes: the child holds a file lock the system releases only+when it exits, and the test takes it after the stop. Ignored child fixtures also need+an explicit launch guard so running ignored tests directly cannot write in the working directory.+The replacement's quoted `cmd /C` script still failed on Windows, and startup assertions skipped+cleanup. Use a guarded Rust parent instead of shell syntax, and stop before asserting on startup.+Its child must inherit the watched group/job: another `Process` or `Launch` creates a separate+Unix group and would no longer test the ancestor's shutdown.+**An isolated PATH still assumed system utilities lived in `/bin`.** The remote setup fixturelinked `mkdir`, `chmod` and `mv` there, so a host with utilities elsewhere got dangling links.Resolve fixture utilities on the host, make their paths absolute, then populate the private PATH.@@ -169,6 +179,10 @@ call it and make them `wait` for the result, not `run_steps(n)`.## Building and running+**A documentation edit rebuilt dependencies in a separate cache.** A sequential review follow-up+used another target directory for its commit hook, triggering an unnecessary build. Separate+build caches are for concurrent work; reuse the current checkout's cache for sequential work.+**A runner's PID isn't the window owner's.** `go run` starts a compiled child, so picturing therunner missed the app (or a name fallback found another app). Search only the launched processand its descendants, and read the UI tree from the same PID that supplied the picture.