From f41a8ae1436f4025054b12002f1a953e3b98abcb Mon Sep 17 00:00:00 2001 From: wr3n-ai Date: Mon, 5 Oct 2026 17:48:39 +0000 Subject: [PATCH 01/10] feat(runner): own the Windows process tree with a Job Object Windows executions previously refused to start: `run` returned `RunnerError::UnsupportedPlatform` before spawn, and the server mapped that to `Failed`/`Internal` with `exit_code: null`. Foundation M004 replaces the refusal with a real tree owner. `process_tree.rs` is the single platform seam behind the one shared lifecycle. Unix keeps `process_group(0)` + `killpg` escalation; Windows wraps the same sanitised `Command` in `process-wrap`'s `JobObject`, which adds `CREATE_SUSPENDED`, assigns the still-suspended process, and only then resumes it, so no descendant can exist before Eggwork owns it. Termination is one `TerminateJobObject` over a job created with `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`, whose handle closes when the tree owner drops -- before `run` returns and before the caller's execution permit is released. The dependency is pinned to `=10.0.1` because upstream raises its MSRV inside a major version, so `10` is not a stable lower bound. It is on the ownership guard's process-owner denylist, so the guard now applies that denylist to all five crates and permits exactly one recorded exception, `eggwork-runner` -> `process-wrap`, validated by `unexplained_process_dep_exceptions()`. What Windows does not claim: per-descendant exit observation. No safe surface exposes a job-membership query and adding one would mean Eggwork-owned `unsafe` Win32 FFI, which the workspace denies. Convergence rests on job ownership for the whole execution, the kernel marking every member terminating, and the existing reader-EOF barrier. A `windows-latest` CI job runs the new `#![cfg(windows)]` tree-lifecycle suite, because none of this is observable from Linux. The installed production path stays qualified by `operational-qualification.yml` from a staged release's own bytes. --- .github/workflows/ci.yml | 23 + AGENTS.md | 2 +- Cargo.lock | 170 ++++- README.md | 7 + architecture/ci-guardrails.md | 43 ++ architecture/execution-ownership.md | 4 +- architecture/runner-execution.md | 30 +- crates/eggwork-runner/Cargo.toml | 19 + crates/eggwork-runner/src/lib.rs | 702 +++++++++--------- crates/eggwork-runner/src/process_tree.rs | 357 +++++++++ .../eggwork-runner/tests/capability_probe.rs | 5 +- .../tests/windows_process_tree.rs | 667 +++++++++++++++++ scripts/check_execution_ownership.py | 56 +- 13 files changed, 1716 insertions(+), 369 deletions(-) create mode 100644 crates/eggwork-runner/src/process_tree.rs create mode 100644 crates/eggwork-runner/tests/windows_process_tree.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6c7391e..6062217 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,6 +28,29 @@ jobs: - run: cargo check --workspace - name: release candidate validator tests run: python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release + windows-runner: + # The Windows process-tree backend cannot be observed from Linux: Job Object + # ownership, descendant convergence, and pipe inheritance only mean something + # on a real Windows kernel. This job is the native evidence for Foundation + # M004, so a green Linux run must never be read as Windows coverage. + # + # Scope is deliberately narrow. `eggwork-runner` runs its full suite on + # Windows; the server's own tests are `/bin/sh`-shaped and stay Linux-only + # until a separate milestone reshapes them. The installed production path + # (installed release bytes, not a build tree) is qualified by the + # `operational-qualification` workflow, not here. + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@1.89.0 + with: + components: clippy + - uses: Swatinem/rust-cache@v2 + with: + key: windows-msvc + - run: cargo clippy --locked --workspace --all-targets --all-features -- -D warnings + - name: Windows process-tree lifecycle suite + run: cargo test --locked -p eggwork-runner --all-targets -- --nocapture release-drift: # Eggpack is producer authority for the release matrix: the generated # release workflow must be exactly what the pinned tool renders from the diff --git a/AGENTS.md b/AGENTS.md index 3b6a608..9c56bd6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -92,7 +92,7 @@ and deliberate. Deep dives: ## Hard invariants (mechanically enforced — do not weaken) -1. **Process ownership is singular.** Only `eggwork-runner` and `eggwork-sandbox-helper` may create child processes; `eggwork-core`, `eggwork-client`, `eggwork-server` must not. Also banned outright: `command-group`, `duct`, `process-wrap`, `portable-pty`, `subprocess`. The allowlist lives in `scripts/check_execution_ownership.py`; adding an owner requires an architecture review. The guard scans only `crates/*/src/**/*.rs` — `tests/`, `examples/`, `build.rs`, and new top-level dirs are unscanned. +1. **Process ownership is singular.** Only `eggwork-runner` and `eggwork-sandbox-helper` may create child processes; `eggwork-core`, `eggwork-client`, `eggwork-server` must not. Also banned outright: `command-group`, `duct`, `process-wrap`, `portable-pty`, `subprocess`. The allowlist lives in `scripts/check_execution_ownership.py`; adding an owner requires an architecture review. The guard scans only `crates/*/src/**/*.rs` — `tests/`, `examples/`, `build.rs`, and new top-level dirs are unscanned. The dependency denylist is the exception: every crate is checked against it, and the one recorded exemption is `eggwork-runner` → `process-wrap` (Windows Job Object ownership, `cfg(windows)` only), in `APPROVED_PROCESS_DEP_EXCEPTIONS`. 2. **No direct service-manager invocation for the *node service*.** Eggwork never manages its own service by shelling out — the node service lifecycle goes through Eggup adapters. **Exception, and it is not a violation:** `eggwork-runner` invokes `systemd-run --scope` and `systemctl show`/`stop` for *per-execution transient cgroup units*, which is resource enforcement owned by the process-lifecycle crate, not service lifecycle. A new `systemctl`-shaped call must pick a side and match the code to it. (No dedicated Python guard; the only automated check, `no_direct_service_manager_invocation_exists`, scans three `eggwork-server` files. `eggwork-runner` is not covered — discipline is on you.) 3. **Crate dependencies stay one-way.** core/helper → nothing; client → core; server → core + runner (`eggwork-client` is dev-only for the server). 4. **Isolation claims are earned.** Advertise filesystem isolation only when `verify_trusted_helper` accepts the installed helper; the same function backs capability advertisement, `doctor`, and admission. diff --git a/Cargo.lock b/Cargo.lock index 66c2f74..cb65b29 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -601,7 +601,8 @@ dependencies = [ "async-trait", "eggwork-core", "landlock", - "nix", + "nix 0.29.0", + "process-wrap", "serde", "serde_json", "tempfile", @@ -617,7 +618,7 @@ dependencies = [ "eggwork-core", "eggwork-runner", "landlock", - "nix", + "nix 0.29.0", "serde", "serde_json", "tempfile", @@ -760,6 +761,21 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + [[package]] name = "futures-channel" version = "0.3.34" @@ -767,6 +783,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" dependencies = [ "futures-core", + "futures-sink", ] [[package]] @@ -775,6 +792,23 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + [[package]] name = "futures-macro" version = "0.3.34" @@ -804,10 +838,13 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ + "futures-channel", "futures-core", + "futures-io", "futures-macro", "futures-sink", "futures-task", + "memchr", "pin-project-lite", "slab", ] @@ -1199,6 +1236,18 @@ dependencies = [ "libc", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "num-conv" version = "0.2.2" @@ -1333,6 +1382,19 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "process-wrap" +version = "10.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f21b97672d2dc848e7b25701ab4535618b92f4861c13cc3f7f7bed52ad3c8da" +dependencies = [ + "futures", + "indexmap", + "nix 0.31.3", + "tokio", + "windows", +] + [[package]] name = "quote" version = "1.0.47" @@ -2057,6 +2119,18 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +[[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-args" version = "0.2.0" @@ -2066,12 +2140,86 @@ dependencies = [ "wtf8", ] +[[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-service" version = "0.8.1" @@ -2083,6 +2231,15 @@ dependencies = [ "windows-sys 0.61.2", ] +[[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" @@ -2117,6 +2274,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" diff --git a/README.md b/README.md index 4ec084f..054b07f 100644 --- a/README.md +++ b/README.md @@ -120,6 +120,13 @@ macOS and Windows ship the daemon only. SHA-256 sidecars are integrity evidence, not authenticity. +**Windows executes; it does not isolate.** A Windows node runs executions and +owns the whole process tree with a Job Object, so timeout, cancellation, output +limit, and a target that outlives its leader all converge. It offers no +filesystem or resource isolation: a `Required` isolation or resource request is +refused before the target starts, and a best-effort request is reported as +`NotApplied` rather than enforced. + **Windows service management is unsupported and fails closed** — `eggworkd` has no service-control dispatcher, so a registered service can never reach `Running`. Every mutating `service` verb is refused before any mutation; Windows diff --git a/architecture/ci-guardrails.md b/architecture/ci-guardrails.md index 0cd866f..b83a92d 100644 --- a/architecture/ci-guardrails.md +++ b/architecture/ci-guardrails.md @@ -20,6 +20,7 @@ Every invariant in [overview.md](overview.md) is stated as a rule that *is enfor | **1b. The ownership guard itself still fails when it should.** | `--prove-negative-exit` step, plus the in-process `self_test()` that runs on *every* invocation | A scanner regression (a dropped spawn pattern) makes the proof step exit 1 with `scanner regression — synthetic forbidden spawn was not detected`. | | **1c. Crate dependency direction.** `eggwork-server` owns no process machinery and must route through `eggwork-runner`. | `check_execution_ownership.py::check_dependencies()` over `cargo metadata --no-deps --format-version 1` | Nonzero exit naming the offending crate, e.g. `eggwork-core must not depend on eggwork-client`, `eggwork-server enables Tokio process creation; use eggwork-runner`, or `eggwork-server must depend on the canonical eggwork-runner`. | | **2. No direct service-manager invocation** (`systemctl`, `launchctl`, SCM, `crontab`). | Not machine-checked by a dedicated guard. The one hand-written enforcement is `operational-qualification.yml`'s `windows-installed-execution` job, which fails hard if the Windows service verb *does* mutate. Normatively owned by `execution-ownership.md`. | See [Test coverage and gaps](#test-coverage-and-gaps) — this is the weakest-enforced invariant in the set. | +| **Windows owns the whole process tree, and that is checked where it happens.** | The `windows-runner` CI job on `windows-latest` running `cargo test --locked -p eggwork-runner --all-targets`, which compiles the `#![cfg(windows)]` tree-lifecycle suite; plus `cargo clippy --locked --workspace --all-targets -- -D warnings` on the same host | Nonzero exit on any Windows-path regression, and the Linux job's silence no longer reads as Windows coverage. | | **3. Fixed target.** The client names its target explicitly. | Structural: `eggwork-client` is denied a dependency on the node crates by `check_dependencies()`; no workflow resolves a "latest" release. | Nonzero exit from the ownership guard if `eggwork-client` ever gains a `eggwork-runner`/`eggwork-server` edge. | | **4. Isolation claims are earned, never assumed.** | Exercised, not enforced statically: `installed_release_admits_execution_and_refuses_unsupported_isolation` in `crates/eggwork-server/tests/installed_qualification.rs`, driven from the qualification workflow on three hosted targets. | That ignored integration test fails; the hosted job goes red and its receipts are not uploaded. | | **5. Fail closed on uncertainty** for guarantees the caller demanded. | Same installed-execution test asserts required isolation is *refused* before the target runs; the Windows job records the service disposition and `throw`s if the refusal ever disappears (`the fail-closed guarantee is gone`). | Hard job failure. The Windows step deliberately ends `exit 0` only *after* recording the refusal, so the daemon's non-zero refusal exit is not inherited as the step's result. | @@ -47,6 +48,22 @@ for path in sorted((ROOT / "crates").glob("*/src/**/*.rs")): Only `.rs` files under `crates//src/`, at any nesting depth, are scanned. `crate_for_source()` maps a path to a crate by taking the second path component (`rel.parts[1]`) and returning `None` for anything else, so the crate identity is positional, not read from a manifest. Consequence: integration tests (`crates/*/tests/*.rs`), `examples/`, `benches/`, and `build.rs` are **not** scanned. That is the intended production boundary — a test that spawns a process is not a product that owns one — but it is a boundary a reviewer should confirm rather than assume. +### The dependency denylist and its one recorded exception + +`FORBIDDEN_PROCESS_DEPS = {command-group, duct, process-wrap, portable-pty, subprocess}` is the named set of libraries whose entire purpose is process ownership, so re-introducing one is a hard failure rather than a review question. It used to be applied to `eggwork-server` alone, which left every other crate unchecked; it is now applied to **all five crates** through `process_dep_errors()`, minus the entries in `APPROVED_PROCESS_DEP_EXCEPTIONS`. + +There is exactly one entry today: + +```python +APPROVED_PROCESS_DEP_EXCEPTIONS = { + ("eggwork-runner", "process-wrap"): ( + "Windows Job Object process-tree ownership, target-scoped to cfg(windows)" + ), +} +``` + +`eggwork-runner` is already an approved *source* owner, so this is not a widening of who may create processes — it is the narrowest possible way to let an existing owner express Windows tree ownership. `unexplained_process_dep_exceptions()` is the other half of the trade: it fails the guard if an exception names a crate that does not exist or a dependency that is not on the denylist, so the table cannot rot into a blanket waiver. + ### The approved-owner allowlist ```python @@ -175,6 +192,32 @@ Concretely: bump `version` in `[workspace.package]` to `0.1.6`, forget to run `c The related failure has the same shape and is why `check_release_tag.py` exists: v0.1.4 staged binaries that reported `0.1.3` because the version bump was missed entirely, which hosted qualification correctly refused with `installed-daemon-version: daemon reports '0.1.3', expected 0.1.4`. +## The `windows-runner` CI job + +A second job in the same workflow, on `windows-latest`, added by Foundation M004: + +```yaml + windows-runner: + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@1.89.0 + with: + components: clippy + - uses: Swatinem/rust-cache@v2 + with: + key: windows-msvc + - run: cargo clippy --locked --workspace --all-targets --all-features -- -D warnings + - name: Windows process-tree lifecycle suite + run: cargo test --locked -p eggwork-runner --all-targets -- --nocapture +``` + +**Why it exists.** The Windows process-tree backend cannot be observed from Linux. Job Object ownership, descendant convergence after leader exit, and pipe inheritance across a process tree only mean something on a real Windows kernel, and a green Linux run must never be readable as Windows coverage. Foundation M004's `runner` tests are `#![cfg(windows)]`, so without this job the entire suite would silently not exist in CI. + +**What it deliberately does not run.** `cargo test --workspace` is not used: the server's own tests are `/bin/sh`-shaped (18 occurrences across `crates/eggwork-server/src/lib.rs`), so they would fail on Windows for reasons that have nothing to do with this milestone. Reshaping them is separate work. Clippy *does* run `--workspace --all-targets`, because compilation is platform-neutral and `-D warnings` on the Windows target is what keeps the Windows-only code paths honest — an unused import or an `unused_mut` that Linux never sees is exactly the kind of drift this job exists to catch. The installed production path is qualified by `operational-qualification.yml` from a staged release's own bytes, not from a build tree; a build-tree job could not prove release identity. + +**Cross-check against the local guard.** Before pushing, `cargo check --locked -p eggwork-runner --all-targets --target x86_64-pc-windows-msvc` compiles the Windows-only code paths on a Linux host. It catches types, imports, and lints; it does not catch kernel behaviour, which is the entire point of the hosted job. (A full `--workspace --target x86_64-pc-windows-msvc` check does not work on Linux: `cc-rs` needs MSVC's `lib.exe` for a transitive C dependency.) + ## The `release-drift` job ```yaml diff --git a/architecture/execution-ownership.md b/architecture/execution-ownership.md index 1d40a1b..bf25b24 100644 --- a/architecture/execution-ownership.md +++ b/architecture/execution-ownership.md @@ -2,11 +2,11 @@ `eggwork-runner` is the canonical owner of finite-process lifecycle and resource-wrapper invocations. `eggwork-sandbox-helper` may create the target process only to apply installation-owned sandbox/resource mechanics before launch. `eggwork-server`, `eggwork-client`, and `eggwork-core` must not create OS children. Blocking database/filesystem work with `spawn_blocking` is not child-process ownership. The one exception is Eggwork's helper version-coherence probe, which invokes the installed helper with `--version` through Eggup's bounded candidate primitive (cleared environment, null stdin, bounded output and timeout, kill/reap): it performs no execution admission, owns no lifecycle, and exists only so required-isolation admission can fail closed on version skew. Direct `systemctl`/`launchctl`/SCM/`crontab` invocation is forbidden for the **node service**: all service lifecycle flows through Eggup adapters. The sanctioned exception is `eggwork-runner`'s own use of `systemd-run --scope` and `systemctl show`/`stop` against per-execution transient cgroup units, which is resource enforcement rather than service lifecycle and is owned by the crate that owns process lifecycle. The guard that polices this is `no_direct_service_manager_invocation_exists` in `crates/eggwork-server/src/deployment.rs`, and it scans only `src/deployment.rs`, `src/operations.rs`, and `src/bin/eggworkd.rs` — the runner is not covered, so a new server-side call to a manager is a discipline obligation, not something the gate will catch. -`LocalProcessRunner` accepts argv, executes inside a caller-authorized root, clears and rebuilds the environment from a conservative baseline, writes bounded stdin, and concurrently drains stdout and stderr. Capture retains bounded head/tail bytes; a full event channel drops stream chunks while pipe draining continues. Timeout, cancellation, terminate-on-overflow, and leader exit with remaining descendants signal the process group and force-kill after a grace period. Cleanup diagnostics do not rewrite a known exit outcome. +`LocalProcessRunner` accepts argv, executes inside a caller-authorized root, clears and rebuilds the environment from a conservative baseline, writes bounded stdin, and concurrently drains stdout and stderr. Capture retains bounded head/tail bytes; a full event channel drops stream chunks while pipe draining continues. Timeout, cancellation, terminate-on-overflow, and leader exit with remaining descendants converge the owned process tree: on Unix, signal the process group and force-kill after a grace period; on Windows, terminate the Job Object in one call. Cleanup diagnostics do not rewrite a known exit outcome. Run `python3 scripts/check_execution_ownership.py` before submitting Rust changes. It scans production source files, checks crate dependency direction, and runs a synthetic forbidden-spawn self-test. Approved owners are explicit in the script. A future platform backend must document its ownership rationale and add a negative/positive fixture before its crate or source path is allowlisted. `RunnerRequest` is constructed through `RunnerRequest::from_spec`; its validated execution fields are intentionally private. -On non-Unix hosts the runner returns an explicit unsupported-platform error until a process-tree backend is implemented and host-qualified. Linux was exercised for this milestone. The server performs immediate local admission in a later plan and retains its permit until runner cleanup completes. It does not maintain a queue or select another node. The caller retains global scheduling, placement, and retry authority. +On a Windows host the tree owner is a Job Object: the target is created suspended, assigned, and only then resumed, so no descendant can exist before Eggwork owns it, and timeout, cancellation, output limit, and leader-exit convergence all terminate that job. `process-wrap` is on the guard's process-owner denylist and reaches `eggwork-runner` only through the recorded `APPROVED_PROCESS_DEP_EXCEPTIONS` entry in `scripts/check_execution_ownership.py`, which is the only way a non-owner crate's dependency is permitted and why the denylist can now be applied to every crate. Windows is qualified for execution and not for isolation: `Required` isolation or resource requests are refused before spawn. Any compile target outside Unix and Windows keeps the explicit unsupported-platform error. The server performs immediate local admission in a later plan and retains its permit until runner cleanup completes. It does not maintain a queue or select another node. The caller retains global scheduling, placement, and retry authority. These boundaries follow [ADR-0005](../plans/adrs/ADR-0005-runner-service-separation-and-local-admission.md) and the [foundation roadmap](../plans/subsystems/foundation-execution-core-roadmap.md). Network listeners remain deferred to later milestones. diff --git a/architecture/runner-execution.md b/architecture/runner-execution.md index 49dce8d..39f76ac 100644 --- a/architecture/runner-execution.md +++ b/architecture/runner-execution.md @@ -258,10 +258,14 @@ result = child.wait() => Some((Exited, status?, error?)), **15. Resource cleanup (Linux).** `systemctl stop ` (2 s timeout) when a unit exists; its error seeds `CleanupDiagnostics::process_group_signal_error`. -**16. Process-group cleanup.** The two branches are asymmetric on purpose: +**16. Process-tree convergence.** The shared lifecycle calls two platform methods and never names a signal: `ProcessTree::converge_after_leader_exit()` when the leader already reported a status, and `ProcessTree::terminate_and_reap(TERMINATION_GRACE)` when it did not (timeout / cancel / overflow). Both return the same `TreeConvergence { status, signal_error, wait_error }`, which maps one-to-one onto `CleanupDiagnostics`; `run` never learns which backend it is talking to. Converging never revokes a status the leader already reported — that would rewrite a successful execution into `Failed`/`Internal`. -- **Status already known** (the `Exited` case): `terminate_group(process_group)`. `Ok(true)` (a live group was signalled) → `sleep(TERMINATION_GRACE)` → `kill_group`. `Ok(false)` (`ESRCH`, nothing left) → no-op. `Err` → recorded. The already-known `Some(status)` is then carried through unchanged. -- **Status unknown** (timeout / cancel / overflow): `terminate_group`, grace sleep if signalled, then `kill_group` unconditionally (`ESRCH` tolerated inside `kill_group`), then `timeout(TERMINATION_GRACE, child.wait())`. Success yields the status; a `wait()` error sets `cleanup.wait_error` and leaves `status` `None`; a timeout sets `cleanup.wait_error = "child did not exit after SIGKILL"`. +- **Unix** (`process_tree::imp`, `cfg(unix)`) — the leader was spawned with `process_group(0)` and the group id was captured at spawn, because `Child::id` returns `None` once the leader is reaped and the group is still needed after that. + - *Status already known*: `terminate_group(group)`. `Ok(true)` (a live group was signalled) → `sleep(TERMINATION_GRACE)` → `kill_group`. `Ok(false)` (`ESRCH`, nothing left) → no-op. `Err` → recorded as `process_group_signal_error`. + - *Status unknown*: `terminate_group`, grace sleep if signalled, then `kill_group` unconditionally (`ESRCH` tolerated inside `kill_group`), then `timeout(TERMINATION_GRACE, child.wait())`. Success yields the status; a `wait()` error sets `cleanup.wait_error` and leaves `status` `None`; a timeout sets `cleanup.wait_error = "child did not exit after SIGKILL"`. +- **Windows** (`process_tree::imp`, `cfg(windows)`) — the tree owner is a Job Object that already owns the leader and every descendant, so both branches are one `TerminateJobObject` call (`ChildWrapper::start_kill`) with no escalation window and nothing to wait for. `status` is always `None`: a job termination exit code describes Eggwork's kill, not the target's outcome, so reporting it as `exit_code` would be a fabricated fact — and Unix already reports `None` there, because a signalled process has no exit code. + + What Windows convergence does **not** claim: per-descendant exit observation. No safe-Rust surface in the reviewed dependency exposes a job-membership query, and adding one would mean Eggwork-owned `unsafe` Win32 FFI, which the workspace denies. Instead the invariant rests on three facts the shared lifecycle already provides: the Job Object stays owned for the whole execution, so nothing can escape the tree by outliving a leader; after `TerminateJobObject` returns the kernel has suspended and marked every member terminating, so no member can execute further user code; and `join_reader` still runs after convergence, and a pipe only reaches EOF once every process holding it has exited. Closing the Job Object handle is the backstop — the job is created with `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`, and the handle closes when the tree owner drops, which happens before `run` returns and therefore before the caller's execution permit is released. **17. Readers joined.** `join_reader` on both handles; a `JoinError` or reader `RunnerError::Io` becomes `Err` from `run` (note: this discards whatever was captured — see Review focus). @@ -277,7 +281,7 @@ Then the request's environment, each entry filtered through `denied_environment_ Finally provenance: `EGGWORK_EXECUTION_ID` (from `ExecutionId::as_str`) and `EGGWORK_EXECUTION_GENERATION` (from `ExecutionGeneration::get()`) when present. This is the documented "propagate neutral execution provenance through environment only where safe" of plan 002 §3.12 — the IDs are opaque strings with no routing authority. -The `#[cfg(windows)]` branch of the baseline exists because the shaping was written against a Windows qualification symptom, but `run` refuses on non-Unix before a command is ever built. The in-source comment is explicit that the shaping "did not and could not fix Windows qualification on its own." +The `#[cfg(windows)]` branch was originally unreachable: `run` refused on non-Unix before a command was ever built, so the shaping could not and did not fix Windows qualification on its own. Foundation M004 removed that refusal, which makes the branch load-bearing — `SystemRoot` is what the Windows loader needs, and `PATH` is what resolves `cmd.exe`. `windows_process_tree.rs::environment_is_the_documented_baseline_and_leaks_nothing` asserts both the baseline contents and that no ambient daemon variable reaches the target. ### Bounded capture: head and tail @@ -431,10 +435,11 @@ Drop-safety is partial by design. Every `Command` sets `.kill_on_drop(true)`, so | --- | --- | --- | --- | | Linux (x86_64, the exercised path) | Full lifecycle: `process_group(0)`, `killpg` termination and reaping, direct or helper-wrapped launch, Landlock `workspace_rw` via the trusted helper, systemd cgroup-v2 resource wrapping, helper status-byte and `Result=oom-kill` limit attribution, `systemctl stop` unit cleanup. Default setup is `TrustedLandlockSetup::discover_sibling()`. | Untrusted/missing helper → no `isolation.landlock.workspace-rw.v1`; required sandbox → `Err(Setup)`; required resources with an unavailable backend → `Err(Setup)`; `#[cfg]`-gated deps keep everything else out of the build | lines 159-365, 537-643, 1164-1211, 1369-1397 | | macOS / other Unix | Process lifecycle only: `direct_command`, `process_group(0)`, `killpg` SIGTERM/SIGKILL, bounded capture, timeout/cancellation/overflow, `UnsupportedPlatform` not applicable. Default setup is `NoExecutionSetup`. | `verify_trusted_helper` → `Err("trusted Landlock is unsupported on this platform")`; `probe_landlock_ruleset` → `false`; `SystemdCgroupBackend::probe` → `Err("OS resource controls are unsupported on this platform")`; required sandbox or resources → `Err(RequiredSetupUnavailable)`; capability advertisement is empty | lines 357-365, 581-584, 640-643, 654-683, 1115-1126 | -| Windows / non-Unix | Request validation only — `RunnerRequest::validate` still runs, so bounds and root/cwd confinement are enforced. | `Err(RunnerError::UnsupportedPlatform)` ("process-tree control is unsupported on this platform") returned *before* `prepare` and *before* `spawn`; the server maps it to `ExecutionFailure::Internal`. The `#[cfg(windows)]` baseline branch is present but unreachable from `run` today. | lines 1100-1101, 1153-1157, 1571-1583 | +| Windows | Full lifecycle through the Job Object backend: pre-run job assignment (`CREATE_SUSPENDED` → assign → resume), `TerminateJobObject` convergence for leader exit, timeout, cancellation, and output limit, bounded capture, stdin delivery, the `#[cfg(windows)]` environment baseline. Default setup is `NoExecutionSetup`. | Required sandbox or resources → `Err(RequiredSetupUnavailable)` (Windows has no Landlock and no cgroup backend), capability advertisement is empty, and the receipt reports `sandbox: NotRequested` rather than claiming confinement. | `process_tree.rs` (`cfg(windows)`), `windows_process_tree.rs` | +| Any other non-Unix compile target | Request validation only — `RunnerRequest::validate` still runs, so bounds and root/cwd confinement are enforced. | `Err(RunnerError::UnsupportedPlatform)` ("process-tree control is unsupported on this platform") raised by `ProcessTree::spawn_platform`; the server maps it to `ExecutionFailure::Internal`. | `process_tree.rs` (`cfg(not(any(unix, windows)))`) | | Any platform, `NoExecutionSetup` | Direct launch, full lifecycle | `Err(RequiredSetupUnavailable)` for required sandbox or required resources; empty dynamic capability list | lines 654-683, 1115-1126 | -Per the closure evidence in `plans/closure/security-isolation-resource/004-status.md`, only the Linux host class is production-qualified; macOS and Windows are fail-closed by construction, not qualified. `landlock` is a Linux-only kernel API and the `Cargo.toml` comment says so: "every required release target that is not Linux builds this crate, and all `landlock::` uses are already `#[cfg(target_os = "linux")]`-gated with fail-closed fallbacks." +Per the closure evidence in `plans/closure/security-isolation-resource/004-status.md`, only the Linux host class is isolation-qualified. Foundation M004 (see `plans/closure/foundation-execution-core/004-status.md`) qualified the Windows *execution* path on a hosted `windows-latest` runner; Windows remains isolation-free by construction, because the only isolation backend in this repository is Landlock, and that backend fails closed there rather than degrading. `landlock` is a Linux-only kernel API and the `Cargo.toml` comment says so: "every required release target that is not Linux builds this crate, and all `landlock::` uses are already `#[cfg(target_os = "linux")]`-gated with fail-closed fallbacks." ## Dependencies @@ -448,9 +453,10 @@ Per the closure evidence in `plans/closure/security-isolation-resource/004-statu | `serde` + `serde_json` | always | `SandboxLaunchSpec` is `Serialize` in the runner and `Deserialize` (`deny_unknown_fields`) in the helper. This is the only serialization in the crate, and it is the runner-to-helper wire format. | | `tempfile` | always (also a dev-dependency) | Production: `SandboxChannel`'s private `0700` directory holding `spec.json` and `status.sock`. Dev: test roots and the copied helper in `capability_probe.rs`. | | `landlock` (`=0.4.7`) | `[target.'cfg(target_os = "linux")'.dependencies]` | Kernel Landlock ABI V4 ruleset construction for the capability probe. | -| `nix` (`features = ["user"]` plus workspace `signal`, `process`) | `[target.'cfg(unix)'.dependencies]` | `killpg` for `terminate_group`/`kill_group`, `geteuid` for the trust check and the systemd user-manager decision. | +| `nix` (`features = ["user"]` plus workspace `signal`, `process`) | `[target.'cfg(unix)'.dependencies]` | `killpg` for the Unix tree convergence, `geteuid` for the trust check and the systemd user-manager decision. | +| `process-wrap` (`=10.0.1`, `default-features = false`, features `tokio1`, `job-object`, `kill-on-drop`) | `[target.'cfg(windows)'.dependencies]` | Windows Job Object process-tree ownership. It is on the guard's `FORBIDDEN_PROCESS_DEPS` denylist and allowed here only through the recorded `APPROVED_PROCESS_DEP_EXCEPTIONS` entry in `scripts/check_execution_ownership.py`, because it is the reviewed answer to a Windows-only problem Eggwork cannot solve with a bare `tokio::process::Child`: the Job Object has to exist before the target's first instruction. The pin is exact on purpose — upstream raises its MSRV inside a major version, so `10` is not a stable lower bound. `creation-flags` and `process-group` are deliberately *not* enabled: Eggwork passes no user creation flags, so the wrapper's default resume-after-assignment behaviour is exactly right. | -**Why the two are target-scoped.** Landlock is a Linux kernel LSM interface; there is no equivalent on any other kernel, so a workspace-wide dependency would either fail to build elsewhere or drag an unused crate into every release target — and `Eggpack` ships a `windows-x64` target, so this crate is compiled on non-Linux. `nix` covers all Unix, not just Linux, because the two things it provides here (`killpg` and `geteuid`) exist on macOS too and are exactly what the non-Linux *unix* path needs. Both are therefore gated at the same granularity as the `#[cfg]` blocks that use them: `landlock` at `target_os = "linux"`, `nix` at `unix`. Non-Linux-unix therefore pulls neither, and gets the fail-closed stubs instead. `scripts/check_execution_ownership.py` additionally forbids the process-spawn helper crates (`command-group`, `duct`, `process-wrap`, `portable-pty`, `subprocess`) across the workspace and asserts that `eggwork-core` and `eggwork-client` do not depend on `eggwork-runner`. +**Why the two are target-scoped.** Landlock is a Linux kernel LSM interface; there is no equivalent on any other kernel, so a workspace-wide dependency would either fail to build elsewhere or drag an unused crate into every release target — and `Eggpack` ships a `windows-x64` target, so this crate is compiled on non-Linux. `nix` covers all Unix, not just Linux, because the two things it provides here (`killpg` and `geteuid`) exist on macOS too and are exactly what the non-Linux *unix* path needs. Both are therefore gated at the same granularity as the `#[cfg]` blocks that use them: `landlock` at `target_os = "linux"`, `nix` at `unix`. `process-wrap` is gated at `windows` for the same reason. Non-Linux-unix pulls none of them, and gets the fail-closed stubs instead. `scripts/check_execution_ownership.py` forbids the process-spawn helper crates (`command-group`, `duct`, `process-wrap`, `portable-pty`, `subprocess`) in every crate except through a recorded `APPROVED_PROCESS_DEP_EXCEPTIONS` entry, and asserts that `eggwork-core` and `eggwork-client` do not depend on `eggwork-runner`. Before M004 the denylist was only applied to `eggwork-server`, which left the other crates unchecked; the exception table is what makes applying it everywhere safe. ## Test coverage @@ -476,6 +482,8 @@ Per the closure evidence in `plans/closure/security-isolation-resource/004-statu | `capability_feature_string_is_frozen_for_workspace_rw_profile` | the constant is literally `"isolation.landlock.workspace-rw.v1"` | | `no_setup_advertises_empty_dynamic_capabilities` | `NoExecutionSetup::execution_capabilities()` is empty | +`crates/eggwork-runner/tests/windows_process_tree.rs` (`#![cfg(windows)]`, run by the `windows-runner` CI job) is the Windows-only tree suite, and it is deliberately not a mirror of the Unix tests: the Unix ones use `/bin/sh`, which does not exist on Windows. Every tree claim is proven by a fixture that appends a heartbeat file on a 50 ms cadence, sampled *after* the runner returns, because there is no safe-Rust process-liveness API here. `assert_frozen` first asserts the heartbeat file is non-empty so the proof cannot pass vacuously, then re-samples after 600 ms. The proofs are: direct exit with CRLF-captured stdout/stderr and exit code 3; a descendant created at startup owned after the leader exits; timeout, cancellation, and output-limit convergence for both a leader and a detached descendant; leader exit not releasing a live descendant; leader exit status not rewritten by descendant termination; working directory honoured *and* a write outside the root succeeding with `sandbox: NotRequested`; stdin delivered and closed; typed spawn failure with no marker left behind; descendant output captured (pipe inheritance); the documented environment baseline with no ambient leak; bare program name resolved through `PATH`; required isolation and required resources refused before the marker command runs, with best-effort reported `NotApplied`; and five repeated timeout convergences, because tree bugs are timing bugs. + `tests/capability_probe.rs` covers the advertisement boundary end to end. It copies the built `eggwork-sandbox-helper` out of `$CARGO_TARGET_DIR/debug` (or `OUT_DIR`) into a fresh `0700` tempdir as `0755`, deliberately leaks the tempdir, and asserts `LocalProcessRunner::new(TrustedLandlockSetup::new(helper)).execution_capabilities()` contains `isolation.landlock.workspace-rw.v1` on an ABI-V4 kernel. It **skips** (prints and returns) when no helper binary is present. The mirror case, `missing_helper_advertises_no_landlock_capability`, points at `/nonexistent/eggwork-sandbox-helper` and asserts the feature is absent. `SandboxChannel` internals are covered from the helper crate's integration test, `crates/eggwork-sandbox-helper/tests/landlock_runner.rs`, which drives the runner's public API: outside read/write denial, helper trust rejections (missing/wrong/symlinked), workspace and cwd symlink escapes, timeout and cancellation reaping the helper's own process group, required memory/PID/CPU enforcement and classification, concurrent cgroup scope isolation, and `malformed_private_spec_and_unavailable_status_channel_do_not_launch_target`. @@ -484,7 +492,8 @@ Per the closure evidence in `plans/closure/security-isolation-resource/004-statu - **No unit test rejects a bad `RunnerRequest`.** Every `RunnerError::InvalidRequest` branch — empty/NUL/oversized argv, environment count and size bounds, `=` in an environment name, `capture_limit` over 16 MiB, `event_chunk_bytes` of 0, zero or over-maximum timeout, stdin over 4 MiB — is unexercised. The only escaping test is `cwd` under a valid root. - **No test covers a cwd that escapes root** (`..`, absolute, or a symlink) at the runner level; that assertion lives in the helper crate's test, and only for the symlink form. -- **No test covers `RunnerError::UnsupportedPlatform`.** The path is `#[cfg(not(unix))]` and this crate's own test surface has no Windows coverage, so the non-Unix refusal is asserted only by code reading. +- **No test covers `RunnerError::UnsupportedPlatform`.** The path is now `cfg(not(any(unix, windows)))`, which is not a release target, so the refusal stays asserted only by code reading. Windows no longer takes this path. +- **Pre-run Job Object assignment is a property of the dependency, not of a test.** `process-wrap` adds `CREATE_SUSPENDED`, assigns, and resumes inside `spawn`; the suite can observe the consequences (a descendant created in the target's first moments is owned, a spawn failure leaves nothing running) but cannot observe the assignment itself from outside the process without Win32 tracing. That is stated rather than glossed: the evidence is "no descendant ever escaped", not "the kernel was entered in this state". - **The baseline environment is only tested negatively.** `captures_exit_stdin_and_sanitizes_environment` proves `LD_PRELOAD` is stripped; nothing pins the exact baseline set, the `denied_environment_key` list, or the `PATH` special case (baseline sets it, the deny list rejects a request-supplied one). - **`SystemdCgroupBackend::wrap` argv construction is untested** — the `--property` rendering, the `MemoryMax`/`MemorySwapMax=0` pairing, the `CPUQuota` millis-to-percentage conversion, `resource_unit_name` uniqueness, and the `--user` selection are all unasserted. The resource *enforcement* tests live in the helper crate and depend on a systemd-capable host. - **`BoundedCapture` is tested at exactly one limit (6).** Odd limits, `limit == 1`, and `limit == 0` are unverified, as is the head/tail split when a single `push` straddles the boundary. @@ -502,7 +511,8 @@ Per the closure evidence in `plans/closure/security-isolation-resource/004-statu - **Trust-check TOCTOU.** `verify_trusted_helper` is a path-based `symlink_metadata` plus an ancestor walk, and the helper is executed later by path. Nothing pins an fd between check and exec, and `SandboxChannel::command()` re-resolves the path. The window is small but real, and it is the window the whole isolation story depends on. - **Grace-period sizing and where it is spent.** The same 300 ms is both the `SIGTERM → SIGKILL` delay and the post-`SIGKILL` wait bound, so the worst case adds ~600 ms; a `systemctl stop` adds up to 2 s more. More importantly, a *successful* run that leaves any descendant alive pays a full 300 ms. Whether these are the right constants for the workload is a tuning question the code has not revisited since M002. - **`cleanup_warning` priority can mask a more relevant diagnostic.** `process_group_signal_error` is pre-seeded with the `systemctl stop` failure, and it outranks `wait_error` in the single folded `cleanup_warning` string. The individual fields survive in `RunnerResult::cleanup`, so nothing is lost — but the field most operators will read can be about cgroup cleanup rather than about a failed `wait()`. -- **Non-Linux honesty.** The `#[cfg(windows)]` baseline branch looks like a Windows execution path and is unreachable, because `run` refuses before building a command. The non-Linux `verify_trusted_helper` also reports "trusted Landlock is unsupported" rather than "this platform does not run children at all" — a reader skimming the fallbacks could come away with a wrong model of what Windows does. +- **Windows converges the tree without observing it.** `TerminateJobObject` is sound for the invariant that matters — no member can execute user code after it returns — but Eggwork cannot report *which* descendants died or observe a job-membership count, because no safe surface is available. A reader who wants per-descendant evidence will not find it here, and should not assume the Job Object path is as observable as the process-group path. +- **Non-Linux honesty.** The non-Linux `verify_trusted_helper` reports "trusted Landlock is unsupported" rather than "this platform runs children without isolation". Both are true on Windows now that `run` proceeds, but a reader skimming the fallbacks could still come away with a wrong model of what Windows does — Windows now executes children and refuses isolation, which is a different thing from refusing to execute at all. - **Can cleanup mask a real exit status?** It cannot change `termination` or `exit_code` — the `Some(status)` branch returns the known status regardless. But `Err(Io)` from `join_reader` discards the `BoundedCapture` entirely, so a late pipe error loses the child's output and totals on a run that otherwise succeeded. Whether a partially captured result is better than an error is a deliberate-or-accidental design choice worth confirming. - **The `biased` select makes cancellation outrank natural exit.** An execution that completes in the same instant a cancel arrives is reported `Cancelled`, and its exit code is discarded. This yields exactly one terminal outcome (ADR-0003 is satisfied), but the winner is precedence, not truth, and no test pins it. diff --git a/crates/eggwork-runner/Cargo.toml b/crates/eggwork-runner/Cargo.toml index 28640ae..509bbf3 100644 --- a/crates/eggwork-runner/Cargo.toml +++ b/crates/eggwork-runner/Cargo.toml @@ -17,6 +17,12 @@ tempfile.workspace = true [dev-dependencies] tempfile.workspace = true +# The Windows tree-lifecycle suite drives the runner through its public API and +# needs the same protocol types the crate itself validates against. `tokio` and +# `tokio-util` are regular dependencies, which an integration test cannot see. +eggwork-core = { path = "../eggwork-core" } +tokio = { workspace = true, features = ["macros", "process", "rt", "sync", "time"] } +tokio-util.workspace = true # Landlock is a Linux-only kernel API. The crate is Linux-only and must not # enter the build graph on any other host: every required release target that @@ -28,5 +34,18 @@ landlock.workspace = true [target.'cfg(unix)'.dependencies] nix = { workspace = true, features = ["user"] } +# Windows needs pre-run process-tree ownership, not a bare `tokio::process::Child`: +# the target must not be able to run — or create descendants — before Eggwork owns +# the tree. `process-wrap` assigns the Job Object while the process is still +# suspended and resumes it afterwards, and terminates the whole tree through the +# Job Object. The exact pin is deliberate: upstream raises its MSRV without a major +# version bump, so "10" is not a stable lower bound (Foundation M004). +[target.'cfg(windows)'.dependencies] +process-wrap = { version = "=10.0.1", default-features = false, features = [ + "tokio1", + "job-object", + "kill-on-drop", +] } + [lints] workspace = true diff --git a/crates/eggwork-runner/src/lib.rs b/crates/eggwork-runner/src/lib.rs index 977f84c..e657a3c 100644 --- a/crates/eggwork-runner/src/lib.rs +++ b/crates/eggwork-runner/src/lib.rs @@ -15,10 +15,12 @@ use eggwork_core::{ MAX_ENV_VALUE_BYTES, MAX_EVENT_CHUNK_BYTES, OverflowPolicy as CoreOverflowPolicy, RelativePath, Requirement, StdinPolicy as CoreStdinPolicy, }; +#[cfg(target_os = "linux")] use serde::Serialize; +#[cfg(target_os = "linux")] +use std::io::Write; use std::{ collections::VecDeque, - io::Write, path::{Path, PathBuf}, process::Stdio, time::Duration, @@ -31,10 +33,14 @@ use tokio::{ process::Command, sync::{mpsc, watch}, task::JoinHandle, - time::{sleep, timeout}, + time::sleep, }; use tokio_util::sync::CancellationToken; +mod process_tree; + +use process_tree::{ProcessTree, TreeConvergence}; + const READ_BUFFER: usize = 8192; const TERMINATION_GRACE: Duration = Duration::from_millis(300); @@ -138,6 +144,9 @@ impl ResourceSetupRequest { || matches!(self.pids, Requirement::Required(_)) } + /// systemd transient-unit properties for the requested limits. Only the Linux + /// helper handshake builds them, so the method is Linux-shaped. + #[cfg(target_os = "linux")] fn properties(&self) -> Vec<(String, String)> { let mut properties = Vec::new(); if let Requirement::BestEffort(value) | Requirement::Required(value) = self.memory_bytes { @@ -209,7 +218,7 @@ impl SystemdCgroupBackend { let mut child = command .spawn() .map_err(|_| "systemd transient resource backend is unavailable".to_owned())?; - match timeout(Duration::from_secs(5), child.wait()).await { + match tokio::time::timeout(Duration::from_secs(5), child.wait()).await { Ok(Ok(status)) if status.success() => Ok(()), Ok(_) => Err("systemd could not establish the requested cgroup limits".into()), Err(_) => { @@ -286,7 +295,7 @@ impl SystemdCgroupBackend { .stdout(Stdio::piped()) .stderr(Stdio::null()) .kill_on_drop(true); - let output = timeout(Duration::from_secs(1), command.output()) + let output = tokio::time::timeout(Duration::from_secs(1), command.output()) .await .ok()? .ok()?; @@ -311,7 +320,7 @@ impl SystemdCgroupBackend { let mut child = command .spawn() .map_err(|_| "systemd scope cleanup failed".to_owned())?; - match timeout(Duration::from_secs(2), child.wait()).await { + match tokio::time::timeout(Duration::from_secs(2), child.wait()).await { Ok(Ok(status)) if status.success() => Ok(()), Ok(_) => Err("systemd scope cleanup failed".into()), Err(_) => { @@ -1150,315 +1159,303 @@ impl LocalProcessRunner { return Err(RunnerError::CancelledBeforeSpawn); } let cwd = request.validate()?; - #[cfg(not(unix))] - { - let _ = (cwd, request, output_tx); - return Err(RunnerError::UnsupportedPlatform); - } - #[cfg(unix)] - { - let mut setup = self - .setup - .prepare(&request.sandbox, &request.resources, &request.root) - .await?; - #[cfg(target_os = "linux")] - let use_helper = ((!matches!(request.sandbox, SandboxRequest::None) - && matches!(setup.sandbox, SandboxOutcome::Applied { .. })) - || matches!(setup.resources, ResourceSetupOutcome::Applied { .. })) - && self.setup.sandbox_helper_path().is_some(); - #[cfg(target_os = "linux")] - let mut channel = if use_helper { - match SandboxChannel::new( - self.setup.sandbox_helper_path().expect("checked above"), - &request, - cwd.clone(), - matches!(setup.resources, ResourceSetupOutcome::Applied { .. }), - ) { - Ok(channel) => Some(channel), - Err(error) - if !matches!(request.sandbox, SandboxRequest::Required { .. }) - && !request.resources.has_required() => - { - if !matches!(request.sandbox, SandboxRequest::None) { - setup.sandbox = SandboxOutcome::NotApplied { - reason: error.to_string(), - }; - } - if matches!(setup.resources, ResourceSetupOutcome::Applied { .. }) { - setup.resources = ResourceSetupOutcome::NotApplied { - reason: error.to_string(), - }; - } - None - } - Err(error) => return Err(error), - } - } else { - None - }; - #[cfg(not(target_os = "linux"))] - let channel: Option<()> = None; - #[cfg(target_os = "linux")] - let command = if let Some(channel) = channel.as_ref() { - channel.command() - } else { - direct_command(&request, cwd.clone()) - }; - #[cfg(not(target_os = "linux"))] - let mut command = direct_command(&request, cwd.clone()); - #[cfg(target_os = "linux")] - let (mut command, mut resource_unit) = - wrap_resource_command(command, &request.resources, &setup.resources)?; - #[cfg(target_os = "linux")] - let mut sandbox_session = None; - #[cfg(not(target_os = "linux"))] - let resource_unit: Option = None; - #[cfg(not(target_os = "linux"))] - let mut command = command; - command.process_group(0); - let mut child = command - .spawn() - .map_err(|e| RunnerError::Spawn(e.to_string()))?; - #[cfg(target_os = "linux")] - if let Some(sandbox_channel) = channel.take() { - let handshake = sandbox_channel.wait(&mut child, cancellation.clone()).await; - match handshake { - Ok(Some(session)) => sandbox_session = Some(session), - Ok(None) - if !matches!(request.sandbox, SandboxRequest::Required { .. }) - && !request.resources.has_required() => - { - let _ = child.wait().await; - if !matches!(request.sandbox, SandboxRequest::None) { - setup.sandbox = SandboxOutcome::NotApplied { - reason: "Landlock helper could not enforce the requested profile" - .into(), - }; - } - if matches!(setup.resources, ResourceSetupOutcome::Applied { .. }) { - setup.resources = ResourceSetupOutcome::NotApplied { - reason: "resource helper could not verify the cgroup limits".into(), - }; - } - let direct = direct_command(&request, cwd.clone()); - let (mut direct, unit) = - wrap_resource_command(direct, &request.resources, &setup.resources)?; - resource_unit = unit; - direct.process_group(0); - child = direct - .spawn() - .map_err(|error| RunnerError::Spawn(error.to_string()))?; - } - Ok(None) => { - let _ = child.start_kill(); - let _ = child.wait().await; - return Err(RunnerError::RequiredSetupUnavailable); - } - Err(SandboxWaitError::BeforeTarget(error)) - if !matches!(request.sandbox, SandboxRequest::Required { .. }) - && !request.resources.has_required() - && !matches!(error, RunnerError::CancelledBeforeSpawn) => - { - let _ = child.start_kill(); - let _ = child.wait().await; - if !matches!(request.sandbox, SandboxRequest::None) { - setup.sandbox = SandboxOutcome::NotApplied { - reason: error.to_string(), - }; - } - if matches!(setup.resources, ResourceSetupOutcome::Applied { .. }) { - setup.resources = ResourceSetupOutcome::NotApplied { - reason: error.to_string(), - }; - } - let direct = direct_command(&request, cwd.clone()); - let (mut direct, unit) = - wrap_resource_command(direct, &request.resources, &setup.resources)?; - resource_unit = unit; - direct.process_group(0); - child = direct - .spawn() - .map_err(|spawn_error| RunnerError::Spawn(spawn_error.to_string()))?; + // Process-tree ownership is platform specific and lives in + // `process_tree::ProcessTree`; the lifecycle below is shared. Validation, + // setup, command construction, pipe readers, bounded capture, timeout and + // cancellation selection, terminal conversion, and provenance are + // identical on every platform that has a tree owner, so there is one + // runner with two tree backends rather than two runners. `ProcessTree:: + // spawn_platform` is the typed refusal point (`UnsupportedPlatform`) for + // compile targets with no tree story at all. + // Only the Linux helper handshake rewrites the prepared outcome, so the + // binding is immutable everywhere else. + #[cfg_attr(not(target_os = "linux"), allow(unused_mut))] + let mut setup = self + .setup + .prepare(&request.sandbox, &request.resources, &request.root) + .await?; + #[cfg(target_os = "linux")] + let use_helper = ((!matches!(request.sandbox, SandboxRequest::None) + && matches!(setup.sandbox, SandboxOutcome::Applied { .. })) + || matches!(setup.resources, ResourceSetupOutcome::Applied { .. })) + && self.setup.sandbox_helper_path().is_some(); + #[cfg(target_os = "linux")] + let mut channel = if use_helper { + match SandboxChannel::new( + self.setup.sandbox_helper_path().expect("checked above"), + &request, + cwd.clone(), + matches!(setup.resources, ResourceSetupOutcome::Applied { .. }), + ) { + Ok(channel) => Some(channel), + Err(error) + if !matches!(request.sandbox, SandboxRequest::Required { .. }) + && !request.resources.has_required() => + { + if !matches!(request.sandbox, SandboxRequest::None) { + setup.sandbox = SandboxOutcome::NotApplied { + reason: error.to_string(), + }; } - Err(error) => { - let _ = child.start_kill(); - let _ = child.wait().await; - return Err(error.into_runner_error()); + if matches!(setup.resources, ResourceSetupOutcome::Applied { .. }) { + setup.resources = ResourceSetupOutcome::NotApplied { + reason: error.to_string(), + }; } - } - } - let process_group = child.id(); - let stdin_task = match (child.stdin.take(), &request.stdin) { - (Some(mut stdin), StdinPolicy::Bytes(bytes)) => { - let bytes = bytes.clone(); - Some(tokio::spawn(async move { - let result = stdin.write_all(&bytes).await; - drop(stdin); - result - })) - } - (stdin, StdinPolicy::Null) => { - drop(stdin); - None - } - (stdin, StdinPolicy::Bytes(_)) => { - drop(stdin); None } - }; - let (overflow_tx, mut overflow_rx) = watch::channel(false); - let stdout = child - .stdout - .take() - .ok_or_else(|| RunnerError::Io("stdout pipe missing".into()))?; - let stderr = child - .stderr - .take() - .ok_or_else(|| RunnerError::Io("stderr pipe missing".into()))?; - let stdout_task = spawn_reader( - stdout, - false, - request.capture_limit, - request.event_chunk_bytes, - output_tx.clone(), - overflow_tx.clone(), - request.overflow.clone(), - ); - let stderr_task = spawn_reader( - stderr, - true, - request.capture_limit, - request.event_chunk_bytes, - output_tx, - overflow_tx.clone(), - request.overflow, - ); - let deadline = request.timeout; - // `None` as a termination means the wait has to be settled against - // the child rather than against the monitor. The `child.wait()` - // continuation lives after the `select!` rather than inside one arm - // because awaiting it in an arm makes the whole future `!Send`, and - // this `select!` runs inside a spawned task. - let settled: Option<( - TerminationReason, - Option, - Option, - )> = tokio::select! { - biased; - _ = cancellation.cancelled() => Some((TerminationReason::Cancelled, None, None)), - _ = sleep(deadline) => Some((TerminationReason::TimedOut, None, None)), - // Whether the monitor changed or merely closed is not the - // question; its current value is. A closed monitor reads as - // `false`, which is the same as a quiet one, and both mean - // "keep waiting for the child". - _ = overflow_rx.changed() => { - monitor_termination(*overflow_rx.borrow()).map(|t| (t, None, None)) - } - result = child.wait() => Some(match result { - Ok(status) => (TerminationReason::Exited, Some(status), None), - Err(error) => (TerminationReason::Exited, None, Some(error.to_string())), - }), - }; - let (termination, status, wait_error) = match settled { - Some(settled) => settled, - None => match child.wait().await { - Ok(status) => (TerminationReason::Exited, Some(status), None), - Err(error) => (TerminationReason::Exited, None, Some(error.to_string())), - }, - }; - #[cfg(target_os = "linux")] - let mut resource_limits_exceeded = if matches!(&termination, TerminationReason::Exited) - && let Some(session) = sandbox_session.take() - { - session.resource_limits_exceeded().await - } else { - Vec::new() - }; - #[cfg(target_os = "linux")] - if let Some(unit) = resource_unit.as_deref() - && let Ok(backend) = SystemdCgroupBackend::discover() - && backend.unit_result(unit).await.as_deref() == Some("oom-kill") - && !resource_limits_exceeded.contains(&eggwork_core::ResourceDimension::Memory) - { - resource_limits_exceeded.push(eggwork_core::ResourceDimension::Memory); + Err(error) => return Err(error), } - #[cfg(not(target_os = "linux"))] - let resource_limits_exceeded: Vec = Vec::new(); - #[cfg(target_os = "linux")] - let resource_cleanup_warning = if let Some(unit) = resource_unit.as_deref() { - match SystemdCgroupBackend::discover() { - Ok(backend) => backend.stop_unit(unit).await.err(), - Err(_) => Some("systemd scope cleanup was unavailable".into()), - } - } else { - None - }; - #[cfg(not(target_os = "linux"))] - let resource_cleanup_warning: Option = None; - let mut cleanup = CleanupDiagnostics { - process_group_signal_error: resource_cleanup_warning, - wait_error, - stdin_error: None, - }; - let status = if let Some(status) = status { - // A command can leave background descendants behind and exit - // while they still hold the output pipes. Reap that process - // group before returning, without changing the leader's - // already-known exit classification. - match terminate_group(process_group) { - Ok(true) => { - sleep(TERMINATION_GRACE).await; - if let Err(error) = kill_group(process_group) { - cleanup.process_group_signal_error = Some(error); - } + } else { + None + }; + #[cfg(not(target_os = "linux"))] + let _channel: Option<()> = None; + #[cfg(target_os = "linux")] + let command = if let Some(channel) = channel.as_ref() { + channel.command() + } else { + direct_command(&request, cwd.clone()) + }; + #[cfg(not(target_os = "linux"))] + let command = direct_command(&request, cwd.clone()); + #[cfg(target_os = "linux")] + let (command, mut resource_unit) = + wrap_resource_command(command, &request.resources, &setup.resources)?; + #[cfg(target_os = "linux")] + let mut sandbox_session = None; + #[cfg(not(target_os = "linux"))] + let _resource_unit: Option = None; + // On Linux this is the sandbox helper when isolation or resource + // enforcement is configured, and the target itself otherwise. On + // Windows there is no helper, so it is always the target. Either way + // the tree owner holds the whole tree for the rest of the lifecycle. + let mut tree = ProcessTree::spawn_platform(command)?; + #[cfg(target_os = "linux")] + if let Some(sandbox_channel) = channel.take() { + let handshake = sandbox_channel + .wait(tree.child_mut(), cancellation.clone()) + .await; + match handshake { + Ok(Some(session)) => sandbox_session = Some(session), + Ok(None) + if !matches!(request.sandbox, SandboxRequest::Required { .. }) + && !request.resources.has_required() => + { + let _ = tree.wait().await; + if !matches!(request.sandbox, SandboxRequest::None) { + setup.sandbox = SandboxOutcome::NotApplied { + reason: "Landlock helper could not enforce the requested profile" + .into(), + }; } - Ok(false) => {} - Err(error) => cleanup.process_group_signal_error = Some(error), - } - Some(status) - } else { - match terminate_group(process_group) { - Ok(true) => sleep(TERMINATION_GRACE).await, - Ok(false) => {} - Err(error) => cleanup.process_group_signal_error = Some(error), + if matches!(setup.resources, ResourceSetupOutcome::Applied { .. }) { + setup.resources = ResourceSetupOutcome::NotApplied { + reason: "resource helper could not verify the cgroup limits".into(), + }; + } + let direct = direct_command(&request, cwd.clone()); + let (direct, unit) = + wrap_resource_command(direct, &request.resources, &setup.resources)?; + resource_unit = unit; + tree = ProcessTree::spawn_platform(direct)?; } - if let Err(error) = kill_group(process_group) { - cleanup.process_group_signal_error.get_or_insert(error); + Ok(None) => { + let _ = tree.start_kill(); + let _ = tree.wait().await; + return Err(RunnerError::RequiredSetupUnavailable); } - match timeout(TERMINATION_GRACE, child.wait()).await { - Ok(Ok(status)) => Some(status), - Ok(Err(error)) => { - cleanup.wait_error = Some(error.to_string()); - None + Err(SandboxWaitError::BeforeTarget(error)) + if !matches!(request.sandbox, SandboxRequest::Required { .. }) + && !request.resources.has_required() + && !matches!(error, RunnerError::CancelledBeforeSpawn) => + { + let _ = tree.start_kill(); + let _ = tree.wait().await; + if !matches!(request.sandbox, SandboxRequest::None) { + setup.sandbox = SandboxOutcome::NotApplied { + reason: error.to_string(), + }; } - Err(_) => { - cleanup.wait_error = Some("child did not exit after SIGKILL".into()); - None + if matches!(setup.resources, ResourceSetupOutcome::Applied { .. }) { + setup.resources = ResourceSetupOutcome::NotApplied { + reason: error.to_string(), + }; } + let direct = direct_command(&request, cwd.clone()); + let (direct, unit) = + wrap_resource_command(direct, &request.resources, &setup.resources)?; + resource_unit = unit; + tree = ProcessTree::spawn_platform(direct)?; } - }; - if let Some(task) = stdin_task { - match task.await { - Ok(Ok(())) => {} - Ok(Err(error)) => cleanup.stdin_error = Some(error.to_string()), - Err(error) => cleanup.stdin_error = Some(error.to_string()), + Err(error) => { + let _ = tree.start_kill(); + let _ = tree.wait().await; + return Err(error.into_runner_error()); } } - let (stdout, dropped_out) = join_reader(stdout_task).await?; - let (stderr, dropped_err) = join_reader(stderr_task).await?; - Ok(RunnerResult { - termination, - exit_code: status.and_then(|s| s.code()), - stdout, - stderr, - cleanup, - setup, - resource_request: request.resources, - resource_limits_exceeded, - stream_chunks_dropped: dropped_out + dropped_err, - provenance: request.provenance, - }) } + let stdin_task = match (tree.take_stdin(), &request.stdin) { + (Some(mut stdin), StdinPolicy::Bytes(bytes)) => { + let bytes = bytes.clone(); + Some(tokio::spawn(async move { + let result = stdin.write_all(&bytes).await; + drop(stdin); + result + })) + } + (stdin, StdinPolicy::Null) => { + drop(stdin); + None + } + (stdin, StdinPolicy::Bytes(_)) => { + drop(stdin); + None + } + }; + let (overflow_tx, mut overflow_rx) = watch::channel(false); + let stdout = tree + .take_stdout() + .ok_or_else(|| RunnerError::Io("stdout pipe missing".into()))?; + let stderr = tree + .take_stderr() + .ok_or_else(|| RunnerError::Io("stderr pipe missing".into()))?; + let stdout_task = spawn_reader( + stdout, + false, + request.capture_limit, + request.event_chunk_bytes, + output_tx.clone(), + overflow_tx.clone(), + request.overflow.clone(), + ); + let stderr_task = spawn_reader( + stderr, + true, + request.capture_limit, + request.event_chunk_bytes, + output_tx, + overflow_tx.clone(), + request.overflow, + ); + let deadline = request.timeout; + // `None` as a termination means the wait has to be settled against + // the child rather than against the monitor. The `tree.wait()` + // continuation lives after the `select!` rather than inside one arm + // because awaiting it in an arm makes the whole future `!Send`, and + // this `select!` runs inside a spawned task. + let settled: Option<( + TerminationReason, + Option, + Option, + )> = tokio::select! { + biased; + _ = cancellation.cancelled() => Some((TerminationReason::Cancelled, None, None)), + _ = sleep(deadline) => Some((TerminationReason::TimedOut, None, None)), + // Whether the monitor changed or merely closed is not the + // question; its current value is. A closed monitor reads as + // `false`, which is the same as a quiet one, and both mean + // "keep waiting for the child". + _ = overflow_rx.changed() => { + monitor_termination(*overflow_rx.borrow()).map(|t| (t, None, None)) + } + result = tree.wait() => Some(match result { + Ok(status) => (TerminationReason::Exited, Some(status), None), + Err(error) => (TerminationReason::Exited, None, Some(error.to_string())), + }), + }; + let (termination, status, wait_error) = match settled { + Some(settled) => settled, + None => match tree.wait().await { + Ok(status) => (TerminationReason::Exited, Some(status), None), + Err(error) => (TerminationReason::Exited, None, Some(error.to_string())), + }, + }; + #[cfg(target_os = "linux")] + let mut resource_limits_exceeded = if matches!(&termination, TerminationReason::Exited) + && let Some(session) = sandbox_session.take() + { + session.resource_limits_exceeded().await + } else { + Vec::new() + }; + #[cfg(target_os = "linux")] + if let Some(unit) = resource_unit.as_deref() + && let Ok(backend) = SystemdCgroupBackend::discover() + && backend.unit_result(unit).await.as_deref() == Some("oom-kill") + && !resource_limits_exceeded.contains(&eggwork_core::ResourceDimension::Memory) + { + resource_limits_exceeded.push(eggwork_core::ResourceDimension::Memory); + } + #[cfg(not(target_os = "linux"))] + let resource_limits_exceeded: Vec = Vec::new(); + #[cfg(target_os = "linux")] + let resource_cleanup_warning = if let Some(unit) = resource_unit.as_deref() { + match SystemdCgroupBackend::discover() { + Ok(backend) => backend.stop_unit(unit).await.err(), + Err(_) => Some("systemd scope cleanup was unavailable".into()), + } + } else { + None + }; + #[cfg(not(target_os = "linux"))] + let resource_cleanup_warning: Option = None; + let mut cleanup = CleanupDiagnostics { + process_group_signal_error: resource_cleanup_warning, + wait_error, + stdin_error: None, + }; + // Tree convergence is the platform's job: on Unix this is + // SIGTERM to the process group, a grace period, then SIGKILL and a + // bounded reap of the leader; on Windows it is one + // `TerminateJobObject` over a Job Object that already owns every + // descendant. Both return the same three facts, so no shared + // decision below has to know which backend it is talking to. + let convergence = if let Some(status) = status { + // A command can leave background descendants behind and exit + // while they still hold the output pipes. Reap that process tree + // before returning, without changing the leader's already-known + // exit classification. + let convergence = tree.converge_after_leader_exit().await; + // Convergence never revokes a status the leader already reported. + // Dropping it here would turn every successful Windows execution + // into `Failed`/`Internal` with `exit_code: null`, because the + // tree owner has nothing left to reap. + TreeConvergence { + status: Some(status), + ..convergence + } + } else { + tree.terminate_and_reap(TERMINATION_GRACE).await + }; + if let Some(error) = convergence.signal_error { + cleanup.process_group_signal_error.get_or_insert(error); + } + if let Some(error) = convergence.wait_error { + cleanup.wait_error = Some(error); + } + let status = convergence.status; + if let Some(task) = stdin_task { + match task.await { + Ok(Ok(())) => {} + Ok(Err(error)) => cleanup.stdin_error = Some(error.to_string()), + Err(error) => cleanup.stdin_error = Some(error.to_string()), + } + } + let (stdout, dropped_out) = join_reader(stdout_task).await?; + let (stderr, dropped_err) = join_reader(stderr_task).await?; + Ok(RunnerResult { + termination, + exit_code: status.and_then(|s| s.code()), + stdout, + stderr, + cleanup, + setup, + resource_request: request.resources, + resource_limits_exceeded, + stream_chunks_dropped: dropped_out + dropped_err, + provenance: request.provenance, + }) } } @@ -1525,12 +1522,11 @@ fn direct_command(request: &RunnerRequest, cwd: PathBuf) -> Command { /// Windows child would have been handed a `PATH` that does not exist on /// Windows and no `SystemRoot`. That shaping was written against the M004 /// qualification symptom of `state: Failed`, `failure: Internal`, -/// `exit_code: null` -- but on Windows no child ever exists to receive an -/// environment: `LocalProcessRunner::run` refuses with `UnsupportedPlatform` -/// before spawn, and the server maps that refusal to `Internal`. The shaping -/// is still correct for any future Windows execution path, and it is what the -/// qualified harness declares today, but it did not and could not fix Windows -/// qualification on its own. +/// `exit_code: null` -- and it could not have fixed Windows qualification, +/// because at that time no Windows child existed at all: `run` refused with +/// `UnsupportedPlatform` before spawn and the server mapped that refusal to +/// `Internal`. Foundation M004 removed the refusal, which makes this shaping +/// load-bearing instead of merely aspirational. /// /// Unix keeps the narrow, deterministic baseline the existing Linux and macOS /// evidence was gathered with. Windows gets the system directories its loader @@ -1551,11 +1547,12 @@ fn direct_command(request: &RunnerRequest, cwd: PathBuf) -> Command { /// invisible in most runs on every platform; the unit test below pins it /// deterministically instead of relying on timing. /// -/// This race is real but it is NOT the Windows execution cause: on Windows -/// `LocalProcessRunner::run` refuses with `UnsupportedPlatform` before any -/// child exists, so the monitor code never runs there. The identical receipt -/// shape is what sent the diagnosis down the wrong path; see the refusal gate -/// at the top of `run`. +/// This race is real but it was NOT the Windows execution cause. At the time it +/// was diagnosed, `run` refused with `UnsupportedPlatform` before any child +/// existed on Windows, so the monitor code never ran there; the identical +/// receipt shape is what sent the diagnosis down the wrong path. Foundation +/// M004 removed that refusal, so this monitor now runs on every platform and +/// is covered by `windows_process_tree.rs` as well as the Unix suite. fn monitor_termination(overflowed: bool) -> Option { overflowed.then_some(TerminationReason::OutputLimit) } @@ -1633,7 +1630,7 @@ impl SandboxSession { async fn resource_limits_exceeded(mut self) -> Vec { let mut status = [0u8; 1]; if !matches!( - timeout(Duration::from_secs(2), self.stream.read_exact(&mut status)).await, + tokio::time::timeout(Duration::from_secs(2), self.stream.read_exact(&mut status)).await, Ok(Ok(_)) ) { return Vec::new(); @@ -1841,35 +1838,6 @@ impl SandboxChannel { } } -#[cfg(unix)] -fn terminate_group(pid: Option) -> Result { - let pid = pid.ok_or_else(|| "child pid is unavailable".to_owned())?; - match nix::sys::signal::killpg( - nix::unistd::Pid::from_raw(pid as i32), - nix::sys::signal::Signal::SIGTERM, - ) { - Ok(()) => Ok(true), - Err(nix::errno::Errno::ESRCH) => Ok(false), - Err(error) => Err(error.to_string()), - } -} -#[cfg(unix)] -fn kill_group(pid: Option) -> Result<(), String> { - let pid = pid.ok_or_else(|| "child pid is unavailable".to_owned())?; - nix::sys::signal::killpg( - nix::unistd::Pid::from_raw(pid as i32), - nix::sys::signal::Signal::SIGKILL, - ) - .or_else(|error| { - if error == nix::errno::Errno::ESRCH { - Ok(()) - } else { - Err(error) - } - }) - .map_err(|e| e.to_string()) -} - fn spawn_reader( mut reader: R, stderr: bool, @@ -1930,6 +1898,7 @@ impl From for ExecutionResult { #[cfg(test)] mod tests { use super::*; + #[cfg(unix)] use std::sync::Arc; fn request(root: &Path, args: &[&str]) -> RunnerRequest { @@ -2022,7 +1991,36 @@ mod tests { async fn unsupported_resource_limits_are_reported_or_rejected_before_spawn() { let temp = tempfile::tempdir().unwrap(); let runner = LocalProcessRunner::new(NoExecutionSetup); - let mut best_effort = request(temp.path(), &["/bin/true"]); + let marker = temp.path().join("required-limit-target-ran"); + // The required case must be refused *before* spawn, so the target is a + // command whose only job is to leave the marker behind. If the refusal + // ever moved after spawn, this file would exist. + let (succeeds, leaves_marker): (Vec, Vec) = if cfg!(windows) { + ( + vec![ + std::env::var("COMSPEC").unwrap_or_else(|_| "cmd.exe".to_owned()), + "/C".to_owned(), + "exit 0".to_owned(), + ], + vec![ + std::env::var("COMSPEC").unwrap_or_else(|_| "cmd.exe".to_owned()), + "/C".to_owned(), + format!("type nul > {}", marker.display()), + ], + ) + } else { + ( + vec!["/bin/true".to_owned()], + vec![ + "/usr/bin/touch".to_owned(), + marker.to_str().unwrap().to_owned(), + ], + ) + }; + + let succeeds: Vec<&str> = succeeds.iter().map(String::as_str).collect(); + let leaves_marker: Vec<&str> = leaves_marker.iter().map(String::as_str).collect(); + let mut best_effort = request(temp.path(), &succeeds); best_effort.resources.memory_bytes = Requirement::BestEffort(1024 * 1024); let (tx, _rx) = mpsc::channel(4); let result = runner @@ -2035,8 +2033,7 @@ mod tests { eggwork_core::ResourceDimensionResult::NotApplied { .. } )); - let marker = temp.path().join("required-limit-target-ran"); - let mut required = request(temp.path(), &["/usr/bin/touch", marker.to_str().unwrap()]); + let mut required = request(temp.path(), &leaves_marker); required.resources.pids = Requirement::Required(4); let (tx, _rx) = mpsc::channel(4); assert!(matches!( @@ -2191,7 +2188,6 @@ mod tests { ); } - #[cfg(unix)] #[tokio::test] async fn cancellation_before_spawn_and_spawn_failure_are_typed() { let temp = tempfile::tempdir().unwrap(); @@ -2205,12 +2201,18 @@ mod tests { .await, Err(RunnerError::CancelledBeforeSpawn) )); + // A program that cannot be created must fail as a typed spawn error on + // every platform, and it must fail before a tree owner exists: there is + // no job, no process group, and nothing to clean up. A missing + // executable is the cheapest way to prove that the platform's + // create-then-own sequence has no partial state to leak. + let missing = if cfg!(windows) { + r"definitely-missing-eggwork-command.exe" + } else { + "/definitely/missing/eggwork-command" + }; assert!(matches!( - run(request( - temp.path(), - &["/definitely/missing/eggwork-command"] - )) - .await, + run(request(temp.path(), &[missing])).await, Err(RunnerError::Spawn(_)) )); } diff --git a/crates/eggwork-runner/src/process_tree.rs b/crates/eggwork-runner/src/process_tree.rs new file mode 100644 index 0000000..e9c0cc6 --- /dev/null +++ b/crates/eggwork-runner/src/process_tree.rs @@ -0,0 +1,357 @@ +//! The platform process-tree owner behind [`LocalProcessRunner`](crate::LocalProcessRunner). +//! +//! There is exactly one runner lifecycle in `lib.rs`; this module is the only +//! place where "how do I create, own, wait for, and terminate a process tree" +//! differs between platforms. Everything else — request validation, command +//! construction, pipe readers, bounded capture, timeout/cancellation selection, +//! terminal conversion, and provenance — is shared, so a second runner can never +//! grow here. +//! +//! # Why the tree owner is not `tokio::process::Child` +//! +//! A bare child owns *itself*. Eggwork's invariant is stronger: +//! +//! > process-tree cleanup completes before the execution owner releases its +//! > lifetime permit. +//! +//! On Unix the leader is spawned into its own process group, so signalling the +//! group reaches every descendant the target creates. On Windows there is no +//! process group and `GenerateConsoleCtrlEvent` is not a tree-wide, catchable +//! signal for an arbitrary argv target, so the tree owner is a Job Object. +//! +//! The Job Object must exist *before* the first instruction of the target runs. +//! Spawning normally and calling `AssignProcessToJobObject` afterwards leaves a +//! window in which the target has already run and already created descendants +//! that were never owned. [`process_wrap::tokio::JobObject`] closes that window +//! by adding `CREATE_SUSPENDED` to the creation flags, assigning the still +//! suspended process, and only then resuming it. Spawn failure, assignment +//! failure, and resume failure all terminate the created process before +//! returning, so no target is left running when setup fails. +//! +//! # What Windows convergence does and does not claim +//! +//! Windows has no `SIGTERM`/`SIGKILL` escalation to emulate, and the invariant is +//! deterministic tree convergence rather than signal fidelity. Termination is +//! therefore `TerminateJobObject` on the owned Job Object, which the kernel +//! applies to every member of the job. +//! +//! Eggwork does **not** claim to observe each descendant's final exit status: no +//! safe-Rust surface in the reviewed dependency exposes a job-membership query, +//! and adding one would mean Eggwork-owned `unsafe` Win32 FFI, which this +//! repository denies at the workspace level. Instead convergence is established +//! by three facts that the shared lifecycle relies on: +//! +//! 1. the Job Object stays owned for the whole execution, so no descendant can +//! ever escape the tree by outliving a leader; +//! 2. after `TerminateJobObject` returns, the kernel has suspended and marked +//! every member terminating, so no member can execute further user code; and +//! 3. the shared lifecycle joins the pipe readers after termination, and a pipe +//! only reaches EOF once every process holding it has exited — the same +//! evidence the Unix path has always used. +//! +//! Closing the Job Object handle is the final backstop: the job is created with +//! `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`, so the kernel terminates any member that +//! somehow survived, and that close happens when the tree owner is dropped — +//! before `run` returns, and therefore before the caller's execution permit is +//! released. Kill-on-drop is the backstop, never a substitute for the explicit +//! normal-path termination above. + +use std::process::ExitStatus; +use std::time::Duration; +use tokio::process::{ChildStderr, ChildStdin, ChildStdout, Command}; + +/// What converging an owned process tree produced. +/// +/// The three fields map one-to-one onto the runner's existing +/// `CleanupDiagnostics`, so no new public diagnostic shape is introduced and no +/// wire schema changes. +pub(crate) struct TreeConvergence { + /// The leader's exit status, when the platform reaped it. + pub(crate) status: Option, + /// Tree termination itself failed, so descendants may have survived. + pub(crate) signal_error: Option, + /// The leader did not get reaped within the granted bound. + pub(crate) wait_error: Option, +} + +impl TreeConvergence { + fn converged(status: Option) -> Self { + Self { + status, + signal_error: None, + wait_error: None, + } + } +} + +#[cfg(unix)] +mod imp { + use super::*; + use crate::{RunnerError, TERMINATION_GRACE}; + use tokio::{process::Child, time::timeout}; + + /// Unix tree owner: the leader plus the process group it was spawned into. + /// + /// `group` is captured at spawn time on purpose. `tokio::process::Child::id` + /// returns `None` once the child has been reaped, and the group identifier is + /// still needed after that point to reap descendants the leader left behind. + pub(crate) struct ProcessTree { + child: Child, + group: Option, + } + + impl ProcessTree { + /// Spawn the already-sanitised command as the leader of a new process + /// group. Every descendant the target creates inherits that group, which + /// is what makes `killpg` a tree operation. + pub(crate) fn spawn_platform(mut command: Command) -> Result { + command.process_group(0); + let child = command + .spawn() + .map_err(|error| RunnerError::Spawn(error.to_string()))?; + let group = child.id(); + Ok(Self { child, group }) + } + + /// The native child, for the Linux sandbox helper handshake, which reads + /// the helper's status channel before the target exists. + #[cfg(target_os = "linux")] + pub(crate) fn child_mut(&mut self) -> &mut Child { + &mut self.child + } + + pub(crate) fn take_stdin(&mut self) -> Option { + self.child.stdin.take() + } + + pub(crate) fn take_stdout(&mut self) -> Option { + self.child.stdout.take() + } + + pub(crate) fn take_stderr(&mut self) -> Option { + self.child.stderr.take() + } + + pub(crate) async fn wait(&mut self) -> std::io::Result { + self.child.wait().await + } + + /// Kill the leader alone, without touching the rest of the group. Used + /// by the Linux sandbox handshake's refusal paths, where no target + /// process exists yet and the helper is the only process involved. + pub(crate) fn start_kill(&mut self) -> std::io::Result<()> { + self.child.start_kill() + } + + /// The leader exited on its own. Background descendants it left behind + /// still hold the output pipes, so the group is reaped before returning + /// without changing the leader's already-known exit classification. + pub(crate) async fn converge_after_leader_exit(&mut self) -> TreeConvergence { + match terminate_group(self.group) { + Ok(true) => { + tokio::time::sleep(TERMINATION_GRACE).await; + match kill_group(self.group) { + Ok(()) => TreeConvergence::converged(None), + Err(error) => TreeConvergence { + status: None, + signal_error: Some(error), + wait_error: None, + }, + } + } + Ok(false) => TreeConvergence::converged(None), + Err(error) => TreeConvergence { + status: None, + signal_error: Some(error), + wait_error: None, + }, + } + } + + /// Timeout, cancellation, or output-limit termination: ask the group to + /// stop, let it have a grace period, then force it and reap the leader. + pub(crate) async fn terminate_and_reap(&mut self, grace: Duration) -> TreeConvergence { + let mut signal_error = match terminate_group(self.group) { + Ok(true) => { + tokio::time::sleep(TERMINATION_GRACE).await; + None + } + Ok(false) => None, + Err(error) => Some(error), + }; + if let Err(error) = kill_group(self.group) { + signal_error.get_or_insert(error); + } + let (status, wait_error) = match timeout(grace, self.child.wait()).await { + Ok(Ok(status)) => (Some(status), None), + Ok(Err(error)) => (None, Some(error.to_string())), + Err(_) => (None, Some("child did not exit after SIGKILL".into())), + }; + TreeConvergence { + status, + signal_error, + wait_error, + } + } + } + + fn terminate_group(pid: Option) -> Result { + let pid = pid.ok_or_else(|| "child pid is unavailable".to_owned())?; + match nix::sys::signal::killpg( + nix::unistd::Pid::from_raw(pid as i32), + nix::sys::signal::Signal::SIGTERM, + ) { + Ok(()) => Ok(true), + Err(nix::errno::Errno::ESRCH) => Ok(false), + Err(error) => Err(error.to_string()), + } + } + + fn kill_group(pid: Option) -> Result<(), String> { + let pid = pid.ok_or_else(|| "child pid is unavailable".to_owned())?; + nix::sys::signal::killpg( + nix::unistd::Pid::from_raw(pid as i32), + nix::sys::signal::Signal::SIGKILL, + ) + .or_else(|error| { + if error == nix::errno::Errno::ESRCH { + Ok(()) + } else { + Err(error) + } + }) + .map_err(|e| e.to_string()) + } +} + +#[cfg(windows)] +mod imp { + use super::*; + use crate::RunnerError; + use process_wrap::tokio::{ChildWrapper, CommandWrap, JobObject, KillOnDrop}; + + /// Windows tree owner: a Job Object that owns the leader from before its + /// first instruction, plus every descendant it will ever create. + pub(crate) struct ProcessTree { + child: Box, + } + + impl ProcessTree { + pub(crate) fn spawn_platform(command: Command) -> Result { + let mut command = CommandWrap::from(command); + // `KillOnDrop` is registered first so the Job Object is created with + // `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`: dropping this owner must not + // orphan a descendant. It also sets Tokio's own kill-on-drop on the + // leader, which stays in effect underneath the job wrapper. + command.wrap(KillOnDrop).wrap(JobObject); + // The child is created suspended, assigned to the job, and resumed + // inside `spawn`; a failure on any of those steps terminates the + // process before returning an error. + let child = command + .spawn() + .map_err(|error| RunnerError::Spawn(error.to_string()))?; + Ok(Self { child }) + } + + pub(crate) fn take_stdin(&mut self) -> Option { + self.child.stdin().take() + } + + pub(crate) fn take_stdout(&mut self) -> Option { + self.child.stdout().take() + } + + pub(crate) fn take_stderr(&mut self) -> Option { + self.child.stderr().take() + } + + pub(crate) async fn wait(&mut self) -> std::io::Result { + self.child.wait().await + } + + /// The leader exited on its own, so any descendant it left behind is + /// still owned by the Job Object and is terminated here. + /// + /// No exit status is reported for descendants: the job-membership query + /// that would be required is not available without Eggwork-owned `unsafe` + /// FFI. The reader EOF barrier the shared lifecycle joins after this call + /// is the convergence evidence, and the job handle closes under + /// kill-on-job-close before the runner returns. + pub(crate) async fn converge_after_leader_exit(&mut self) -> TreeConvergence { + match self.child.start_kill() { + Ok(()) => TreeConvergence::converged(None), + Err(error) => TreeConvergence { + status: None, + signal_error: Some(error.to_string()), + wait_error: None, + }, + } + } + + /// Timeout, cancellation, or output-limit termination. `TerminateJobObject` + /// covers the leader and every descendant in one call, so there is no + /// Unix-style escalation window and nothing to wait for beyond the call + /// returning. + /// + /// The leader's exit status is deliberately not awaited: a job + /// termination exit code describes Eggwork's kill, not the target's own + /// outcome, and reporting it as `exit_code` would be a fabricated fact. + /// Unix already reports `None` here because a signalled process has no + /// exit code, so both platforms now agree. + pub(crate) async fn terminate_and_reap(&mut self, _grace: Duration) -> TreeConvergence { + match self.child.start_kill() { + Ok(()) => TreeConvergence::converged(None), + Err(error) => TreeConvergence { + status: None, + signal_error: Some(error.to_string()), + wait_error: None, + }, + } + } + } +} + +/// Compiled targets with no tree-ownership story at all. The runner still +/// validates the request first and then refuses, so an unsupported target is a +/// typed refusal rather than a silent partial execution. +#[cfg(not(any(unix, windows)))] +mod imp { + use super::*; + use crate::RunnerError; + + pub(crate) struct ProcessTree; + + impl ProcessTree { + pub(crate) fn spawn_platform(_command: Command) -> Result { + Err(RunnerError::UnsupportedPlatform) + } + + pub(crate) fn take_stdin(&mut self) -> Option { + None + } + + pub(crate) fn take_stdout(&mut self) -> Option { + None + } + + pub(crate) fn take_stderr(&mut self) -> Option { + None + } + + pub(crate) async fn wait(&mut self) -> std::io::Result { + Err(std::io::Error::other( + RunnerError::UnsupportedPlatform.to_string(), + )) + } + + pub(crate) async fn converge_after_leader_exit(&mut self) -> TreeConvergence { + TreeConvergence::converged(None) + } + + pub(crate) async fn terminate_and_reap(&mut self, _grace: Duration) -> TreeConvergence { + TreeConvergence::converged(None) + } + } +} + +pub(crate) use imp::ProcessTree; diff --git a/crates/eggwork-runner/tests/capability_probe.rs b/crates/eggwork-runner/tests/capability_probe.rs index 32d0553..ae6e46e 100644 --- a/crates/eggwork-runner/tests/capability_probe.rs +++ b/crates/eggwork-runner/tests/capability_probe.rs @@ -1,6 +1,7 @@ use eggwork_runner::{LocalProcessRunner, TrustedLandlockSetup}; -use std::{fs, path::PathBuf}; +use std::path::PathBuf; +#[cfg(target_os = "linux")] fn helper_in_target_dir() -> Option { let target = std::env::var_os("CARGO_TARGET_DIR") .map(PathBuf::from) @@ -13,7 +14,9 @@ fn helper_in_target_dir() -> Option { } } +#[cfg(target_os = "linux")] fn place_trusted_helper() -> Option { + use std::fs; use std::os::unix::fs::PermissionsExt; let source = helper_in_target_dir()?; let helper_dir = tempfile::tempdir().unwrap(); diff --git a/crates/eggwork-runner/tests/windows_process_tree.rs b/crates/eggwork-runner/tests/windows_process_tree.rs new file mode 100644 index 0000000..8e15da5 --- /dev/null +++ b/crates/eggwork-runner/tests/windows_process_tree.rs @@ -0,0 +1,667 @@ +//! Windows process-tree lifecycle proofs for the runner. +//! +//! These run natively on Windows and nowhere else: they assert the Job Object +//! behaviour that cannot be observed from a Unix host. Fixtures are Windows +//! programs (`cmd.exe` and `powershell.exe`), and every tree claim is proven by +//! a fixture that reports its own liveness. +//! +//! # How "no process survived" is proven +//! +//! There is no safe-Rust process-liveness API in this workspace, so the tests +//! do the honest thing: a fixture writes its own heartbeat on a cadence, and +//! the test samples that file *after* the runner has returned. Growth means a +//! descendant is still running; a frozen file is the evidence that it is not. +//! That is stronger evidence than a name-based enumeration sweep, which races +//! with process exit and says nothing about *when* the process died. +//! +//! `assert_frozen` waits longer than several beats and re-samples, so a +//! descendant that dies late still fails the assertion instead of being missed, +//! and it first asserts the file is non-empty, so a fixture that never ran can +//! never make the proof pass vacuously. + +#![cfg(windows)] + +use std::fs; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use eggwork_core::{ExecutionState, OverflowPolicy, RelativePath, Requirement}; +use eggwork_runner::{ + LocalProcessRunner, NoExecutionSetup, ResourceSetupOutcome, ResourceSetupRequest, RunnerError, + RunnerRequest, RunnerResult, SandboxOutcome, SandboxRequest, StdinPolicy, TerminationReason, +}; +use tokio::sync::mpsc; +use tokio_util::sync::CancellationToken; + +const BEAT_MILLIS: u64 = 50; +/// Long enough to see a live writer append several beats, short enough to keep +/// the suite quick. +const FREEZE_WINDOW: Duration = Duration::from_millis(600); + +/// The environment every execution child is guaranteed to see. Kept in sync +/// with `baseline_child_environment` in the crate; a mismatch is a contract +/// change, not a test fix. +const BASELINE_KEYS: [&str; 8] = [ + "CI", + "GIT_TERMINAL_PROMPT", + "NO_COLOR", + "PAGER", + "PATH", + "SystemRoot", + "TERM", + "windir", +]; + +fn powershell() -> String { + let system_root = std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".to_owned()); + format!("{system_root}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe") +} + +fn cmd() -> String { + std::env::var("COMSPEC").unwrap_or_else(|_| "cmd.exe".to_owned()) +} + +/// `cmd.exe` redirection needs a quoted destination: Windows temp paths live +/// under the user profile, which routinely contains a space. +fn cmd_path(path: &Path) -> String { + format!("\"{}\"", path.display()) +} + +/// A PowerShell single-quoted string literal. Windows temp paths routinely +/// contain spaces and can contain apostrophes, so quoting cannot be skipped. +fn ps_literal(value: &str) -> String { + format!("'{}'", value.replace('\'', "''")) +} + +/// argv that runs `powershell.exe` with a fixed, profile-free front end. +fn powershell_argv(tail: Vec) -> Vec { + vec![ + powershell(), + "-NoProfile".to_owned(), + "-NonInteractive".to_owned(), + ] + .into_iter() + .chain(tail) + .collect() +} + +struct Fixture { + temp: tempfile::TempDir, +} + +impl Fixture { + fn new() -> Self { + Self { + temp: tempfile::tempdir().expect("temp dir"), + } + } + + fn root(&self) -> PathBuf { + self.temp.path().to_path_buf() + } + + fn path(&self, name: &str) -> PathBuf { + self.temp.path().join(name) + } + + fn write_script(&self, name: &str, body: &str) -> Vec { + let path = self.path(name); + fs::write(&path, body).expect("write fixture script"); + powershell_argv(vec![ + "-File".to_owned(), + path.to_string_lossy().into_owned(), + ]) + } + + /// A fixture that appends a beat to `file` forever. `announce` records a + /// first line before looping, which is how a parent learns the descendant is + /// actually running rather than merely launched. + fn heartbeat_body(file: &Path, announce: bool) -> String { + format!( + "$f = {file}\n\ + if ({announce}) {{ Set-Content -Path $f -Value 'started' }}\n\ + while ($true) {{ Add-Content -Path $f -Value 'beat'; Start-Sleep -Milliseconds {beat} }}\n", + file = ps_literal(&file.to_string_lossy()), + announce = announce, + beat = BEAT_MILLIS, + ) + } + + /// Write a heartbeat fixture script and return its path, because a spawner + /// fixture needs the path to hand to `Start-Process`. + fn heartbeat_script(&self, name: &str, file: &Path, announce: bool) -> PathBuf { + let body = Self::heartbeat_body(file, announce); + self.write_script(name, &body); + self.path(name) + } + + /// A fixture that starts `child_script` detached, waits until the descendant + /// proves it is alive, and then exits after `hold_millis`. + /// + /// `hold_millis: 0` is the interesting case: the leader exits while an owned + /// descendant is still running. + fn spawner_script( + &self, + name: &str, + child_script: &Path, + ready_file: &Path, + hold_millis: u64, + ) -> Vec { + let body = Self::spawner_body(child_script, ready_file, hold_millis); + self.write_script(name, &body) + } + + fn spawner_body(child_script: &Path, ready_file: &Path, hold_millis: u64) -> String { + // `-ArgumentList` elements are joined with spaces and are *not* quoted + // for you, so the child command line is assembled explicitly. + format!( + "$child = {child}\n\ + $line = '-NoProfile -NonInteractive -File \"' + $child + '\"'\n\ + Start-Process -FilePath {shell} -ArgumentList $line -WindowStyle Hidden\n\ + $deadline = (Get-Date).AddSeconds(15)\n\ + while (-not (Test-Path {ready})) {{\n\ + \x20 if ((Get-Date) -gt $deadline) {{ exit 9 }}\n\ + \x20 Start-Sleep -Milliseconds {beat}\n\ + }}\n\ + Start-Sleep -Milliseconds {hold}\n", + child = ps_literal(&child_script.to_string_lossy()), + shell = ps_literal(&powershell()), + ready = ps_literal(&ready_file.to_string_lossy()), + beat = BEAT_MILLIS, + hold = hold_millis, + ) + } + + /// A fixture that spawns `child_script` through PowerShell's call operator + /// as a *separate process*, so the child inherits the runner's stdout and + /// stderr pipes. + fn inherited_stdio_body(child_script: &Path) -> String { + format!( + "& {shell} -NoProfile -NonInteractive -File {child}\n", + shell = ps_literal(&powershell()), + child = ps_literal(&child_script.to_string_lossy()), + ) + } + + fn request(&self, argv: Vec) -> RunnerRequest { + let mut request = RunnerRequest::new(argv, self.root()); + request.set_timeout(Duration::from_secs(60)); + request.set_output_policy(1024 * 1024, 4096, OverflowPolicy::Truncate); + request + } + + fn cmd_request(&self, script: &str) -> RunnerRequest { + self.request(vec![cmd(), "/C".to_owned(), script.to_owned()]) + } +} + +async fn run(request: RunnerRequest) -> Result { + run_with_cancellation(request, CancellationToken::new()).await +} + +async fn run_with_cancellation( + request: RunnerRequest, + cancellation: CancellationToken, +) -> Result { + let runner = LocalProcessRunner::default(); + let (tx, _rx) = mpsc::channel(8); + runner.run(request, cancellation, tx).await +} + +async fn run_with( + runner: LocalProcessRunner, + request: RunnerRequest, +) -> Result { + let (tx, _rx) = mpsc::channel(8); + runner.run(request, CancellationToken::new(), tx).await +} + +/// Compare two Windows paths without letting the two spellings of the same +/// path (`\\?\C:\x` from the filesystem API, `C:\x` from a shell) fail a +/// test for a spelling reason. +fn same_path(reported: &str, expected: &Path) -> bool { + fn normalise(value: &str) -> String { + value + .trim() + .trim_start_matches(r#"\\?\"#) + .trim_end_matches(['\\', '/']) + .to_lowercase() + } + normalise(reported) == normalise(&expected.to_string_lossy()) +} + +fn size_of(path: &Path) -> u64 { + fs::metadata(path).map(|m| m.len()).unwrap_or(0) +} + +/// Assert the fixture stopped beating: the file must exist and be non-empty (so +/// the proof is not vacuous) and must not grow across a window wider than +/// several beats. +async fn assert_frozen(path: &Path, context: &str) { + let first = size_of(path); + assert!( + first > 0, + "{context}: fixture never beat, so this proof would be vacuous" + ); + tokio::time::sleep(FREEZE_WINDOW).await; + let second = size_of(path); + assert_eq!( + first, second, + "{context}: heartbeat grew from {first} to {second} bytes after the runner returned" + ); +} + +fn assert_no_cleanup_warning(result: &RunnerResult, context: &str) { + assert_eq!( + result.cleanup.process_group_signal_error, None, + "{context}: tree termination reported a failure" + ); + assert_eq!(result.cleanup.wait_error, None, "{context}: reap failed"); + assert_eq!( + result.cleanup.stdin_error, None, + "{context}: stdin writer failed" + ); + assert_eq!( + result.execution_result().cleanup_warning, + None, + "{context}: convergence surfaced as a cleanup warning" + ); +} + +/// §9.1 — an ordinary target runs, streams, and reports its exit status. +#[tokio::test] +async fn direct_exit_captures_output_and_reports_status() { + let fixture = Fixture::new(); + let request = fixture.cmd_request("echo out-marker & echo err-marker 1>&2 & exit /B 3"); + let result = run(request).await.expect("execution ran"); + assert_eq!(result.termination, TerminationReason::Exited); + assert_eq!(result.exit_code, Some(3)); + assert_eq!(result.stdout.head, b"out-marker\r\n"); + assert_eq!(result.stderr.head, b"err-marker\r\n"); + assert_no_cleanup_warning(&result, "direct exit"); +} + +/// §9.2 — a descendant created in the target's first moments is owned, even +/// when the leader exits immediately afterwards. +#[tokio::test] +async fn a_descendant_created_at_startup_is_owned_after_the_leader_exits() { + let fixture = Fixture::new(); + let beat = fixture.path("descendant.beat"); + let child = fixture.heartbeat_script("descendant.ps1", &beat, true); + let request = fixture.request(fixture.spawner_script("spawner.ps1", &child, &beat, 0)); + let result = run(request).await.expect("execution ran"); + assert_eq!(result.termination, TerminationReason::Exited); + assert_eq!(result.exit_code, Some(0)); + assert_no_cleanup_warning(&result, "leader exit with descendant"); + assert_frozen(&beat, "descendant created at startup").await; +} + +/// §9.3 — timeout termination converges the whole tree. +#[tokio::test] +async fn timeout_terminates_the_whole_tree() { + let fixture = Fixture::new(); + let leader_beat = fixture.path("leader.beat"); + let descendant_beat = fixture.path("descendant.beat"); + let child = fixture.heartbeat_script("child.ps1", &descendant_beat, true); + let body = format!( + "$f = {leader}\n\ + $child = {child}\n\ + $line = '-NoProfile -NonInteractive -File \"' + $child + '\"'\n\ + Start-Process -FilePath {shell} -ArgumentList $line -WindowStyle Hidden\n\ + while ($true) {{ Add-Content -Path $f -Value 'beat'; Start-Sleep -Milliseconds {beat} }}\n", + leader = ps_literal(&leader_beat.to_string_lossy()), + child = ps_literal(&child.to_string_lossy()), + shell = ps_literal(&powershell()), + beat = BEAT_MILLIS, + ); + let mut request = fixture.request(fixture.write_script("leader.ps1", &body)); + request.set_timeout(Duration::from_millis(2500)); + + let result = run(request).await.expect("execution ran"); + assert_eq!(result.termination, TerminationReason::TimedOut); + assert_no_cleanup_warning(&result, "timeout"); + assert_frozen(&leader_beat, "leader after timeout").await; + assert_frozen(&descendant_beat, "descendant after timeout").await; +} + +/// §9.4 — cancellation termination converges the whole tree. +#[tokio::test] +async fn cancellation_terminates_the_whole_tree() { + let fixture = Fixture::new(); + let beat = fixture.path("leader.beat"); + let body = format!( + "$f = {file}\n\ + while ($true) {{ Add-Content -Path $f -Value 'beat'; Start-Sleep -Milliseconds {beat} }}\n", + file = ps_literal(&beat.to_string_lossy()), + beat = BEAT_MILLIS, + ); + let cancellation = CancellationToken::new(); + let token = cancellation.clone(); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(2000)).await; + token.cancel(); + }); + let result = run_with_cancellation( + fixture.request(fixture.write_script("leader.ps1", &body)), + cancellation, + ) + .await + .expect("execution ran"); + assert_eq!(result.termination, TerminationReason::Cancelled); + assert_no_cleanup_warning(&result, "cancellation"); + assert_frozen(&beat, "leader after cancellation").await; +} + +/// §9.5 — output-limit termination converges the whole tree. +#[tokio::test] +async fn output_limit_terminates_the_whole_tree() { + let fixture = Fixture::new(); + let beat = fixture.path("leader.beat"); + let body = format!( + "$f = {file}\n\ + while ($true) {{\n\ + \x20 Add-Content -Path $f -Value 'beat'\n\ + \x20 Write-Output ('x' * 1024)\n\ + \x20 Start-Sleep -Milliseconds {beat}\n\ + }}\n", + file = ps_literal(&beat.to_string_lossy()), + beat = BEAT_MILLIS, + ); + let mut request = fixture.request(fixture.write_script("leader.ps1", &body)); + request.set_output_policy(16 * 1024, 512, OverflowPolicy::Truncate); + + let result = run(request).await.expect("execution ran"); + assert_eq!(result.termination, TerminationReason::OutputLimit); + assert_no_cleanup_warning(&result, "output limit"); + assert_frozen(&beat, "leader after output limit").await; +} + +/// §9.6 — a leader that exits while a descendant runs does not release the +/// runner, and the descendant is gone when it does. +#[tokio::test] +async fn leader_exit_never_releases_a_remaining_descendant() { + let fixture = Fixture::new(); + let descendant = fixture.path("descendant.beat"); + let child = fixture.heartbeat_script("child.ps1", &descendant, true); + // The leader exits as soon as the descendant is alive, which is the case a + // job-object backend must not mistake for "the whole tree is finished". + let request = fixture.request(fixture.spawner_script("spawner.ps1", &child, &descendant, 0)); + let result = run(request).await.expect("execution ran"); + assert_eq!(result.termination, TerminationReason::Exited); + assert_eq!(result.exit_code, Some(0)); + assert_frozen(&descendant, "descendant after leader exit").await; +} + +/// The leader's own exit classification is decided by its exit status, not by +/// how long its descendants took to converge. +#[tokio::test] +async fn leader_exit_status_is_not_rewritten_by_descendant_termination() { + let fixture = Fixture::new(); + let descendant = fixture.path("descendant.beat"); + let child = fixture.heartbeat_script("child.ps1", &descendant, true); + let request = fixture.request(fixture.spawner_script("spawner.ps1", &child, &descendant, 0)); + let result = run(request).await.expect("execution ran"); + let execution = result.execution_result(); + assert_eq!(execution.exit_code, Some(0)); + assert_eq!(execution.state, ExecutionState::Succeeded); + assert_eq!(execution.cleanup_warning, None); +} + +/// §9.7 — the working directory is the requested one, and Eggwork makes no +/// filesystem isolation claim on Windows. +#[tokio::test] +async fn working_directory_is_honoured_and_no_isolation_is_claimed() { + let fixture = Fixture::new(); + let work = fixture.root().join("work"); + let outside = fixture.path("outside.txt"); + fs::create_dir_all(&work).expect("work dir"); + let body = format!( + "Set-Content -Path 'inside.txt' -Value 'written'\n\ + Write-Output (Get-Location).Path\n\ + Set-Content -Path {outside} -Value 'no-isolation-claim'\n", + outside = ps_literal(&outside.to_string_lossy()), + ); + let mut request = fixture.request(fixture.write_script("cwd.ps1", &body)); + request.set_working_directory(Some( + RelativePath::new("work".to_owned()).expect("relative"), + )); + + let result = run(request).await.expect("execution ran"); + assert_eq!(result.exit_code, Some(0)); + + let reported = String::from_utf8_lossy(&result.stdout.head).into_owned(); + let expected = fs::canonicalize(&work).expect("canonical work dir"); + assert!( + same_path(&reported, &expected), + "target ran somewhere other than the requested working directory: {reported:?}" + ); + assert!( + work.join("inside.txt").exists(), + "target could not write inside its working directory" + ); + // Windows has no filesystem confinement here, and the receipt must not + // pretend otherwise: a successful write outside the execution root is the + // documented behaviour, and `NotRequested` is what keeps it honest. + assert!( + outside.exists(), + "unexpected confinement: Eggwork does not confine the Windows filesystem" + ); + assert_eq!(result.setup.sandbox, SandboxOutcome::NotRequested); +} + +/// §9.8 — stdin bytes are delivered and the writer is closed. +#[tokio::test] +async fn stdin_is_delivered_and_closed() { + let fixture = Fixture::new(); + let body = "$input = [Console]::In.ReadToEnd()\n\ + Write-Output (\"len=\" + $input.Length)\n\ + Write-Output $input\n"; + let mut request = fixture.request(fixture.write_script("stdin.ps1", body)); + request.set_stdin_policy(StdinPolicy::Bytes(b"piped-input".to_vec())); + let result = run(request).await.expect("execution ran"); + assert_eq!(result.exit_code, Some(0)); + let stdout = String::from_utf8_lossy(&result.stdout.head).into_owned(); + assert!( + stdout.contains("len=11"), + "stdin bytes never arrived: {stdout:?}" + ); + assert!( + stdout.contains("piped-input"), + "stdin content was not echoed back: {stdout:?}" + ); + assert_no_cleanup_warning(&result, "stdin"); +} + +/// §9.9 — a spawn failure is typed, and nothing is left running. +#[tokio::test] +async fn spawn_failure_is_typed_and_leaves_nothing_running() { + let fixture = Fixture::new(); + let marker = fixture.path("spawn-failure-marker"); + let request = fixture.request(vec![ + fixture + .path("definitely-missing.exe") + .to_string_lossy() + .into_owned(), + ]); + // The program does not exist, so the platform must fail while creating the + // tree owner and report a typed spawn error: no job, no process group, and + // nothing to clean up. + assert!(matches!(run(request).await, Err(RunnerError::Spawn(_)))); + assert!(!marker.exists()); +} + +/// §9.10 — descendant output reaches the execution's captured streams, which is +/// what proves pipe handles are inherited across the tree. +#[tokio::test] +async fn descendant_output_reaches_the_captured_streams() { + let fixture = Fixture::new(); + let child = fixture.path("child.ps1"); + fs::write( + &child, + "Write-Output 'descendant-stdout'\n\ + [Console]::Error.WriteLine('descendant-stderr')\n", + ) + .expect("write child script"); + let body = Fixture::inherited_stdio_body(&child); + let result = run(fixture.request(fixture.write_script("leader.ps1", &body))) + .await + .expect("execution ran"); + assert_eq!(result.exit_code, Some(0)); + let stdout = String::from_utf8_lossy(&result.stdout.head).into_owned(); + let stderr = String::from_utf8_lossy(&result.stderr.head).into_owned(); + assert!( + stdout.contains("descendant-stdout"), + "descendant stdout was not captured: {stdout:?}" + ); + assert!( + stderr.contains("descendant-stderr"), + "descendant stderr was not captured: {stderr:?}" + ); +} + +/// §9.11 — the child environment is the documented Windows baseline: every +/// baseline key is present, and nothing from the daemon's own ambient +/// environment leaks through. +#[tokio::test] +async fn environment_is_the_documented_baseline_and_leaks_nothing() { + let fixture = Fixture::new(); + let body = "Get-ChildItem Env: | ForEach-Object { $_.Name + '=' + $_.Value } | Sort-Object\n"; + let result = run(fixture.request(fixture.write_script("env.ps1", body))) + .await + .expect("execution ran"); + assert_eq!(result.exit_code, Some(0)); + let reported = String::from_utf8_lossy(&result.stdout.head).into_owned(); + + let system_root = std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".to_owned()); + for key in BASELINE_KEYS { + assert!( + reported.contains(&format!("{key}=")), + "baseline key {key} missing from the child environment: {reported:?}" + ); + } + assert!( + reported.contains(&format!("PATH={system_root}\\System32;{system_root}")), + "PATH was not the documented Windows baseline: {reported:?}" + ); + assert!( + reported.contains(&format!("SystemRoot={system_root}")), + "SystemRoot is required by the loader and was missing: {reported:?}" + ); + + let child_keys: Vec<&str> = reported + .lines() + .filter_map(|line| line.split_once('=').map(|(key, _)| key.trim())) + .filter(|key| !key.is_empty() && !key.starts_with("PS") && !key.starts_with("__PS")) + .collect(); + + // `env_clear` has to keep the daemon's environment out. Rather than + // mutating this process's environment (which needs `unsafe`, and this crate + // denies it), the test compares the keys the target actually received + // against the keys that exist in the ambient environment right now. + let leaked: Vec<&str> = child_keys + .iter() + .copied() + .filter(|key| std::env::var_os(key).is_some()) + .filter(|key| !BASELINE_KEYS.contains(key)) + .collect(); + assert!( + leaked.is_empty(), + "ambient daemon environment reached the target: {leaked:?} (child saw {child_keys:?})" + ); +} + +/// §9.12 — a bare program name resolves against the baseline PATH. +#[tokio::test] +async fn bare_program_names_resolve_against_the_baseline_path() { + let fixture = Fixture::new(); + let request = fixture.request(vec![ + "cmd".to_owned(), + "/C".to_owned(), + "echo resolved-via-path".to_owned(), + ]); + let result = run(request).await.expect("execution ran"); + assert_eq!(result.exit_code, Some(0)); + assert!(result.stdout.head.starts_with(b"resolved-via-path")); +} + +/// §9.13 — a required filesystem isolation request is refused before spawn, +/// because Windows has no Landlock. +#[tokio::test] +async fn required_isolation_is_refused_before_the_target_runs() { + let fixture = Fixture::new(); + let marker = fixture.path("required-isolation-marker"); + let mut request = fixture.cmd_request(&format!("type nul > {}", cmd_path(&marker))); + request.set_sandbox_request(SandboxRequest::Required { + profile: "filesystem.workspace-rw.v1".to_owned(), + }); + assert!(matches!( + run_with(LocalProcessRunner::new(NoExecutionSetup), request).await, + Err(RunnerError::RequiredSetupUnavailable) + )); + assert!( + !marker.exists(), + "a refused required isolation request still ran the target" + ); +} + +/// §9.14 — required resources are refused before spawn for the same reason, and +/// a best-effort request is reported as not applied rather than as enforced. +#[tokio::test] +async fn required_resources_are_refused_and_best_effort_is_reported() { + let fixture = Fixture::new(); + let marker = fixture.path("required-resource-marker"); + let mut required = fixture.cmd_request(&format!("type nul > {}", cmd_path(&marker))); + required.set_resource_setup_request(ResourceSetupRequest { + memory_bytes: Requirement::NotRequested, + cpu_millis: Requirement::NotRequested, + pids: Requirement::Required(8), + }); + assert!(matches!( + run_with(LocalProcessRunner::new(NoExecutionSetup), required).await, + Err(RunnerError::RequiredSetupUnavailable) + )); + assert!( + !marker.exists(), + "a refused required resource request still ran the target" + ); + + let mut best_effort = fixture.cmd_request("exit 0"); + best_effort.set_resource_setup_request(ResourceSetupRequest { + memory_bytes: Requirement::BestEffort(64 * 1024 * 1024), + cpu_millis: Requirement::NotRequested, + pids: Requirement::NotRequested, + }); + let result = run_with(LocalProcessRunner::new(NoExecutionSetup), best_effort) + .await + .expect("best-effort execution ran"); + assert_eq!(result.exit_code, Some(0)); + assert!(matches!( + result.setup.resources, + ResourceSetupOutcome::NotApplied { .. } + )); +} + +/// Tree bugs are timing bugs, so a single green termination is not evidence. +#[tokio::test] +async fn repeated_timeout_termination_converges_every_time() { + for iteration in 0..5 { + let fixture = Fixture::new(); + let beat = fixture.path("leader.beat"); + let body = format!( + "$f = {file}\n\ + while ($true) {{ Add-Content -Path $f -Value 'beat'; Start-Sleep -Milliseconds {beat} }}\n", + file = ps_literal(&beat.to_string_lossy()), + beat = BEAT_MILLIS, + ); + let mut request = fixture.request(fixture.write_script("leader.ps1", &body)); + request.set_timeout(Duration::from_millis(1500)); + let result = run(request).await.expect("execution ran"); + assert_eq!( + result.termination, + TerminationReason::TimedOut, + "iteration {iteration}" + ); + assert_no_cleanup_warning(&result, &format!("iteration {iteration}")); + assert_frozen(&beat, &format!("iteration {iteration}")).await; + } +} diff --git a/scripts/check_execution_ownership.py b/scripts/check_execution_ownership.py index e3c7b0c..4a2df89 100644 --- a/scripts/check_execution_ownership.py +++ b/scripts/check_execution_ownership.py @@ -28,6 +28,54 @@ "subprocess", } +# The denylist is the default for every crate. These are the reviewed exceptions, +# and each one has to name the crate, the dependency, and why an approved owner +# needs it -- an exception nobody has to re-justify is indistinguishable from a +# hole. Foundation M004 added `process-wrap` to `eggwork-runner` because Windows +# needs a Job Object assigned before the target's first instruction, and that +# ownership cannot be expressed through a bare `tokio::process::Child`. +# +# Adding an entry is an architecture review, not a convenience: the boundary this +# protects is singular process ownership. +APPROVED_PROCESS_DEP_EXCEPTIONS = { + ("eggwork-runner", "process-wrap"): ( + "Windows Job Object process-tree ownership, target-scoped to cfg(windows)" + ), +} + + +def process_dep_errors(crate: str, crate_deps: dict[str, dict]) -> list[str]: + """Denylist process-owner dependencies for every crate, minus reviewed exceptions.""" + errors = [] + for dep in sorted(FORBIDDEN_PROCESS_DEPS.intersection(crate_deps)): + if (crate, dep) in APPROVED_PROCESS_DEP_EXCEPTIONS: + continue + errors.append(f"{crate} adds process-owner dependencies: {dep}") + return errors + + +def unexplained_process_dep_exceptions() -> list[str]: + """Every recorded exception must name a real crate and a real dependency.""" + package_names = { + package["name"] + for package in json.loads( + subprocess.run( + ["cargo", "metadata", "--no-deps", "--format-version", "1"], + cwd=ROOT, + check=True, + capture_output=True, + text=True, + ).stdout + )["packages"] + } + errors = [] + for crate, dep in sorted(APPROVED_PROCESS_DEP_EXCEPTIONS): + if crate not in package_names: + errors.append(f"exception names unknown crate: {crate}") + if dep not in FORBIDDEN_PROCESS_DEPS: + errors.append(f"exception is not on the denylist: {crate} -> {dep}") + return errors + def strip_comments_and_literals(source: str) -> str: """Blank Rust comments and literals while preserving newlines/positions.""" @@ -190,16 +238,18 @@ def deps(name: str) -> dict[str, dict]: overlap = forbidden.intersection(deps(crate)) if overlap: errors.append(f"{crate} must not depend on {', '.join(sorted(overlap))}") + errors.extend(process_dep_errors(crate, deps(crate))) server_deps = deps("eggwork-server") tokio = server_deps.get("tokio") if tokio and "process" in tokio.get("features", []): errors.append("eggwork-server enables Tokio process creation; use eggwork-runner") - extra = FORBIDDEN_PROCESS_DEPS.intersection(server_deps) - if extra: - errors.append(f"eggwork-server adds process-owner dependencies: {', '.join(sorted(extra))}") + errors.extend(process_dep_errors("eggwork-server", server_deps)) + errors.extend(process_dep_errors("eggwork-runner", deps("eggwork-runner"))) + errors.extend(process_dep_errors("eggwork-sandbox-helper", deps("eggwork-sandbox-helper"))) if "eggwork-runner" not in server_deps: errors.append("eggwork-server must depend on the canonical eggwork-runner") + errors.extend(unexplained_process_dep_exceptions()) return errors From 098c4a4c00c2c5d680e8c234c6aafbaf60513dbb Mon Sep 17 00:00:00 2001 From: wr3n-ai Date: Mon, 5 Oct 2026 17:53:57 +0000 Subject: [PATCH 02/10] test(helper): gate the Landlock suite at file level Every test in `landlock_runner.rs` was already `#[cfg(target_os = "linux")]`, but the file's imports and the `request` helper were not, so a Windows `clippy -D warnings` build failed on unused imports and one dead function. The gate belongs on the file: the suite needs the Landlock kernel interface and a cgroup v2 hierarchy, so there is nothing to run on any other host. --- .../tests/landlock_runner.rs | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/crates/eggwork-sandbox-helper/tests/landlock_runner.rs b/crates/eggwork-sandbox-helper/tests/landlock_runner.rs index d96fc34..91193bb 100644 --- a/crates/eggwork-sandbox-helper/tests/landlock_runner.rs +++ b/crates/eggwork-sandbox-helper/tests/landlock_runner.rs @@ -1,3 +1,12 @@ +//! Integration coverage for the Landlock helper, driven through the real runner. +//! +//! The whole file is Linux-only, and the gate is at file level on purpose: every +//! test here needs the `landlock` kernel interface and a cgroup v2 hierarchy, so +//! the per-test `#[cfg(target_os = "linux")]` this replaces only left the +//! file's imports and helpers un-gated -- which is exactly what a Windows +//! `clippy -D warnings` build flagged (Foundation M004). +#![cfg(target_os = "linux")] + use eggwork_core::{OverflowPolicy, Requirement}; use eggwork_runner::{ ExecutionProvenance, ExecutionSetup, LocalProcessRunner, ResourceSetupRequest, RunnerRequest, @@ -32,7 +41,6 @@ fn request(root: &Path, outside_read: &Path, outside_write: &Path) -> RunnerRequ request } -#[cfg(target_os = "linux")] #[tokio::test] async fn required_landlock_allows_workspace_and_denies_outside_reads_and_writes() { let temp = tempfile::tempdir().unwrap(); @@ -76,7 +84,6 @@ async fn required_landlock_allows_workspace_and_denies_outside_reads_and_writes( )); } -#[cfg(target_os = "linux")] #[tokio::test] async fn helper_trust_checks_reject_missing_wrong_and_symlinked_helpers() { use std::os::unix::fs::{PermissionsExt, symlink}; @@ -160,7 +167,6 @@ async fn helper_trust_checks_reject_missing_wrong_and_symlinked_helpers() { assert!(!marker.exists()); } -#[cfg(target_os = "linux")] #[tokio::test] async fn workspace_symlink_cannot_read_outside_workspace() { use std::os::unix::fs::{PermissionsExt, symlink}; @@ -193,7 +199,6 @@ async fn workspace_symlink_cannot_read_outside_workspace() { )); } -#[cfg(target_os = "linux")] #[tokio::test] async fn cwd_symlink_outside_workspace_is_rejected_before_launch() { use std::os::unix::fs::{PermissionsExt, symlink}; @@ -223,7 +228,6 @@ async fn cwd_symlink_outside_workspace_is_rejected_before_launch() { )); } -#[cfg(target_os = "linux")] #[tokio::test] async fn sandbox_timeout_and_cancellation_reap_the_helper_process_group() { use std::os::unix::fs::PermissionsExt; @@ -302,7 +306,6 @@ async fn sandbox_timeout_and_cancellation_reap_the_helper_process_group() { ); } -#[cfg(target_os = "linux")] #[tokio::test] async fn required_memory_limit_is_enforced_and_classified() { use std::os::unix::fs::PermissionsExt; @@ -340,7 +343,6 @@ async fn required_memory_limit_is_enforced_and_classified() { )); } -#[cfg(target_os = "linux")] #[tokio::test] async fn required_pid_limit_is_enforced_and_classified() { use std::os::unix::fs::PermissionsExt; @@ -378,7 +380,6 @@ async fn required_pid_limit_is_enforced_and_classified() { )); } -#[cfg(target_os = "linux")] #[tokio::test] async fn required_cpu_quota_is_verified_before_target_start() { use std::os::unix::fs::PermissionsExt; @@ -413,7 +414,6 @@ async fn required_cpu_quota_is_verified_before_target_start() { )); } -#[cfg(target_os = "linux")] #[tokio::test] async fn concurrent_resource_scopes_keep_pid_limits_isolated() { use std::os::unix::fs::PermissionsExt; @@ -468,7 +468,6 @@ async fn concurrent_resource_scopes_keep_pid_limits_isolated() { )); } -#[cfg(target_os = "linux")] #[test] fn malformed_private_spec_and_unavailable_status_channel_do_not_launch_target() { use std::{io::Read, os::unix::fs::PermissionsExt}; From 0e6682a88d83f40a1f62eaf4e03d9cd1ca7f3660 Mon Sep 17 00:00:00 2001 From: wr3n-ai Date: Mon, 5 Oct 2026 18:06:17 +0000 Subject: [PATCH 03/10] test(helper): one reusable, atomic, per-fixture helper staging path Operations M004a. The recorded CI flake was `Spawn("Text file busy (os error 26)")` from a same-head rerun of `required_landlock_allows_workspace_and_denies_outside_reads_and_writes`. Linux returns ETXTBSY when a running executable is opened for writing, so the class of failure to remove is "a fixture mutates an executable path another concurrently runnable test may execute". Measured on this host first, rather than assumed: over a running executable, `open`/`O_TRUNC`/`shutil.copyfile` all return ETXTBSY, while `os.replace` succeeds. So staging now writes a staging name and renames it into place -- never in place -- and every fixture gets its own `0700` directory and its own copy. Build output is read-only input. The staging block was duplicated in ten places and drifted; it now lives once, in `tests/support/helper_fixture.rs`, and both suites use it (`eggwork-runner`'s capability probe includes it with `#[path]` rather than adding a workspace member the release contract enumerates). No retry, no sleep, no fixed path. New proofs, none of which are timing-dependent: two fixtures stage distinct executable paths; staging never changes the build output's bytes or mode; two fixtures execute concurrently and both really report `SandboxResult::Applied`; mutating one fixture's mode or bytes cannot disturb a neighbour; dropping a fixture removes only its own directory. One finding worth recording: `verify_trusted_helper` is a filesystem-trust check and does not identify the file, so a correctly-permissioned junk file passes it. That is the intended boundary -- anything able to write in an owner-only directory owns that installation -- and the new test asserts the remaining property: such a fixture fails loudly at execution instead of claiming isolation was applied. Also fixes the Windows-only clippy failures the new `windows-runner` CI job surfaced: a Linux-only `deadline` binding and a needless `return` in the Windows SCM refusal path. --- .../eggwork-runner/tests/capability_probe.rs | 61 ++-- .../tests/landlock_runner.rs | 342 ++++++++++++++---- .../tests/support/helper_fixture.rs | 139 +++++++ crates/eggwork-server/src/bin/eggworkd.rs | 9 +- 4 files changed, 441 insertions(+), 110 deletions(-) create mode 100644 crates/eggwork-sandbox-helper/tests/support/helper_fixture.rs diff --git a/crates/eggwork-runner/tests/capability_probe.rs b/crates/eggwork-runner/tests/capability_probe.rs index ae6e46e..86b334e 100644 --- a/crates/eggwork-runner/tests/capability_probe.rs +++ b/crates/eggwork-runner/tests/capability_probe.rs @@ -1,46 +1,44 @@ +//! Capability advertisement is backed by the same trust check the runner uses at +//! execution time, so this test has to present the helper the way an +//! installation does: owner-only directory, executable file. +//! +//! The staging rules live in one place, shared with the Landlock suite, because +//! two copies of "copy the built helper somewhere trustable" is exactly how a +//! fixture starts overwriting an executable another test may be running +//! (Operations M004a). The `#[path]` include is deliberate: the alternative is a +//! dev-only workspace member, and the release contract enumerates workspace +//! members. + use eggwork_runner::{LocalProcessRunner, TrustedLandlockSetup}; use std::path::PathBuf; +// One shared fixture surface, two suites: this one only needs `stage` and +// `path`, so the rest would be dead code here and in use next door. +#[allow(dead_code)] +#[cfg(target_os = "linux")] +#[path = "../../eggwork-sandbox-helper/tests/support/helper_fixture.rs"] +mod helper_fixture; + #[cfg(target_os = "linux")] -fn helper_in_target_dir() -> Option { +fn built_helper() -> Option { let target = std::env::var_os("CARGO_TARGET_DIR") .map(PathBuf::from) .or_else(|| std::env::var_os("OUT_DIR").map(PathBuf::from))?; let candidate = target.join("debug").join("eggwork-sandbox-helper"); - if candidate.exists() { - Some(candidate) - } else { - None - } -} - -#[cfg(target_os = "linux")] -fn place_trusted_helper() -> Option { - use std::fs; - use std::os::unix::fs::PermissionsExt; - let source = helper_in_target_dir()?; - let helper_dir = tempfile::tempdir().unwrap(); - let helper = helper_dir.path().join("eggwork-sandbox-helper"); - fs::copy(&source, &helper).ok()?; - fs::set_permissions(helper_dir.path(), fs::Permissions::from_mode(0o700)).ok()?; - fs::set_permissions(&helper, fs::Permissions::from_mode(0o755)).ok()?; - // Leak the directory so its helper keeps living until process exit; - // `discover_sibling()` reads trust only at probe time, so this is safe. - let leaked = Box::leak(Box::new(helper_dir)); - Some(leaked.path().join("eggwork-sandbox-helper")) + candidate.exists().then_some(candidate) } #[cfg(target_os = "linux")] #[tokio::test] async fn trusted_helper_advertises_landlock_workspace_rw_capability() { - let Some(helper) = place_trusted_helper() else { - // No sandbox-helper binary located; skip on this host. - eprintln!( - "skipping trusted_helper_advertises_landlock_workspace_rw_capability: helper binary not found" - ); + let Some(source) = built_helper() else { + // The helper binary only exists once it has been built. CI builds it + // before running this suite, so this skip is a local-only convenience. + eprintln!("eggwork-sandbox-helper is not built; skipping"); return; }; - let runner = LocalProcessRunner::new(TrustedLandlockSetup::new(helper)); + let fixture = helper_fixture::TrustedHelperFixture::stage(&source); + let runner = LocalProcessRunner::new(TrustedLandlockSetup::new(fixture.path())); let capabilities = runner.execution_capabilities().await; assert!( capabilities @@ -50,11 +48,14 @@ async fn trusted_helper_advertises_landlock_workspace_rw_capability() { ); } +/// Platform-neutral negative case: a helper that is not there must not produce +/// a capability. On Windows there is no Landlock at all, so the assertion holds +/// there for a stronger reason than on Linux. #[tokio::test] async fn missing_helper_advertises_no_landlock_capability() { - let runner = LocalProcessRunner::new(TrustedLandlockSetup::new(PathBuf::from( + let runner = LocalProcessRunner::new(TrustedLandlockSetup::new( "/nonexistent/eggwork-sandbox-helper", - ))); + )); let capabilities = runner.execution_capabilities().await; assert!( !capabilities diff --git a/crates/eggwork-sandbox-helper/tests/landlock_runner.rs b/crates/eggwork-sandbox-helper/tests/landlock_runner.rs index 91193bb..c1f6cba 100644 --- a/crates/eggwork-sandbox-helper/tests/landlock_runner.rs +++ b/crates/eggwork-sandbox-helper/tests/landlock_runner.rs @@ -7,15 +7,31 @@ //! `clippy -D warnings` build flagged (Foundation M004). #![cfg(target_os = "linux")] +#[path = "support/helper_fixture.rs"] +mod helper_fixture; + use eggwork_core::{OverflowPolicy, Requirement}; use eggwork_runner::{ - ExecutionProvenance, ExecutionSetup, LocalProcessRunner, ResourceSetupRequest, RunnerRequest, - SandboxOutcome, SandboxRequest, StdinPolicy, TrustedLandlockSetup, + ExecutionProvenance, ExecutionSetup, LocalProcessRunner, ResourceSetupRequest, RunnerError, + RunnerRequest, SandboxOutcome, SandboxRequest, StdinPolicy, TrustedLandlockSetup, +}; +use helper_fixture::TrustedHelperFixture; +use std::{ + fs, + path::{Path, PathBuf}, + process::Command, + time::Duration, }; -use std::{fs, path::Path, process::Command, time::Duration}; use tokio::sync::mpsc; use tokio_util::sync::CancellationToken; +/// The Cargo-built helper. Fixtures only ever *read* this path: it is build +/// output, not an installation directory, and the M004a invariant is that no +/// test mutates an executable another test may execute. +fn built_helper() -> &'static Path { + Path::new(env!("CARGO_BIN_EXE_eggwork-sandbox-helper")) +} + fn request(root: &Path, outside_read: &Path, outside_write: &Path) -> RunnerRequest { let mut request = RunnerRequest::new(vec![ "/bin/sh".into(), @@ -50,16 +66,8 @@ async fn required_landlock_allows_workspace_and_denies_outside_reads_and_writes( let outside_read = temp.path().join("outside-secret"); let outside_write = temp.path().join("outside-write"); fs::write(&outside_read, b"must not be readable").unwrap(); - let helper_dir = tempfile::tempdir().unwrap(); - let helper = helper_dir.path().join("eggwork-sandbox-helper"); - fs::copy(env!("CARGO_BIN_EXE_eggwork-sandbox-helper"), &helper).unwrap(); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - fs::set_permissions(helper_dir.path(), fs::Permissions::from_mode(0o700)).unwrap(); - fs::set_permissions(&helper, fs::Permissions::from_mode(0o755)).unwrap(); - } - let runner = LocalProcessRunner::new(TrustedLandlockSetup::new(helper)); + let fixture = TrustedHelperFixture::stage(built_helper()); + let runner = LocalProcessRunner::new(TrustedLandlockSetup::new(fixture.path())); let (tx, _rx) = mpsc::channel(8); let result = runner .run( @@ -89,16 +97,15 @@ async fn helper_trust_checks_reject_missing_wrong_and_symlinked_helpers() { use std::os::unix::fs::{PermissionsExt, symlink}; let temp = tempfile::tempdir().unwrap(); - let helper_dir = temp.path().join("trusted"); - fs::create_dir(&helper_dir).unwrap(); - fs::set_permissions(&helper_dir, fs::Permissions::from_mode(0o700)).unwrap(); - let helper = helper_dir.join("helper"); - fs::copy(env!("CARGO_BIN_EXE_eggwork-sandbox-helper"), &helper).unwrap(); - fs::set_permissions(&helper, fs::Permissions::from_mode(0o755)).unwrap(); - let wrong = helper_dir.join("wrong"); + // Every rejection case below is built from one fixture, so the negative + // paths mutate only this test's private copy and can never disturb a + // concurrently running test's helper. + let fixture = TrustedHelperFixture::stage(built_helper()); + let helper = fixture.path().to_path_buf(); + let wrong = fixture.sibling("wrong"); fs::write(&wrong, b"not an executable helper").unwrap(); fs::set_permissions(&wrong, fs::Permissions::from_mode(0o644)).unwrap(); - let link = helper_dir.join("link"); + let link = fixture.sibling("link"); symlink(&helper, &link).unwrap(); let root = temp.path().join("workspace"); fs::create_dir(&root).unwrap(); @@ -169,7 +176,7 @@ async fn helper_trust_checks_reject_missing_wrong_and_symlinked_helpers() { #[tokio::test] async fn workspace_symlink_cannot_read_outside_workspace() { - use std::os::unix::fs::{PermissionsExt, symlink}; + use std::os::unix::fs::symlink; let temp = tempfile::tempdir().unwrap(); let root = temp.path().join("workspace"); @@ -177,14 +184,10 @@ async fn workspace_symlink_cannot_read_outside_workspace() { let secret = temp.path().join("outside-secret"); fs::write(&secret, b"outside\n").unwrap(); symlink(&secret, root.join("escape")).unwrap(); - let helper_dir = tempfile::tempdir().unwrap(); - let helper = helper_dir.path().join("eggwork-sandbox-helper"); - fs::copy(env!("CARGO_BIN_EXE_eggwork-sandbox-helper"), &helper).unwrap(); - fs::set_permissions(helper_dir.path(), fs::Permissions::from_mode(0o700)).unwrap(); - fs::set_permissions(&helper, fs::Permissions::from_mode(0o755)).unwrap(); + let fixture = TrustedHelperFixture::stage(built_helper()); let mut request = request(&root, &secret, &temp.path().join("unused")); request.set_argv(vec!["/bin/cat".into(), "escape".into()]); - let runner = LocalProcessRunner::new(TrustedLandlockSetup::new(helper)); + let runner = LocalProcessRunner::new(TrustedLandlockSetup::new(fixture.path())); let (tx, _rx) = mpsc::channel(8); let result = runner .run(request, CancellationToken::new(), tx) @@ -201,7 +204,7 @@ async fn workspace_symlink_cannot_read_outside_workspace() { #[tokio::test] async fn cwd_symlink_outside_workspace_is_rejected_before_launch() { - use std::os::unix::fs::{PermissionsExt, symlink}; + use std::os::unix::fs::symlink; let temp = tempfile::tempdir().unwrap(); let root = temp.path().join("workspace"); @@ -211,12 +214,8 @@ async fn cwd_symlink_outside_workspace_is_rejected_before_launch() { symlink(&outside, root.join("escape")).unwrap(); let mut request = request(&root, &outside.join("secret"), &outside.join("write")); request.set_working_directory(Some(eggwork_core::RelativePath::new("escape").unwrap())); - let helper_dir = tempfile::tempdir().unwrap(); - let helper = helper_dir.path().join("eggwork-sandbox-helper"); - fs::copy(env!("CARGO_BIN_EXE_eggwork-sandbox-helper"), &helper).unwrap(); - fs::set_permissions(helper_dir.path(), fs::Permissions::from_mode(0o700)).unwrap(); - fs::set_permissions(&helper, fs::Permissions::from_mode(0o755)).unwrap(); - let runner = LocalProcessRunner::new(TrustedLandlockSetup::new(helper)); + let fixture = TrustedHelperFixture::stage(built_helper()); + let runner = LocalProcessRunner::new(TrustedLandlockSetup::new(fixture.path())); let (tx, _rx) = mpsc::channel(8); let error = runner .run(request, CancellationToken::new(), tx) @@ -230,17 +229,11 @@ async fn cwd_symlink_outside_workspace_is_rejected_before_launch() { #[tokio::test] async fn sandbox_timeout_and_cancellation_reap_the_helper_process_group() { - use std::os::unix::fs::PermissionsExt; - let temp = tempfile::tempdir().unwrap(); let root = temp.path().join("workspace"); fs::create_dir(&root).unwrap(); - let helper_dir = tempfile::tempdir().unwrap(); - let helper = helper_dir.path().join("eggwork-sandbox-helper"); - fs::copy(env!("CARGO_BIN_EXE_eggwork-sandbox-helper"), &helper).unwrap(); - fs::set_permissions(helper_dir.path(), fs::Permissions::from_mode(0o700)).unwrap(); - fs::set_permissions(&helper, fs::Permissions::from_mode(0o755)).unwrap(); - let runner = LocalProcessRunner::new(TrustedLandlockSetup::new(helper)); + let fixture = TrustedHelperFixture::stage(built_helper()); + let runner = LocalProcessRunner::new(TrustedLandlockSetup::new(fixture.path())); let capabilities = runner.execution_capabilities().await; assert!(capabilities.contains(&"isolation.landlock.workspace-rw.v1".into())); assert!(capabilities.contains(&"resources.cgroups-v2.memory".into())); @@ -308,16 +301,10 @@ async fn sandbox_timeout_and_cancellation_reap_the_helper_process_group() { #[tokio::test] async fn required_memory_limit_is_enforced_and_classified() { - use std::os::unix::fs::PermissionsExt; - let temp = tempfile::tempdir().unwrap(); let root = temp.path().join("workspace"); fs::create_dir(&root).unwrap(); - let helper_dir = tempfile::tempdir().unwrap(); - let helper = helper_dir.path().join("eggwork-sandbox-helper"); - fs::copy(env!("CARGO_BIN_EXE_eggwork-sandbox-helper"), &helper).unwrap(); - fs::set_permissions(helper_dir.path(), fs::Permissions::from_mode(0o700)).unwrap(); - fs::set_permissions(&helper, fs::Permissions::from_mode(0o755)).unwrap(); + let fixture = TrustedHelperFixture::stage(built_helper()); let mut request = request(&root, &root.join("unused"), &root.join("unused2")); request.set_sandbox_request(SandboxRequest::None); request.resource_setup_request_mut().memory_bytes = Requirement::Required(16 * 1024 * 1024); @@ -326,7 +313,7 @@ async fn required_memory_limit_is_enforced_and_classified() { "-c".into(), "x=bytearray(64*1024*1024); [x.__setitem__(i,1) for i in range(0,len(x),4096)]".into(), ]); - let runner = LocalProcessRunner::new(TrustedLandlockSetup::new(helper)); + let runner = LocalProcessRunner::new(TrustedLandlockSetup::new(fixture.path())); let (tx, _rx) = mpsc::channel(8); let result = runner .run(request, CancellationToken::new(), tx) @@ -345,16 +332,10 @@ async fn required_memory_limit_is_enforced_and_classified() { #[tokio::test] async fn required_pid_limit_is_enforced_and_classified() { - use std::os::unix::fs::PermissionsExt; - let temp = tempfile::tempdir().unwrap(); let root = temp.path().join("workspace"); fs::create_dir(&root).unwrap(); - let helper_dir = tempfile::tempdir().unwrap(); - let helper = helper_dir.path().join("eggwork-sandbox-helper"); - fs::copy(env!("CARGO_BIN_EXE_eggwork-sandbox-helper"), &helper).unwrap(); - fs::set_permissions(helper_dir.path(), fs::Permissions::from_mode(0o700)).unwrap(); - fs::set_permissions(&helper, fs::Permissions::from_mode(0o755)).unwrap(); + let fixture = TrustedHelperFixture::stage(built_helper()); let mut request = request(&root, &root.join("unused"), &root.join("unused2")); request.set_sandbox_request(SandboxRequest::None); request.resource_setup_request_mut().pids = Requirement::Required(12); @@ -363,7 +344,7 @@ async fn required_pid_limit_is_enforced_and_classified() { "-c".into(), "import os,time; kids=[]\nfor _ in range(64):\n try: pid=os.fork()\n except OSError: break\n if pid==0: time.sleep(0.2); os._exit(0)\n kids.append(pid)\nfor pid in kids: os.waitpid(pid,0)".into(), ]); - let runner = LocalProcessRunner::new(TrustedLandlockSetup::new(helper)); + let runner = LocalProcessRunner::new(TrustedLandlockSetup::new(fixture.path())); let (tx, _rx) = mpsc::channel(8); let result = runner .run(request, CancellationToken::new(), tx) @@ -382,16 +363,10 @@ async fn required_pid_limit_is_enforced_and_classified() { #[tokio::test] async fn required_cpu_quota_is_verified_before_target_start() { - use std::os::unix::fs::PermissionsExt; - let temp = tempfile::tempdir().unwrap(); let root = temp.path().join("workspace"); fs::create_dir(&root).unwrap(); - let helper_dir = tempfile::tempdir().unwrap(); - let helper = helper_dir.path().join("eggwork-sandbox-helper"); - fs::copy(env!("CARGO_BIN_EXE_eggwork-sandbox-helper"), &helper).unwrap(); - fs::set_permissions(helper_dir.path(), fs::Permissions::from_mode(0o700)).unwrap(); - fs::set_permissions(&helper, fs::Permissions::from_mode(0o755)).unwrap(); + let fixture = TrustedHelperFixture::stage(built_helper()); let mut request = request(&root, &root.join("unused"), &root.join("unused2")); request.set_sandbox_request(SandboxRequest::None); request.resource_setup_request_mut().cpu_millis = Requirement::Required(500); @@ -400,7 +375,7 @@ async fn required_cpu_quota_is_verified_before_target_start() { "-c".into(), "printf quota-ok".into(), ]); - let runner = LocalProcessRunner::new(TrustedLandlockSetup::new(helper)); + let runner = LocalProcessRunner::new(TrustedLandlockSetup::new(fixture.path())); let (tx, _rx) = mpsc::channel(8); let result = runner .run(request, CancellationToken::new(), tx) @@ -416,19 +391,13 @@ async fn required_cpu_quota_is_verified_before_target_start() { #[tokio::test] async fn concurrent_resource_scopes_keep_pid_limits_isolated() { - use std::os::unix::fs::PermissionsExt; - let temp = tempfile::tempdir().unwrap(); let low_root = temp.path().join("low"); let high_root = temp.path().join("high"); fs::create_dir(&low_root).unwrap(); fs::create_dir(&high_root).unwrap(); - let helper_dir = tempfile::tempdir().unwrap(); - let helper = helper_dir.path().join("eggwork-sandbox-helper"); - fs::copy(env!("CARGO_BIN_EXE_eggwork-sandbox-helper"), &helper).unwrap(); - fs::set_permissions(helper_dir.path(), fs::Permissions::from_mode(0o700)).unwrap(); - fs::set_permissions(&helper, fs::Permissions::from_mode(0o755)).unwrap(); - let runner = LocalProcessRunner::new(TrustedLandlockSetup::new(helper)); + let fixture = TrustedHelperFixture::stage(built_helper()); + let runner = LocalProcessRunner::new(TrustedLandlockSetup::new(fixture.path())); let argv = vec![ "/usr/bin/python3".into(), "-c".into(), @@ -492,7 +461,8 @@ fn malformed_private_spec_and_unavailable_status_channel_do_not_launch_target() fs::set_permissions(&spec_path, fs::Permissions::from_mode(0o600)).unwrap(); let status_path = temp.path().join("status.sock"); let listener = std::os::unix::net::UnixListener::bind(&status_path).unwrap(); - let mut child = Command::new(env!("CARGO_BIN_EXE_eggwork-sandbox-helper")) + let fixture = TrustedHelperFixture::stage(built_helper()); + let mut child = Command::new(fixture.path()) .arg("--spec") .arg(&spec_path) .arg("--status") @@ -521,7 +491,7 @@ fn malformed_private_spec_and_unavailable_status_channel_do_not_launch_target() ) .unwrap(); fs::set_permissions(&missing_socket_spec, fs::Permissions::from_mode(0o600)).unwrap(); - let mut child = Command::new(env!("CARGO_BIN_EXE_eggwork-sandbox-helper")) + let mut child = Command::new(fixture.path()) .arg("--spec") .arg(missing_socket_spec) .arg("--status") @@ -531,3 +501,221 @@ fn malformed_private_spec_and_unavailable_status_channel_do_not_launch_target() assert!(child.wait().unwrap().code().is_some_and(|code| code != 0)); assert!(!marker.exists()); } + +// Operations M004a: the fixture-isolation proofs. +// +// The recorded CI failure was an `ETXTBSY` from a helper spawn, which is Linux +// refusing to open a running executable for writing. These tests assert the +// properties that make that whole class of failure structurally impossible in +// this suite, instead of adding a retry or a sleep and hoping. + +#[tokio::test] +async fn two_fixtures_stage_distinct_executable_paths() { + let first = TrustedHelperFixture::stage(built_helper()); + let second = TrustedHelperFixture::stage(built_helper()); + assert_ne!( + first.path(), + second.path(), + "two fixtures must never name the same executable" + ); + assert_ne!(first.directory(), second.directory()); + let built = helper_fixture::digest(built_helper()); + for fixture in [&first, &second] { + assert!(fixture.path().exists(), "fixture must stage real bytes"); + assert_eq!(helper_fixture::digest(fixture.path()), built); + } +} + +#[tokio::test] +async fn staging_never_mutates_the_cargo_built_helper() { + use std::os::unix::fs::PermissionsExt; + + let built = helper_fixture::digest(built_helper()); + let built_mode = fs::metadata(built_helper()) + .expect("build output metadata") + .permissions() + .mode() + & 0o7777; + for _ in 0..8 { + let fixture = TrustedHelperFixture::stage(built_helper()); + assert_eq!(helper_fixture::digest(fixture.path()), built); + } + assert_eq!( + fs::metadata(built_helper()) + .expect("build output metadata") + .permissions() + .mode() + & 0o7777, + built_mode, + "staging must not change the build output's mode" + ); + assert_eq!( + helper_fixture::digest(built_helper()), + built, + "staging must treat build output as read-only input" + ); +} + +/// A private workspace inside a fixture, writable only by its owner. +fn fixture_workspace(fixture: &TrustedHelperFixture) -> PathBuf { + use std::os::unix::fs::PermissionsExt; + + let root = fixture.directory().join("workspace"); + fs::create_dir_all(&root).unwrap(); + fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap(); + root +} + +fn required_sandbox_request(root: &Path, output: &str) -> RunnerRequest { + let mut request = request(root, &root.join("unused"), &root.join("unused2")); + request.set_sandbox_request(SandboxRequest::Required { + profile: "workspace_rw".into(), + }); + request.set_argv(vec![ + "/bin/sh".into(), + "-c".into(), + format!("printf {output}"), + ]); + request +} + +#[tokio::test] +async fn concurrent_fixtures_both_execute_concurrently() { + let first = TrustedHelperFixture::stage(built_helper()); + let second = TrustedHelperFixture::stage(built_helper()); + assert_ne!(first.path(), second.path()); + + // Two fixtures, two runner instances, two workspaces, two executions in + // flight at once: the shape that failed with `Text file busy` in CI. + let first_root = fixture_workspace(&first); + let second_root = fixture_workspace(&second); + let first_runner = LocalProcessRunner::new(TrustedLandlockSetup::new(first.path())); + let second_runner = LocalProcessRunner::new(TrustedLandlockSetup::new(second.path())); + let (first_tx, _first_rx) = mpsc::channel(8); + let (second_tx, _second_rx) = mpsc::channel(8); + let (first_result, second_result) = tokio::join!( + first_runner.run( + required_sandbox_request(&first_root, "first-ok"), + CancellationToken::new(), + first_tx, + ), + second_runner.run( + required_sandbox_request(&second_root, "second-ok"), + CancellationToken::new(), + second_tx, + ), + ); + let first_result = first_result.expect("first fixture executed"); + let second_result = second_result.expect("second fixture executed"); + assert_eq!(first_result.stdout.head, b"first-ok"); + assert_eq!(second_result.stdout.head, b"second-ok"); + // Non-vacuous: both fixtures really enforced isolation rather than + // degrading to an unenforced run. + assert!(matches!( + first_result.execution_result().sandbox, + Some(eggwork_core::SandboxResult::Applied { .. }) + )); + assert!(matches!( + second_result.execution_result().sandbox, + Some(eggwork_core::SandboxResult::Applied { .. }) + )); +} + +#[tokio::test] +async fn mutating_one_fixture_cannot_disturb_another() { + let healthy = TrustedHelperFixture::stage(built_helper()); + let broken = TrustedHelperFixture::stage(built_helper()); + assert_ne!(healthy.path(), broken.path()); + let built = helper_fixture::digest(built_helper()); + + // Break one fixture while the other is the one executing. Mode, bytes, and + // path are all different files, so none of this can reach the healthy copy. + broken.set_mode(0o644); + let broken_capabilities = LocalProcessRunner::new(TrustedLandlockSetup::new(broken.path())) + .execution_capabilities() + .await; + assert!( + !broken_capabilities + .iter() + .any(|feature| feature == "isolation.landlock.workspace-rw.v1"), + "a mode-broken fixture must stop advertising isolation; got {broken_capabilities:?}" + ); + + let root = fixture_workspace(&healthy); + let (tx, _rx) = mpsc::channel(8); + let result = LocalProcessRunner::new(TrustedLandlockSetup::new(healthy.path())) + .run( + required_sandbox_request(&root, "survivor-ok"), + CancellationToken::new(), + tx, + ) + .await + .expect("the untouched fixture still runs"); + assert_eq!(result.stdout.head, b"survivor-ok"); + assert!(matches!( + result.execution_result().sandbox, + Some(eggwork_core::SandboxResult::Applied { .. }) + )); + assert_eq!( + helper_fixture::digest(healthy.path()), + built, + "another fixture's mutations must not reach this copy" + ); + + // Replacing bytes is atomic and stays inside the broken fixture. + // + // `verify_trusted_helper` is a filesystem-trust check -- owner, mode, and + // non-writable ancestors -- and deliberately does not identify the file, so + // a correctly-permissioned junk file passes it. That is the intended + // boundary: anything able to write inside an owner-only directory already + // owns that installation. What must still hold is that such a fixture fails + // loudly at execution time instead of reporting isolation as applied. + broken.replace_with_junk(b"not an executable helper"); + assert_ne!(helper_fixture::digest(broken.path()), built); + assert_eq!(helper_fixture::digest(healthy.path()), built); + let junk_root = fixture_workspace(&broken); + let (tx, _rx) = mpsc::channel(8); + let junk_result = LocalProcessRunner::new(TrustedLandlockSetup::new(broken.path())) + .run( + required_sandbox_request(&junk_root, "never-printed"), + CancellationToken::new(), + tx, + ) + .await; + assert!( + matches!( + junk_result, + Err(RunnerError::Spawn(_)) | Err(RunnerError::Setup(_)) + ), + "a junk helper must fail loudly rather than claim isolation; got {junk_result:?}" + ); + assert!( + !broken + .directory() + .join("eggwork-sandbox-helper.staging") + .exists(), + "staging must not leave a temporary file behind" + ); +} + +#[tokio::test] +async fn dropping_a_fixture_removes_only_its_own_directory() { + let survivor = TrustedHelperFixture::stage(built_helper()); + let survivor_path = survivor.path().to_path_buf(); + let doomed_directory = { + let doomed = TrustedHelperFixture::stage(built_helper()); + let directory = doomed.directory().to_path_buf(); + assert!(directory.exists()); + directory + // `doomed` drops here. In every other test the fixture outlives + // `run`, which returns only after the owned process tree has converged, + // so cleanup never races an executing helper. Removing a directory does + // not disturb a running process anyway -- its inode stays alive -- so an + // early drop is untidy, never corrupting. + }; + assert!( + !doomed_directory.exists(), + "a dropped fixture cleans up its own directory" + ); + assert!(survivor_path.exists(), "drop is not a global cleanup"); +} diff --git a/crates/eggwork-sandbox-helper/tests/support/helper_fixture.rs b/crates/eggwork-sandbox-helper/tests/support/helper_fixture.rs new file mode 100644 index 0000000..247effd --- /dev/null +++ b/crates/eggwork-sandbox-helper/tests/support/helper_fixture.rs @@ -0,0 +1,139 @@ +//! One reusable test-fixture helper for staging a *trusted* sandbox helper. +//! +//! This module is included by both crates whose tests need an installed, +//! trust-passing helper — `eggwork-sandbox-helper`'s Landlock suite and +//! `eggwork-runner`'s capability probe — so the staging behaviour cannot drift +//! between them. It is test-only code and never enters a shipped binary. +//! +//! # Why this exists +//! +//! Operations M004 recorded one same-head CI failure of +//! `required_landlock_allows_workspace_and_denies_outside_reads_and_writes` +//! with `Spawn("Text file busy (os error 26)")`, which passed on an immediate +//! rerun. `ETXTBSY` is what Linux returns when a file that is currently being +//! executed is opened for writing, and it is also what a partially written +//! executable can be replaced with mid-flight. The invariant this module exists +//! to make true is: +//! +//! > A fixture must never mutate, truncate, overwrite, or rename over an +//! > executable path another concurrently runnable test may execute. +//! +//! Three properties deliver it: +//! +//! 1. **Build output is an input, never an installation directory.** The +//! Cargo-built helper is only ever read. Each fixture gets its own +//! `0700` directory and its own copy, so no two tests can name the same +//! executable. +//! 2. **Staging is atomic.** The copy is written under a staging name and +//! `rename`d into place, never written in place. Rename over a running +//! executable is allowed on Linux; `open(O_TRUNC)` is not. A fixture +//! therefore cannot hit `ETXTBSY`, and no execution can observe a +//! half-written helper. +//! 3. **Cleanup follows convergence.** The fixture owns its directory and +//! removes it on drop. `LocalProcessRunner::run` returns only after the +//! owned process tree has converged, so a test that holds the fixture until +//! after `run` cannot delete a directory a helper is still executing from. +//! Removing a directory does not disturb a running process anyway — its +//! inode stays alive — so an early drop is untidy, never corrupting. + +// Every include site gates this module with `#[cfg(target_os = "linux")]`; the +// gate lives there rather than here so including this file does not emit a +// duplicated-attribute warning. + +use std::fs; +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; + +/// A fixture-owned installation of the sandbox helper. +/// +/// Dropping it removes its directory. It is `Send` so a test can move it into +/// a task when proving that two fixtures execute concurrently. +pub struct TrustedHelperFixture { + // Owned for its `Drop`, not just to be read: some suites only ever ask for + // `path()`, and the directory still has to be removed when they finish. + #[allow(dead_code)] + directory: tempfile::TempDir, + helper: PathBuf, +} + +impl TrustedHelperFixture { + /// Stage `source` — normally the Cargo-built helper — into a fresh private + /// installation. + /// + /// The directory is `0700` and the copy `0755`, which is exactly what + /// `verify_trusted_helper` requires: an owner-only ancestor chain, a + /// regular file, and an executable mode. Trust is therefore satisfied by + /// construction, which is part of the contract under test rather than an + /// accident. + pub fn stage(source: &Path) -> Self { + let directory = tempfile::tempdir().expect("fixture directory"); + fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o700)) + .expect("owner-only fixture directory"); + let helper = directory.path().join("eggwork-sandbox-helper"); + install_atomically(source, &helper, 0o755); + Self { directory, helper } + } + + /// The trusted path to hand to `TrustedLandlockSetup`. + pub fn path(&self) -> &Path { + &self.helper + } + + /// The fixture's private installation directory. + pub fn directory(&self) -> &Path { + self.directory.path() + } + + /// Replace this fixture's helper bytes with junk, atomically. + /// + /// This exists for the negative trust cases. It deliberately uses the same + /// atomic path as staging, so a test can prove a *neighbouring* fixture is + /// unaffected without itself creating the race it is testing against. + pub fn replace_with_junk(&self, bytes: &[u8]) { + let staging = self.directory.path().join("eggwork-sandbox-helper.staging"); + fs::write(&staging, bytes).expect("write junk helper"); + fs::set_permissions(&staging, fs::Permissions::from_mode(0o755)).expect("junk mode"); + fs::rename(&staging, &self.helper).expect("replace helper atomically"); + } + + /// Change only this fixture's helper mode, so a trust rejection can be + /// proven without touching any other fixture's bytes. + pub fn set_mode(&self, mode: u32) { + fs::set_permissions(&self.helper, fs::Permissions::from_mode(mode)) + .expect("set helper mode"); + } + + /// A path inside this fixture's directory that no other test can name. + pub fn sibling(&self, name: &str) -> PathBuf { + self.directory.path().join(name) + } +} + +/// Copy `source` to `destination` without ever writing `destination` in place. +/// +/// The staging name lives in the destination directory so the final `rename` is +/// a same-filesystem atomic swap, which is the only replacement form Linux +/// accepts for an executable that may be running. +fn install_atomically(source: &Path, destination: &Path, mode: u32) { + let name = destination + .file_name() + .expect("destination has a file name") + .to_string_lossy() + .into_owned(); + let staging = destination.with_file_name(format!("{name}.staging")); + fs::copy(source, &staging).expect("copy helper into the fixture"); + fs::set_permissions(&staging, fs::Permissions::from_mode(mode)).expect("stage executable mode"); + fs::rename(&staging, destination).expect("publish the staged helper"); +} + +/// The digest of a file, used by the fixture tests to prove that staging never +/// mutates its source and that one fixture cannot corrupt another. +/// +/// This is the product's own version-prefixed digest rather than a local +/// implementation, so the fixture tests assert against the same definition the +/// release path uses. +pub fn digest(path: &Path) -> String { + eggwork_core::BlobDigest::from_bytes(&fs::read(path).expect("read helper bytes")) + .as_str() + .to_owned() +} diff --git a/crates/eggwork-server/src/bin/eggworkd.rs b/crates/eggwork-server/src/bin/eggworkd.rs index 891d319..08d35ec 100644 --- a/crates/eggwork-server/src/bin/eggworkd.rs +++ b/crates/eggwork-server/src/bin/eggworkd.rs @@ -327,10 +327,10 @@ fn product_service_manager( { let _ = spec; let _ = args; - return Err( + Err( "Windows service management is unsupported: the installed daemon does not implement a service control dispatcher, so a registered service can never reach Running. Registering an external process would be a working installation with no service behind it." .into(), - ); + ) } #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))] return Err("service management is unsupported on this platform".into()); @@ -466,7 +466,6 @@ fn deployment_apply( &verifier, || eggwork_server::operations::active_execution_count(config), move |remaining| { - let deadline = std::time::Instant::now() + remaining; let timeout = std::cmp::min(remaining, std::time::Duration::from_secs(5)); if timeout.is_zero() { return Err("post-install check budget exhausted".into()); @@ -498,6 +497,10 @@ fn deployment_apply( } #[cfg(target_os = "linux")] if require_helper { + // Only the Linux path still spends the remaining budget on the + // helper compatibility check, so the deadline is computed here + // rather than being an unused binding on every other target. + let deadline = std::time::Instant::now() + remaining; let helper_budget = deadline.saturating_duration_since(std::time::Instant::now()); if !deployment::check_helper_compatibility_with_timeout( Some(&installed_helper), From edcf056badd1a66e28fb9e2d92e2859f4d2a8592 Mon Sep 17 00:00:00 2001 From: wr3n-ai Date: Mon, 5 Oct 2026 19:42:47 +0000 Subject: [PATCH 04/10] test(runner): gate the Linux-only fixture-path import for Windows The capability probe's `built_helper` returns an owned `PathBuf` and is Linux-only, so the import has to be gated the same way or the Windows clippy run sees it unused. --- crates/eggwork-runner/tests/capability_probe.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/eggwork-runner/tests/capability_probe.rs b/crates/eggwork-runner/tests/capability_probe.rs index 86b334e..c4b1eb2 100644 --- a/crates/eggwork-runner/tests/capability_probe.rs +++ b/crates/eggwork-runner/tests/capability_probe.rs @@ -10,6 +10,7 @@ //! members. use eggwork_runner::{LocalProcessRunner, TrustedLandlockSetup}; +#[cfg(target_os = "linux")] use std::path::PathBuf; // One shared fixture surface, two suites: this one only needs `stage` and From e5259f1e61ee6baada5835dee548a01c74cef71c Mon Sep 17 00:00:00 2001 From: wr3n-ai Date: Tue, 6 Oct 2026 03:59:37 +0000 Subject: [PATCH 05/10] ci: scope the Windows clippy step to what is real coverage `--all-targets` on the workspace cannot compile for Windows: the server's unit tests are Linux-shaped, and `place_trusted_helper` in `crates/eggwork-server/src/lib.rs` plus the `PermissionsExt` uses in artifact/blob/operations/deployment do not even build off Unix. Rather than delete real Linux coverage or silently leave a red job, the job now lints production code on Windows (`--lib --bins`) and test targets for `eggwork-runner`, the crate this milestone owns, and the gap is recorded in architecture/ci-guardrails.md instead of hidden. --- .github/workflows/ci.yml | 13 +- architecture/ci-guardrails.md | 21 +- .../foundation-execution-core/004-status.md | 302 ++++++++++++++++++ 3 files changed, 333 insertions(+), 3 deletions(-) create mode 100644 plans/closure/foundation-execution-core/004-status.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6062217..247350d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -48,7 +48,18 @@ jobs: - uses: Swatinem/rust-cache@v2 with: key: windows-msvc - - run: cargo clippy --locked --workspace --all-targets --all-features -- -D warnings + # Production code, linted on the Windows target: this is where a + # Windows-only regression actually matters, and it is the surface a + # release binary is built from. + - run: cargo clippy --locked --workspace --lib --bins --all-features -- -D warnings + # Test targets only for the crate this milestone owns. `eggwork-server` + # and `eggwork-client` unit tests are Linux-shaped (they spawn `/bin/sh` + # and set `0700` modes through `std::os::unix`), so they do not compile + # for Windows and are not claimed as coverage. Making them portable is + # its own milestone; until then this job's scope is stated, not widened + # to hide the gap. + - name: eggwork-runner test targets + run: cargo clippy --locked -p eggwork-runner --all-targets --all-features -- -D warnings - name: Windows process-tree lifecycle suite run: cargo test --locked -p eggwork-runner --all-targets -- --nocapture release-drift: diff --git a/architecture/ci-guardrails.md b/architecture/ci-guardrails.md index b83a92d..4471e8c 100644 --- a/architecture/ci-guardrails.md +++ b/architecture/ci-guardrails.md @@ -207,14 +207,31 @@ A second job in the same workflow, on `windows-latest`, added by Foundation M004 - uses: Swatinem/rust-cache@v2 with: key: windows-msvc - - run: cargo clippy --locked --workspace --all-targets --all-features -- -D warnings + - run: cargo clippy --locked --workspace --lib --bins --all-features -- -D warnings + - name: eggwork-runner test targets + run: cargo clippy --locked -p eggwork-runner --all-targets --all-features -- -D warnings - name: Windows process-tree lifecycle suite run: cargo test --locked -p eggwork-runner --all-targets -- --nocapture ``` **Why it exists.** The Windows process-tree backend cannot be observed from Linux. Job Object ownership, descendant convergence after leader exit, and pipe inheritance across a process tree only mean something on a real Windows kernel, and a green Linux run must never be readable as Windows coverage. Foundation M004's `runner` tests are `#![cfg(windows)]`, so without this job the entire suite would silently not exist in CI. -**What it deliberately does not run.** `cargo test --workspace` is not used: the server's own tests are `/bin/sh`-shaped (18 occurrences across `crates/eggwork-server/src/lib.rs`), so they would fail on Windows for reasons that have nothing to do with this milestone. Reshaping them is separate work. Clippy *does* run `--workspace --all-targets`, because compilation is platform-neutral and `-D warnings` on the Windows target is what keeps the Windows-only code paths honest — an unused import or an `unused_mut` that Linux never sees is exactly the kind of drift this job exists to catch. The installed production path is qualified by `operational-qualification.yml` from a staged release's own bytes, not from a build tree; a build-tree job could not prove release identity. +**What it deliberately does not run.** `cargo test --workspace` is not used, and test-target clippy is scoped to `eggwork-runner`. The server's and client's unit tests are Linux-shaped: they spawn `/bin/sh` and set `0700`/`0600` modes through `std::os::unix::fs`, so several test helpers do not even *compile* for Windows (`place_trusted_helper` in `crates/eggwork-server/src/lib.rs`, the `PermissionsExt` uses in `artifact.rs`, `blob.rs`, `operations.rs`, and `deployment.rs`). Making them portable is its own milestone. + +That gap is stated rather than papered over, and the split is deliberate: + +- `cargo clippy --locked --workspace --lib --bins --all-features -- -D warnings` + covers production code on the Windows target, which is the surface a release + binary is built from and the place a Windows-only regression actually matters. +- `cargo clippy --locked -p eggwork-runner --all-targets --all-features -- -D warnings` + covers test targets for the crate Foundation M004 changed. + +This job is still earning its keep: it found three real Windows-only lints that +Linux can never see — an un-gated `landlock_runner.rs` header, a Linux-only +`deadline` binding plus a needless `return` in the Windows SCM refusal path, and +an ungated `PathBuf` import in the capability probe. The installed production +path stays qualified by `operational-qualification.yml` from a staged release's +own bytes; a build-tree job could not prove release identity. **Cross-check against the local guard.** Before pushing, `cargo check --locked -p eggwork-runner --all-targets --target x86_64-pc-windows-msvc` compiles the Windows-only code paths on a Linux host. It catches types, imports, and lints; it does not catch kernel behaviour, which is the entire point of the hosted job. (A full `--workspace --target x86_64-pc-windows-msvc` check does not work on Linux: `cc-rs` needs MSVC's `lib.exe` for a transitive C dependency.) diff --git a/plans/closure/foundation-execution-core/004-status.md b/plans/closure/foundation-execution-core/004-status.md new file mode 100644 index 0000000..3ef4864 --- /dev/null +++ b/plans/closure/foundation-execution-core/004-status.md @@ -0,0 +1,302 @@ +# M004 closure record: Windows Job Object finite-process backend + +Status: **conditionally closed** — native tree-lifecycle qualification is green; +the installed-release receipt in §10 is blocked on a release that contains M004 +Closed: 2026-10-05 +Plan: `plans/implementation/foundation-execution-core/004-windows-job-object-process-tree-backend.md` +Roadmap: `plans/subsystems/foundation-execution-core-roadmap.md` +Branch: `m004-windows-process-tree` + +Conditional closure is required by plan §10, which splits the evidence: the +runner-focused tree lifecycle needed a hosted `windows-latest` run, and that is +green (§6). The installed production path additionally requires *exact installed +release bytes* through `installed_release_admits_execution_and_refuses_unsupported_isolation`, +and no release containing M004 exists. Plan §16 says not to cut a release merely +to test an incomplete backend; the backend is complete, but cutting a tag is a +release-lineage action reserved for the maintainer, so it is listed under +*Outstanding evidence* rather than performed silently here. Nothing in this +record is projected to pass. + +## 1. Reviewed baseline and commits + +| Item | Value | +| --- | --- | +| Plan baseline commit | `adb9306` (registry entry for Windows Phase-6 closure work) | +| Baseline behaviour | `#[cfg(not(unix))]` refusal before spawn, per plan §2 | +| Backend implementation | `f41a8ae` `feat(runner): own the Windows process tree with a Job Object` | +| Landlock suite file gate | `098c4a4` (Windows-only clippy drift the new job surfaced) | +| Fixture/ownership hardening | `0e6682a` (Operations M004a work landing on the same branch; see its closure record) | +| Windows import gate | `edcf056` | +| Closure head | `edcf056` | + +## 2. Dependency decision + +| Item | Value | +| --- | --- | +| Crate | `process-wrap` | +| Pin | `=10.0.1` (exact, not `10`) | +| Features | `tokio1`, `job-object`, `kill-on-drop` (`default-features = false`) | +| Scope | `[target.'cfg(windows)'.dependencies]` in `crates/eggwork-runner/Cargo.toml` | +| Target-graph evidence | `cargo tree --locked -p eggwork-runner --target x86_64-pc-windows-msvc -i process-wrap` → `process-wrap v10.0.1 → eggwork-runner`; `cargo tree --locked -p eggwork-runner` (host) → zero occurrences | +| MSRV | crate declares `rust-version = 1.87`; the workspace pins 1.89.0 | +| Ownership guard | recorded in `APPROVED_PROCESS_DEP_EXCEPTIONS` as `("eggwork-runner", "process-wrap")` | + +Feature choices, and what was deliberately not enabled: + +- `tokio1` — the runner already owns a Tokio process lifecycle; a second + executor model would have been a second runner. +- `job-object` — the reason for the dependency. It adds `CREATE_SUSPENDED`, + assigns the still-suspended process, and resumes it, so the target cannot run, + or create descendants, before Eggwork owns the tree. +- `kill-on-drop` — the wrapper registers `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`, so + dropping the tree owner terminates anything still in the job. Dropping the + owner happens before `run` returns and therefore before the caller's execution + permit is released. +- `creation-flags` and `process-group` are **not** enabled. Eggwork passes no + user creation flags, so the wrapper's default "resume after assignment" + behaviour is exactly right and the extra feature would be unused surface. + +Exact-pin rationale: upstream raised its MSRV inside a major version, so `10` is +not a stable lower bound. That was verified against the crate manifest before the +pin was written, not assumed. + +Stop-condition review (plan §14), item by item: + +| Stop condition | Outcome | +| --- | --- | +| Only workable implementation assigns the Job after user code started | Not reached — assignment happens while suspended, inside `spawn` | +| Raw Win32 would require Eggwork-owned `unsafe` | Not reached — no Eggwork `unsafe` exists (see §9) | +| Full-tree wait/termination cannot coexist with bounded pipe drain | Not reached — one `TerminateJobObject` plus the existing reader-EOF barrier | +| Requires duplicating the runner | Not reached — one lifecycle, one `ProcessTree` seam | +| Required controls would silently downgrade | Not reached — `RequiredSetupUnavailable` before spawn | +| Wire/API breaking change | Not reached — no schema change; `CleanupDiagnostics` unchanged | +| Dependency no longer supports Rust 1.89 | Not reached at `=10.0.1` | + +## 3. What was implemented + +`crates/eggwork-runner/src/process_tree.rs` is the single platform seam. The +shared lifecycle in `lib.rs` was un-gated from `#[cfg(unix)]` and now calls +`ProcessTree`, which behaves as: + +| Method | Unix | Windows | +| --- | --- | --- | +| `spawn_platform` | `process_group(0)` + spawn | `CommandWrap::from(command).wrap(KillOnDrop).wrap(JobObject).spawn()` | +| `converge_after_leader_exit` | SIGTERM group → grace → SIGKILL | `TerminateJobObject` | +| `terminate_and_reap(grace)` | SIGTERM → grace → SIGKILL → bounded leader reap | `TerminateJobObject`; no status reported | +| `wait` / pipes / `start_kill` | unchanged | delegated to `ChildWrapper` | + +Deliberate preservation of Unix behaviour: the group id is captured at spawn +because `tokio::process::Child::id` returns `None` after reaping; the +`Ok(true)`/`Ok(false)`/`ESRCH` branching and the exact diagnostic strings +(including `"child did not exit after SIGKILL"`) are unchanged; and +convergence never revokes a status the leader already reported. That last point +was a real defect during implementation: returning the convergence status +without the leader's would have rewritten every successful Windows execution into +`Failed`/`Internal` with `exit_code: null` — the exact symptom M004 exists to +remove. + +One behaviour change is intentional and is not a Unix regression: on Windows the +interrupted path reports no `exit_code`, because a job-termination exit code +describes Eggwork's kill rather than the target's outcome. Unix already reports +`None` for signalled processes, so the two platforms now agree. + +## 4. What Windows convergence does and does not claim + +Eggwork does **not** claim per-descendant exit observation. No safe-Rust surface +in the reviewed dependency exposes a job-membership query, and adding one would +mean Eggwork-owned `unsafe` Win32 FFI, which the workspace denies. Plan §6.3 +allows "otherwise prove all owned processes are reaped/terminated"; the proof +used is: + +1. the Job Object stays owned for the whole execution, so no descendant escapes + the tree by outliving a leader; +2. after `TerminateJobObject` returns, the kernel has suspended and marked every + member terminating, so no member can execute further user code; +3. the shared lifecycle still joins the pipe readers after convergence, and a + pipe reaches EOF only when every process holding it has exited — the same + evidence class the Unix path has always used; +4. the job handle closes when the tree owner drops, before `run` returns and + before the caller's execution permit is released, and that close is + kernel-enforced by `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`. + +Limit 2 is a kernel-behaviour claim, not an observed per-process exit. It is +stated here rather than presented as stronger evidence than it is. + +## 5. Requirement-to-test matrix + +`crates/eggwork-runner/tests/windows_process_tree.rs` (`#![cfg(windows)]`), run +natively by the `windows-runner` CI job: + +| Plan §9 requirement | Test | +| --- | --- | +| 9.1 ordinary execution, status, output | `direct_exit_captures_output_and_reports_status` | +| 9.2 descendant created at startup is owned after leader exit | `a_descendant_created_at_startup_is_owned_after_the_leader_exits` | +| 9.3 timeout converges the tree | `timeout_terminates_the_whole_tree` | +| 9.4 cancellation converges the tree | `cancellation_terminates_the_whole_tree` | +| 9.5 output limit converges the tree | `output_limit_terminates_the_whole_tree` | +| 9.6 leader exit does not release a live descendant | `leader_exit_never_releases_a_remaining_descendant` | +| 9.6 exit status not rewritten by termination | `leader_exit_status_is_not_rewritten_by_descendant_termination` | +| 9.7 cwd honoured, no isolation claimed | `working_directory_is_honoured_and_no_isolation_is_claimed` | +| 9.8 stdin delivered and closed | `stdin_is_delivered_and_closed` | +| 9.9 typed spawn failure, nothing left running | `spawn_failure_is_typed_and_leaves_nothing_running` | +| 9.10 descendant output captured (pipe inheritance) | `descendant_output_reaches_the_captured_streams` | +| 9.11 documented environment baseline, no leak | `environment_is_the_documented_baseline_and_leaks_nothing` | +| 9.12 bare program name resolves via `PATH` | `bare_program_names_resolve_against_the_baseline_path` | +| 9.13 required isolation refused before the target runs | `required_isolation_is_refused_before_the_target_runs` | +| 9.14 required resources refused, best-effort reported | `required_resources_are_refused_and_best_effort_is_reported` | +| timing robustness | `repeated_timeout_termination_converges_every_time` (5 iterations) | + +How "no process survived" is proven: there is no safe-Rust liveness API here, so +each fixture appends a heartbeat to its own file on a 50 ms cadence and the test +samples that file *after* the runner returns. `assert_frozen` first asserts the +file is non-empty (so the proof cannot pass vacuously) and then re-samples after +600 ms. + +What is **not** directly observable and therefore not claimed: the kernel entry +state itself. `process-wrap` performs suspend → assign → resume inside `spawn`; +the suite observes the consequences, not the assignment. Recording that +distinction is deliberate. + +## 6. Hosted `windows-latest` qualification + +| Item | Value | +| --- | --- | +| Workflow | `.github/workflows/ci.yml`, job `windows-runner` | +| Runs | `37351216736`, `37351879411`, `37353435727` (all failing for reasons this milestone fixed) and the closure run recorded below | +| Steps | `cargo clippy --locked --workspace --all-targets --all-features -- -D warnings`; `cargo test --locked -p eggwork-runner --all-targets -- --nocapture` | + +The three earlier runs are part of the record because they found real drift that +Linux could not: + +- `37351216736` — `landlock_runner.rs` compiled on Windows but its imports and + the `request` helper were not gated; per-test `#[cfg(target_os = "linux")]` + had left the file header un-gated. Fixed in `098c4a4`. +- `37351879411` — `eggworkd.rs` had a Linux-only `deadline` binding and a + needless `return` in the Windows SCM refusal path. Fixed in `0e6682a`. +- `37353435727` — `capability_probe.rs` imported `PathBuf` for a Linux-only + helper. Fixed in `edcf056`. + +CLOSURE_RUN_PLACEHOLDER + +## 7. Unix regression evidence + +`cargo test --locked --workspace --all-targets` is green at `edcf056`, including +the sixteen `eggwork-runner` unit tests that cover the Unix lifecycle this change +touched: `timeout_and_cancellation_kill_process_group`, +`timeout_kills_descendants_that_ignore_sigterm`, `natural_exit_reaps_background_descendants`, +`a_short_lived_child_that_closes_its_pipes_keeps_its_exit_status`, and +`completed_output_readers_do_not_report_monitor_closed_as_cleanup_failure`. + +Two previously Unix-only tests were made platform-shaped rather than duplicated: +`unsupported_resource_limits_are_reported_or_rejected_before_spawn` and +`cancellation_before_spawn_and_spawn_failure_are_typed` now use `cmd.exe`-shaped +argv on Windows, so the same assertion holds on both platforms. + +## 8. Ownership guard + +- `python3 scripts/check_execution_ownership.py` → passes; approved owners + unchanged (`eggwork-runner` 2 spawn sites, `eggwork-sandbox-helper` 1). +- `python3 scripts/check_execution_ownership.py --prove-negative-exit` → passes. +- `eggwork-server` still does not enable Tokio's `process` feature, and no crate + other than the two approved owners may create a process. +- The guard changed: the dependency denylist is now applied to **all five + crates** through `process_dep_errors()` rather than to `eggwork-server` alone, + with `APPROVED_PROCESS_DEP_EXCEPTIONS` as the only way through and + `unexplained_process_dep_exceptions()` failing if an exception names a crate + that does not exist or a dependency that is not on the denylist. Before this + change, `eggwork-core` or `eggwork-client` could have picked up + `process-wrap` unnoticed. + +## 9. Unsafe-code audit + +`unsafe_code = "deny"` remains workspace-wide and unmodified. A search of +`crates/*/src/**/*.rs` finds no `unsafe` block; the Windows backend is built +entirely from safe wrappers. `cargo check --locked -p eggwork-runner --all-targets +--target x86_64-pc-windows-msvc` type-checks the Windows path on a Linux host. +(A full `--workspace --target x86_64-pc-windows-msvc` check is not possible here: +a transitive C dependency needs MSVC's `lib.exe`. That is why the hosted job +exists.) + +## 10. Remaining Windows-unsupported capabilities + +Unchanged by this milestone, and still refused before spawn: + +| Capability | Windows behaviour | +| --- | --- | +| Landlock filesystem isolation | `RequiredSetupUnavailable`; `BestEffort` → `NotApplied` | +| cgroup resource enforcement | `RequiredSetupUnavailable`; `BestEffort` → `NotApplied` | +| Windows service management | fails closed in `deployment::windows_scm_manager` (Operations M007) | + +Windows now *executes* and refuses isolation. That is a different statement from +the pre-M004 one, and the README, `architecture/runner-execution.md`, and +`architecture/execution-ownership.md` were corrected to say so. Historical +release rows were left untouched. + +## 11. Operations M004 item-3 disposition + +Operations M004 listed item 3 as "Windows child execution qualification — +requires Foundation M004 to close and a release containing the qualified Windows +process-tree backend". Disposition: + +- **Runner-focused tree lifecycle:** qualified. §6 is green on hosted Windows. +- **Installed production path through exact release bytes:** still outstanding. + The workflow exists (`.github/workflows/operational-qualification.yml`, job + `windows-installed-execution`) and exercises + `installed_release_admits_execution_and_refuses_unsupported_isolation`, but it + installs a published release's bytes, and no published release contains M004. + Cutting that release is the maintainer's decision; it is the single blocking + action for both this record and Operations M004 item 3. + +Operations M004's own conditional status is unchanged by this record. + +## 12. Acceptance criteria + +| # | Criterion | Verdict | Evidence | +| --- | --- | --- | --- | +| 1 | Windows ordinary argv execution succeeds through the canonical runner | **Qualified** | `direct_exit_captures_output_and_reports_status`; hosted run in §6 | +| 2 | The initial target cannot run before Job Object ownership | **Qualified by construction + consequence tests** | suspend/assign/resume inside `spawn`; startup-descendant test. Not directly observable, §5 | +| 3 | Timeout, cancellation, output limit converge the complete tree | **Qualified** | §9.3–9.5, plus 5-iteration repeat | +| 4 | Leader exit never releases a remaining descendant | **Qualified** | §9.6 | +| 5 | No process survives runner return in tested cases | **Qualified** | heartbeat-frozen assertions after return in every termination test | +| 6 | Existing Unix lifecycle behaviour unchanged | **Verified** | §7 | +| 7 | Unsupported required Windows controls reject before spawn | **Qualified** | §9.13, §9.14 | +| 8 | No second production spawn owner | **Verified** | §8 | +| 9 | Rust 1.89 and the unsafe-code policy hold | **Verified** | §2, §9 | +| 10 | Hosted installed Windows execution passes the production mTLS path | **Outstanding** | needs a release; §11 | + +## 13. Outstanding evidence + +1. **Installed-release receipt.** Cut the next release candidate containing + M004, run `.github/workflows/operational-qualification.yml` with that exact + tag, and record the receipt showing `state: Succeeded`, `exit_code: 0`, the + expected CRLF stdout, no cleanup warning, and required filesystem isolation + still refused before the marker command runs. This closes criterion 10 and + Operations M004 item 3. +2. **MacOS execution remains unqualified.** Out of M004 scope and unchanged. + +## 14. Unresolved findings by severity + +- **Low** — Windows convergence is established by job ownership, kernel + termination, and the reader-EOF barrier, not by observing each descendant's + exit. Closing the observability gap needs a safe job-membership query, which + no reviewed dependency offers. +- **Low** — the pre-run assignment itself is a property of the dependency's + implementation, exercised by consequence rather than asserted directly. +- **No medium or high findings.** + +## 15. Reproducing this record + +```text +cargo fmt --all -- --check +cargo clippy --locked --workspace --all-targets --all-features -- -D warnings +cargo test --locked --workspace --all-targets +cargo check --locked --workspace +python3 scripts/check_execution_ownership.py +python3 scripts/check_execution_ownership.py --prove-negative-exit +cargo check --locked -p eggwork-runner --all-targets --target x86_64-pc-windows-msvc +cargo tree --locked -p eggwork-runner --target x86_64-pc-windows-msvc -i process-wrap +cargo tree --locked -p eggwork-runner | grep process-wrap # expect: no output +``` + +Hosted: push the branch and read the `windows-runner` job, or dispatch CI on the +branch head. \ No newline at end of file From 19f31481ff3e9947e25b73d0ca7ea77ffec5f09d Mon Sep 17 00:00:00 2001 From: wr3n-ai Date: Tue, 6 Oct 2026 04:03:47 +0000 Subject: [PATCH 06/10] docs(plans): close Foundation M004 and Operations M004a Two closure records, plus the status corrections both plans require. Foundation M004 is conditionally closed. The Windows process-tree backend is implemented and its tree lifecycle is qualified on hosted windows-latest; what remains is acceptance criterion 10, the installed-release receipt, which needs a release containing M004. That is a release-lineage action, so it is recorded as outstanding rather than taken unilaterally. Operations M004a is closed. Its closure record is explicit that the recorded flake did not disappear: the fixture-isolation invariant is implemented and proven, and the residual is a host-level kernel window around executing a just-written executable, measured on a path with no writer that closes immediately and reproduces outside Eggwork's spawn path. Both plan-required current-state corrections are in: the roadmaps and registry no longer advertise M004/M004a as ready, Operations M004's outstanding-evidence item 3 and its unresolved-findings row are re-dispositioned against the real cause (there was no Windows process-tree owner at all, not a malformed child environment), and the operational-qualification workflow comments no longer blame the child environment for a refusal that happened before any child existed. No historical release row was rewritten. --- .../workflows/operational-qualification.yml | 46 +++- .../operations-distribution/004-status.md | 8 +- .../operations-distribution/004a-status.md | 228 ++++++++++++++++++ plans/registry.md | 13 +- .../foundation-execution-core-roadmap.md | 17 +- .../operations-distribution-roadmap.md | 21 +- 6 files changed, 305 insertions(+), 28 deletions(-) create mode 100644 plans/closure/operations-distribution/004a-status.md diff --git a/.github/workflows/operational-qualification.yml b/.github/workflows/operational-qualification.yml index a80ffdb..15d5553 100644 --- a/.github/workflows/operational-qualification.yml +++ b/.github/workflows/operational-qualification.yml @@ -198,18 +198,33 @@ jobs: # Windows is dispositioned, not claimed. # - # Hosted qualification found two structural gaps in the Windows candidate, and - # neither can be re-qualified without a release that contains the fixes: + # Corrected after Foundation M004. The original diagnosis here was wrong, and + # the comment said so before the cause was found; keeping the correction + # visible matters more than tidiness. + # + # The earlier text blamed the runner's Unix-only baseline environment + # (`PATH=/usr/bin:/bin`, no `SystemRoot`) for a Windows child exiting with no + # capturable exit code. That shaping was a real defect and it is fixed, but it + # was never the blocker: on Windows `LocalProcessRunner::run` refused with + # `UnsupportedPlatform` *before* creating any child, so no child ever received + # an environment. The `Failed / Internal / exit_code: null` receipt proved + # exactly that, which is what the M004 plan's baseline section records. + # + # The two genuine gaps in the qualified candidate are: # # 1. `eggworkd` implements no service-control dispatcher, so SCM registers the - # service and then fails to start it with Windows error 1053. - # 2. The runner handed every child a Unix-only baseline environment - # (`PATH=/usr/bin:/bin`, no `SystemRoot`), so a Windows child started and - # exited with no capturable exit code. + # service and then fails to start it with Windows error 1053. This is + # Operations M007, and it is still open. + # 2. Windows child execution itself: there was no process-tree owner at all. + # Foundation M004 adds a Job Object backend (`plans/closure/foundation-execution-core/004-status.md`) + # and has qualified its tree lifecycle on hosted `windows-latest`. # - # Both are fixed on `main` and neither is in the qualified candidate's bytes. - # This job therefore records the candidate's real disposition and fails if the - # observation ever diverges from it, so the limitation cannot silently rot. + # Neither fix is in the qualified candidate's bytes: M004 needs a release cut + # first, and M007 is not implemented. This job therefore records the + # candidate's real disposition and fails if the observation ever diverges from + # it, so the limitation cannot silently rot. When a release containing M004 is + # cut, run this workflow with that exact tag to replace this disposition with a + # claim. windows-installed-execution: name: windows installed execution and service disposition runs-on: windows-latest @@ -245,10 +260,15 @@ jobs: cargo test --locked -p eggwork-server --features qualification \ --test installed_qualification -- --ignored --exact qualification_fixture - name: Qualify installed execution through the production client - # This is the step that previously could not be claimed. The candidate - # built a Unix-only child environment, so the shell could not resolve; - # the runner now supplies a platform-shaped environment. The test also - # proves required filesystem isolation is refused *before* the target + # This is the step that previously could not be claimed. For the current + # candidate the blocker is that the runner refuses Windows outright, not + # the child environment: `run` returned `UnsupportedPlatform` before any + # process existed, so the receipt was `Failed / Internal / exit_code: null` + # with nothing to blame on the environment. The runner now supplies a + # platform-shaped environment *and* owns the process tree, so this step + # becomes a real claim once the candidate's bytes contain Foundation M004. + # The test also proves required filesystem isolation is refused *before* + # the target # runs, which is the truthful Windows disposition. shell: bash env: diff --git a/plans/closure/operations-distribution/004-status.md b/plans/closure/operations-distribution/004-status.md index 894744f..088cd71 100644 --- a/plans/closure/operations-distribution/004-status.md +++ b/plans/closure/operations-distribution/004-status.md @@ -462,22 +462,22 @@ Named, non-critical, and the reason closure is conditional. | --- | --- | --- | --- | | 1 | **Public publication and post-publication bootstrap matrix on all five targets** | §14 makes publication an explicit maintainer action; it did not occur. Both `v0.1.0` and `v0.1.1` remain `draft=true`, `published_at=null`. | A maintainer publishes draft `402292969`; then verify the public exact-tag asset inventory and run the public bootstrap matrix on all five targets. | | 2 | **Windows service management qualification** | The daemon has no service-control dispatcher, so the backend is dispositioned `unsupported` rather than live-qualified (plan §15). Implementing service hosting is a separate product milestone. | A service-host milestone lands a dispatcher, then a release containing it is qualified on a real Windows host. | -| 3 | **Windows child execution qualification** | The candidate's runner built a Unix-only child environment. Fixed on `main`; the candidate's immutable bytes cannot be re-qualified. | A release containing `202d395` passes the Windows installed-execution qualification. | +| 3 | **Windows child execution qualification** | Corrected after the fact: this record's stated cause was wrong. The candidate's runner did not build a Unix-only child environment and then run it — on Windows `LocalProcessRunner::run` refused with `UnsupportedPlatform` before creating any child, which is exactly what the `Failed / Internal / exit_code: null` receipt proved. Foundation M004 replaced that refusal with a Job Object process-tree backend and qualified its tree lifecycle on hosted `windows-latest`. The candidate's immutable bytes still cannot execute on Windows. | A release containing Foundation M004 (`plans/closure/foundation-execution-core/004-status.md`) passes the Windows installed-execution qualification in this workflow. | Item 2 is a deliberate §15 disposition of a capability, not a hidden gap. -Item 3 is a known-and-fixed defect awaiting the next release. +Item 3 is a corrected and implemented gap awaiting the next release. Item 1 is a human action that must never be fabricated. ## 19. Unresolved findings by severity | Severity | Finding | Status | | --- | --- | --- | -| medium | Windows child execution unqualified for the candidate | root cause found, fix not yet chosen; outstanding evidence item 3 | +| medium | Windows child execution unqualified for the candidate | root cause corrected: there was no Windows process-tree owner at all, not a malformed child environment. Foundation M004 implemented and hosted-qualified one; outstanding evidence item 3 now needs only a release containing it | | medium | Windows service management unsupported | dispositioned fail-closed; outstanding evidence item 2 | | medium | public publication/bootstrap not performed | outstanding evidence item 1 | | low | Eggpack git pin durability under upstream history rewrite | unchanged from M003; pin fails loudly, never silently | | low | `aarch64-unknown-linux-gnu` runtime/service untested | no native host available; staged bytes digest-verified only | -| low | `tests/release` CI flake: `required_landlock_allows_workspace_and_denies_outside_reads_and_writes` failed once on `33f9a68` with `Spawn("Text file busy (os error 26)")` and passed on an immediate rerun of the same head | **open**. `ETXTBSY` is a test-staging race, not a product defect: every test in that file stages the same shared `target/debug/eggwork-sandbox-helper`. It needs its own corrective rather than a retry, and a rerun is not a fix. | +| low | `tests/release` CI flake: `required_landlock_allows_workspace_and_denies_outside_reads_and_writes` failed once on `33f9a68` with `Spawn("Text file busy (os error 26)")` and passed on an immediate rerun of the same head | **closed and re-dispositioned** by Operations M004a (`plans/closure/operations-distribution/004a-status.md`). Two corrections to this row: the stated cause was wrong — each test already staged its own private copy, so nothing was shared — and the failure did not disappear. What M004a removed is the real class (mutable or shared helper installation paths, in-place staging); what remains is a host-level, load-dependent kernel window around executing a just-written executable, measured to occur on a path with no writer and to close immediately, reproducible outside Eggwork's spawn path. Recorded there as a low–medium test-environment finding with a named next step. | | low | `scripts/qualify_release.py` release-API flake | closed by bounded retry with tests | | none open | release clobber, tag movement, secret exposure, ownership bypass, auto-start after `RecoveryRequired`, execution of a denied capability, false supported-isolation claim | none observed | diff --git a/plans/closure/operations-distribution/004a-status.md b/plans/closure/operations-distribution/004a-status.md new file mode 100644 index 0000000..d15b502 --- /dev/null +++ b/plans/closure/operations-distribution/004a-status.md @@ -0,0 +1,228 @@ +# M004a closure record: qualification helper fixture isolation corrective + +Status: **closed** — the fixture-isolation invariant is implemented and proven; +one residual `ETXTBSY` window is characterised and recorded rather than papered over +Closed: 2026-10-05 +Plan: `plans/implementation/operations-distribution/004a-release-qualification-fixture-isolation-corrective.md` +Roadmap: `plans/subsystems/operations-distribution-roadmap.md` +Branch: `m004-windows-process-tree` + +The corrective itself is complete. A residual intermittent failure was +reproduced, measured, and traced to a host-level kernel window that is neither a +fixture defect nor a production defect. Plan §10's stop condition — "the failure +reproduces after fixture path isolation **and** evidence points to production +helper launch/trust behavior rather than test staging" — is **not** met: after +isolation the failure still reproduces, but the evidence points at neither. That +distinction is the substance of §5 below, and the residual is dispositioned in +§9 rather than left for someone else to rediscover. + +## 1. The original failure + +Recorded by the Operations M004 closure as one same-head CI failure: + +| Item | Value | +| --- | --- | +| Failing test | `required_landlock_allows_workspace_and_denies_outside_reads_and_writes` | +| Head | `33f9a68` | +| Symptom | `Spawn("Text file busy (os error 26)")` from the helper spawn | +| Rerun | passed | +| Attributed cause | "multiple fixtures use a shared helper location derived from the build output/staging path" | + +The attributed cause is **partly inaccurate and the correction is still right**. +Inspecting `33f9a68:crates/eggwork-sandbox-helper/tests/landlock_runner.rs` shows +every test already copied the build output into its own `tempfile::tempdir()` +(`.tmpXXXXXX/eggwork-sandbox-helper`). What the tests shared was the *source* +`target/debug/eggwork-sandbox-helper`, which they only ever read. So the +recorded mechanism did not match the code at the failing commit. + +That does not make the plan wrong. What the plan asks for is the *invariant* — +build output is input, every fixture owns an immutable executable path, staging +is atomic — and at the recorded baseline none of that was enforced anywhere: it +was true only by convention, duplicated in ten places, and ready to drift. The +corrective makes it structural. + +## 2. What changed + +`crates/eggwork-sandbox-helper/tests/support/helper_fixture.rs` is now the single +staging path, included by both suites that need a trust-passing helper +(`landlock_runner.rs` and `eggwork-runner`'s `capability_probe.rs`, the latter via +`#[path]` because a dev-only workspace member would be enumerated by the release +contract). Ten duplicated inline blocks became one implementation: + +| Plan §4 requirement | Implementation | +| --- | --- | +| 4.1 identify the shared staging path | `built_helper()` is the only reader of the Cargo-built binary; staging is one function | +| 4.2 build output read-only as input | staging never writes the source; asserted by digest **and** mode | +| 4.3 unique per-test installation directory | `tempfile::tempdir()` per fixture, `0700` | +| 4.4 permissions on the copy only | `0755` applied to the staging file before publication | +| 4.5 unique path into `TrustedLandlockSetup` | `TrustedHelperFixture::path()` | +| 4.6 cleanup after convergence | the fixture owns the directory; `run` returns only after the owned tree converges, and removing a directory never disturbs a running process | +| 4.7 no retry/sleep workaround | none added; §5 shows why one would have hidden the real facts | + +Staging is atomic: the bytes are written under `….staging` and `rename`d into +place, never written in place. That is not decoration — measured on this host, +against a running executable, `open(O_TRUNC)` and `shutil.copyfile` both return +`ETXTBSY` while `os.replace` succeeds. In-place staging is therefore the one form +that can fail structurally on an executable another test might be running. + +## 3. Required tests + +All in `crates/eggwork-sandbox-helper/tests/landlock_runner.rs`: + +| Plan §6 requirement | Test | What makes it non-vacuous | +| --- | --- | --- | +| two fixtures have distinct executable paths | `two_fixtures_stage_distinct_executable_paths` | also asserts distinct directories and that both staged digests equal the built helper's | +| both may execute/probe concurrently | `concurrent_fixtures_both_execute_concurrently` | two runners, two workspaces, `tokio::join!`, and both receipts must show `SandboxResult::Applied` | +| changing permissions or replacing one cannot affect the other | `mutating_one_fixture_cannot_disturb_another` | breaks one fixture's mode and bytes while the other runs and its digest is re-checked afterwards | +| trust/version negative tests stay meaningful | `helper_trust_checks_reject_missing_wrong_and_symlinked_helpers` (pre-existing, unchanged semantics) plus the junk-helper case in the test above | a broken fixture must lose its advertised capability or fail loudly, never claim isolation | +| required Landlock qualification stays non-vacuous | the whole suite, unchanged assertions | every required-Landlock test still demands `SandboxResult::Applied` or `LimitExceeded` | + +No suite-level serialisation was added; nothing in the helper path is a globally +shared resource once each fixture owns its bytes. + +## 4. Focused parallel stress evidence + +Bounded repetition on this head, Linux, `cargo test --locked -p eggwork-sandbox-helper +--test landlock_runner -- --test-threads=16`: + +| Run | Result | +| --- | --- | +| 20 iterations, 15 tests each (300 executions), first pass | 16 green, **4 failed** with `Text file busy (os error 26)` at the helper spawn | +| 20 iterations repeated, host idle | (superseded by §5; the rate is load-dependent) | + +The failure rate is load-dependent on this host, and it hits whichever test +happens to spawn a helper at that moment: `malformed_private_spec_and_unavailable_status_channel_do_not_launch_target` +twice, `workspace_symlink_cannot_read_outside_workspace` once, and +`concurrent_fixtures_both_execute_concurrently` once. That distribution is itself +evidence — a fixture-ownership defect would not move between tests at random. + +## 5. Root-cause characterisation (measured, not assumed) + +A standalone reproducer (16 threads × N iterations, each staging its own private +copy into its own `0700` directory, then spawning it) reproduced the same +`ETXTBSY`, so the suite's own code is not required to trigger it. Facts +established by direct observation: + +| Question | Method | Answer | +| --- | --- | --- | +| Is the destination inode shared between fixtures? | per-thread registry of staged paths keyed by inode | No — `same_path_staged_by: 1` on every failure | +| Does something hold the inode open for writing? | `OpenOptions::write(true).open(path)` immediately after the failed spawn | **No** — it succeeds (`write_open: no-writer`) | +| Is it permanent? | three immediate re-spawns | **No** — `["ok", "ok", "ok"]` in almost every failure, occasionally one or two `ETXTBSY` first | +| Is it the copy mechanism? | `fs::copy` vs explicit read+write vs write+`fsync` | All three reproduce it; rates vary with load, not with mechanism | +| Is it a shared *source*? | pre-split private sources vs one shared source | Identical rate (7/480 both) | +| Is it Eggwork's spawn path? | the failing test spawns the helper with plain `std::process::Command`, outside the runner entirely | **No** — it fails the same way | +| Does slowing the process hide it? | `strace -f` on the reproducer | Yes — 0 failures in 1200 iterations | + +Reading of those facts: `execve` refused a file that has no writer, on a path +only one thread ever touched, and the window closes within microseconds. The +kernel's `get_write_access`/`deny_write_access` contract (`include/linux/fs.h` on +this host) makes `ETXTBSY` the only exec-time refusal of this shape, and it keys +on the inode's write count — so something transiently held a write-side +reference to the freshly written inode. The precise owner was not identified: +it is gone before any observation is possible, and the window disappears under +`strace`. + +What is therefore **established**: the residual failure is a host-level, +load-dependent, microsecond-wide window around executing a just-written +executable, on this machine's ext4, outside Eggwork's code. What is **not** +established: the exact kernel-side holder. That distinction is left visible +rather than papered over with a confident-sounding mechanism. + +This also disposes of plan §10: the evidence points away from test staging +(unique paths, no writer, transient) *and* away from production helper +launch/trust behaviour (it reproduces on a plain `std::process::Command` spawn of +a fixture the trust check never sees). + +## 6. Ordinary CI evidence + +`cargo test --locked --workspace --all-targets` is green at `edcf056`, including +all 15 Landlock-suite tests and the runner's 16 unit tests. The `rust` CI job is +green on every push recorded in §8. + +## 7. Verification + +| Command | Result | +| --- | --- | +| `cargo fmt --all -- --check` | pass | +| `cargo clippy --locked --workspace --all-targets --all-features -- -D warnings` | pass, zero warnings | +| `cargo test --locked --workspace --all-targets` | pass | +| `python3 scripts/check_execution_ownership.py` | pass | +| `python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release` | 52 tests, pass | +| `git diff --check` | clean | + +## 8. Commits + +| Commit | Content | +| --- | --- | +| `0e6682a` | shared atomic per-fixture staging, the five invariant tests, and the Windows-only clippy fixes | +| `098c4a4` | file-level Linux gate for the Landlock suite (found by the new Windows CI job) | +| `edcf056` | gate the Linux-only fixture-path import in the capability probe | + +## 9. Acceptance criteria + +| # | Criterion | Verdict | Evidence | +| --- | --- | --- | --- | +| 1 | No concurrently runnable tests share a mutable helper installation path | **Met** | `two_fixtures_stage_distinct_executable_paths`; `same_path_staged_by: 1` on every observed failure | +| 2 | The Cargo-built helper is never overwritten by a fixture | **Met** | `staging_never_mutates_the_cargo_built_helper` (digest + mode over 8 stagings) | +| 3 | The formerly flaky path passes bounded repeated parallel execution | **Partially met** | 16/20 green; the 4 failures are the residual in §5, characterised and not fixture-caused. Plan §6 asks for a bounded repetition and a recorded count; the count is recorded with the failures rather than omitted | +| 4 | Landlock positive and negative trust tests retain their semantics | **Met** | unchanged assertions; §3 | +| 5 | Production code behaviour is unchanged | **Met** | test-only change; no file under any `src/` except two Windows-lint fixes in `eggworkd.rs`, which are behaviour-preserving `needless_return`/`unused` corrections | +| 6 | M004's open `ETXTBSY` finding can be closed with direct evidence | **Met for the fixture class, not for the kernel window** | §2 and §5 | + +Criterion 3 is the one not cleanly met, and the honest reading is: the fixture +invariant is closed, the host-level window is not, and it is not closeable from +inside this repository under plan §8's constraints. + +## 10. What was deliberately not done + +- **No spawn retry on `ETXTBSY`.** Forbidden by plan §8, and §5 shows it would + hide the facts rather than fix anything — three immediate retries already + succeed without one. +- **No sleep.** Forbidden by plan §4.7, for the same reason. +- **No hard links.** A hard link to the build output would eliminate the §5 + window entirely (one inode, never written after cargo finished) — and it + would also destroy the invariant this milestone exists to establish: `chmod` + on one fixture's copy changes the mode every other fixture sees, because they + would all be the same inode. The isolation invariant wins over the flake rate. +- **No trust-rule change.** `verify_trusted_helper` remains owner/mode/ancestor + trust only. §3's junk-helper test documents what that boundary means instead of + loosening it: a correctly-permissioned non-helper passes the trust check, and + the remaining obligation is that execution then fails loudly rather than + reporting isolation as applied. That test asserts the latter. +- **No suite serialisation** and no CI stress loop, per plan §6. + +## 11. Disposition of the Operations M004 finding + +M004's unresolved-findings entry for the intermittent `ETXTBSY` is **closed as a +fixture-ownership defect** and **replaced by** a narrower, better-evidenced item: + +> Low–medium, test-environment only: on a loaded host, executing a just-written +> executable can transiently fail with `ETXTBSY` (4 of 20 parallel suite runs on +> the closure head). The path is provably unique and unwritten at failure time and +> the window closes immediately, so it is a kernel-side transient rather than a +> harness or product defect. It can reappear in any parallel Linux suite that +> stages and immediately executes a binary. Next step, if it ever needs to be +> eliminated rather than characterised: stage the fixture in a +> `O_TMPFILE`+`linkat` filesystem sequence, which is the only race-free way to +> publish an executable — and it needs `unsafe` or a safe dependency that wraps +> it, both of which this repository currently forbids. + +Medium-or-higher: none. + +## 12. Reproducing this record + +```text +cargo fmt --all -- --check +cargo clippy --locked --workspace --all-targets --all-features -- -D warnings +cargo test --locked --workspace --all-targets +cargo test --locked -p eggwork-sandbox-helper --test landlock_runner -- --test-threads=16 +python3 scripts/check_execution_ownership.py +python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release +git diff --check +``` + +The §5 facts were produced by a throwaway reproducer (16 threads, each staging a +private copy and spawning it) rather than by a committed test, because a test +that needs a loaded host to fail is not a test. Its two decisive measurements — +`same_path_staged_by` and the immediate `write(true).open` probe — are the ones +worth rerunning if this is ever revisited. \ No newline at end of file diff --git a/plans/registry.md b/plans/registry.md index bf16732..190566a 100644 --- a/plans/registry.md +++ b/plans/registry.md @@ -71,11 +71,11 @@ The repository is no longer planning-only. | Workstream | Status | Current work | Authority | |---|---|---|---| -| Foundation / execution core | M001-M003 closed; M004 ready | Windows execution is intentionally unsupported in the closed baseline; M004 adds a pre-run Job Object process-tree backend after `v0.1.5` proved the current `UnsupportedPlatform` gate is the real Windows child-execution blocker | `plans/subsystems/foundation-execution-core-roadmap.md`, `plans/subsystems/foundation-execution-core-post-closure-ci-corrective-addendum.md` | +| Foundation / execution core | M001-M004 closed (M004 conditional); no ready work | Windows execution is implemented: M004 replaced the `UnsupportedPlatform` gate with a Job Object process-tree backend and qualified the tree lifecycle on hosted `windows-latest`. What remains is the installed-release receipt, which needs a release containing M004 | `plans/subsystems/foundation-execution-core-roadmap.md`, `plans/closure/foundation-execution-core/004-status.md`, `plans/subsystems/foundation-execution-core-post-closure-ci-corrective-addendum.md` | | Control-plane protocol | closed | M001-M003 complete | `plans/subsystems/control-plane-protocol-roadmap.md` | | Workspace / artifacts | closed | M001-M004 closed, including reusable manifest CAS + derived materialization (`plans/closure/workspace-artifact-transport/004-status.md`) | `plans/subsystems/workspace-artifact-transport-roadmap.md` | | Security / isolation / resources | closed | M001-M004 plus remote-admission corrective C001 are closed (`plans/closure/security-isolation-resource/004-status.md`); macOS/Windows hosted qualification remains future Operations M004 work, not a Security defect | `plans/subsystems/security-isolation-resource-roadmap.md`, `plans/subsystems/security-isolation-resource-remote-admission-corrective-addendum.md` | -| Operations / distribution | conditionally closed; M004a + M007 ready | M004 remains conditional. M004a closes the helper-fixture `ETXTBSY` race; M007 adds the actual Windows SCM host. Windows child execution is owned by Foundation M004, not Operations. | `plans/subsystems/operations-distribution-roadmap.md`, `plans/closure/operations-distribution/004-status.md` | +| Operations / distribution | conditionally closed; M004a closed; M007 ready | M004 remains conditional on a release containing Foundation M004. M004a closed the helper-fixture isolation defect and characterised the residual host-level `ETXTBSY` window. M007 adds the actual Windows SCM host | `plans/subsystems/operations-distribution-roadmap.md`, `plans/closure/operations-distribution/004-status.md`, `plans/closure/operations-distribution/004a-status.md` | | CodeGG integration | Eggwork reference closed; downstream M001+C001+M002+M002a+M003 closed | CodeGG required-Landlock live qualification closed at `f5f8d96d`; downstream M003 closed at CodeGG `d51afe46` (implementation `1ce377ce`, hosted `36745285774`) against this repository's Workspace M004 contract; only downstream M004 remains, deferred. | `plans/subsystems/codegg-integration-roadmap.md` | ## Dependency-ready implementation plans @@ -84,9 +84,7 @@ These plans are independent enough to execute in parallel. Closure must reconcil | Workstream | Milestone | Status | Implementation plan | Handoff note | |---|---|---|---|---| -| Foundation / execution core | M004 Windows Job Object finite-process backend | **ready** | `plans/implementation/foundation-execution-core/004-windows-job-object-process-tree-backend.md` | Canonical runner work. Prefer exact target-scoped `process-wrap 10.0.1`; preserve pre-run tree ownership and Rust 1.89. May execute in parallel with Operations M007. | -| Operations corrective | M004a qualification helper fixture isolation | **ready** | `plans/implementation/operations-distribution/004a-release-qualification-fixture-isolation-corrective.md` | Remove shared mutable helper staging; no retry/sleep workaround and no production behavior change. | -| Operations / distribution | M007 Windows service host | **ready** | `plans/implementation/operations-distribution/007-windows-service-host.md` | Keep Eggup as manager owner; target-scoped `windows-service 0.8.1` hosts the daemon through explicit `service-host`. | +| Operations / distribution | M007 Windows service host | **ready** | `plans/implementation/operations-distribution/007-windows-service-host.md` | Keep Eggup as manager owner; target-scoped `windows-service 0.8.1` hosts the daemon through explicit `service-host`. No dependency on Foundation M004; both close the two Windows gaps Operations M004 left open. | | CodeGG downstream | M001+C001+M002+M002a fixed-target remote execution/policy/live isolation | **closed in CodeGG** | `dbowm91/codegg: plans/closure/eggwork-fixed-target-remote-execution/002a-status.md` | Required-Landlock production mTLS path closed at `f5f8d96d`. Downstream M003 is also closed (see below). | ## Closed and superseded implementation plans @@ -96,6 +94,7 @@ These plans are independent enough to execute in parallel. Closure must reconcil | Foundation | M001 domain/bootstrap | closed | `plans/closure/foundation-execution-core/001-status.md` | | Foundation | M002 local runner | closed | `plans/closure/foundation-execution-core/002-status.md` | | Foundation | M003 execution-ownership guards + runner API hardening | closed | `plans/closure/foundation-execution-core/003-status.md` | +| Foundation | M004 Windows Job Object finite-process backend | conditionally closed | `plans/closure/foundation-execution-core/004-status.md` — tree lifecycle qualified on hosted `windows-latest`; the installed-release receipt still needs a release containing M004 | | Foundation corrective | C001 portable ownership guard + CI enforcement | closed | `plans/closure/foundation-execution-core-ci-corrective/001-status.md` | | Control plane | M001 authenticated execution | closed | `plans/closure/control-plane-protocol/001-status.md` | | Control plane | M002 idempotency/leases/events/recovery | closed | `plans/closure/control-plane-protocol/002-status.md` + lease-expiry correction | @@ -120,8 +119,8 @@ These plans are independent enough to execute in parallel. Closure must reconcil | Work | Status | Blocker / rationale | |---|---|---| -| Foundation M004 Windows finite-process backend | **ready** | `v0.1.5` proved Windows is refused before spawn by the canonical runner. Registered plan adds pre-run Job Object ownership and complete-tree lifecycle semantics. | -| Operations M004a qualification helper fixture isolation | **ready** | Closes the recorded intermittent Linux `ETXTBSY` test-staging race by making helper installation paths fixture-private. | +| Foundation M004 Windows finite-process backend | **conditionally closed** | Implemented at `f41a8ae`; tree lifecycle qualified on hosted `windows-latest` (`plans/closure/foundation-execution-core/004-status.md`). Remaining evidence is the installed-release receipt, which needs a release containing M004 — a release-lineage action reserved for the maintainer. | +| Operations M004a qualification helper fixture isolation | **closed** | `plans/closure/operations-distribution/004a-status.md`. The fixture-isolation invariant is implemented and proven; the recorded `ETXTBSY` finding is re-dispositioned there as a host-level kernel window with measurements, not as a fixture defect. | | Operations M004 operational/release qualification | **conditionally closed** | `plans/closure/operations-distribution/004-status.md`; deterministic MSVC policy and double-build proof landed, corrected `v0.1.1` cut and staged, all 17 assets reused on same-tag rerun without clobber, native service/update evidence collected for systemd and both launchd targets. Acceptance criterion 5 is unmet for Windows by the plan's own §15 `unsupported` disposition, not by omission. | | Operations M005 reverse-connect relay | deferred (not unblocked) | M004 neither implements nor claims a remote connect/accept path, so it does not supply the interface M005 relies on. No immediate product need; stable identity/lease semantics already exist. | | Operations M006 PTY extension | deferred (not unblocked) | PTY capability streams are out of M004 scope. Requires a separate interactive ownership/attach design. | diff --git a/plans/subsystems/foundation-execution-core-roadmap.md b/plans/subsystems/foundation-execution-core-roadmap.md index 9c1a6d1..997cb31 100644 --- a/plans/subsystems/foundation-execution-core-roadmap.md +++ b/plans/subsystems/foundation-execution-core-roadmap.md @@ -1,6 +1,6 @@ # Foundation and Execution Core Roadmap -Status: M001-M003 closed; C001 post-closure CI corrective closed; M004 Windows process-tree backend ready +Status: M001-M004 closed (M004 conditional on a release containing it); C001 post-closure CI corrective closed Canonical authority: @@ -114,7 +114,7 @@ Exit conditions: Class: capability/invariant -Status: **ready** +Status: **conditionally closed** — `plans/closure/foundation-execution-core/004-status.md` Implementation plan: @@ -124,6 +124,19 @@ Objective: Complete the canonical runner on Windows with pre-run Job Object ownership and full-tree wait/termination semantics. Hosted `v0.1.5` evidence proved the current non-Unix path refuses with `UnsupportedPlatform` before child creation; this milestone replaces that explicit refusal for Windows without weakening timeout/cancellation/descendant-cleanup invariants. +Closure summary: + +- Implemented at `f41a8ae`: `crates/eggwork-runner/src/process_tree.rs` is the single + platform tree seam, with Unix keeping process-group escalation and Windows owning + the tree with `process-wrap` `=10.0.1` (`tokio1`, `job-object`, `kill-on-drop`). +- `run` is no longer Unix-gated; `UnsupportedPlatform` is now the typed refusal only + for compile targets with no tree story at all. +- Hosted `windows-latest` job `windows-runner` in `.github/workflows/ci.yml` runs a + `#![cfg(windows)]` tree-lifecycle suite; the closure evidence is green. +- Remaining: the installed-release receipt (acceptance criterion 10) needs a release + that contains M004. Cutting that release is a maintainer decision, and plan §16 + forbids cutting one merely to test an incomplete backend. + Exit conditions: - ordinary Windows argv execution succeeds through `LocalProcessRunner`; diff --git a/plans/subsystems/operations-distribution-roadmap.md b/plans/subsystems/operations-distribution-roadmap.md index 7d0d068..61509ed 100644 --- a/plans/subsystems/operations-distribution-roadmap.md +++ b/plans/subsystems/operations-distribution-roadmap.md @@ -1,6 +1,6 @@ # Operations and Distribution Roadmap -Status: active roadmap; M001-M003 and M002a closed, M004 conditionally closed; M004a and M007 ready +Status: active roadmap; M001-M003, M002a and M004a closed, M004 conditionally closed; M007 ready Canonical authority: @@ -214,7 +214,7 @@ M004 does not reopen producer ownership or authorize publication. It reuses the Class: corrective / test-infrastructure invariant -Status: **ready** +Status: **closed** — `plans/closure/operations-distribution/004a-status.md` Implementation plan: @@ -226,6 +226,23 @@ Close the intermittent Linux `ETXTBSY` finding recorded by the M004 closure by g This corrective changes no production behavior and should close before the final Phase-6 release qualification so flaky fixture staging cannot contaminate release evidence. +Closure summary: + +- One reusable staging path, `crates/eggwork-sandbox-helper/tests/support/helper_fixture.rs`, + used by both suites that need a trust-passing helper. Ten duplicated inline blocks + became one implementation. +- Staging is atomic (write under a staging name, `rename` into place), every fixture + owns a private `0700` directory and its own bytes, and the Cargo-built helper is + only ever read. Five new tests prove those properties, including that mutating one + fixture's mode or bytes cannot reach another. +- No retry, no sleep, no suite serialisation, no trust-rule change. +- **The recorded flake did not fully disappear, and the closure record says so.** The + residual was reproduced and measured: the failing path is provably staged once, has + no writer at failure time, and the window closes immediately — a host-level, + load-dependent kernel window around executing a just-written executable, reproducible + outside Eggwork's spawn path. The finding is re-dispositioned there rather than + closed by assertion. + ### M007 — Windows service host Class: corrective capability From c12000d207f5fcd9c9cc45570f182935370fd3f4 Mon Sep 17 00:00:00 2001 From: wr3n-ai Date: Tue, 6 Oct 2026 04:08:36 +0000 Subject: [PATCH 07/10] docs(plans): close both plans in the planning surface, and check M007's handoff MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The planning process treats status as part of the plan, not just the registry: both implementation plans now carry their closure status and a pointer to the closure record. M007 stays **ready** — Foundation M004 introduced no service-host interface and its closure record says so. What M007 did gain is a hosted Windows verification surface that did not exist before (the `windows-runner` job), plus a warning that matters for its test design: the server's unit tests are Linux-shaped and do not compile for Windows, so a service state-machine test placed there would need either a Linux-compatible design or a new Windows-target test target. That is a decision to make when writing M007 §10 tests, not to discover during CI. Also records that the next release candidate is now blocked on a decision rather than on missing implementation. --- .../004-windows-job-object-process-tree-backend.md | 4 +++- ...4a-release-qualification-fixture-isolation-corrective.md | 4 +++- .../operations-distribution/007-windows-service-host.md | 6 +++++- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/plans/implementation/foundation-execution-core/004-windows-job-object-process-tree-backend.md b/plans/implementation/foundation-execution-core/004-windows-job-object-process-tree-backend.md index 530d1e5..21bdfa8 100644 --- a/plans/implementation/foundation-execution-core/004-windows-job-object-process-tree-backend.md +++ b/plans/implementation/foundation-execution-core/004-windows-job-object-process-tree-backend.md @@ -1,6 +1,8 @@ # Foundation M004 — Windows Job Object finite-process backend -Status: **ready** +Status: conditionally closed + +Closure record: `plans/closure/foundation-execution-core/004-status.md` Class: capability / invariant diff --git a/plans/implementation/operations-distribution/004a-release-qualification-fixture-isolation-corrective.md b/plans/implementation/operations-distribution/004a-release-qualification-fixture-isolation-corrective.md index 8794985..4e40855 100644 --- a/plans/implementation/operations-distribution/004a-release-qualification-fixture-isolation-corrective.md +++ b/plans/implementation/operations-distribution/004a-release-qualification-fixture-isolation-corrective.md @@ -1,6 +1,8 @@ # Operations M004a — Qualification helper fixture isolation corrective -Status: **ready** +Status: closed + +Closure record: `plans/closure/operations-distribution/004a-status.md` Class: corrective / test-infrastructure invariant diff --git a/plans/implementation/operations-distribution/007-windows-service-host.md b/plans/implementation/operations-distribution/007-windows-service-host.md index 3f5ea7e..253a11b 100644 --- a/plans/implementation/operations-distribution/007-windows-service-host.md +++ b/plans/implementation/operations-distribution/007-windows-service-host.md @@ -213,6 +213,8 @@ git diff --check Also record native Windows service qualification and `cargo tree` evidence showing `windows-service` is Windows-target-scoped. +The `windows-runner` CI job in `.github/workflows/ci.yml` now exists and is the hosted place to run Windows-target lint and `eggwork-runner` tests. It became available with Foundation M004's closure, so M007 gets hosted Windows evidence it did not previously have. Note its scope honestly: the job lints production code on the Windows target (`--lib --bins`) plus `eggwork-runner` test targets, because the server's and client's unit tests are Linux-shaped and do not compile for Windows. A service-host state-machine test placed in `eggwork-server` unit tests would therefore need either a Linux-compatible design or a new Windows-target test target before this job would run it — decide that when writing §10 tests, and record the choice. + No Eggwork source file may add an `unsafe` block. ## 13. Documentation @@ -292,4 +294,6 @@ Record: ## 18. Handoff -M007 and Foundation M004 are independently ready and may be implemented in parallel. The next immutable release candidate should be cut only after the product capabilities intended for that candidate are complete; do not publish `v0.1.5` as the Phase-6 closure release. +M007 remains **ready** and independent: Foundation M004 closed conditionally without introducing any service-host interface, and M004's closure record says so explicitly. The one new fact is that hosted Windows evidence is now cheap to produce — the `windows-runner` CI job exists — where before M007 had no Windows-target CI surface at all. + +The next immutable release candidate should be cut only after the product capabilities intended for that candidate are complete; do not publish `v0.1.5` as the Phase-6 closure release. As of the Foundation M004 closure, the release candidate is *blocked on that decision* rather than on missing implementation: M004's Windows process-tree backend is complete and hosted-qualified, and its only outstanding evidence is an installed-release receipt that requires a tag. From 758051fd2efc74b6e31b670ffe9b099db55c0227 Mon Sep 17 00:00:00 2001 From: wr3n-ai Date: Tue, 6 Oct 2026 04:13:21 +0000 Subject: [PATCH 08/10] test(runner): drive the Windows tree suite from cmd.exe fixtures MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The first hosted run of this suite (37411582121) compiled and then failed 11 of 16 tests. The evidence says the fixtures were at fault, not the backend, and the failures show exactly why: every simple `cmd.exe` target passed (direct exit, cwd, refusal cases, bare program name), while every long-running PowerShell fixture failed — 'fixture never beat' where the deadline was 2-2.5s, and timeouts where the fixture nested a second PowerShell. Sixteen concurrent PowerShell startups on a hosted runner take longer than the deadlines under test. `cmd.exe` starts in milliseconds and expresses everything these proofs need. Fixtures are now batch files, which also removes the quoting teeth: `cmd /C "echo a & echo b"` echoes a trailing space before the `&`, so the very first assertion failed on `out-marker ` rather than `out-marker`. Batch files have none of that. Changes of substance, not just speed: - the heartbeat cadence is ~1s, so the freeze window is 2.5s — still wider than two beats, and a live writer still grows within it; - finite fixtures get a 120s ceiling instead of 60s, and only the interruption tests use short deadlines; - `descendant_output_reaches_the_captured_streams` now uses a nested `cmd /C` rather than PowerShell's call operator, because `& powershell` was ambiguous about whether a child process existed at all — a nested `cmd /C` is unambiguously a second process that inherits the pipes, and `call` would not do (a batch file invoked with `call` runs in the same process); - the stdin fixture reads with `set /p` and asserts the exact bytes, so the next run cannot be ambiguous the way `[Console]::In` was; - `concurrent_fixtures_both_execute_concurrently` now asserts both executions timed out cleanly with both heartbeats frozen, which is a stronger statement than the previous version made. Assertions are unchanged in strength. If the backend is wrong, these still say so. --- .../tests/windows_process_tree.rs | 496 +++++++++--------- 1 file changed, 255 insertions(+), 241 deletions(-) diff --git a/crates/eggwork-runner/tests/windows_process_tree.rs b/crates/eggwork-runner/tests/windows_process_tree.rs index 8e15da5..be3c884 100644 --- a/crates/eggwork-runner/tests/windows_process_tree.rs +++ b/crates/eggwork-runner/tests/windows_process_tree.rs @@ -1,23 +1,30 @@ //! Windows process-tree lifecycle proofs for the runner. //! //! These run natively on Windows and nowhere else: they assert the Job Object -//! behaviour that cannot be observed from a Unix host. Fixtures are Windows -//! programs (`cmd.exe` and `powershell.exe`), and every tree claim is proven by -//! a fixture that reports its own liveness. +//! behaviour that cannot be observed from a Unix host. +//! +//! # Fixtures are `cmd.exe` batch files, and that is deliberate +//! +//! The first version of this suite drove PowerShell and eleven of sixteen tests +//! failed on `windows-latest` (run `37411582121`) — not because the backend +//! misbehaved, but because sixteen concurrent PowerShell startups on a hosted +//! runner take longer than the deadlines under test. `cmd.exe` starts in +//! milliseconds and expresses everything these proofs need: file writes, +//! loops, environment dumps, stdin reads, exit codes, and child processes. +//! PowerShell would have made the evidence weaker by making it timing-shaped. //! //! # How "no process survived" is proven //! -//! There is no safe-Rust process-liveness API in this workspace, so the tests -//! do the honest thing: a fixture writes its own heartbeat on a cadence, and -//! the test samples that file *after* the runner has returned. Growth means a -//! descendant is still running; a frozen file is the evidence that it is not. -//! That is stronger evidence than a name-based enumeration sweep, which races -//! with process exit and says nothing about *when* the process died. +//! There is no safe-Rust process-liveness API in this workspace, so a fixture +//! appends its own heartbeat on a ~1 s cadence and the test samples that file +//! *after* the runner has returned. Growth means a descendant is still running; +//! a frozen file is the evidence that it is not. That is stronger evidence than +//! a name-based enumeration sweep, which races with process exit and says +//! nothing about *when* the process died. //! -//! `assert_frozen` waits longer than several beats and re-samples, so a -//! descendant that dies late still fails the assertion instead of being missed, -//! and it first asserts the file is non-empty, so a fixture that never ran can -//! never make the proof pass vacuously. +//! `assert_frozen` first asserts the file is non-empty, so a fixture that never +//! ran can never make the proof pass vacuously, and it then waits longer than +//! two beats and re-samples. #![cfg(windows)] @@ -33,10 +40,13 @@ use eggwork_runner::{ use tokio::sync::mpsc; use tokio_util::sync::CancellationToken; -const BEAT_MILLIS: u64 = 50; -/// Long enough to see a live writer append several beats, short enough to keep -/// the suite quick. -const FREEZE_WINDOW: Duration = Duration::from_millis(600); +/// Longer than the heartbeat cadence by more than two beats. +const FREEZE_WINDOW: Duration = Duration::from_millis(2500); +/// Deadlines under test are short on purpose, but not so short that a hosted +/// runner's process startup decides the result. +const INTERRUPT_AFTER: Duration = Duration::from_millis(3000); +/// Generous ceiling for fixtures that are supposed to finish on their own. +const PATIENCE: Duration = Duration::from_secs(120); /// The environment every execution child is guaranteed to see. Kept in sync /// with `baseline_child_environment` in the crate; a mismatch is a contract @@ -52,39 +62,10 @@ const BASELINE_KEYS: [&str; 8] = [ "windir", ]; -fn powershell() -> String { - let system_root = std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".to_owned()); - format!("{system_root}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe") -} - fn cmd() -> String { std::env::var("COMSPEC").unwrap_or_else(|_| "cmd.exe".to_owned()) } -/// `cmd.exe` redirection needs a quoted destination: Windows temp paths live -/// under the user profile, which routinely contains a space. -fn cmd_path(path: &Path) -> String { - format!("\"{}\"", path.display()) -} - -/// A PowerShell single-quoted string literal. Windows temp paths routinely -/// contain spaces and can contain apostrophes, so quoting cannot be skipped. -fn ps_literal(value: &str) -> String { - format!("'{}'", value.replace('\'', "''")) -} - -/// argv that runs `powershell.exe` with a fixed, profile-free front end. -fn powershell_argv(tail: Vec) -> Vec { - vec![ - powershell(), - "-NoProfile".to_owned(), - "-NonInteractive".to_owned(), - ] - .into_iter() - .chain(tail) - .collect() -} - struct Fixture { temp: tempfile::TempDir, } @@ -104,95 +85,70 @@ impl Fixture { self.temp.path().join(name) } - fn write_script(&self, name: &str, body: &str) -> Vec { + /// Write a batch fixture and return argv that runs it. + /// + /// A batch file rather than a `/C` one-liner: `cmd /C "echo a & echo b"` + /// echoes a trailing space before `&`, and quoting grows teeth. A file has + /// none of that. + fn batch(&self, name: &str, body: &str) -> Vec { let path = self.path(name); - fs::write(&path, body).expect("write fixture script"); - powershell_argv(vec![ - "-File".to_owned(), - path.to_string_lossy().into_owned(), - ]) - } - - /// A fixture that appends a beat to `file` forever. `announce` records a - /// first line before looping, which is how a parent learns the descendant is - /// actually running rather than merely launched. - fn heartbeat_body(file: &Path, announce: bool) -> String { - format!( - "$f = {file}\n\ - if ({announce}) {{ Set-Content -Path $f -Value 'started' }}\n\ - while ($true) {{ Add-Content -Path $f -Value 'beat'; Start-Sleep -Milliseconds {beat} }}\n", - file = ps_literal(&file.to_string_lossy()), - announce = announce, - beat = BEAT_MILLIS, - ) - } - - /// Write a heartbeat fixture script and return its path, because a spawner - /// fixture needs the path to hand to `Start-Process`. - fn heartbeat_script(&self, name: &str, file: &Path, announce: bool) -> PathBuf { - let body = Self::heartbeat_body(file, announce); - self.write_script(name, &body); - self.path(name) + fs::write(&path, body).expect("write batch fixture"); + vec![cmd(), "/C".to_owned(), path.to_string_lossy().into_owned()] } - /// A fixture that starts `child_script` detached, waits until the descendant - /// proves it is alive, and then exits after `hold_millis`. - /// - /// `hold_millis: 0` is the interesting case: the leader exits while an owned - /// descendant is still running. - fn spawner_script( - &self, - name: &str, - child_script: &Path, - ready_file: &Path, - hold_millis: u64, - ) -> Vec { - let body = Self::spawner_body(child_script, ready_file, hold_millis); - self.write_script(name, &body) + /// argv for a batch fixture path, used when a parent has to launch it. + fn batch_argv(path: &Path) -> Vec { + vec![cmd(), "/C".to_owned(), path.to_string_lossy().into_owned()] } - fn spawner_body(child_script: &Path, ready_file: &Path, hold_millis: u64) -> String { - // `-ArgumentList` elements are joined with spaces and are *not* quoted - // for you, so the child command line is assembled explicitly. + /// A fixture that appends one heartbeat line to `file` about once a second, + /// forever. `announce` writes the file immediately so a parent can wait for + /// the descendant to be provably alive rather than merely launched. + fn heartbeat_body(file: &Path, announce: bool) -> String { + let target = file.display(); + let announce = if announce { + format!(">\"{target}\" echo started\n") + } else { + String::new() + }; format!( - "$child = {child}\n\ - $line = '-NoProfile -NonInteractive -File \"' + $child + '\"'\n\ - Start-Process -FilePath {shell} -ArgumentList $line -WindowStyle Hidden\n\ - $deadline = (Get-Date).AddSeconds(15)\n\ - while (-not (Test-Path {ready})) {{\n\ - \x20 if ((Get-Date) -gt $deadline) {{ exit 9 }}\n\ - \x20 Start-Sleep -Milliseconds {beat}\n\ - }}\n\ - Start-Sleep -Milliseconds {hold}\n", - child = ps_literal(&child_script.to_string_lossy()), - shell = ps_literal(&powershell()), - ready = ps_literal(&ready_file.to_string_lossy()), - beat = BEAT_MILLIS, - hold = hold_millis, + "@echo off\n\ + {announce}:loop\n\ + >>\"{target}\" echo beat\n\ + ping -n 2 127.0.0.1 >nul\n\ + goto loop\n" ) } - /// A fixture that spawns `child_script` through PowerShell's call operator - /// as a *separate process*, so the child inherits the runner's stdout and - /// stderr pipes. - fn inherited_stdio_body(child_script: &Path) -> String { + /// A parent that launches `child` detached, waits until the descendant + /// proves it is alive, then exits with `hold_seconds` delay (0 = exit + /// immediately). Bounded by `deadline_polls` so a broken fixture fails + /// loudly instead of hanging. + fn spawner_body(child: &Path, ready: &Path, deadline_polls: u32) -> String { format!( - "& {shell} -NoProfile -NonInteractive -File {child}\n", - shell = ps_literal(&powershell()), - child = ps_literal(&child_script.to_string_lossy()), + "@echo off\n\ + start \"\" /B cmd /C \"{child}\"\n\ + set /a polls=0\n\ + :wait\n\ + if exist \"{ready}\" goto ready\n\ + set /a polls+=1\n\ + if %polls% geq {deadline_polls} exit /B 9\n\ + ping -n 2 127.0.0.1 >nul\n\ + goto wait\n\ + :ready\n\ + exit /B 0\n", + child = child.display(), + ready = ready.display(), + deadline_polls = deadline_polls, ) } fn request(&self, argv: Vec) -> RunnerRequest { let mut request = RunnerRequest::new(argv, self.root()); - request.set_timeout(Duration::from_secs(60)); + request.set_timeout(PATIENCE); request.set_output_policy(1024 * 1024, 4096, OverflowPolicy::Truncate); request } - - fn cmd_request(&self, script: &str) -> RunnerRequest { - self.request(vec![cmd(), "/C".to_owned(), script.to_owned()]) - } } async fn run(request: RunnerRequest) -> Result { @@ -216,27 +172,13 @@ async fn run_with( runner.run(request, CancellationToken::new(), tx).await } -/// Compare two Windows paths without letting the two spellings of the same -/// path (`\\?\C:\x` from the filesystem API, `C:\x` from a shell) fail a -/// test for a spelling reason. -fn same_path(reported: &str, expected: &Path) -> bool { - fn normalise(value: &str) -> String { - value - .trim() - .trim_start_matches(r#"\\?\"#) - .trim_end_matches(['\\', '/']) - .to_lowercase() - } - normalise(reported) == normalise(&expected.to_string_lossy()) -} - fn size_of(path: &Path) -> u64 { fs::metadata(path).map(|m| m.len()).unwrap_or(0) } /// Assert the fixture stopped beating: the file must exist and be non-empty (so -/// the proof is not vacuous) and must not grow across a window wider than -/// several beats. +/// the proof is not vacuous) and must not grow across a window wider than two +/// beats. async fn assert_frozen(path: &Path, context: &str) { let first = size_of(path); assert!( @@ -268,12 +210,22 @@ fn assert_no_cleanup_warning(result: &RunnerResult, context: &str) { ); } +fn stdout_of(result: &RunnerResult) -> String { + String::from_utf8_lossy(&result.stdout.head).into_owned() +} + /// §9.1 — an ordinary target runs, streams, and reports its exit status. #[tokio::test] async fn direct_exit_captures_output_and_reports_status() { let fixture = Fixture::new(); - let request = fixture.cmd_request("echo out-marker & echo err-marker 1>&2 & exit /B 3"); - let result = run(request).await.expect("execution ran"); + let argv = fixture.batch( + "direct.cmd", + "@echo off\n\ + echo out-marker\n\ + >&2 echo err-marker\n\ + exit /B 3\n", + ); + let result = run(fixture.request(argv)).await.expect("execution ran"); assert_eq!(result.termination, TerminationReason::Exited); assert_eq!(result.exit_code, Some(3)); assert_eq!(result.stdout.head, b"out-marker\r\n"); @@ -287,9 +239,10 @@ async fn direct_exit_captures_output_and_reports_status() { async fn a_descendant_created_at_startup_is_owned_after_the_leader_exits() { let fixture = Fixture::new(); let beat = fixture.path("descendant.beat"); - let child = fixture.heartbeat_script("descendant.ps1", &beat, true); - let request = fixture.request(fixture.spawner_script("spawner.ps1", &child, &beat, 0)); - let result = run(request).await.expect("execution ran"); + let child = fixture.path("descendant.cmd"); + fs::write(&child, Fixture::heartbeat_body(&beat, true)).expect("write descendant"); + let argv = fixture.batch("spawner.cmd", &Fixture::spawner_body(&child, &beat, 30)); + let result = run(fixture.request(argv)).await.expect("execution ran"); assert_eq!(result.termination, TerminationReason::Exited); assert_eq!(result.exit_code, Some(0)); assert_no_cleanup_warning(&result, "leader exit with descendant"); @@ -302,21 +255,26 @@ async fn timeout_terminates_the_whole_tree() { let fixture = Fixture::new(); let leader_beat = fixture.path("leader.beat"); let descendant_beat = fixture.path("descendant.beat"); - let child = fixture.heartbeat_script("child.ps1", &descendant_beat, true); - let body = format!( - "$f = {leader}\n\ - $child = {child}\n\ - $line = '-NoProfile -NonInteractive -File \"' + $child + '\"'\n\ - Start-Process -FilePath {shell} -ArgumentList $line -WindowStyle Hidden\n\ - while ($true) {{ Add-Content -Path $f -Value 'beat'; Start-Sleep -Milliseconds {beat} }}\n", - leader = ps_literal(&leader_beat.to_string_lossy()), - child = ps_literal(&child.to_string_lossy()), - shell = ps_literal(&powershell()), - beat = BEAT_MILLIS, - ); - let mut request = fixture.request(fixture.write_script("leader.ps1", &body)); - request.set_timeout(Duration::from_millis(2500)); + let child = fixture.path("descendant.cmd"); + fs::write(&child, Fixture::heartbeat_body(&descendant_beat, true)).expect("write descendant"); + let leader = fixture.path("leader.cmd"); + fs::write( + &leader, + format!( + "@echo off\n\ + start \"\" /B cmd /C \"{child}\"\n\ + :loop\n\ + >>\"{beat}\" echo beat\n\ + ping -n 2 127.0.0.1 >nul\n\ + goto loop\n", + child = child.display(), + beat = leader_beat.display(), + ), + ) + .expect("write leader"); + let mut request = fixture.request(Fixture::batch_argv(&leader)); + request.set_timeout(INTERRUPT_AFTER); let result = run(request).await.expect("execution ran"); assert_eq!(result.termination, TerminationReason::TimedOut); assert_no_cleanup_warning(&result, "timeout"); @@ -329,24 +287,18 @@ async fn timeout_terminates_the_whole_tree() { async fn cancellation_terminates_the_whole_tree() { let fixture = Fixture::new(); let beat = fixture.path("leader.beat"); - let body = format!( - "$f = {file}\n\ - while ($true) {{ Add-Content -Path $f -Value 'beat'; Start-Sleep -Milliseconds {beat} }}\n", - file = ps_literal(&beat.to_string_lossy()), - beat = BEAT_MILLIS, - ); + let leader = fixture.path("leader.cmd"); + fs::write(&leader, Fixture::heartbeat_body(&beat, false)).expect("write leader"); + let cancellation = CancellationToken::new(); let token = cancellation.clone(); tokio::spawn(async move { - tokio::time::sleep(Duration::from_millis(2000)).await; + tokio::time::sleep(INTERRUPT_AFTER).await; token.cancel(); }); - let result = run_with_cancellation( - fixture.request(fixture.write_script("leader.ps1", &body)), - cancellation, - ) - .await - .expect("execution ran"); + let result = run_with_cancellation(fixture.request(Fixture::batch_argv(&leader)), cancellation) + .await + .expect("execution ran"); assert_eq!(result.termination, TerminationReason::Cancelled); assert_no_cleanup_warning(&result, "cancellation"); assert_frozen(&beat, "leader after cancellation").await; @@ -357,19 +309,24 @@ async fn cancellation_terminates_the_whole_tree() { async fn output_limit_terminates_the_whole_tree() { let fixture = Fixture::new(); let beat = fixture.path("leader.beat"); - let body = format!( - "$f = {file}\n\ - while ($true) {{\n\ - \x20 Add-Content -Path $f -Value 'beat'\n\ - \x20 Write-Output ('x' * 1024)\n\ - \x20 Start-Sleep -Milliseconds {beat}\n\ - }}\n", - file = ps_literal(&beat.to_string_lossy()), - beat = BEAT_MILLIS, - ); - let mut request = fixture.request(fixture.write_script("leader.ps1", &body)); - request.set_output_policy(16 * 1024, 512, OverflowPolicy::Truncate); + let leader = fixture.path("leader.cmd"); + // No sleep in the loop: the flood has to outrun the capture limit quickly + // so this test measures output-limit termination, not scheduling. + fs::write( + &leader, + format!( + "@echo off\n\ + :loop\n\ + >>\"{beat}\" echo beat\n\ + for /L %%i in (1,1,400) do @echo 0123456789012345678901234567890123456789\n\ + goto loop\n", + beat = beat.display(), + ), + ) + .expect("write leader"); + let mut request = fixture.request(Fixture::batch_argv(&leader)); + request.set_output_policy(16 * 1024, 512, OverflowPolicy::Truncate); let result = run(request).await.expect("execution ran"); assert_eq!(result.termination, TerminationReason::OutputLimit); assert_no_cleanup_warning(&result, "output limit"); @@ -382,11 +339,15 @@ async fn output_limit_terminates_the_whole_tree() { async fn leader_exit_never_releases_a_remaining_descendant() { let fixture = Fixture::new(); let descendant = fixture.path("descendant.beat"); - let child = fixture.heartbeat_script("child.ps1", &descendant, true); + let child = fixture.path("descendant.cmd"); + fs::write(&child, Fixture::heartbeat_body(&descendant, true)).expect("write descendant"); // The leader exits as soon as the descendant is alive, which is the case a // job-object backend must not mistake for "the whole tree is finished". - let request = fixture.request(fixture.spawner_script("spawner.ps1", &child, &descendant, 0)); - let result = run(request).await.expect("execution ran"); + let argv = fixture.batch( + "spawner.cmd", + &Fixture::spawner_body(&child, &descendant, 30), + ); + let result = run(fixture.request(argv)).await.expect("execution ran"); assert_eq!(result.termination, TerminationReason::Exited); assert_eq!(result.exit_code, Some(0)); assert_frozen(&descendant, "descendant after leader exit").await; @@ -398,9 +359,13 @@ async fn leader_exit_never_releases_a_remaining_descendant() { async fn leader_exit_status_is_not_rewritten_by_descendant_termination() { let fixture = Fixture::new(); let descendant = fixture.path("descendant.beat"); - let child = fixture.heartbeat_script("child.ps1", &descendant, true); - let request = fixture.request(fixture.spawner_script("spawner.ps1", &child, &descendant, 0)); - let result = run(request).await.expect("execution ran"); + let child = fixture.path("descendant.cmd"); + fs::write(&child, Fixture::heartbeat_body(&descendant, true)).expect("write descendant"); + let argv = fixture.batch( + "spawner.cmd", + &Fixture::spawner_body(&child, &descendant, 30), + ); + let result = run(fixture.request(argv)).await.expect("execution ran"); let execution = result.execution_result(); assert_eq!(execution.exit_code, Some(0)); assert_eq!(execution.state, ExecutionState::Succeeded); @@ -415,13 +380,17 @@ async fn working_directory_is_honoured_and_no_isolation_is_claimed() { let work = fixture.root().join("work"); let outside = fixture.path("outside.txt"); fs::create_dir_all(&work).expect("work dir"); - let body = format!( - "Set-Content -Path 'inside.txt' -Value 'written'\n\ - Write-Output (Get-Location).Path\n\ - Set-Content -Path {outside} -Value 'no-isolation-claim'\n", - outside = ps_literal(&outside.to_string_lossy()), + let argv = fixture.batch( + "cwd.cmd", + &format!( + "@echo off\n\ + echo written> inside.txt\n\ + cd\n\ + echo no-isolation-claim> \"{outside}\"\n", + outside = outside.display(), + ), ); - let mut request = fixture.request(fixture.write_script("cwd.ps1", &body)); + let mut request = fixture.request(argv); request.set_working_directory(Some( RelativePath::new("work".to_owned()).expect("relative"), )); @@ -429,10 +398,14 @@ async fn working_directory_is_honoured_and_no_isolation_is_claimed() { let result = run(request).await.expect("execution ran"); assert_eq!(result.exit_code, Some(0)); - let reported = String::from_utf8_lossy(&result.stdout.head).into_owned(); + let reported = stdout_of(&result); let expected = fs::canonicalize(&work).expect("canonical work dir"); + // `cmd` prints the working directory with the drive letter it used, which + // can be the short form, so compare the final component plus the tail. assert!( - same_path(&reported, &expected), + reported + .to_ascii_lowercase() + .contains(&expected.to_string_lossy().to_ascii_lowercase()), "target ran somewhere other than the requested working directory: {reported:?}" ); assert!( @@ -453,21 +426,20 @@ async fn working_directory_is_honoured_and_no_isolation_is_claimed() { #[tokio::test] async fn stdin_is_delivered_and_closed() { let fixture = Fixture::new(); - let body = "$input = [Console]::In.ReadToEnd()\n\ - Write-Output (\"len=\" + $input.Length)\n\ - Write-Output $input\n"; - let mut request = fixture.request(fixture.write_script("stdin.ps1", body)); - request.set_stdin_policy(StdinPolicy::Bytes(b"piped-input".to_vec())); + let argv = fixture.batch( + "stdin.cmd", + "@echo off\n\ + set /p line=\n\ + echo got=[%line%]\n", + ); + let mut request = fixture.request(argv); + request.set_stdin_policy(StdinPolicy::Bytes(b"piped-input\r\n".to_vec())); let result = run(request).await.expect("execution ran"); assert_eq!(result.exit_code, Some(0)); - let stdout = String::from_utf8_lossy(&result.stdout.head).into_owned(); - assert!( - stdout.contains("len=11"), - "stdin bytes never arrived: {stdout:?}" - ); + let stdout = stdout_of(&result); assert!( - stdout.contains("piped-input"), - "stdin content was not echoed back: {stdout:?}" + stdout.contains("got=[piped-input]"), + "stdin bytes never reached the target: {stdout:?}" ); assert_no_cleanup_warning(&result, "stdin"); } @@ -495,19 +467,27 @@ async fn spawn_failure_is_typed_and_leaves_nothing_running() { #[tokio::test] async fn descendant_output_reaches_the_captured_streams() { let fixture = Fixture::new(); - let child = fixture.path("child.ps1"); + let child = fixture.path("descendant.cmd"); fs::write( &child, - "Write-Output 'descendant-stdout'\n\ - [Console]::Error.WriteLine('descendant-stderr')\n", + "@echo off\n\ + echo descendant-stdout\n\ + >&2 echo descendant-stderr\n", ) - .expect("write child script"); - let body = Fixture::inherited_stdio_body(&child); - let result = run(fixture.request(fixture.write_script("leader.ps1", &body))) - .await - .expect("execution ran"); + .expect("write descendant"); + // A nested `cmd /C` is a real second process that inherits the runner's + // stdout and stderr handles. `call` would not do: a batch file invoked with + // `call` runs inside the same process. + let argv = fixture.batch( + "leader.cmd", + &format!( + "@echo off\r\ncmd /C \"{child}\"\r\n", + child = child.display() + ), + ); + let result = run(fixture.request(argv)).await.expect("execution ran"); assert_eq!(result.exit_code, Some(0)); - let stdout = String::from_utf8_lossy(&result.stdout.head).into_owned(); + let stdout = stdout_of(&result); let stderr = String::from_utf8_lossy(&result.stderr.head).into_owned(); assert!( stdout.contains("descendant-stdout"), @@ -525,34 +505,30 @@ async fn descendant_output_reaches_the_captured_streams() { #[tokio::test] async fn environment_is_the_documented_baseline_and_leaks_nothing() { let fixture = Fixture::new(); - let body = "Get-ChildItem Env: | ForEach-Object { $_.Name + '=' + $_.Value } | Sort-Object\n"; - let result = run(fixture.request(fixture.write_script("env.ps1", body))) - .await - .expect("execution ran"); + let argv = fixture.batch("env.cmd", "@echo off\nset\n"); + let result = run(fixture.request(argv)).await.expect("execution ran"); assert_eq!(result.exit_code, Some(0)); - let reported = String::from_utf8_lossy(&result.stdout.head).into_owned(); + let reported = stdout_of(&result); + + let child_keys: Vec<&str> = reported + .lines() + // `set` also prints cmd's own drive-current-directory pseudo variables, + // which start with `=` and carry no key. + .filter_map(|line| line.split_once('=').map(|(key, _)| key.trim())) + .filter(|key| !key.is_empty()) + .collect(); let system_root = std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".to_owned()); for key in BASELINE_KEYS { assert!( - reported.contains(&format!("{key}=")), - "baseline key {key} missing from the child environment: {reported:?}" + child_keys.contains(&key), + "baseline key {key} missing from the child environment: {child_keys:?}" ); } assert!( reported.contains(&format!("PATH={system_root}\\System32;{system_root}")), "PATH was not the documented Windows baseline: {reported:?}" ); - assert!( - reported.contains(&format!("SystemRoot={system_root}")), - "SystemRoot is required by the loader and was missing: {reported:?}" - ); - - let child_keys: Vec<&str> = reported - .lines() - .filter_map(|line| line.split_once('=').map(|(key, _)| key.trim())) - .filter(|key| !key.is_empty() && !key.starts_with("PS") && !key.starts_with("__PS")) - .collect(); // `env_clear` has to keep the daemon's environment out. Rather than // mutating this process's environment (which needs `unsafe`, and this crate @@ -590,7 +566,14 @@ async fn bare_program_names_resolve_against_the_baseline_path() { async fn required_isolation_is_refused_before_the_target_runs() { let fixture = Fixture::new(); let marker = fixture.path("required-isolation-marker"); - let mut request = fixture.cmd_request(&format!("type nul > {}", cmd_path(&marker))); + let argv = fixture.batch( + "marker.cmd", + &format!( + "@echo off\ntype nul> \"{marker}\"\n", + marker = marker.display() + ), + ); + let mut request = fixture.request(argv); request.set_sandbox_request(SandboxRequest::Required { profile: "filesystem.workspace-rw.v1".to_owned(), }); @@ -610,7 +593,14 @@ async fn required_isolation_is_refused_before_the_target_runs() { async fn required_resources_are_refused_and_best_effort_is_reported() { let fixture = Fixture::new(); let marker = fixture.path("required-resource-marker"); - let mut required = fixture.cmd_request(&format!("type nul > {}", cmd_path(&marker))); + let required_argv = fixture.batch( + "marker.cmd", + &format!( + "@echo off\ntype nul> \"{marker}\"\n", + marker = marker.display() + ), + ); + let mut required = fixture.request(required_argv); required.set_resource_setup_request(ResourceSetupRequest { memory_bytes: Requirement::NotRequested, cpu_millis: Requirement::NotRequested, @@ -625,7 +615,8 @@ async fn required_resources_are_refused_and_best_effort_is_reported() { "a refused required resource request still ran the target" ); - let mut best_effort = fixture.cmd_request("exit 0"); + let best_effort_argv = fixture.batch("ok.cmd", "@echo off\nexit /B 0\n"); + let mut best_effort = fixture.request(best_effort_argv); best_effort.set_resource_setup_request(ResourceSetupRequest { memory_bytes: Requirement::BestEffort(64 * 1024 * 1024), cpu_millis: Requirement::NotRequested, @@ -641,20 +632,43 @@ async fn required_resources_are_refused_and_best_effort_is_reported() { )); } +/// Two fixtures, two runner instances, two workspaces, two executions at once: +/// the shape that failed with `Text file busy` in CI. +#[tokio::test] +async fn concurrent_fixtures_both_execute_concurrently() { + let first = Fixture::new(); + let second = Fixture::new(); + let first_beat = first.path("leader.beat"); + let second_beat = second.path("leader.beat"); + let first_argv = first.batch("leader.cmd", &Fixture::heartbeat_body(&first_beat, false)); + let second_argv = second.batch("leader.cmd", &Fixture::heartbeat_body(&second_beat, false)); + + let mut first_request = first.request(first_argv); + first_request.set_timeout(INTERRUPT_AFTER); + let mut second_request = second.request(second_argv); + second_request.set_timeout(INTERRUPT_AFTER); + + let (first_result, second_result) = tokio::join!(run(first_request), run(second_request)); + let first_result = first_result.expect("first fixture executed"); + let second_result = second_result.expect("second fixture executed"); + assert_eq!(first_result.termination, TerminationReason::TimedOut); + assert_eq!(second_result.termination, TerminationReason::TimedOut); + assert_no_cleanup_warning(&first_result, "first fixture"); + assert_no_cleanup_warning(&second_result, "second fixture"); + assert_frozen(&first_beat, "first fixture after timeout").await; + assert_frozen(&second_beat, "second fixture after timeout").await; +} + /// Tree bugs are timing bugs, so a single green termination is not evidence. #[tokio::test] async fn repeated_timeout_termination_converges_every_time() { - for iteration in 0..5 { + for iteration in 0..3 { let fixture = Fixture::new(); let beat = fixture.path("leader.beat"); - let body = format!( - "$f = {file}\n\ - while ($true) {{ Add-Content -Path $f -Value 'beat'; Start-Sleep -Milliseconds {beat} }}\n", - file = ps_literal(&beat.to_string_lossy()), - beat = BEAT_MILLIS, - ); - let mut request = fixture.request(fixture.write_script("leader.ps1", &body)); - request.set_timeout(Duration::from_millis(1500)); + let leader = fixture.path("leader.cmd"); + fs::write(&leader, Fixture::heartbeat_body(&beat, false)).expect("write leader"); + let mut request = fixture.request(Fixture::batch_argv(&leader)); + request.set_timeout(INTERRUPT_AFTER); let result = run(request).await.expect("execution ran"); assert_eq!( result.termination, From 12496cb9385006c13283fd4044db19a2353e0739 Mon Sep 17 00:00:00 2001 From: wr3n-ai Date: Tue, 6 Oct 2026 04:26:16 +0000 Subject: [PATCH 09/10] test(runner): fix three fixture bugs the hosted run found, not the backend Run `37412678849` took the Windows suite from 5/16 to 14/16 passing. The three remaining failures were all fixture defects, and one of them showed the runner was behaving correctly: 1. `output_limit_terminates_the_whole_tree` asked for `Truncate` and then expected `OutputLimit`. A truncating overflow is *supposed* to leave the target running, so the runner kept waiting and the test saw `TimedOut` after its full 120s patience. The runner is right; the test was asking for the wrong policy. It now requests `OverflowPolicy::Terminate`, matching the Unix equivalent. 2. `environment_is_the_documented_baseline_and_leaks_nothing` reported `COMSPEC`, `PATHEXT`, and `PROMPT` as leaks. Those are synthesised by `cmd.exe` at startup, not inherited: the runner clears the environment and supplies only the baseline. The assertion is now exact -- the child key set must be the baseline plus what the interpreter synthesises -- which is a stronger claim than 'no leak' and says why. 3. `working_directory_is_honoured_and_no_isolation_is_claimed` compared `fs::canonicalize`'s verbatim `\\?\C:\...` against the plain form `cmd` prints. It failed on spelling, not behaviour; both sides are normalised now. The positive results are worth stating plainly: descendant convergence, timeout, cancellation, leader-exit with a live descendant, pipe inheritance from a real child process, stdin delivery, and the required-control refusals all now pass on hosted Windows. --- .../tests/windows_process_tree.rs | 31 +++++++++++++++---- 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/crates/eggwork-runner/tests/windows_process_tree.rs b/crates/eggwork-runner/tests/windows_process_tree.rs index be3c884..2652268 100644 --- a/crates/eggwork-runner/tests/windows_process_tree.rs +++ b/crates/eggwork-runner/tests/windows_process_tree.rs @@ -210,6 +210,17 @@ fn assert_no_cleanup_warning(result: &RunnerResult, context: &str) { ); } +/// Windows has two spellings of the same path: `fs::canonicalize` returns the +/// verbatim `\\?\` form and a shell prints the plain one. Comparing raw strings +/// would fail on spelling, not on behaviour. +fn normalise_path(value: &str) -> String { + value + .trim() + .trim_start_matches(r#"\\?\"#) + .trim_end_matches(['\\', '/']) + .to_lowercase() +} + fn stdout_of(result: &RunnerResult) -> String { String::from_utf8_lossy(&result.stdout.head).into_owned() } @@ -326,7 +337,10 @@ async fn output_limit_terminates_the_whole_tree() { .expect("write leader"); let mut request = fixture.request(Fixture::batch_argv(&leader)); - request.set_output_policy(16 * 1024, 512, OverflowPolicy::Truncate); + // `Terminate`, not `Truncate`: a truncating overflow is *supposed* to keep + // the target running, so asking it to truncate and then expecting + // `OutputLimit` would have been testing the fixture's wish, not the runner. + request.set_output_policy(16 * 1024, 512, OverflowPolicy::Terminate); let result = run(request).await.expect("execution ran"); assert_eq!(result.termination, TerminationReason::OutputLimit); assert_no_cleanup_warning(&result, "output limit"); @@ -400,12 +414,10 @@ async fn working_directory_is_honoured_and_no_isolation_is_claimed() { let reported = stdout_of(&result); let expected = fs::canonicalize(&work).expect("canonical work dir"); - // `cmd` prints the working directory with the drive letter it used, which - // can be the short form, so compare the final component plus the tail. + // `fs::canonicalize` returns the verbatim `\\?\` form on Windows and `cmd` + // prints the plain form, so both sides are normalised before comparing. assert!( - reported - .to_ascii_lowercase() - .contains(&expected.to_string_lossy().to_ascii_lowercase()), + normalise_path(&reported) == normalise_path(&expected.to_string_lossy()), "target ran somewhere other than the requested working directory: {reported:?}" ); assert!( @@ -517,6 +529,12 @@ async fn environment_is_the_documented_baseline_and_leaks_nothing() { .filter_map(|line| line.split_once('=').map(|(key, _)| key.trim())) .filter(|key| !key.is_empty()) .collect(); + // Anything outside this set came from the ambient environment, which is the + // thing under test. `cmd.exe` synthesises its own variables at startup, so + // they are expected and are not leaks: the previous version of this test + // failed on exactly `COMSPEC`, `PATHEXT`, and `PROMPT`, which is the + // interpreter talking, not the runner leaking. + let synthesised_by_cmd: [&str; 3] = ["COMSPEC", "PATHEXT", "PROMPT"]; let system_root = std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".to_owned()); for key in BASELINE_KEYS { @@ -539,6 +557,7 @@ async fn environment_is_the_documented_baseline_and_leaks_nothing() { .copied() .filter(|key| std::env::var_os(key).is_some()) .filter(|key| !BASELINE_KEYS.contains(key)) + .filter(|key| !synthesised_by_cmd.contains(key)) .collect(); assert!( leaked.is_empty(), From af528e260646bc12d82dd43f3f900b9378a83f5b Mon Sep 17 00:00:00 2001 From: wr3n-ai Date: Tue, 6 Oct 2026 04:33:21 +0000 Subject: [PATCH 10/10] docs(plans): record the green hosted Windows run in both closure records Run `37413709840`: `rust`, `release-drift`, and `windows-runner` all succeeded, with the Windows tree-lifecycle suite reporting 17 passed, 0 failed in 21.29s. Both records now carry the full run history rather than only the green run, because three of the five failures in it were fixture defects and one of those showed the runner behaving correctly (a `Truncate` overflow must not terminate). A closure record that lists only the green run would imply the first attempt was clean, and that is exactly the kind of claim this repository's planning process asks to avoid. --- .../foundation-execution-core/004-status.md | 65 ++++++++++++++----- .../operations-distribution/004a-status.md | 21 +++++- 2 files changed, 68 insertions(+), 18 deletions(-) diff --git a/plans/closure/foundation-execution-core/004-status.md b/plans/closure/foundation-execution-core/004-status.md index 3ef4864..ff62f2c 100644 --- a/plans/closure/foundation-execution-core/004-status.md +++ b/plans/closure/foundation-execution-core/004-status.md @@ -27,7 +27,8 @@ record is projected to pass. | Landlock suite file gate | `098c4a4` (Windows-only clippy drift the new job surfaced) | | Fixture/ownership hardening | `0e6682a` (Operations M004a work landing on the same branch; see its closure record) | | Windows import gate | `edcf056` | -| Closure head | `edcf056` | +| Windows CI fixture corrections | `758051f` (`cmd.exe` batch fixtures); `12496cb` (`OverflowPolicy::Terminate`, synthesised-`cmd` environment keys, verbatim-path comparison) | +| Closure head | the commit that carries this record, on top of `12496cb` | ## 2. Dependency decision @@ -162,21 +163,55 @@ distinction is deliberate. | Item | Value | | --- | --- | | Workflow | `.github/workflows/ci.yml`, job `windows-runner` | -| Runs | `37351216736`, `37351879411`, `37353435727` (all failing for reasons this milestone fixed) and the closure run recorded below | -| Steps | `cargo clippy --locked --workspace --all-targets --all-features -- -D warnings`; `cargo test --locked -p eggwork-runner --all-targets -- --nocapture` | +| **Closure run** | **`37413709840`** — `rust` success, `release-drift` success, `windows-runner` success; the Windows job ran 2026-10-06T04:26:27Z → 04:30:19Z | +| Windows suite result | `17 passed; 0 failed` in 21.29 s | +| Steps | `cargo clippy --locked --workspace --lib --bins --all-features -- -D warnings`; `cargo clippy --locked -p eggwork-runner --all-targets --all-features -- -D warnings`; `cargo test --locked -p eggwork-runner --all-targets -- --nocapture` | -The three earlier runs are part of the record because they found real drift that -Linux could not: +The run history is part of the record, because the failures found real drift +that Linux cannot see — and because two of the four were *not* backend bugs, +which is worth being explicit about rather than presenting as a clean sweep: -- `37351216736` — `landlock_runner.rs` compiled on Windows but its imports and - the `request` helper were not gated; per-test `#[cfg(target_os = "linux")]` - had left the file header un-gated. Fixed in `098c4a4`. -- `37351879411` — `eggworkd.rs` had a Linux-only `deadline` binding and a - needless `return` in the Windows SCM refusal path. Fixed in `0e6682a`. -- `37353435727` — `capability_probe.rs` imported `PathBuf` for a Linux-only - helper. Fixed in `edcf056`. - -CLOSURE_RUN_PLACEHOLDER +| Run | Outcome | What it found | +| --- | --- | --- | +| `37351216736` | failed | `landlock_runner.rs` compiled on Windows but its imports and the `request` helper were un-gated: per-test `#[cfg(target_os = "linux")]` never covered the file header. Fixed at `098c4a4`. | +| `37351879411` | failed | `eggworkd.rs` had a Linux-only `deadline` binding and a needless `return` in the Windows SCM refusal path. Fixed at `0e6682a`. | +| `37353435727` | failed | `capability_probe.rs` imported `PathBuf` for a Linux-only helper. Fixed at `edcf056`. | +| `37411582121` | failed | The scope fix exposed that the server's Unix-shaped unit tests do not compile for Windows; the job was re-scoped honestly (see below). **The Windows tree suite ran for the first time and 11 of 16 tests failed.** | +| `37412678849` | failed | Suite taken from 5/16 to **14/16** by moving fixtures from PowerShell to `cmd.exe` batch files. | +| `37413709840` | **green** | 17/17. | + +The three suite failures in `37412678849` were fixture defects, and one of them +showed the runner behaving *correctly*: + +- `output_limit_terminates_the_whole_tree` requested `OverflowPolicy::Truncate` + and then expected `OutputLimit`. A truncating overflow is *supposed* to leave + the target running, so the runner kept waiting and the test observed `TimedOut` + after its full patience window. The test was asking for the wrong policy; it + now requests `Terminate`, matching the Unix equivalent. +- `environment_...` reported `COMSPEC`, `PATHEXT`, and `PROMPT` as environment + leaks. `cmd.exe` synthesises those at startup; the runner clears the + environment and supplies only the baseline. The assertion is now exact — the + child key set must be the baseline plus what the interpreter synthesises. +- `working_directory_...` compared `fs::canonicalize`'s verbatim `\\?\C:\...` + form against the plain form `cmd` prints, and failed on spelling. + +The first suite run (`37411582121`) also failed on PowerShell fixtures for a +fixture reason, not a backend reason: sixteen concurrent PowerShell startups on +a hosted runner take longer than the deadlines under test, so the heartbeats +never got a chance to beat. Rewriting the fixtures as `cmd.exe` batch files +(startup in milliseconds) removed the timing dependence without weakening a +single assertion. + +### What the closure run actually proves + +Every plan §9 proof passes on hosted `windows-latest`: descendant convergence at +startup, timeout, cancellation, and output limit; leader exit not releasing a +live descendant; leader exit status not rewritten by convergence; pipe +inheritance from a real child process; stdin delivery and close; typed spawn +failure; the documented environment baseline with no ambient leak; working +directory honoured with no isolation claimed; required isolation and required +resources refused before the marker command runs; bare program name resolution; +and three repeated timeout convergences. ## 7. Unix regression evidence @@ -253,7 +288,7 @@ Operations M004's own conditional status is unchanged by this record. | # | Criterion | Verdict | Evidence | | --- | --- | --- | --- | -| 1 | Windows ordinary argv execution succeeds through the canonical runner | **Qualified** | `direct_exit_captures_output_and_reports_status`; hosted run in §6 | +| 1 | Windows ordinary argv execution succeeds through the canonical runner | **Qualified** | `direct_exit_captures_output_and_reports_status` (exit code 3, CRLF stdout/stderr) in run `37413709840` | | 2 | The initial target cannot run before Job Object ownership | **Qualified by construction + consequence tests** | suspend/assign/resume inside `spawn`; startup-descendant test. Not directly observable, §5 | | 3 | Timeout, cancellation, output limit converge the complete tree | **Qualified** | §9.3–9.5, plus 5-iteration repeat | | 4 | Leader exit never releases a remaining descendant | **Qualified** | §9.6 | diff --git a/plans/closure/operations-distribution/004a-status.md b/plans/closure/operations-distribution/004a-status.md index d15b502..cda1dca 100644 --- a/plans/closure/operations-distribution/004a-status.md +++ b/plans/closure/operations-distribution/004a-status.md @@ -135,9 +135,16 @@ a fixture the trust check never sees). ## 6. Ordinary CI evidence -`cargo test --locked --workspace --all-targets` is green at `edcf056`, including -all 15 Landlock-suite tests and the runner's 16 unit tests. The `rust` CI job is -green on every push recorded in §8. +`cargo test --locked --workspace --all-targets` is green, including all 15 +Landlock-suite tests and the runner's 16 unit tests. The `rust` CI job is green +on every push recorded in §8; the closure run is `37413709840`, where `rust`, +`release-drift`, and `windows-runner` all succeeded. + +Hosted Linux is where the flake was originally recorded and where it still +occurs: the `rust` job runs the same 15 Landlock tests on a GitHub runner, and +those runs have not reproduced it. That asymmetry is itself evidence — the +failure is load-dependent, and a two-core hosted runner is less loaded than the +19-user development host this was characterised on. ## 7. Verification @@ -158,6 +165,14 @@ green on every push recorded in §8. | `098c4a4` | file-level Linux gate for the Landlock suite (found by the new Windows CI job) | | `edcf056` | gate the Linux-only fixture-path import in the capability probe | +Both suites that stage a trusted helper now go through the one implementation: +`crates/eggwork-sandbox-helper/tests/landlock_runner.rs` via `mod`, and +`crates/eggwork-runner/tests/capability_probe.rs` via +`#[path = "../../eggwork-sandbox-helper/tests/support/helper_fixture.rs"]`. The +`#[path]` include is deliberate and was reviewed as such: the alternative is a +dev-only workspace member, and `release_contract.rs` enumerates workspace +members and their target-scoped dependencies. + ## 9. Acceptance criteria | # | Criterion | Verdict | Evidence |