oficina / equipo Public

fix: keep namespace exit proof independent of scratch cleanup

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 855f4394ac1b8cc636d7156e24f69f2cc357a232 parent 5c1de26
5 files changed, +849 −31
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md +506 −0
  • internal/runner/containment/linux.go +3 −4
  • internal/runner/containment/linux_test.go +6 −2
  • internal/runner/containment/recovery.go +61 −19
  • internal/runner/containment/recovery_test.go +273 −6

CI passed — run details

diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md
index a9964557..dd938505 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md
@@ -2376,3 +2376,509 @@ The remote worker proof is pending the controller's push. Local capability is pr
Recovery intentionally blocks same-boot reuse if launch identity or durable exit evidence is unavailable. It does not infer a successful provider outcome from containment. Account-content hashing, provider preflight, the in-namespace relay, check execution, capture integration and provider certification remain later tasks. This task does not make a provider run or claim the release is certified.
No push, merge, deployment, sign-in, enrolment, credential import, model prompt or subagent was performed. All test processes and cgroups were cleaned up. After saving these reports, the task-owned evidence directory under TMPDIR is removed. Go caches are unchanged. No server or background process is left running by this task. The requested report remains under `.superpowers` (already ignored); the full controller section is committed.
+
+
+## Task 2 fix round 1: Exit proof and scratch cleanup
+
+Date: 2026-11-03. Base: `5c1de26` on `plan-2b`. Author: `codex <codex~paul@keymail.dev>`.
+Commit subject: `fix: keep namespace exit proof independent of scratch cleanup`.
+Status: DONE_WITH_CONCERNS. Both requested fixes pass the covering gates. One existing test helper returned EINTR on a verification run; the unchanged rerun passed. Remote CI remains for the controller.
+
+### Changes and files
+
+`internal/runner/containment/linux.go` now uses the same cleanup operation as recovery. It joins any cleanup error with the process error without changing the saved namespace-exit proof.
+
+`internal/runner/containment/recovery.go` restores owner directory access before removing scratch. The walk skips symlinks, including a symlink at the attempt root. Only directories receive mode 0700; file permissions and external symlink targets stay untouched. Cleanup errors carry the `namespace_scratch_cleanup` prefix and retain their underlying error. A failed cleanup can be retried without losing Verified or changing the outcome.
+
+Same-boot recovery distinguishes an absent recorded init from an unproven identity. ESRCH, a vanished proc entry, differing start ticks or namespace, and an observed pidfd exit establish that the recorded init is gone. Recovery checks the saved launch record before making this inference, saves a verified exit with `Code=-1`, `Signal=0` and an observation time, and signals no replacement process. Other lookup errors, malformed records, non-init identities and mismatched saved records still fail closed. IDs and namespace names are checked for their expected format before the absent-identity path.
+
+`internal/runner/containment/recovery_test.go` adds real namespace tests for 0555, 0500 and 0000 scratch directories under both tmp and the private home, with natural exit and Stop. Recovery tests cover a read-only tree, an external symlink, repeated cleanup failures and successful retry. The crash test kills a separate test runner, observes its init exit, requires pidfd_open to return ESRCH, and verifies that no exit file exists before recovery. Reuse tests use an unrelated test-owned sleep process and check that it survives both ticks and namespace mismatches. The tests also require inferred exit proofs to survive a second Recover unchanged.
+
+`internal/runner/containment/{linux,recovery}_test.go` now obtains the host home through `os.UserHomeDir()`. No test in this package hard-codes the operator's home.
+
+This section is appended to the task report and `docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md`. The task report remains in the already ignored `.superpowers` directory; the identical controller section is committed with the four Go files.
+
+### Interpretations
+
+The round-1 dispatch supersedes the original brief's commit subject, full CI and push instructions. Only containment tests and `make runner-namespace-test` ran. The original report's statement that missing same-boot exit evidence always blocks recovery is superseded by this fix.
+
+The old missing-exit rejection is replaced by the actual runner-crash test. The old stale durable ticks test now requires a verified unknown outcome while the test-owned process at that PID stays alive. Submitted records that differ from the saved record still fail. The unrelated-process reuse fixture synthesizes the durable PID collision, avoiding host PID exhaustion or any scan of unrelated processes.
+
+Unknown outcome remains the existing `provider.Exit` convention: Code -1 and Signal 0. A cleanup failure does not change proof. Journal persistence errors retain the existing failure behavior. Cleanup runs after namespace teardown; the threat model still trusts other processes running as the host account.
+
+The malformed-record preservation test passed against the original implementation before production changes. Explicit format checks are necessary once absent identities can be verified; mutations below prove that omitting those checks would accept malformed records.
+
+### RED evidence
+
+All commands ran in `/home/paulca/amadan.net/oficina/equipo-plan-2b`, on `plan-2b`, with CGO disabled, default Go caches and the existing on-disk TMPDIR. Tests for both review issues were written before production changes.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestNamespace' -count=1
+```
+
+Exit 1, compiled successfully. Output excerpts:
+
+```text
+--- FAIL: TestNamespaceRecoveryStaleDurableTicks (0.07s)
+ recovery_test.go:176: absent recorded identity not recovered: ... Verified:false} namespace_identity_unproven
+--- FAIL: TestNamespaceReadOnlyScratch (0.36s)
+ --- FAIL: TestNamespaceReadOnlyScratch/0555/stop=false (0.06s)
+ recovery_test.go:304: read-only scratch invalidated exit: ... Verified:false} unlinkat .../tmp/cache/nested/file: permission denied
+ --- FAIL: TestNamespaceReadOnlyScratch/0500/stop=true (0.06s)
+ recovery_test.go:304: read-only scratch invalidated exit: ... Verified:false} unlinkat .../tmp/cache/nested/file: permission denied
+ --- FAIL: TestNamespaceReadOnlyScratch/0000/stop=false (0.06s)
+ recovery_test.go:304: read-only scratch invalidated exit: ... Verified:false} openfdat .../tmp: permission denied
+--- FAIL: TestNamespaceRecoveryReadOnlyScratch (0.06s)
+ recovery_test.go:353: read-only recovery invalidated exit: ... Verified:false} openfdat .../cache/nested/link: permission denied
+--- FAIL: TestNamespaceCleanupFailureKeepsProof (0.06s)
+ recovery_test.go:389: cleanup failure changed proof: ... Verified:false} unlinkat ...: permission denied
+--- FAIL: TestNamespaceRecoveryCrashBeforeExit (0.05s)
+ recovery_test.go:446: absent init not recovered with unknown outcome: ... Verified:false} namespace_identity_unproven
+--- FAIL: TestNamespaceRecoveryReusedPID (0.17s)
+ --- FAIL: TestNamespaceRecoveryReusedPID/ticks (0.08s)
+ recovery_test.go:476: absent init not recovered with unknown outcome: ... Verified:false} namespace_identity_unproven
+ --- FAIL: TestNamespaceRecoveryReusedPID/namespace (0.09s)
+ recovery_test.go:476: absent init not recovered with unknown outcome: ... Verified:false} namespace_identity_unproven
+FAIL
+rastrillo-budget/v1 ran 2.447s
+FAIL amadan.net/oficina/equipo/internal/runner/containment 2.449s
+```
+
+All six read-only combinations failed. Red test cleanup restored the fixture directory permissions and removed its scratch.
+
+Preservation check before implementation:
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestNamespaceRecoveryMalformedRecord$' -count=1
+```
+
+```text
+ok amadan.net/oficina/equipo/internal/runner/containment 0.143s
+```
+
+### GREEN evidence
+
+After implementation, before mutations:
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestNamespace' -count=1
+```
+
+```text
+ok amadan.net/oficina/equipo/internal/runner/containment 2.607s
+```
+
+After restoring all mutations, one run of that same command exited 1:
+
+```text
+--- FAIL: TestNamespaceStartingThreadExit (0.09s)
+ linux_test.go:415: owned unrelated control exited: -1 interrupted system call
+FAIL
+rastrillo-budget/v1 ran 2.032s
+FAIL amadan.net/oficina/equipo/internal/runner/containment 2.034s
+```
+
+The existing `alive` test helper treats an interrupted zero-time poll as a failure. No process exit was reported by poll in this failure. The helper was left unchanged in this focused fix. Both requested gates then passed without changing production or test code:
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestNamespace' -count=1
+make runner-namespace-test
+```
+
+```text
+ok amadan.net/oficina/equipo/internal/runner/containment 2.078s
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestNamespace' -count=1
+ok amadan.net/oficina/equipo/internal/runner/containment 2.047s
+```
+
+These are real Linux namespace tests, including the delegated cgroup capability test; no skips were introduced. `git diff --check` passed and all changed Go files were formatted with gofmt.
+
+### Guard mutations
+
+Each mutation was applied alone and restored in a finally block. All 12 compiled and exited 1 with the named test failing. No mutation survived and no mutation is retained. Commands and complete output follow (the first mutation output repeats the same permission failure for six modes/exit paths).
+
+#### 1. owner-permissions
+
+```diff
+--- internal/runner/containment/recovery.go
++++ internal/runner/containment/recovery.go
+@@ -234,7 +234,7 @@
+ return err
+ }
+ if d.IsDir() {
+- return os.Chmod(path, 0700)
++ return nil
+ }
+ return nil
+ })
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestNamespaceReadOnlyScratch$' -count=1
+```
+
+```text
+--- FAIL: TestNamespaceReadOnlyScratch (0.32s)
+ --- FAIL: TestNamespaceReadOnlyScratch/0555/stop=false (0.06s)
+ recovery_test.go:304: read-only scratch invalidated exit: {Record:{ID:1cda917d4180a745b940c7ba53c748af AttemptKey:attempt-fixture BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID:pid:[4026533069] ManifestHash:fixture-policy HostPID:616268 StartTicks:856354757} Exit:{Code:0 Signal:0 ObservedAt:2026-11-03 11:37:14.847461332 +0000 UTC} Verified:true} namespace_scratch_cleanup: unlinkat /home/paulca/t/e2b/TestNamespaceReadOnlyScratch0555stop=false2958658476/001/state/attempt-1cda917d4180a745b940c7ba53c748af/tmp/cache/nested/file: permission denied
+ linux_test.go:58: cleanup: namespace_scratch_cleanup: unlinkat /home/paulca/t/e2b/TestNamespaceReadOnlyScratch0555stop=false2958658476/001/state/attempt-1cda917d4180a745b940c7ba53c748af/tmp/cache/nested/file: permission denied
+ --- FAIL: TestNamespaceReadOnlyScratch/0555/stop=true (0.05s)
+ recovery_test.go:304: read-only scratch invalidated exit: {Record:{ID:2a0a5c723b7938b622f27977b41db5a5 AttemptKey:attempt-fixture BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID:pid:[4026533132] ManifestHash:fixture-policy HostPID:616277 StartTicks:856354762} Exit:{Code:-1 Signal:9 ObservedAt:2026-11-03 11:37:14.899798178 +0000 UTC} Verified:true} namespace_scratch_cleanup: unlinkat /home/paulca/t/e2b/TestNamespaceReadOnlyScratch0555stop=true1276642074/001/state/attempt-2a0a5c723b7938b622f27977b41db5a5/tmp/cache/nested/file: permission denied
+ linux_test.go:58: cleanup: namespace_scratch_cleanup: unlinkat /home/paulca/t/e2b/TestNamespaceReadOnlyScratch0555stop=true1276642074/001/state/attempt-2a0a5c723b7938b622f27977b41db5a5/tmp/cache/nested/file: permission denied
+ --- FAIL: TestNamespaceReadOnlyScratch/0500/stop=false (0.05s)
+ recovery_test.go:304: read-only scratch invalidated exit: {Record:{ID:e201f34bc599079ab24e2f942b957914 AttemptKey:attempt-fixture BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID:pid:[4026533071] ManifestHash:fixture-policy HostPID:616286 StartTicks:856354767} Exit:{Code:0 Signal:0 ObservedAt:2026-11-03 11:37:14.950980826 +0000 UTC} Verified:true} namespace_scratch_cleanup: unlinkat /home/paulca/t/e2b/TestNamespaceReadOnlyScratch0500stop=false3032694844/001/state/attempt-e201f34bc599079ab24e2f942b957914/tmp/cache/nested/file: permission denied
+ linux_test.go:58: cleanup: namespace_scratch_cleanup: unlinkat /home/paulca/t/e2b/TestNamespaceReadOnlyScratch0500stop=false3032694844/001/state/attempt-e201f34bc599079ab24e2f942b957914/tmp/cache/nested/file: permission denied
+ --- FAIL: TestNamespaceReadOnlyScratch/0500/stop=true (0.05s)
+ recovery_test.go:304: read-only scratch invalidated exit: {Record:{ID:e00521312aba890077d12f7afc5b6041 AttemptKey:attempt-fixture BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID:pid:[4026533132] ManifestHash:fixture-policy HostPID:616295 StartTicks:856354772} Exit:{Code:-1 Signal:9 ObservedAt:2026-11-03 11:37:15.00379682 +0000 UTC} Verified:true} namespace_scratch_cleanup: unlinkat /home/paulca/t/e2b/TestNamespaceReadOnlyScratch0500stop=true1117198659/001/state/attempt-e00521312aba890077d12f7afc5b6041/tmp/cache/nested/file: permission denied
+ linux_test.go:58: cleanup: namespace_scratch_cleanup: unlinkat /home/paulca/t/e2b/TestNamespaceReadOnlyScratch0500stop=true1117198659/001/state/attempt-e00521312aba890077d12f7afc5b6041/tmp/cache/nested/file: permission denied
+ --- FAIL: TestNamespaceReadOnlyScratch/0000/stop=false (0.05s)
+ recovery_test.go:304: read-only scratch invalidated exit: {Record:{ID:992239942fcd9036abb27926e6a555b1 AttemptKey:attempt-fixture BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID:pid:[4026533135] ManifestHash:fixture-policy HostPID:616305 StartTicks:856354778} Exit:{Code:0 Signal:0 ObservedAt:2026-11-03 11:37:15.058119002 +0000 UTC} Verified:true} namespace_scratch_cleanup: open /home/paulca/t/e2b/TestNamespaceReadOnlyScratch0000stop=false1418144697/001/state/attempt-992239942fcd9036abb27926e6a555b1/home: permission denied
+ linux_test.go:58: cleanup: namespace_scratch_cleanup: open /home/paulca/t/e2b/TestNamespaceReadOnlyScratch0000stop=false1418144697/001/state/attempt-992239942fcd9036abb27926e6a555b1/home: permission denied
+ --- FAIL: TestNamespaceReadOnlyScratch/0000/stop=true (0.05s)
+ recovery_test.go:304: read-only scratch invalidated exit: {Record:{ID:80ad49f0dcd9af2bcba593188f4f74f4 AttemptKey:attempt-fixture BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID:pid:[4026533132] ManifestHash:fixture-policy HostPID:616314 StartTicks:856354783} Exit:{Code:-1 Signal:9 ObservedAt:2026-11-03 11:37:15.110908426 +0000 UTC} Verified:true} namespace_scratch_cleanup: open /home/paulca/t/e2b/TestNamespaceReadOnlyScratch0000stop=true2609492772/001/state/attempt-80ad49f0dcd9af2bcba593188f4f74f4/home: permission denied
+ linux_test.go:58: cleanup: namespace_scratch_cleanup: open /home/paulca/t/e2b/TestNamespaceReadOnlyScratch0000stop=true2609492772/001/state/attempt-80ad49f0dcd9af2bcba593188f4f74f4/home: permission denied
+FAIL
+rastrillo-budget/v1 ran 319ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.321s
+FAIL
+```
+
+#### 2. proof-independent
+
+```diff
+--- internal/runner/containment/recovery.go
++++ internal/runner/containment/recovery.go
+@@ -220,7 +220,8 @@
+
+ // Scratch has the durable launch ID. Cleanup cannot undo an observed exit.
+ func (m *Manager) finishRecovery(proof Proof) (Proof, error) {
+- return proof, removeScratch(filepath.Join(m.cfg.ScratchRoot, "attempt-"+proof.Record.ID))
++ err := removeScratch(filepath.Join(m.cfg.ScratchRoot, "attempt-"+proof.Record.ID))
++ if err != nil { proof.Verified = false }; return proof, err
+ }
+
+ func removeScratch(dir string) error {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestNamespaceCleanupFailureKeepsProof$' -count=1
+```
+
+```text
+--- FAIL: TestNamespaceCleanupFailureKeepsProof (0.06s)
+ recovery_test.go:389: cleanup failure changed proof: {Record:{ID:f93c9f0a656cce7ca2f7213268c3bd80 AttemptKey:attempt-fixture BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID:pid:[4026533069] ManifestHash:fixture-policy HostPID:616433 StartTicks:856354816} Exit:{Code:0 Signal:0 ObservedAt:2026-11-03 11:37:15.441338634 +0000 UTC} Verified:false} namespace_scratch_cleanup: unlinkat /home/paulca/t/e2b/TestNamespaceCleanupFailureKeepsProof4160287334/001/state/attempt-f93c9f0a656cce7ca2f7213268c3bd80: permission denied
+FAIL
+rastrillo-budget/v1 ran 55ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.057s
+FAIL
+```
+
+#### 3. cleanup-error
+
+```diff
+--- internal/runner/containment/recovery.go
++++ internal/runner/containment/recovery.go
+@@ -220,7 +220,7 @@
+
+ // Scratch has the durable launch ID. Cleanup cannot undo an observed exit.
+ func (m *Manager) finishRecovery(proof Proof) (Proof, error) {
+- return proof, removeScratch(filepath.Join(m.cfg.ScratchRoot, "attempt-"+proof.Record.ID))
++ _ = removeScratch(filepath.Join(m.cfg.ScratchRoot, "attempt-"+proof.Record.ID)); return proof, nil
+ }
+
+ func removeScratch(dir string) error {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestNamespaceCleanupFailureKeepsProof$' -count=1
+```
+
+```text
+--- FAIL: TestNamespaceCleanupFailureKeepsProof (0.05s)
+ recovery_test.go:389: cleanup failure changed proof: {Record:{ID:de2d4fb06b0fc7b3bb413d95ff3eae08 AttemptKey:attempt-fixture BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID:pid:[4026532943] ManifestHash:fixture-policy HostPID:616640 StartTicks:856354851} Exit:{Code:0 Signal:0 ObservedAt:2026-11-03 11:37:15.78345124 +0000 UTC} Verified:true} <nil>
+FAIL
+rastrillo-budget/v1 ran 46ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.048s
+FAIL
+```
+
+#### 4. symlink-target
+
+```diff
+--- internal/runner/containment/recovery.go
++++ internal/runner/containment/recovery.go
+@@ -233,7 +233,8 @@
+ if err != nil {
+ return err
+ }
+- if d.IsDir() {
++ info, statErr := os.Stat(path)
++ if statErr == nil && info.IsDir() {
+ return os.Chmod(path, 0700)
+ }
+ return nil
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestNamespaceRecoveryReadOnlyScratch$' -count=1
+```
+
+```text
+--- FAIL: TestNamespaceRecoveryReadOnlyScratch (0.05s)
+ recovery_test.go:360: symlink target permissions changed: &{002 4096 2147484096 {99995670 63929302636 0x80d840} {66306 30540801 2 16832 1001 1001 0 0 4096 4096 8 {1793705836 99995670} {1793705836 99995670} {1793705836 99995670} [0 0 0]}} <nil>
+FAIL
+rastrillo-budget/v1 ran 47ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.049s
+FAIL
+```
+
+#### 5. gone-init
+
+```diff
+--- internal/runner/containment/recovery.go
++++ internal/runner/containment/recovery.go
+@@ -57,7 +57,7 @@
+ func exactPID(r Record) (int, error) {
+ fd, e := unix.PidfdOpen(r.HostPID, 0)
+ if e == unix.ESRCH {
+- return -1, errNamespaceExited
++ return -1, errIdentity
+ }
+ if e != nil {
+ return -1, e
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestNamespaceRecoveryCrashBeforeExit$' -count=1
+```
+
+```text
+--- FAIL: TestNamespaceRecoveryCrashBeforeExit (0.05s)
+ recovery_test.go:446: absent init not recovered with unknown outcome: {Record:{ID:6fed6488dc6566b2219008dc106f8316 AttemptKey:parent-death BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID:pid:[4026532942] ManifestHash:parent-policy HostPID:616894 StartTicks:856354913} Exit:{Code:-1 Signal:0 ObservedAt:0001-01-01 00:00:00 +0000 UTC} Verified:false} namespace_identity_unproven
+FAIL
+rastrillo-budget/v1 ran 48ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.050s
+FAIL
+```
+
+#### 6. ticks-mismatch
+
+```diff
+--- internal/runner/containment/recovery.go
++++ internal/runner/containment/recovery.go
+@@ -62,8 +62,8 @@
+ if e != nil {
+ return -1, e
+ }
+- ticks, ns, e := identity(r.HostPID)
+- if errors.Is(e, os.ErrNotExist) || (e == nil && (ticks != r.StartTicks || ns != r.NamespaceID)) {
++ ticks, ns, e := identity(r.HostPID); _ = ticks
++ if errors.Is(e, os.ErrNotExist) || (e == nil && (false || ns != r.NamespaceID)) {
+ unix.Close(fd)
+ return -1, errNamespaceExited
+ }
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestNamespaceRecoveryStaleDurableTicks$' -count=1
+```
+
+```text
+--- FAIL: TestNamespaceRecoveryStaleDurableTicks (0.07s)
+ recovery_test.go:176: absent recorded identity not recovered: {Record:{ID:5ce4122cf3d1ac00af8e0e5e248ccc4e AttemptKey:attempt-fixture BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID:pid:[4026532944] ManifestHash:fixture-policy HostPID:617022 StartTicks:856354944} Exit:{Code:-1 Signal:9 ObservedAt:2026-11-03 11:37:16.708993771 +0000 UTC} Verified:true} <nil>
+FAIL
+rastrillo-budget/v1 ran 69ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.070s
+FAIL
+```
+
+#### 7. namespace-mismatch
+
+```diff
+--- internal/runner/containment/recovery.go
++++ internal/runner/containment/recovery.go
+@@ -63,7 +63,7 @@
+ return -1, e
+ }
+ ticks, ns, e := identity(r.HostPID)
+- if errors.Is(e, os.ErrNotExist) || (e == nil && (ticks != r.StartTicks || ns != r.NamespaceID)) {
++ if errors.Is(e, os.ErrNotExist) || (e == nil && (ticks != r.StartTicks || false)) {
+ unix.Close(fd)
+ return -1, errNamespaceExited
+ }
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestNamespaceRecoveryReusedPID/namespace$' -count=1
+```
+
+```text
+--- FAIL: TestNamespaceRecoveryReusedPID (0.06s)
+ --- FAIL: TestNamespaceRecoveryReusedPID/namespace (0.06s)
+ recovery_test.go:476: absent init not recovered with unknown outcome: {Record:{ID:0c773f6c11bb26406ac753ad3fea1827 AttemptKey:attempt-fixture BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID:pid:[1] ManifestHash:fixture-policy HostPID:617176 StartTicks:856354978} Exit:{Code:-1 Signal:0 ObservedAt:0001-01-01 00:00:00 +0000 UTC} Verified:false} namespace_identity_unproven
+FAIL
+rastrillo-budget/v1 ran 57ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.059s
+FAIL
+```
+
+#### 8. unknown-outcome
+
+```diff
+--- internal/runner/containment/recovery.go
++++ internal/runner/containment/recovery.go
+@@ -191,6 +191,7 @@
+ }
+ fd, e := exactPID(r)
+ if errors.Is(e, errNamespaceExited) {
++ proof.Exit.Code = 0
+ proof.Verified = true
+ proof.Exit.ObservedAt = time.Now().UTC()
+ if e = durableJSON(m.cfg.ScratchRoot, r.ID+".exit.json", proof); e != nil {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestNamespaceRecoveryCrashBeforeExit$' -count=1
+```
+
+```text
+--- FAIL: TestNamespaceRecoveryCrashBeforeExit (0.06s)
+ recovery_test.go:446: absent init not recovered with unknown outcome: {Record:{ID:abffcd565878741acef85b591bd5db30 AttemptKey:parent-death BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID:pid:[4026532944] ManifestHash:parent-policy HostPID:617307 StartTicks:856355006} Exit:{Code:0 Signal:0 ObservedAt:2026-11-03 11:37:17.340388664 +0000 UTC} Verified:true} <nil>
+FAIL
+rastrillo-budget/v1 ran 57ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.059s
+FAIL
+```
+
+#### 9. durable-exit
+
+```diff
+--- internal/runner/containment/recovery.go
++++ internal/runner/containment/recovery.go
+@@ -193,7 +193,7 @@
+ if errors.Is(e, errNamespaceExited) {
+ proof.Verified = true
+ proof.Exit.ObservedAt = time.Now().UTC()
+- if e = durableJSON(m.cfg.ScratchRoot, r.ID+".exit.json", proof); e != nil {
++ if e = error(nil); e != nil {
+ proof.Verified = false
+ return proof, e
+ }
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestNamespaceRecoveryCrashBeforeExit$' -count=1
+```
+
+```text
+--- FAIL: TestNamespaceRecoveryCrashBeforeExit (0.05s)
+ recovery_test.go:446: recovery proof not durable: {Record:{ID:253199739898d5f68e5434a4145f0116 AttemptKey:parent-death BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID:pid:[4026533069] ManifestHash:parent-policy HostPID:617460 StartTicks:856355038} Exit:{Code:-1 Signal:0 ObservedAt:2026-11-03 11:37:17.660847264 +0000 UTC} Verified:true} <nil>
+FAIL
+rastrillo-budget/v1 ran 52ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.053s
+FAIL
+```
+
+#### 10. saved-record-match
+
+```diff
+--- internal/runner/containment/recovery.go
++++ internal/runner/containment/recovery.go
+@@ -186,7 +186,7 @@
+ }
+ stored, readErr := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, r.ID+".json"))
+ var durable Record
+- if readErr != nil || json.Unmarshal(stored, &durable) != nil || durable != r {
++ if readErr != nil || json.Unmarshal(stored, &durable) != nil || false {
+ return proof, errIdentity
+ }
+ fd, e := exactPID(r)
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestNamespaceRecoveryIdentity/reused_pid$' -count=1
+```
+
+```text
+--- FAIL: TestNamespaceRecoveryIdentity (0.07s)
+ --- FAIL: TestNamespaceRecoveryIdentity/reused_pid (0.01s)
+ recovery_test.go:42: uncertain identity accepted: {Record:{ID:2506f4816eb36e89dc8e53f3f870a80f AttemptKey:attempt-fixture BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID:pid:[4026533069] ManifestHash:fixture-policy HostPID:617587 StartTicks:856355070} Exit:{Code:-1 Signal:0 ObservedAt:2026-11-03 11:37:17.965976171 +0000 UTC} Verified:true} <nil>
+ recovery_test.go:64: recover exact identity: {Record:{ID:2506f4816eb36e89dc8e53f3f870a80f AttemptKey:attempt-fixture BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID:pid:[4026533069] ManifestHash:fixture-policy HostPID:617587 StartTicks:856355069} Exit:{Code:-1 Signal:0 ObservedAt:0001-01-01 00:00:00 +0000 UTC} Verified:false} namespace_identity_unproven
+FAIL
+rastrillo-budget/v1 ran 69ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.071s
+FAIL
+```
+
+#### 11. malformed-id
+
+```diff
+--- internal/runner/containment/recovery.go
++++ internal/runner/containment/recovery.go
+@@ -156,8 +156,8 @@
+ // absent, the kernel has finished killing its namespace. Its outcome is unknown.
+ func (m *Manager) Recover(ctx context.Context, r Record) (Proof, error) {
+ proof := Proof{Record: r, Exit: provider.Exit{Code: -1}}
+- _, idErr := hex.DecodeString(r.ID)
+- if len(r.ID) != 32 || idErr != nil || strings.ContainsAny(r.ID, "/.\\") || r.AttemptKey == "" || r.BootID == "" || r.ManifestHash == "" {
++ _, idErr := hex.DecodeString(r.ID); _ = idErr
++ if len(r.ID) != 32 || false || strings.ContainsAny(r.ID, "/.\\") || r.AttemptKey == "" || r.BootID == "" || r.ManifestHash == "" {
+ return proof, errIdentity
+ }
+ boot, e := bootID()
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestNamespaceRecoveryMalformedRecord/id$' -count=1
+```
+
+```text
+--- FAIL: TestNamespaceRecoveryMalformedRecord (0.08s)
+ --- FAIL: TestNamespaceRecoveryMalformedRecord/id (0.08s)
+ recovery_test.go:518: malformed record accepted: {Record:{ID:zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz AttemptKey:attempt-fixture BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID:pid:[4026533069] ManifestHash:fixture-policy HostPID:617712 StartTicks:856355102} Exit:{Code:-1 Signal:0 ObservedAt:2026-11-03 11:37:18.320341693 +0000 UTC} Verified:true} <nil>
+FAIL
+rastrillo-budget/v1 ran 83ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.084s
+FAIL
+```
+
+#### 12. malformed-namespace
+
+```diff
+--- internal/runner/containment/recovery.go
++++ internal/runner/containment/recovery.go
+@@ -170,7 +170,8 @@
+ return m.finishRecovery(proof)
+ }
+ nsID, nsErr := strconv.ParseUint(strings.TrimSuffix(strings.TrimPrefix(r.NamespaceID, "pid:["), "]"), 10, 64)
+- if r.HostPID <= 0 || r.StartTicks == 0 || nsErr != nil || nsID == 0 || r.NamespaceID != fmt.Sprintf("pid:[%d]", nsID) {
++ _ = nsID; _ = nsErr
++ if r.HostPID <= 0 || r.StartTicks == 0 || r.NamespaceID == "" {
+ return proof, errIdentity
+ }
+ saved, readErr := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, r.ID+".exit.json"))
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestNamespaceRecoveryMalformedRecord/namespace$' -count=1
+```
+
+```text
+--- FAIL: TestNamespaceRecoveryMalformedRecord (0.09s)
+ --- FAIL: TestNamespaceRecoveryMalformedRecord/namespace (0.09s)
+ recovery_test.go:518: malformed record accepted: {Record:{ID:4c7eb1621774dd6be136f34847a2976d AttemptKey:attempt-fixture BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID:invalid ManifestHash:fixture-policy HostPID:617855 StartTicks:856355138} Exit:{Code:-1 Signal:0 ObservedAt:2026-11-03 11:37:18.688079894 +0000 UTC} Verified:true} <nil>
+FAIL
+rastrillo-budget/v1 ran 89ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.090s
+FAIL
+```
+
+### User-facing strings
+
+No UI text, README prose or copy.go entries were added. New internal strings are `namespace_exited` (the private identity result) and `namespace_scratch_cleanup` (the cleanup error prefix, followed by the underlying filesystem error). If mapped into the app later, they need individually pending copy.go entries and review before release. New test diagnostics concern invalidated proof, retained scratch, changed symlink targets, cleanup retry, unreaped init, missing or non-durable inferred proof, and malformed records. No copy-review skill or server was invoked.
+
+### Concerns and handback
+
+The existing test-helper EINTR failure occurred once and is recorded above; the final covering gates pass. The controller still owns remote CI verification and independent review. No push, merge, deployment, provider prompt, sign-in, enrolment, credential home, agent or subagent was used. No full suite or make ci ran.
+
+All test-owned processes and scratch were cleaned up. The mutation evidence directory is removed after transferring its contents into both reports. No server or watcher was started. The branch is ready for controller review.
diff --git a/internal/runner/containment/linux.go b/internal/runner/containment/linux.go
index 928de68c..f863b1e2 100644
--- a/internal/runner/containment/linux.go
+++ b/internal/runner/containment/linux.go
@@ -356,10 +356,9 @@ func (m *Manager) lifecycle(ctx context.Context, r Record, argv []string, mounts
p.proof.Verified = false
}
}
- if cleanupErr := os.RemoveAll(dir); cleanupErr != nil && p.err == nil {
- p.err = cleanupErr
- p.proof.Verified = false
- }
+ var cleanupErr error
+ p.proof, cleanupErr = m.finishRecovery(p.proof)
+ p.err = errors.Join(p.err, cleanupErr)
cleanupScratch = false
close(p.done)
}
diff --git a/internal/runner/containment/linux_test.go b/internal/runner/containment/linux_test.go
index fbf88912..4e28ea1e 100644
--- a/internal/runner/containment/linux_test.go
+++ b/internal/runner/containment/linux_test.go
@@ -272,6 +272,10 @@ func TestNamespaceCgroupMoveKeepsMembership(t *testing.T) {
exited(t, fd)
}
func TestNamespaceHidesHostControl(t *testing.T) {
+ home, e := os.UserHomeDir()
+ if e != nil {
+ t.Fatal(e)
+ }
m, l := fixture(t)
listener, e := net.Listen("tcp", "127.0.0.1:0")
if e != nil {
@@ -295,7 +299,7 @@ func TestNamespaceHidesHostControl(t *testing.T) {
l.Policy.Env = map[string]string{"LANG": "C.UTF-8"}
t.Setenv("EQUIPO_TEST_HOST_SECRET", "must-not-inherit")
p := launch(t, m, l, fmt.Sprintf(`import os,socket,json
-paths=['/sys/fs/cgroup','/run/user/%d/bus','/run/user/%d/systemd/private','/home/paulca','/proc/1/root/home/paulca','/etc/claude-code/managed-settings.json','/etc/codex/config.toml']
+paths=['/sys/fs/cgroup','/run/user/%d/bus','/run/user/%d/systemd/private',%s,%s,'/etc/claude-code/managed-settings.json','/etc/codex/config.toml']
assert all(not os.path.exists(p) for p in paths), paths
assert os.listdir('/home')==['runner']
assert 'EQUIPO_TEST_HOST_SECRET' not in os.environ
@@ -309,7 +313,7 @@ try:
raise AssertionError('cgroup exposed')
except OSError: pass
print('isolated')
-`, os.Getuid(), os.Getuid(), listener.Addr().(*net.TCPAddr).Port))
+`, os.Getuid(), os.Getuid(), strconv.Quote(home), strconv.Quote("/proc/1/root"+home), listener.Addr().(*net.TCPAddr).Port))
output, e := io.ReadAll(p.Stdout())
if e != nil {
t.Fatal(e)
diff --git a/internal/runner/containment/recovery.go b/internal/runner/containment/recovery.go
index 74149455..def9c643 100644
--- a/internal/runner/containment/recovery.go
+++ b/internal/runner/containment/recovery.go
@@ -2,6 +2,7 @@ package containment
import (
"context"
+ "encoding/hex"
"encoding/json"
"errors"
"fmt"
@@ -27,6 +28,7 @@ type Proof struct {
}
var errIdentity = errors.New("namespace_identity_unproven")
+var errNamespaceExited = errors.New("namespace_exited")
func bootID() (string, error) {
b, e := os.ReadFile("/proc/sys/kernel/random/boot_id")
@@ -54,11 +56,29 @@ func identity(pid int) (uint64, string, error) {
}
func exactPID(r Record) (int, error) {
fd, e := unix.PidfdOpen(r.HostPID, 0)
+ if e == unix.ESRCH {
+ return -1, errNamespaceExited
+ }
if e != nil {
return -1, e
}
ticks, ns, e := identity(r.HostPID)
- if e != nil || ticks != r.StartTicks || ns != r.NamespaceID {
+ if errors.Is(e, os.ErrNotExist) || (e == nil && (ticks != r.StartTicks || ns != r.NamespaceID)) {
+ unix.Close(fd)
+ return -1, errNamespaceExited
+ }
+ if e != nil {
+ unix.Close(fd)
+ return -1, errIdentity
+ }
+ // Check exit before /proc status: an exiting init may already have lost it.
+ polls := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}}
+ n, e := unix.Poll(polls, 0)
+ if e == nil && n > 0 && polls[0].Revents&unix.POLLIN != 0 {
+ unix.Close(fd)
+ return -1, errNamespaceExited
+ }
+ if e != nil || n != 0 {
unix.Close(fd)
return -1, errIdentity
}
@@ -76,14 +96,6 @@ func exactPID(r Record) (int, error) {
unix.Close(fd)
return -1, errIdentity
}
- // A readable descriptor refers to an exited process, even if the PID has
- // already been recycled while /proc was read. Never signal that replacement.
- polls := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}}
- n, e := unix.Poll(polls, 0)
- if e != nil || n != 0 {
- unix.Close(fd)
- return -1, errIdentity
- }
return fd, nil
}
func waitPID(ctx context.Context, fd int) error {
@@ -140,11 +152,12 @@ func durableJSON(root, name string, v any) error {
return d.Sync()
}
-// Recover never enumerates host processes. An absent same-boot PID without a
-// durable exit proof remains uncertain; a new boot proves absence, not outcome.
+// Recover never enumerates host processes. Once the saved init identity is
+// absent, the kernel has finished killing its namespace. Its outcome is unknown.
func (m *Manager) Recover(ctx context.Context, r Record) (Proof, error) {
proof := Proof{Record: r, Exit: provider.Exit{Code: -1}}
- if len(r.ID) != 32 || strings.ContainsAny(r.ID, "/.\\") || r.AttemptKey == "" || r.BootID == "" || r.ManifestHash == "" {
+ _, idErr := hex.DecodeString(r.ID)
+ if len(r.ID) != 32 || idErr != nil || strings.ContainsAny(r.ID, "/.\\") || r.AttemptKey == "" || r.BootID == "" || r.ManifestHash == "" {
return proof, errIdentity
}
boot, e := bootID()
@@ -156,7 +169,8 @@ func (m *Manager) Recover(ctx context.Context, r Record) (Proof, error) {
proof.Exit.ObservedAt = time.Now().UTC()
return m.finishRecovery(proof)
}
- if r.HostPID <= 0 || r.StartTicks == 0 || r.NamespaceID == "" {
+ nsID, nsErr := strconv.ParseUint(strings.TrimSuffix(strings.TrimPrefix(r.NamespaceID, "pid:["), "]"), 10, 64)
+ if r.HostPID <= 0 || r.StartTicks == 0 || nsErr != nil || nsID == 0 || r.NamespaceID != fmt.Sprintf("pid:[%d]", nsID) {
return proof, errIdentity
}
saved, readErr := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, r.ID+".exit.json"))
@@ -176,6 +190,15 @@ func (m *Manager) Recover(ctx context.Context, r Record) (Proof, error) {
return proof, errIdentity
}
fd, e := exactPID(r)
+ if errors.Is(e, errNamespaceExited) {
+ proof.Verified = true
+ proof.Exit.ObservedAt = time.Now().UTC()
+ if e = durableJSON(m.cfg.ScratchRoot, r.ID+".exit.json", proof); e != nil {
+ proof.Verified = false
+ return proof, e
+ }
+ return m.finishRecovery(proof)
+ }
if e != nil {
return proof, errIdentity
}
@@ -195,12 +218,31 @@ func (m *Manager) Recover(ctx context.Context, r Record) (Proof, error) {
return m.finishRecovery(proof)
}
-// Scratch has the durable launch ID, so recovery can remove only this attempt
-// after proving its namespace gone. Unknown same-boot identities keep it.
+// Scratch has the durable launch ID. Cleanup cannot undo an observed exit.
func (m *Manager) finishRecovery(proof Proof) (Proof, error) {
- if err := os.RemoveAll(filepath.Join(m.cfg.ScratchRoot, "attempt-"+proof.Record.ID)); err != nil {
- proof.Verified = false
- return proof, err
+ return proof, removeScratch(filepath.Join(m.cfg.ScratchRoot, "attempt-"+proof.Record.ID))
+}
+
+func removeScratch(dir string) error {
+ // Namespace members are gone before this walk. WalkDir does not follow
+ // symlinks, including the root, so only owned scratch directories change.
+ err := filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error {
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ if d.IsDir() {
+ return os.Chmod(path, 0700)
+ }
+ return nil
+ })
+ if err == nil {
+ err = os.RemoveAll(dir)
+ }
+ if err != nil {
+ return fmt.Errorf("namespace_scratch_cleanup: %w", err)
}
- return proof, nil
+ return nil
}
diff --git a/internal/runner/containment/recovery_test.go b/internal/runner/containment/recovery_test.go
index 3532f980..4014b08f 100644
--- a/internal/runner/containment/recovery_test.go
+++ b/internal/runner/containment/recovery_test.go
@@ -4,12 +4,16 @@ import (
"bufio"
"context"
"encoding/json"
+ "errors"
+ "fmt"
"os"
+ "os/exec"
"path/filepath"
"testing"
"time"
"amadan.net/oficina/equipo/internal/runner/provider"
+ "golang.org/x/sys/unix"
)
func TestNamespaceRecoveryIdentity(t *testing.T) {
@@ -62,6 +66,10 @@ func TestNamespaceRecoveryIdentity(t *testing.T) {
exited(t, fd)
}
func TestNamespaceMountEscape(t *testing.T) {
+ home, e := os.UserHomeDir()
+ if e != nil {
+ t.Fatal(e)
+ }
m, l := fixture(t)
outsideHome := t.TempDir()
if e := os.Chmod(outsideHome, 0700); e != nil {
@@ -73,7 +81,7 @@ func TestNamespaceMountEscape(t *testing.T) {
}{
{"traversal", func(l *provider.Launch) { l.Workspace += "/../workspace" }},
{"outside private home", func(l *provider.Launch) { l.Binding.Home = outsideHome }},
- {"broad home", func(l *provider.Launch) { l.Binding.Home = "/home/paulca" }},
+ {"broad home", func(l *provider.Launch) { l.Binding.Home = home }},
{"protected state", func(l *provider.Launch) { l.Workspace = m.cfg.ScratchRoot }},
{"parent of protected state", func(l *provider.Launch) { l.Workspace = filepath.Dir(m.cfg.ScratchRoot) }},
{"host runtime", func(l *provider.Launch) {
@@ -164,14 +172,14 @@ func TestNamespaceRecoveryStaleDurableTicks(t *testing.T) {
t.Fatal(e)
}
defer m.persist(r)
- if proof, e := m.Recover(context.Background(), bad); e == nil || proof.Verified {
- t.Fatal("reused PID accepted")
+ if proof, e := m.Recover(context.Background(), bad); e != nil || !proof.Verified || proof.Exit.Code != -1 || proof.Exit.Signal != 0 {
+ t.Fatalf("absent recorded identity not recovered: %+v %v", proof, e)
}
alive(t, fd)
}
func TestNamespaceRecoveryUnavailableProof(t *testing.T) {
- for _, kind := range []string{"missing", "corrupt", "record", "unverified", "timestamp"} {
+ for _, kind := range []string{"corrupt", "record", "unverified", "timestamp"} {
t.Run(kind, func(t *testing.T) {
m, l := fixture(t)
p := launch(t, m, l, "pass")
@@ -189,8 +197,6 @@ func TestNamespaceRecoveryUnavailableProof(t *testing.T) {
t.Fatal(e)
}
switch kind {
- case "missing":
- e = os.Remove(path)
case "corrupt":
e = os.WriteFile(path, []byte("{"), 0600)
case "record":
@@ -253,3 +259,264 @@ func TestNamespaceScratchIdentity(t *testing.T) {
t.Fatalf("scratch not bound to durable ID: %v", e)
}
}
+
+// Restore fixture permissions even when testing the unfixed implementation.
+func writableFixture(t *testing.T, dir string) {
+ t.Helper()
+ t.Cleanup(func() {
+ _ = filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error {
+ if err == nil && d.IsDir() {
+ return os.Chmod(path, 0700)
+ }
+ return err
+ })
+ })
+}
+
+func TestNamespaceReadOnlyScratch(t *testing.T) {
+ for _, mode := range []int{0555, 0500, 0000} {
+ for _, stop := range []bool{false, true} {
+ t.Run(fmt.Sprintf("%04o/stop=%t", mode, stop), func(t *testing.T) {
+ m, l := fixture(t)
+ script := fmt.Sprintf(`import os,sys
+for base in ['/tmp', '/home/runner']:
+ os.makedirs(base+'/cache/nested')
+ open(base+'/cache/nested/file','w').write('owned')
+ os.chmod(base+'/cache/nested',%d)
+ os.chmod(base+'/cache',%d)
+ os.chmod(base,%d)
+print('ready',flush=True)
+sys.stdin.readline()
+`, mode, mode, mode)
+ p := launch(t, m, l, script)
+ r := record(t, m, p)
+ dir := filepath.Join(m.cfg.ScratchRoot, "attempt-"+r.ID)
+ writableFixture(t, dir)
+ if _, e := bufio.NewReader(p.Stdout()).ReadString('\n'); e != nil {
+ t.Fatal(e)
+ }
+ if !stop {
+ p.Stdin().Close()
+ _, _ = p.Wait(context.Background())
+ }
+ proof, e := m.Stop(context.Background(), r.ID)
+ if e != nil || !proof.Verified {
+ t.Fatalf("read-only scratch invalidated exit: %+v %v", proof, e)
+ }
+ if _, e := os.Stat(dir); !os.IsNotExist(e) {
+ t.Fatalf("scratch remains: %v", e)
+ }
+ recovered, e := m.Recover(context.Background(), r)
+ if e != nil || recovered != proof {
+ t.Fatalf("saved proof changed: %+v %v", recovered, e)
+ }
+ })
+ }
+ }
+}
+
+func TestNamespaceRecoveryReadOnlyScratch(t *testing.T) {
+ m, l := fixture(t)
+ p := launch(t, m, l, "pass")
+ r := record(t, m, p)
+ if _, e := p.Wait(context.Background()); e != nil {
+ t.Fatal(e)
+ }
+ dir := filepath.Join(m.cfg.ScratchRoot, "attempt-"+r.ID)
+ nested := filepath.Join(dir, "cache", "nested")
+ if e := os.MkdirAll(nested, 0700); e != nil {
+ t.Fatal(e)
+ }
+ writableFixture(t, dir)
+ if e := os.WriteFile(filepath.Join(nested, "file"), []byte("owned"), 0400); e != nil {
+ t.Fatal(e)
+ }
+ outside := t.TempDir()
+ marker := filepath.Join(outside, "keep")
+ if e := os.WriteFile(marker, []byte("outside"), 0400); e != nil {
+ t.Fatal(e)
+ }
+ if e := os.Symlink(outside, filepath.Join(nested, "link")); e != nil {
+ t.Fatal(e)
+ }
+ if e := os.Chmod(outside, 0500); e != nil {
+ t.Fatal(e)
+ }
+ defer os.Chmod(outside, 0700)
+ for _, path := range []string{nested, filepath.Dir(nested), dir} {
+ if e := os.Chmod(path, 0500); e != nil {
+ t.Fatal(e)
+ }
+ }
+ proof, e := m.Recover(context.Background(), r)
+ if e != nil || !proof.Verified {
+ t.Fatalf("read-only recovery invalidated exit: %+v %v", proof, e)
+ }
+ if _, e := os.Stat(dir); !os.IsNotExist(e) {
+ t.Fatalf("scratch remains: %v", e)
+ }
+ info, e := os.Stat(outside)
+ if e != nil || info.Mode().Perm() != 0500 {
+ t.Fatalf("symlink target permissions changed: %v %v", info, e)
+ }
+ if b, e := os.ReadFile(marker); e != nil || string(b) != "outside" {
+ t.Fatalf("symlink target changed: %q %v", b, e)
+ }
+}
+
+func TestNamespaceCleanupFailureKeepsProof(t *testing.T) {
+ m, l := fixture(t)
+ p := launch(t, m, l, "pass")
+ r := record(t, m, p)
+ if _, e := p.Wait(context.Background()); e != nil {
+ t.Fatal(e)
+ }
+ want, e := m.Stop(context.Background(), r.ID)
+ if e != nil {
+ t.Fatal(e)
+ }
+ dir := filepath.Join(m.cfg.ScratchRoot, "attempt-"+r.ID)
+ if e := os.Mkdir(dir, 0700); e != nil {
+ t.Fatal(e)
+ }
+ if e := os.Chmod(m.cfg.ScratchRoot, 0500); e != nil {
+ t.Fatal(e)
+ }
+ defer os.Chmod(m.cfg.ScratchRoot, 0700)
+ for range 2 {
+ proof, e := m.Recover(context.Background(), r)
+ if !errors.Is(e, os.ErrPermission) || proof != want {
+ t.Fatalf("cleanup failure changed proof: %+v %v", proof, e)
+ }
+ }
+ if e := os.Chmod(m.cfg.ScratchRoot, 0700); e != nil {
+ t.Fatal(e)
+ }
+ proof, e := m.Recover(context.Background(), r)
+ if e != nil || proof != want {
+ t.Fatalf("cleanup retry: %+v %v", proof, e)
+ }
+ if _, e := os.Stat(dir); !os.IsNotExist(e) {
+ t.Fatalf("scratch remains: %v", e)
+ }
+}
+
+func TestNamespaceRecoveryCrashBeforeExit(t *testing.T) {
+ m, l := fixture(t)
+ c := exec.Command(os.Args[0])
+ c.Env = append(os.Environ(), "EQUIPO_NAMESPACE_PARENT_TEST=1", "EQUIPO_TEST_STATE="+m.cfg.ScratchRoot, "EQUIPO_TEST_WORKSPACE="+l.Workspace)
+ stdout, e := c.StdoutPipe()
+ if e != nil {
+ t.Fatal(e)
+ }
+ c.Stderr = os.Stderr
+ if e = c.Start(); e != nil {
+ t.Fatal(e)
+ }
+ t.Cleanup(func() { c.Process.Kill(); c.Wait() })
+ var r Record
+ if e = json.NewDecoder(stdout).Decode(&r); e != nil {
+ t.Fatal(e)
+ }
+ fd := descriptor(t, r.HostPID)
+ t.Cleanup(func() { unix.PidfdSendSignal(fd, unix.SIGKILL, nil, 0) })
+ if e = c.Process.Kill(); e != nil {
+ t.Fatal(e)
+ }
+ c.Wait()
+ exited(t, fd)
+ deadline := time.Now().Add(5 * time.Second)
+ for {
+ probe, err := unix.PidfdOpen(r.HostPID, 0)
+ if err == unix.ESRCH {
+ break
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ unix.Close(probe)
+ if time.Now().After(deadline) {
+ t.Fatal("namespace init was not reaped")
+ }
+ time.Sleep(time.Millisecond)
+ }
+ if _, e := os.Stat(filepath.Join(m.cfg.ScratchRoot, r.ID+".exit.json")); !os.IsNotExist(e) {
+ t.Fatalf("crash fixture has exit proof: %v", e)
+ }
+ assertUnknownRecovery(t, m, r)
+}
+
+func TestNamespaceRecoveryReusedPID(t *testing.T) {
+ for _, kind := range []string{"ticks", "namespace"} {
+ t.Run(kind, func(t *testing.T) {
+ m, l := fixture(t)
+ p := launch(t, m, l, "pass")
+ r := record(t, m, p)
+ if _, e := p.Wait(context.Background()); e != nil {
+ t.Fatal(e)
+ }
+ if e := os.Remove(filepath.Join(m.cfg.ScratchRoot, r.ID+".exit.json")); e != nil {
+ t.Fatal(e)
+ }
+ control, fd := ownedControl(t)
+ r.HostPID = control.Process.Pid
+ ticks, ns, e := identity(r.HostPID)
+ if e != nil {
+ t.Fatal(e)
+ }
+ r.StartTicks, r.NamespaceID = ticks, ns
+ if kind == "ticks" {
+ r.StartTicks++
+ } else {
+ r.NamespaceID = "pid:[1]"
+ }
+ if e := m.persist(r); e != nil {
+ t.Fatal(e)
+ }
+ assertUnknownRecovery(t, m, r)
+ alive(t, fd)
+ })
+ }
+}
+
+func assertUnknownRecovery(t *testing.T, m *Manager, r Record) {
+ t.Helper()
+ proof, e := m.Recover(context.Background(), r)
+ if e != nil || !proof.Verified || proof.Record != r || proof.Exit.Code != -1 || proof.Exit.Signal != 0 || proof.Exit.ObservedAt.IsZero() {
+ t.Fatalf("absent init not recovered with unknown outcome: %+v %v", proof, e)
+ }
+ again, e := m.Recover(context.Background(), r)
+ if e != nil || again != proof {
+ t.Fatalf("recovery proof not durable: %+v %v", again, e)
+ }
+ if _, e := os.Stat(filepath.Join(m.cfg.ScratchRoot, "attempt-"+r.ID)); !os.IsNotExist(e) {
+ t.Fatalf("scratch remains: %v", e)
+ }
+}
+
+func TestNamespaceRecoveryMalformedRecord(t *testing.T) {
+ for _, kind := range []string{"namespace", "id"} {
+ t.Run(kind, func(t *testing.T) {
+ m, l := fixture(t)
+ p := launch(t, m, l, "pass")
+ r := record(t, m, p)
+ if _, e := p.Wait(context.Background()); e != nil {
+ t.Fatal(e)
+ }
+ if e := os.Remove(filepath.Join(m.cfg.ScratchRoot, r.ID+".exit.json")); e != nil {
+ t.Fatal(e)
+ }
+ if kind == "namespace" {
+ r.NamespaceID = "invalid"
+ } else {
+ r.ID = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
+ }
+ if e := m.persist(r); e != nil {
+ t.Fatal(e)
+ }
+ if proof, e := m.Recover(context.Background(), r); !errors.Is(e, errIdentity) || proof.Verified {
+ t.Fatalf("malformed record accepted: %+v %v", proof, e)
+ }
+ })
+ }
+}