runner: Task 17 review 1, prove start errors, stop on an unproven base
A start that fails after its namespace was recorded ends only once that namespace's exit is established. checkrun prepares and launches a diagnostic only after a proven base run, so the step keeps the base run's namespace. Tests for the receiver's per-kind limits past 64 MiB, and for refused bundles (hash mismatch, unsafe zip) launching nothing.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
7 files changed,
+371
−11
.rastrillo/budgets.txt+2 −2docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md+40 −0internal/runner/checkrun/run.go+13 −6internal/runner/checkrun/run_test.go+54 −0internal/runner/linuxworker/gate.go+13 −1internal/runner/linuxworker/worker_test.go+193 −2internal/runner/thin/hosted_worker_test.go+56 −0
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index d927dfda..dbe0d351 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -39,8 +39,8 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full |
| perf GET /releases/* skip Verified runner release file downloads, not browser GET screens. |
| perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen. |
| time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s; |
| -time internal/runner/linuxworker 30s Hosted slice 2 Task 17: each test starts real bubblewrap namespaces through the containment manager over real git stores (base gates, pins, restart and cancel proof, offline, staged cache, six dependency outcomes); measured 11.6 to 14.5s on a loaded docs-t1. |
| -size internal/runner/thin 36073 35768 Protocols 31-35, merge credential, publication guards, kept work, scans, 36 lookups; Mac pin, Engineering, asks, F probes, D1, P2, held reports; 38 Design step, renderer; hosted slice 2 Task 11 moved the base-gate checks to checkrun (source down) and pinned the primary and Mac behaviour with tests (test up), and its round 1 fixes added the worker step-engine wiring test; Task 12 added Link.TokenSource and Link.HTTPClient (a hosted runner's bearer is read at each dial and its dial goes through the proxy) and their two tests; 35831/35453. Task 14 review round 1 added Link.ReconnectWait (the wait between connections, a fake clock's in the hosted renewal tests, which drive the real Link through certificate rotation and bearer renewal); 35839/35453. Task 15: the hosted pack (inboundHeader selects by attempt and kind, Worker.Hosted indexes the base and the candidate into an empty store, pack_incomplete) and hosted_pack_test.go; 35863/35688. Task 17 wiring for the Linux checks worker (hosted_worker.go): Options.Hosted (HostedLink: the session's in-memory credential, proxy client, Work context, Flush on a failed renewal and token_renewal_failed), WorkerKind.Checks and Probe, runHosted, the Linux worker refusal outside hosted-run, the hand-off of an indexed hosted attempt and its deps bundle to the kind's checks, the receiver's per-kind transfer limits; its two tests; 36073/35768. |
| +time internal/runner/linuxworker 30s Hosted slice 2 Task 17: each test starts real bubblewrap namespaces through the containment manager over real git stores (base gates, pins, restart and cancel proof, offline, staged cache, six dependency outcomes); measured 11.6 to 14.5s on a loaded docs-t1; review round 1 tests: 15 to 23s under load. |
| +size internal/runner/thin 36076 35824 Protocols 31-35, merge credential, publication guards, kept work, scans, 36 lookups; Mac pin, Engineering, asks, F probes, D1, P2, held reports; 38 Design step, renderer; hosted slice 2 Task 11 moved the base-gate checks to checkrun (source down) and pinned the primary and Mac behaviour with tests (test up), and its round 1 fixes added the worker step-engine wiring test; Task 12 added Link.TokenSource and Link.HTTPClient (a hosted runner's bearer is read at each dial and its dial goes through the proxy) and their two tests; 35831/35453. Task 14 review round 1 added Link.ReconnectWait (the wait between connections, a fake clock's in the hosted renewal tests, which drive the real Link through certificate rotation and bearer renewal); 35839/35453. Task 15: the hosted pack (inboundHeader selects by attempt and kind, Worker.Hosted indexes the base and the candidate into an empty store, pack_incomplete) and hosted_pack_test.go; 35863/35688. Task 17 wiring for the Linux checks worker (hosted_worker.go): Options.Hosted (HostedLink: the session's in-memory credential, proxy client, Work context, Flush on a failed renewal and token_renewal_failed), WorkerKind.Checks and Probe, runHosted, the Linux worker refusal outside hosted-run, the hand-off of an indexed hosted attempt and its deps bundle to the kind's checks, the receiver's per-kind transfer limits; its two tests; 36073/35768. Review round 1: the deps header checked before the wait, and TestDepsPackPerKindLimits (the receiver past the old 64 MiB and chunk limits); 36076/35824. |
| time internal/thintest 240s Thin contract and page tests, the Assistant's and the models' included, share one harness. Measured 202s on a shared 16 CPU box (2026-11-13); CI runs two lanes. |
| time internal/runner/mac 45s Real processes killed and proven gone: groups, sessions, the runner-user sweep, turns, restarts; probes end to end. Measured 29.3s locally. |
| time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s). |
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md| index ca432217..e9aed4ec 100644 |
| --- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| +++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| @@ -1297,3 +1297,43 @@ Mutations (each applied by an exact-string replace from a script under `$TMPDIR` |
| - **210** the worker refuses the deps transfer (Valid closed to deps again). In `internal/wire/mac_engineering.go`, `case TransferKindHostedPack, TransferKindDeps:` became `case TransferKindHostedPack:`. `CGO_ENABLED=0 go test ./internal/runner/linuxworker -run TestHostedBaseGatesFromBase -count=1`: exit 1, `worker_test.go:308: report {ChangeDiffs: ChangeFiles:<nil> BaseChecks: BaseChecksSHA: Failure:<nil> Copy:<nil> TaskID:tk1 StepID:s1 Attempt:1 State:failed Reason:placement_refused BaseSHA:87b34786f707...`. Restored (`cp`, `cmp` identical). |
| Mutations 197 and 201 first failed to build (an unused variable); they were rewritten as above and then failed on their assertions. 204 first removed only the kill on cancel and survived, because `Run`'s deferred `kill` still ended the namespace; it was rewritten to remove every kill. 208 first hung its test until the go test timeout; `TestHostedRunRenewal` now bounds that wait and fails with the line above. |
| + |
| +### Task 17 review round 1 (t17-r1.md: findings 1 to 3 fixed, worker-level refused bundles added; finding 4 ruled exempt) |
| + |
| +Rulings: finding 4 (the log tail's "Not run: the dependencies were refused (...)") is exempt, as technical output. The order (index the hosted pack, then await the deps bundle) is accepted. |
| + |
| +1. **A start error proves nothing by itself.** `bwrapGate.Run` now keeps the namespace ID once its record is kept. When the start then fails, the run is `Terminated` only if `Verify` establishes that namespace's exit (containment's exit proof, through `Forget`). Otherwise it is `Terminated: false` and the record stays for recovery. A start that failed before any record stays `Terminated: true`. |
| +2. **An unproven base run stops the run.** In `checkrun.Run`, the diagnostic's preparation (`Inputs.Diagnostic`) moved after the base gate run, under the same guard as its launch: `certified && changedGate && res.Terminated`. An unproven base run therefore prepares and launches nothing more. The step keeps the base run's namespace ID, and the existing tail fails the run `StepFailed`, unterminated, with the base's reason. |
| + - **The primary's behaviour** is otherwise identical: `TestPrimaryChecksUnchanged` and every checkrun test pass unchanged. |
| + - It differs in only two places: |
| + - An unproven certified base run whose candidate changed a gate file no longer runs a diagnostic. The report's output is the base run's alone, not the composed diagnostic text. |
| + - A diagnostic tree that cannot be prepared is now found after the base run. It still ends `cannot_run` `checks_unavailable`, and the base run's `BaseChecks` and `BaseChecksSHA` are cleared, so the report is the same as before (`TestChecksRunDiagnosticUnavailable`). |
| +3. **Receiver limits.** `TestDepsPackPerKindLimits` (thin) sends a 67,256,334-byte deps transfer in 457 chunks, past both the old 64 MiB and its 456 chunks. `State.pack` assembles it byte for byte. The same chunks as a `hosted_pack` are refused, and so is a deps transfer declaring `MaxChunks(deps)+1` chunks. |
| +4. **Refused bundles.** `TestHostedDepsRefused` covers a module whose .mod does not match the base pin (`ErrHashMismatch`) and a zip holding `../../escape.go` (`ErrUnsafePath`). Each ends `cannot_run` `checks_unavailable`, the log tail names the error, and no gate is launched. Launches are counted at the gate's `start`, as the review asked. `TestHostedDeps` now asserts zero launches the same way. |
| + |
| +Red, before the fixes: |
| +- `go test ./internal/runner/linuxworker -run 'TestHostedStartErrorUnverified|TestHostedUnprovenBaseStops' -count=1` failed: |
| + - `worker_test.go:809: verified exit false: result {... Reason:checks_unavailable Code:0 Terminated:true ...}, record left true, recorded [00000000000000000000000000000001]` |
| + - `worker_test.go:837: launches [".../tree" ".../tree-diagnostic"], want only the base gate's` |
| +- `go test ./internal/runner/checkrun -run TestChecksRunStopsOnUnprovenBase -count=1` failed: `run_test.go:269: runs [{argv:[/usr/bin/make ci] ...} ...]` (two runs, a diagnostic prepared). |
| +- The fixture first wrote a made-up boot ID, which containment proves ended by itself (another boot). It now writes `/proc/sys/kernel/random/boot_id`, and the test still fails on the unfixed code (mutation 211). |
| +- `TestDepsPackPerKindLimits` and `TestHostedDepsRefused` cover code that already existed: mutations 214 to 217 are their failing evidence. `TestChecksRunDiagnosticUnavailable` was written with its fix: mutation 218 is its evidence. |
| + |
| +Green: |
| +- `CGO_ENABLED=0 go test ./internal/runner/linuxworker ./internal/runner/thin -run 'TestHosted|TestLinuxWorker|TestPrimaryChecks|TestDepsPack' -count=1`: ok (linuxworker 15 to 23 s under load, thin 36 s). |
| +- `go test ./internal/runner/checkrun -count=1`: ok. |
| +- `make budget build vet`: exit 0. The thin record is 36076/35824, with the reason added. gofmt and `git diff --check`: clean. |
| + |
| +`make runner-namespace-test` on docs-t1 is green (exit 0) with an on-disk TMPDIR short enough for the Unix socket paths: `T=$(mktemp -d /home/paulca/t17-XXXX); TMPDIR=$T make runner-namespace-test; rm -rf "$T"`. The suggested `/home/paulca/.cache/t17-XXXX` was still too long: `TestNamespaceOpenCodeBinaryAfterAttestation` and `TestNamespacePiTreeSwapAfterAttestation` failed with `bind: invalid argument`, the same failure as before. Both directories were removed. |
| + |
| +Mutations (scripted exact-string replace under `$TMPDIR`, one at a time, the file restored from a copy and `cmp`-checked): |
| +- **211** a start error always reports Terminated (no exit proof for a recorded namespace). In `internal/runner/linuxworker/gate.go`, `unavailable.Terminated = recorded == "" || g.Verify(recorded)` became `unavailable.Terminated = recorded == "" || true`. `CGO_ENABLED=0 go test ./internal/runner/linuxworker -run TestHostedStartErrorUnverified -count=1`: exit 1, `worker_test.go:898: verified exit false: result {Output: Reason:checks_unavailable Code:0 Terminated:true Sandbox:bubblewrap Evidence:<nil>}, record left true, recorded [000000000000000000000000000000`. Restored (`cp`, `cmp` identical). |
| +- **212** the diagnostic is prepared and launched after an unproven base run (checkrun). In `internal/runner/checkrun/run.go`, `if certified && changedGate && res.Terminated {` became `if certified && changedGate {`. `CGO_ENABLED=0 go test ./internal/runner/checkrun -run TestChecksRunStopsOnUnprovenBase -count=1`: exit 1, `run_test.go:269: runs [{argv:[/usr/bin/make ci] dir:/home/paulca/.cache/tmp/TestChecksRunStopsOnUnprovenBase1046359132/002/tree pins:[{Source:/home/paulca/.cache/tmp/TestChecksRunStopsOnUnprovenBase10`. Restored (`cp`, `cmp` identical). |
| +- **213** the same, through the hosted worker. In `internal/runner/checkrun/run.go`, `if certified && changedGate && res.Terminated {` became `if certified && changedGate {`. `CGO_ENABLED=0 go test ./internal/runner/linuxworker -run TestHostedUnprovenBaseStops -count=1`: exit 1, `worker_test.go:927: launches ["/home/paulca/.cache/tmp/TestHostedUnprovenBaseStops3367443669/001/steps/a0fbfa9ff65cdb0e/tree" "/home/paulca/.cache/tmp/TestHostedUnprovenBaseStops3367443669/001/steps/a`. Restored (`cp`, `cmp` identical). |
| +- **214** the receiver's chunk check back to the old limit. In `internal/runner/thin/relay.go`, `if tot > wire.MaxChunks(want.Kind) {` became `if tot > wire.MaxTransferChunks {`. `CGO_ENABLED=0 go test ./internal/runner/thin -run TestDepsPackPerKindLimits -count=1`: exit 1, `hosted_worker_test.go:126: a 67256334 byte deps transfer in 457 chunks: 0 bytes, pack refused`. Restored (`cp`, `cmp` identical). |
| +- **215** the receiver's byte check back to the old limit. In `internal/runner/thin/relay.go`, `int64(buf.Len()+len(data)) > wire.MaxBytes(want.Kind) {` became `int64(buf.Len()+len(data)) > wire.MaxTransferBytes {`. `CGO_ENABLED=0 go test ./internal/runner/thin -run TestDepsPackPerKindLimits -count=1`: exit 1, `hosted_worker_test.go:126: a 67256334 byte deps transfer in 457 chunks: 0 bytes, pack refused`. Restored (`cp`, `cmp` identical). |
| +- **216** a hash mismatch is not told apart (no reason in the log tail). In `internal/runner/linuxworker/worker.go`, `errors.Is(err, depsbundle.ErrUnsafePath), errors.Is(err, depsbundle.ErrHashMismatch):` became `errors.Is(err, depsbundle.ErrUnsafePath):`. `CGO_ENABLED=0 go test ./internal/runner/linuxworker -run TestHostedDepsRefused -count=1`: exit 1, `worker_test.go:812: report {ChangeDiffs: ChangeFiles:<nil> BaseChecks: BaseChecksSHA: Failure:<nil> Copy:<nil> TaskID:tk1 StepID:s1 Attempt:1 State:done Reason:checks_unavailable BaseSHA:7eb6675fc5888`. Restored (`cp`, `cmp` identical). |
| +- **217** an unsafe path is not told apart. In `internal/runner/linuxworker/worker.go`, `errors.Is(err, depsbundle.ErrUnsafePath), errors.Is(err, depsbundle.ErrHashMismatch):` became `errors.Is(err, depsbundle.ErrHashMismatch):`. `CGO_ENABLED=0 go test ./internal/runner/linuxworker -run TestHostedDepsRefused -count=1`: exit 1, `worker_test.go:812: report {ChangeDiffs: ChangeFiles:<nil> BaseChecks: BaseChecksSHA: Failure:<nil> Copy:<nil> TaskID:tk1 StepID:s1 Attempt:1 State:done Reason:checks_unavailable BaseSHA:2fa767b056a7a`. Restored (`cp`, `cmp` identical). |
| +- **218** a diagnostic that cannot be prepared reports the base run (no reset). In `internal/runner/checkrun/run.go`, `out.BaseChecks, out.BaseChecksSHA = "", ""` became `_ = 0` (sed). `CGO_ENABLED=0 go test ./internal/runner/checkrun -run TestChecksRunDiagnosticUnavailable -count=1`: exit 1, `run_test.go:283: outcome {Checks:cannot_run BaseChecks:passed Reason:checks_unavailable ... BaseChecksSHA:0a3c108f... }`. Restored (`cp`, `cmp` identical). |
| + |
| +One guard was merged. Mutations taken first on two separate guards (the diagnostic's preparation, and its launch) showed that the launch guard alone survived: with the tree never prepared, nothing launches. Preparation and launch are now one block under one guard, and mutations 212 and 213 remove that guard. |
diff --git a/internal/runner/checkrun/run.go b/internal/runner/checkrun/run.go| index f3b4e3ca..1550c536 100644 |
| --- a/internal/runner/checkrun/run.go |
| +++ b/internal/runner/checkrun/run.go |
| @@ -127,11 +127,6 @@ func Run(ctx context.Context, g gate.Runner, repo checks.Repo, in Inputs) Outcom |
| chosen := candidateGate |
| certified := baseErr == nil |
| diagnostic := "" |
| - if certified && changedGate && in.Diagnostic != nil { |
| - if diagnostic, err = in.Diagnostic(ctx); err != nil { |
| - return done(wire.ChecksCannotRun, "checks_unavailable") |
| - } |
| - } |
| if certified { |
| trusted, err := os.MkdirTemp(filepath.Dir(in.Workspace), "base-gates-") |
| if err != nil { |
| @@ -180,7 +175,19 @@ func Run(ctx context.Context, g gate.Runner, repo checks.Repo, in Inputs) Outcom |
| if certified && res.Terminated && res.Reason == "" && res.Code == 0 { |
| out.BaseChecksSHA = in.BaseSHA |
| } |
| - if certified && changedGate { |
| + // A base run whose end is not proven stops everything after it: no |
| + // diagnostic is prepared or launched, since its namespace would |
| + // replace the base run's record and recovery would then prove the |
| + // wrong one. The tail below fails the run, unterminated. |
| + if certified && changedGate && res.Terminated { |
| + if in.Diagnostic != nil { |
| + if diagnostic, err = in.Diagnostic(ctx); err != nil { |
| + // As when this was decided before any run: nothing of the |
| + // base run is reported. |
| + out.BaseChecks, out.BaseChecksSHA = "", "" |
| + return done(wire.ChecksCannotRun, "checks_unavailable") |
| + } |
| + } |
| baseOutput := fmt.Sprintf("Base gate certification (exit %d, %s):\n%s\n", res.Code, res.Reason, tailBytes(res.Output, wire.MaxChecksOutput/3)) |
| if candidateOK && diagnostic != "" { |
| if in.Prepare != nil { |
diff --git a/internal/runner/checkrun/run_test.go b/internal/runner/checkrun/run_test.go| index 7e0d4b8d..59959eff 100644 |
| --- a/internal/runner/checkrun/run_test.go |
| +++ b/internal/runner/checkrun/run_test.go |
| @@ -229,3 +229,57 @@ func TestChecksRunRefusesMissingInputs(t *testing.T) { |
| t.Fatalf("whole inputs refused: %+v", out) |
| } |
| } |
| + |
| +// unprovenGate's runs record their namespace and never establish its |
| +// exit (a gate that timed out and could not be proven stopped). |
| +type unprovenGate struct{ execGate } |
| + |
| +func (g *unprovenGate) Run(ctx context.Context, attempt, dir string, argv []string, _ time.Duration, record func(string) error) gate.Result { |
| + id := fmt.Sprintf("ns-%d", len(g.runs)+1) |
| + g.runs = append(g.runs, execRun{argv: argv, dir: dir, pins: gate.Pins(ctx), attempt: attempt, recorded: id}) |
| + if err := record(id); err != nil { |
| + return gate.Result{Reason: "checks_unavailable", Terminated: true} |
| + } |
| + return gate.Result{Reason: "checks_timeout", Code: -1, Sandbox: wire.SandboxBubblewrap} |
| +} |
| + |
| +// TestChecksRunStopsOnUnprovenBase (Task 17 review 1, finding 2): a base |
| +// gate run whose end is not proven stops the run at once. The candidate |
| +// changed a base gate file, but no diagnostic tree is prepared and no |
| +// second run launches, so the step's recorded namespace stays the base |
| +// run's and its recovery must still prove that one. |
| +func TestChecksRunStopsOnUnprovenBase(t *testing.T) { |
| + r, tree, base, candidate := repo(t, |
| + map[string]string{".equipo/gates.json": contract, "Makefile": budgetGate, "size.txt": "1\n", "budgets.txt": "1\n"}, |
| + map[string]string{"Makefile": "ci:\n\ttrue\n"}) |
| + g := &unprovenGate{} |
| + var recorded []string |
| + prepared, diagnostics := 0, 0 |
| + out := Run(context.Background(), g, r, Inputs{Workspace: tree, BaseSHA: base, CandidateSHA: candidate, Attempt: "checks/k", |
| + Record: func(id string) error { recorded = append(recorded, id); return nil }, |
| + Prepare: func(context.Context, string) error { prepared++; return nil }, |
| + Diagnostic: func(context.Context) (string, error) { |
| + diagnostics++ |
| + return filepath.Join(t.TempDir(), "diagnostic"), nil |
| + }}) |
| + if out.State != wire.StepFailed || out.Terminated || out.Reason != "checks_timeout" || out.BaseChecksSHA != "" { |
| + t.Fatalf("outcome %+v", out) |
| + } |
| + if len(g.runs) != 1 || len(recorded) != 1 || recorded[0] != "ns-1" || diagnostics != 0 || prepared != 1 { |
| + t.Fatalf("runs %+v, recorded %v, diagnostics prepared %d, trees prepared %d", g.runs, recorded, diagnostics, prepared) |
| + } |
| +} |
| + |
| +// TestChecksRunDiagnosticUnavailable: a diagnostic tree that cannot be |
| +// prepared ends cannot_run checks_unavailable and reports nothing of the |
| +// base run (as when it was prepared before any run). |
| +func TestChecksRunDiagnosticUnavailable(t *testing.T) { |
| + r, tree, base, candidate := repo(t, |
| + map[string]string{".equipo/gates.json": contract, "Makefile": budgetGate, "size.txt": "1\n", "budgets.txt": "1\n"}, |
| + map[string]string{"Makefile": "ci:\n\ttrue\n"}) |
| + out := Run(context.Background(), &execGate{}, r, Inputs{Workspace: tree, BaseSHA: base, CandidateSHA: candidate, Attempt: "checks/k", Record: func(string) error { return nil }, |
| + Diagnostic: func(context.Context) (string, error) { return "", fmt.Errorf("no checkout") }}) |
| + if out.State != wire.StepDone || !out.Terminated || out.Checks != wire.ChecksCannotRun || out.Reason != "checks_unavailable" || out.BaseChecks != "" || out.BaseChecksSHA != "" { |
| + t.Fatalf("outcome %+v", out) |
| + } |
| +} |
diff --git a/internal/runner/linuxworker/gate.go b/internal/runner/linuxworker/gate.go| index 15b09745..4f18329e 100644 |
| --- a/internal/runner/linuxworker/gate.go |
| +++ b/internal/runner/linuxworker/gate.go |
| @@ -118,9 +118,21 @@ func (g *bwrapGate) Run(ctx context.Context, attempt, dir string, argv []string, |
| } |
| pctx, kill := context.WithCancel(context.Background()) |
| defer kill() |
| + recorded := "" |
| proc, err := g.start(pctx, provider.Launch{AttemptKey: attempt + "/" + rand.Text(), Workspace: dir, Policy: policy}, argv, |
| - func(_ context.Context, r containment.Record) error { return record(r.ID) }) |
| + func(_ context.Context, r containment.Record) error { |
| + if err := record(r.ID); err != nil { |
| + return err |
| + } |
| + recorded = r.ID |
| + return nil |
| + }) |
| if err != nil { |
| + // A namespace recorded before its start failed may have run: |
| + // its end must be established (containment's exit proof) before |
| + // the run counts as ended; otherwise its record stays for |
| + // recovery. |
| + unavailable.Terminated = recorded == "" || g.Verify(recorded) |
| return unavailable |
| } |
| out := &lineTail{max: wire.MaxChecksLines} |
diff --git a/internal/runner/linuxworker/worker_test.go b/internal/runner/linuxworker/worker_test.go| index 2cf7e0fb..acf58a76 100644 |
| --- a/internal/runner/linuxworker/worker_test.go |
| +++ b/internal/runner/linuxworker/worker_test.go |
| @@ -1,6 +1,7 @@ |
| package linuxworker |
| import ( |
| + "archive/zip" |
| "bytes" |
| "context" |
| "crypto/sha256" |
| @@ -719,6 +720,7 @@ func TestHostedDeps(t *testing.T) { |
| stageLimits = tc.limits |
| } |
| r.dispatch(base, tc.candidate, emptyBundle(t, tc.want...)) |
| + launches := r.countLaunches() |
| rep := r.run() |
| if rep.State != wire.StepDone || rep.Checks != wire.ChecksCannotRun || rep.Reason != tc.reason || !rep.Termination || rep.Gate != "" || rep.ChecksSandbox != "" { |
| t.Fatalf("report %+v", rep) |
| @@ -726,8 +728,91 @@ func TestHostedDeps(t *testing.T) { |
| if tc.reason == "checks_unavailable" && !strings.Contains(rep.LogTail, "go.sum") { |
| t.Fatalf("log tail %q does not say why", rep.LogTail) |
| } |
| - if recs, err := r.m.Records(context.Background()); err != nil || len(recs) != 0 { |
| - t.Fatalf("a gate ran: %v %v", recs, err) |
| + if *launches != 0 { |
| + t.Fatalf("%d gate launches", *launches) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// countLaunches counts the kind's gate launches (each still started). |
| +func (r *rig) countLaunches() *int { |
| + g := r.kind.Gate.(*bwrapGate) |
| + n, start := new(int), g.start |
| + g.start = func(ctx context.Context, l provider.Launch, argv []string, record func(context.Context, containment.Record) error) (provider.Process, error) { |
| + *n++ |
| + return start(ctx, l, argv, record) |
| + } |
| + return n |
| +} |
| + |
| +// TestHostedDepsRefused (review 1): a bundle whose module does not match |
| +// the base's pin, or whose zip holds an unsafe path, ends cannot_run |
| +// checks_unavailable, saying why, with no gate launched. |
| +func TestHostedDepsRefused(t *testing.T) { |
| + m := depsbundle.Module{Path: "example.com/m", Version: "v1.0.0"} |
| + gomod := "module example.com/m\n" |
| + modHash, err := dirhash.Hash1([]string{"go.mod"}, func(string) (io.ReadCloser, error) { return io.NopCloser(strings.NewReader(gomod)), nil }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + unsafeZip := func(t *testing.T) []byte { |
| + cache := t.TempDir() |
| + at := filepath.Join(cache, "cache", "download", "example.com", "m", "@v") |
| + if err := os.MkdirAll(at, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + var z bytes.Buffer |
| + zw := zip.NewWriter(&z) |
| + for _, name := range []string{"example.com/m@v1.0.0/go.mod", "example.com/m@v1.0.0/../../escape.go"} { |
| + w, err := zw.Create(name) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + _, _ = w.Write([]byte(gomod)) |
| + } |
| + if err := zw.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + for ext, data := range map[string][]byte{".zip": z.Bytes(), ".mod": []byte(gomod), ".info": []byte(`{"Version":"v1.0.0"}`)} { |
| + if err := os.WriteFile(filepath.Join(at, "v1.0.0"+ext), data, 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + b, err := depsbundle.Build(context.Background(), cache, []depsbundle.Module{m}, wire.DepsTransferMax) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return b.Bytes() |
| + } |
| + realModule := func(t *testing.T) []byte { |
| + cache := t.TempDir() |
| + fixtureModule(t, cache, m, map[string]string{"go.mod": gomod, "m.go": "package m\n"}) |
| + b, err := depsbundle.Build(context.Background(), cache, []depsbundle.Module{m}, wire.DepsTransferMax) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return b.Bytes() |
| + } |
| + for _, tc := range []struct { |
| + name, sum string |
| + bundle func(*testing.T) []byte |
| + why string |
| + }{ |
| + {"a module that does not match its pin", "example.com/m v1.0.0 " + fakeSum("zip") + "\nexample.com/m v1.0.0/go.mod " + fakeSum("mod") + "\n", realModule, "does not match"}, |
| + {"an unsafe path in a zip", "example.com/m v1.0.0 " + fakeSum("zip") + "\nexample.com/m v1.0.0/go.mod " + modHash + "\n", unsafeZip, "unsafe path"}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + r := newRig(t) |
| + base := map[string]string{"go.mod": "module example.com/app\n\nrequire example.com/m v1.0.0\n", "go.sum": tc.sum, "Makefile": "ci:\n\t@echo ran\n"} |
| + r.dispatch(base, map[string]string{"NEWS": "news\n"}, tc.bundle(t)) |
| + launches := r.countLaunches() |
| + rep := r.run() |
| + if rep.State != wire.StepDone || rep.Checks != wire.ChecksCannotRun || rep.Reason != "checks_unavailable" || !rep.Termination || !strings.Contains(rep.LogTail, tc.why) { |
| + t.Fatalf("report %+v", rep) |
| + } |
| + if *launches != 0 { |
| + t.Fatalf("%d gate launches", *launches) |
| } |
| }) |
| } |
| @@ -743,3 +828,109 @@ func TestHostedReasonsRegistered(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// recordOnDisk writes a namespace record into the manager's scratch root |
| +// as containment does once it has persisted one, with its exit proof: |
| +// verified, or (an exit containment could not establish) not. |
| +func recordOnDisk(t *testing.T, scratch, id string, verified bool) containment.Record { |
| + t.Helper() |
| + boot, err := os.ReadFile("/proc/sys/kernel/random/boot_id") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rec := containment.Record{ID: id, AttemptKey: "checks/k/x", BootID: strings.TrimSpace(string(boot)), ManifestHash: "m", PolicyHash: "p", ParentPID: 1, ParentTicks: 1} |
| + raw, _ := json.Marshal(rec) |
| + if err := os.WriteFile(filepath.Join(scratch, id+".json"), raw, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + proof := containment.Proof{Record: rec, Exit: provider.Exit{Code: -1, ObservedAt: time.Now().UTC()}, Verified: verified} |
| + raw, _ = json.Marshal(proof) |
| + if err := os.WriteFile(filepath.Join(scratch, id+".exit.json"), raw, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + return rec |
| +} |
| + |
| +// unprovenProc is a started namespace whose exit is never established. |
| +type unprovenProc struct{} |
| + |
| +func (unprovenProc) Stdin() io.WriteCloser { return nopWriter{} } |
| +func (unprovenProc) Stdout() io.ReadCloser { return io.NopCloser(strings.NewReader("")) } |
| +func (unprovenProc) Stderr() io.ReadCloser { return io.NopCloser(strings.NewReader("")) } |
| +func (unprovenProc) ID() string { return "" } |
| +func (unprovenProc) Wait(context.Context) (provider.Exit, error) { |
| + return provider.Exit{Code: -1}, errors.New("namespace exit not established") |
| +} |
| + |
| +type nopWriter struct{} |
| + |
| +func (nopWriter) Write(p []byte) (int, error) { return len(p), nil } |
| +func (nopWriter) Close() error { return nil } |
| + |
| +// TestHostedStartErrorUnverified (review 1, finding 1): a start that |
| +// fails after its namespace was recorded is Terminated only once that |
| +// namespace's exit is established; when containment could not establish |
| +// it, the run is not Terminated and the record stays for recovery. |
| +func TestHostedStartErrorUnverified(t *testing.T) { |
| + r := newRig(t) |
| + work := filepath.Join(r.root, "work") |
| + if err := os.Mkdir(work, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, verified := range []bool{false, true} { |
| + id := fmt.Sprintf("%032x", map[bool]int{false: 1, true: 2}[verified]) |
| + g := NewGate(r.m, "", StagedUnder(r.deps)).(*bwrapGate) |
| + g.start = func(ctx context.Context, _ provider.Launch, _ []string, record func(context.Context, containment.Record) error) (provider.Process, error) { |
| + rec := recordOnDisk(t, r.scratch, id, verified) |
| + if err := record(ctx, rec); err != nil { |
| + return nil, err |
| + } |
| + return nil, errors.New("namespace_startup_failed: admission refused") |
| + } |
| + var recorded []string |
| + res := g.Run(context.Background(), "checks/start", work, []string{"/usr/bin/true"}, time.Minute, func(id string) error { recorded = append(recorded, id); return nil }) |
| + recs, err := r.m.Records(context.Background()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + left := slices.ContainsFunc(recs, func(c containment.Record) bool { return c.ID == id }) |
| + if res.Terminated != verified || left == verified || res.Reason != "checks_unavailable" || !slices.Equal(recorded, []string{id}) { |
| + t.Fatalf("verified exit %v: result %+v, record left %v, recorded %v", verified, res, left, recorded) |
| + } |
| + } |
| +} |
| + |
| +// TestHostedUnprovenBaseStops (review 1, finding 2): a base gate whose |
| +// namespace exit is not established ends the attempt there: no |
| +// diagnostic is launched over it (checkrun's TestChecksRunStopsOnUnprovenBase |
| +// counts its preparation), the base run's namespace stays recorded, and |
| +// recovery cannot prove the attempt ended. |
| +func TestHostedUnprovenBaseStops(t *testing.T) { |
| + r := newRig(t) |
| + base := map[string]string{".equipo/gates.json": contract, "Makefile": gateMake, "size.txt": "1\n", "budgets.txt": "1\n"} |
| + r.dispatch(base, map[string]string{"Makefile": "ci:\n\t@echo candidate gate\n"}, emptyBundle(t)) |
| + g := r.kind.Gate.(*bwrapGate) |
| + var launches []string |
| + g.start = func(ctx context.Context, l provider.Launch, _ []string, record func(context.Context, containment.Record) error) (provider.Process, error) { |
| + id := fmt.Sprintf("%032x", len(launches)+1) |
| + launches = append(launches, l.Workspace) |
| + if err := record(ctx, recordOnDisk(t, r.scratch, id, false)); err != nil { |
| + return nil, err |
| + } |
| + return unprovenProc{}, nil |
| + } |
| + rep := r.run() |
| + if rep.State != wire.StepFailed || rep.Termination || rep.BaseChecksSHA != "" { |
| + t.Fatalf("report %+v", rep) |
| + } |
| + if len(launches) != 1 || strings.HasSuffix(launches[0], "-diagnostic") { |
| + t.Fatalf("launches %q, want only the base gate's", launches) |
| + } |
| + first := fmt.Sprintf("%032x", 1) |
| + if rec, err := r.kind.Record(first); err != nil || r.kind.Gate.Verify(rec) { |
| + t.Fatalf("recovery proved the unproven base namespace ended: %q %v", rec, err) |
| + } |
| + if recs, err := r.m.Records(context.Background()); err != nil || len(recs) != 1 || recs[0].ID != first { |
| + t.Fatalf("records %v %v, want the base run's kept", recs, err) |
| + } |
| +} |
diff --git a/internal/runner/thin/hosted_worker_test.go b/internal/runner/thin/hosted_worker_test.go| index 958de34d..c5d4a3f3 100644 |
| --- a/internal/runner/thin/hosted_worker_test.go |
| +++ b/internal/runner/thin/hosted_worker_test.go |
| @@ -1,8 +1,14 @@ |
| package thin |
| import ( |
| + "bytes" |
| "context" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/hex" |
| "errors" |
| + "strconv" |
| + "strings" |
| "testing" |
| "time" |
| @@ -78,3 +84,53 @@ func TestHostedFlushWaitsForReports(t *testing.T) { |
| t.Fatal("Flush waited after every report was acked") |
| } |
| } |
| + |
| +// TestDepsPackPerKindLimits (Task 17 review 1, finding 3): the receiver |
| +// assembles a deps transfer past the old 64 MiB and its chunk count |
| +// (wire.MaxChunks and MaxBytes of its kind), refuses the same bytes as a |
| +// hosted pack, and refuses a deps transfer declaring more chunks than |
| +// its own limit. |
| +func TestDepsPackPerKindLimits(t *testing.T) { |
| + ctx := context.Background() |
| + s, err := OpenState(ctx, t.TempDir()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer s.Close() |
| + data := bytes.Repeat([]byte("dependency bundle "), (wire.MaxTransferBytes+wire.MaxBlobChunk)/18+1) |
| + total := (len(data) + wire.MaxBlobChunk - 1) / wire.MaxBlobChunk |
| + if total <= wire.MaxTransferChunks || int64(len(data)) <= wire.MaxTransferBytes { |
| + t.Fatalf("%d bytes in %d chunks do not pass the old limits", len(data), total) |
| + } |
| + sum := sha256.Sum256(data) |
| + send := func(h wire.TransferHeader, chunks [][]byte, declared int) { |
| + for i, part := range chunks { |
| + b := wire.Blob{Transfer: h, Index: i, Total: declared, SHA256: hex.EncodeToString(sum[:]), Data: base64.StdEncoding.EncodeToString(part)} |
| + if err := s.AcceptChunk(ctx, h.ID+"-"+strconv.Itoa(i), b); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + } |
| + var chunks [][]byte |
| + for i := 0; i < len(data); i += wire.MaxBlobChunk { |
| + chunks = append(chunks, data[i:min(len(data), i+wire.MaxBlobChunk)]) |
| + } |
| + base, candidate := strings.Repeat("a", 40), strings.Repeat("b", 40) |
| + header := func(id, kind string) wire.TransferHeader { |
| + return wire.TransferHeader{ID: id, Direction: wire.TransferInbound, Kind: kind, Repo: "amadan.net/oficina/sample", TaskID: "tk1", StepID: "s1", Attempt: 1, BaseSHA: base, CandidateSHA: candidate} |
| + } |
| + deps, pack := header("tr_deps", wire.TransferKindDeps), header("tr_pack", wire.TransferKindHostedPack) |
| + send(deps, chunks, total) |
| + send(pack, chunks, total) |
| + if got, err := s.pack(ctx, deps); err != nil || !bytes.Equal(got, data) { |
| + t.Fatalf("a %d byte deps transfer in %d chunks: %d bytes, %v", len(data), total, len(got), err) |
| + } |
| + if _, err := s.pack(ctx, pack); !errors.Is(err, errPackRefused) { |
| + t.Fatalf("the same bytes as a hosted pack: %v, want refused", err) |
| + } |
| + over := header("tr_over", wire.TransferKindDeps) |
| + send(over, chunks[:1], wire.MaxChunks(wire.TransferKindDeps)+1) |
| + if _, err := s.pack(ctx, over); !errors.Is(err, errPackRefused) { |
| + t.Fatalf("a deps transfer declaring %d chunks: %v, want refused", wire.MaxChunks(wire.TransferKindDeps)+1, err) |
| + } |
| +} |