runner: move the gate contract and base-gate checks out of thin
gate holds Result, Runner and the read-only pins a run carries in its context; checkrun holds the base gates from BaseSHA, the dependency stage and the needs_network mapping, and thin's primary checks call it. runWorker takes its termination kind and record conversion from a WorkerKind; the Mac passes today's. Options.HostedWorker is unused until Task 17. thin's budget record moves to 35809/35291.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
29 files changed,
+1,285
−379
.rastrillo/budgets.txt+1 −1docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md+32 −0internal/runner/{thin => checkrun}/base_gates.go+142 −34internal/runner/checkrun/run.go+315 −0internal/runner/checkrun/run_test.go+197 −0internal/runner/checks/repo.go+6 −0internal/runner/gate/gate.go+56 −0internal/runner/gate/gate_test.go+61 −0internal/runner/thin/base_gates_shim_test.go+27 −0internal/runner/thin/copy_commands.go+2 −2internal/runner/thin/facts.go+4 −2internal/runner/thin/fakeworker.go+2 −1internal/runner/thin/fakeworker_testbuild.go+4 −3internal/runner/thin/go_checks.go+0 −54internal/runner/thin/judge.go+100 −215internal/runner/thin/judge_hosted.go+0 −15internal/runner/thin/mac.go+8 −7internal/runner/thin/mac_stall_test.go+2 −1internal/runner/thin/mac_test.go+3 −2internal/runner/thin/primary_checks_test.go+200 −0internal/runner/thin/review_fixes_test.go+5 −1internal/runner/thin/run.go+41 −6internal/runner/thin/sandbox_consent_test.go+7 −6internal/runner/thin/unsandboxed_d1_test.go+6 −5internal/runner/thin/worker.go+2 −13internal/runner/thin/worker_checks.go+8 −8internal/runner/thin/worker_conns_test.go+1 −1internal/runner/thin/worker_kind_test.go+50 −0internal/runner/thin/worker_test.go+3 −2
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 7958b799..d42a6ad4 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -39,7 +39,7 @@ 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; |
| -size internal/runner/thin 36245 35005 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; 36245/35005. |
| +size internal/runner/thin 35809 35291 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); 35809/35291. |
| 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 93c0254d..154431cc 100644 |
| --- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| +++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| @@ -681,3 +681,35 @@ Also run: |
| - `CGO_ENABLED=0 go test ./internal/hostedimage/... ./internal/isolatedjob/... ./cmd/equipo-hosted-image -count=1`: ok. |
| - `make budget build vet hosted-image-check`: ok. The make target now runs the three new tests. |
| - staticcheck v0.7.0, gitleaks `dir` on `internal/hostedimage` (after the fixture value was split), lanes-check, gofmt and `git diff --check`: clean. |
| + |
| +## Task 11 |
| + |
| +A shared gate contract and the base-gate checks flow, out of `internal/runner/thin`. Behaviour unchanged for the Linux primary and the Mac worker. |
| + |
| +- `internal/runner/gate` (leaf: standard library and `checks` only): `Result`, `Runner`, and `Mount` with `WithPins`/`Pins`, which carry checkrun's read-only base gate files to the runner through the context (`Runner.Run` has no parameter for them). |
| +- `internal/runner/checkrun`: `Run(ctx, gate.Runner, checks.Repo, Inputs) Outcome`, moved from `Engineer.checks`: base gates from BaseSHA (`ReadBaseGates`, `InstallBaseGates`, `FindGate`), needs_macos, the Go requirement, the dependency stage, the gate, the diagnostic, BaseChecks/BaseChecksSHA and the needs_network mapping. `checks.Repo` is new (`Git`, `GitDir`). |
| +- Beyond the brief's fields, `Inputs` has `Attempt`, `Record`, `Prepare` (the checks tree's `.git`), `Diagnostic` (the primary's fresh candidate tree), `Hosted` (hosted CI's verdict) and `Log`. `Outcome` has `State`, `Terminated`, `Gate`, `LogTail` and `ExitCode`. Without these the step report cannot come out the same. |
| +- thin keeps what only the primary does: the judged tree, hosted CI, the diagnostic tree, and the hosted phase for a candidate with no gate. `primaryGate` is its `gate.Runner`, over `runGateAs`. |
| +- `GateRunner` became `gate.Runner`, and `gateResult` became `gate.Result`. `WorkerKind` (`Gate`, `Termination`, `Record`) replaces `workerSetup.gate`. `runWorker` takes its termination kind and record conversion from it, and `macKind` gives today's values. `Options.HostedWorker *WorkerKind` is added but not used yet (Task 17). |
| +- Test fixtures changed only because a type moved, with the same assertions: `gateResult{...}`/`res.reason` became `rungate.Result{...}`/`res.Reason` in worker_test, mac_test, mac_stall_test, sandbox_consent_test and unsandboxed_d1_test; `workerSetup{gate: g}` became `kind: macKind(g)` in worker_conns_test; TestRunnerReasonsAreKnown also scans `../checkrun/run.go`, where the checks reasons now live; and `base_gates_shim_test.go` keeps the base-gate tests' helper names. |
| +- Red: the new tests did not compile, because the packages and names did not exist. TestPrimaryChecksUnchanged's report and launch expectations were first run against the unchanged code at 51eec914, and passed, before anything moved. |
| +- Budgets: thin goes from 36245/35005 to 35809/35291 (source down 436; test up 286, from the new tests). |
| + |
| +Mutation checks. Each was applied by sed and the named tests run with `go test <pkg> -run '<Test>' -count=1`, outside the agent sandbox because the primary's tests need bwrap. Every run compiled and failed on its assertion. Each file was restored and checked with `cmp` against a copy, except 63 (below). |
| + |
| +61. BaseChecksSHA set on any pass, not only a certified one (`checkrun/run.go`). TestChecksRunBaseChecksSHAOnlyOnBasePass: FAIL, `run_test.go:153: uncertified {Checks:passed ...}`. TestPrimaryChecksUnchanged/uncertified_candidate_gate: FAIL, `primary_checks_test.go:144: report changed`. Restored. |
| +62. The gate run without its pins (`gate.WithPins` dropped). TestChecksRunBaseGatesFromBase: FAIL, `run_test.go:133: pins []`. TestPrimaryChecksUnchanged/certified_pass: FAIL, `primary_checks_test.go:160: gate launch {... pins:[]}, want pins [.equipo/gates.json Makefile budgets.txt]`. Restored. |
| +63. The Mac kind says `namespace` (`thin/run.go` macKind). TestMacWorkerUnchanged: FAIL, `worker_kind_test.go:28: Mac kind {... Termination:namespace ...}`. The scripted restore failed (the backup copy was never made), so the line was restored by hand and checked: `git diff` shows no `TerminationNamespace`, and TestMacWorkerUnchanged passes again. |
| +64. `WorkerKind.verify` ignores a record that cannot be converted. TestMacWorkerUnchanged: FAIL, `worker_kind_test.go:45: an unconvertible record verified`. Restored. |
| + |
| +Also run: |
| +- `go test ./internal/runner/gate ./internal/runner/checkrun ./internal/runner/thin -run 'TestPrimaryChecks|TestMacWorker|TestChecks|TestWorker' -count=1`: ok. thin took 52s. |
| +- `make budget build vet`: ok. |
| +- `GOOS=darwin GOARCH=arm64 CGO_ENABLED=0 go build ./...`: fails only on `internal/toolproxy/stdio.go` (`unix.O_PATH`), the same as at 51eec914. |
| +- `go test ./internal/runner/... ./internal/thintest/... -count=1`, once, on a loaded docs-t1 (load about 28 on 16 CPUs). Every failure is unrelated to this task: |
| + - Failures that also happen at 51eec914 (checked in a throwaway worktree): |
| + - containment TestNamespaceOpenCodeBinaryAfterAttestation: the socket path under `$TMPDIR` is too long; |
| + - provider/pi TestPiFakeReviewInNamespace: `provider_policy_rejected`; |
| + - 33 thin Design, Preview, Devbox, Site and Render tests: the secret scanner cannot run in this environment. |
| + - Failures that passed when rerun alone: metered TestMeteredRaceAdmitsExactlyOne and thintest TestExploreRoundTrip. |
| + - thin hit the default 10-minute `go test` timeout. Rerun once with `-timeout 45m`, it finished in 829s: the 33 failures above, and nothing else failed. Its 45s time record is far below that under this load. The new TestPrimaryChecksUnchanged adds about 25 to 35s of real bwrap runs. The time record is not changed. |
diff --git a/internal/runner/thin/base_gates.go b/internal/runner/checkrun/base_gates.go| similarity index 56% |
| rename from internal/runner/thin/base_gates.go |
| rename to internal/runner/checkrun/base_gates.go |
| index 477f3002..0b976799 100644 |
| --- a/internal/runner/thin/base_gates.go |
| +++ b/internal/runner/checkrun/base_gates.go |
| @@ -1,4 +1,4 @@ |
| -package thin |
| +package checkrun |
| import ( |
| "context" |
| @@ -6,27 +6,104 @@ import ( |
| "errors" |
| "fmt" |
| "io" |
| + "io/fs" |
| "os" |
| "os/exec" |
| "path" |
| "path/filepath" |
| + "regexp" |
| "slices" |
| "strings" |
| + "amadan.net/oficina/equipo/internal/runner/checks" |
| + "amadan.net/oficina/equipo/internal/runner/gate" |
| "amadan.net/oficina/equipo/internal/runner/provider" |
| "amadan.net/oficina/equipo/internal/runner/workspace" |
| ) |
| +// Gate is how a repository checks itself, in Amadan's order: |
| +// .amadan/ci.d/ (each executable step in order), else .amadan/ci, else |
| +// `make ci`. Text is what the gate's files say, for what it needs; Pins |
| +// are the base gate files a certified run mounts read-only. |
| +type Gate struct { |
| + Name string |
| + Argv []string |
| + Text string |
| + Pins []gate.Mount |
| +} |
| + |
| +const ciDScript = `set -u |
| +for s in .amadan/ci.d/*; do |
| + [ -f "$s" ] || continue |
| + echo "=== ${s##*/}" |
| + if [ ! -x "$s" ]; then echo "${s##*/} is not executable"; exit 126; fi |
| + "./$s" || exit $? |
| +done` |
| + |
| +// MakeCI matches a makefile's ci target. |
| +var MakeCI = regexp.MustCompile(`(?m)^ci[ \t]*:([^=]|$)`) |
| + |
| +// FindGate looks for the repository's gate in the tree, reading only |
| +// regular files inside it. |
| +func FindGate(dir string) (Gate, bool) { |
| + root, err := os.OpenRoot(dir) |
| + if err != nil { |
| + return Gate{}, false |
| + } |
| + defer root.Close() |
| + read := func(name string) (string, bool) { |
| + info, err := root.Lstat(name) |
| + if err != nil || !info.Mode().IsRegular() { |
| + return "", false |
| + } |
| + f, err := root.Open(name) |
| + if err != nil { |
| + return "", false |
| + } |
| + defer f.Close() |
| + raw, _ := io.ReadAll(io.LimitReader(f, 64<<10)) |
| + return string(raw), true |
| + } |
| + if entries, err := fs.ReadDir(root.FS(), ".amadan/ci.d"); err == nil { |
| + var text strings.Builder |
| + n := 0 |
| + for _, ent := range entries { |
| + if s, ok := read(".amadan/ci.d/" + ent.Name()); ok { |
| + text.WriteString(s + "\n") |
| + n++ |
| + } |
| + } |
| + if n > 0 { |
| + return Gate{Name: ".amadan/ci.d", Argv: []string{"/usr/bin/bash", "-c", ciDScript}, Text: text.String()}, true |
| + } |
| + } |
| + if s, ok := read(".amadan/ci"); ok { |
| + return Gate{Name: ".amadan/ci", Argv: []string{"/usr/bin/bash", "-c", "exec ./.amadan/ci"}, Text: s}, true |
| + } |
| + for _, name := range []string{"GNUmakefile", "makefile", "Makefile"} { |
| + if s, ok := read(name); ok && MakeCI.MatchString(s) { |
| + return Gate{Name: "make ci", Argv: []string{"/usr/bin/make", "ci"}, Text: s}, true |
| + } |
| + } |
| + return Gate{}, false |
| +} |
| + |
| const gateContract = ".equipo/gates.json" |
| const maxGateBytes = 4 << 20 |
| var errBaseGate = errors.New("base gate evidence unavailable") |
| +var shaPattern = regexp.MustCompile(`^(?:[0-9a-f]{40}|[0-9a-f]{64})$`) |
| + |
| type baseGateFile struct { |
| body []byte |
| mode os.FileMode |
| } |
| +// BaseGates are the base commit's gate files: its gate contract, every |
| +// standard gate selector and every file the contract names. |
| +type BaseGates map[string]baseGateFile |
| + |
| func standardGate(name string) bool { |
| return name == gateContract || name == ".amadan/ci" || name == ".amadan/ci.d" || strings.HasPrefix(name, ".amadan/ci.d/") || slices.Contains([]string{"Makefile", "makefile", "GNUmakefile"}, path.Base(name)) || path.Ext(name) == ".mk" |
| } |
| @@ -45,6 +122,31 @@ func gateGit(ctx context.Context, git, gitDir string, limit int, args ...string) |
| return out, nil |
| } |
| +// boundedOutput runs cmd and returns at most limit bytes of its stdout; |
| +// past that it stops the command and reports clipped. Nothing beyond |
| +// limit is held in memory. |
| +func boundedOutput(cmd *exec.Cmd, limit int) ([]byte, bool, error) { |
| + if cmd.Stderr == nil { |
| + cmd.Stderr = io.Discard |
| + } |
| + pipe, err := cmd.StdoutPipe() |
| + if err != nil { |
| + return nil, false, err |
| + } |
| + if err := cmd.Start(); err != nil { |
| + return nil, false, err |
| + } |
| + out, readErr := io.ReadAll(io.LimitReader(pipe, int64(limit)+1)) |
| + if len(out) > limit { |
| + _ = cmd.Process.Kill() |
| + _, _ = io.Copy(io.Discard, pipe) |
| + _ = cmd.Wait() |
| + return out[:limit], true, nil |
| + } |
| + err = cmd.Wait() |
| + return out, false, errors.Join(readErr, err) |
| +} |
| + |
| func gateListing(ctx context.Context, git, gitDir, sha string) (map[string]string, error) { |
| if !shaPattern.MatchString(sha) { |
| return nil, errBaseGate |
| @@ -74,9 +176,10 @@ func safeGatePath(name string) bool { |
| return name != "" && name != "." && path.Clean(name) == name && !strings.HasPrefix(name, "/") && !strings.HasPrefix(name, "../") && !strings.ContainsAny(name, "\x00\\\n\r") && name != ".git" && !strings.HasPrefix(name, ".git/") |
| } |
| -// readBaseGates reads only immutable base objects. The contract names every |
| +// ReadBaseGates reads only immutable base objects. The contract names every |
| // supporting file the gate consumes; standard gate selectors are always pinned. |
| -func readBaseGates(ctx context.Context, git, gitDir, base string) (map[string]baseGateFile, error) { |
| +func ReadBaseGates(ctx context.Context, repo checks.Repo, base string) (BaseGates, error) { |
| + git, gitDir := repo.Git, repo.GitDir |
| listing, err := gateListing(ctx, git, gitDir, base) |
| if err != nil { |
| return nil, err |
| @@ -135,7 +238,7 @@ func readBaseGates(ctx context.Context, git, gitDir, base string) (map[string]ba |
| } |
| names[name] = true |
| } |
| - out := map[string]baseGateFile{} |
| + out := BaseGates{} |
| total := 0 |
| for name := range names { |
| if _, exists := listing[name]; !exists { |
| @@ -155,16 +258,17 @@ func readBaseGates(ctx context.Context, git, gitDir, base string) (map[string]ba |
| return out, nil |
| } |
| -// installBaseGates replaces candidate gate selectors, including newly added |
| -// selectors, before choosing a gate. Separate copies become read-only mounts. |
| -func installBaseGates(ctx context.Context, tree workspace.TaskTree, candidate string, files map[string]baseGateFile, trusted string) (gate, error) { |
| - listing, err := gateListing(ctx, tree.Git, tree.GitDir, candidate) |
| +// InstallBaseGates replaces candidate gate selectors in dir (the |
| +// candidate's tree), including newly added selectors, before choosing a |
| +// gate. Separate copies under trusted become read-only mounts. |
| +func InstallBaseGates(ctx context.Context, repo checks.Repo, dir, candidate string, files BaseGates, trusted string) (Gate, error) { |
| + listing, err := gateListing(ctx, repo.Git, repo.GitDir, candidate) |
| if err != nil { |
| - return gate{}, err |
| + return Gate{}, err |
| } |
| - root, err := os.OpenRoot(tree.Dir) |
| + root, err := os.OpenRoot(dir) |
| if err != nil { |
| - return gate{}, err |
| + return Gate{}, err |
| } |
| defer root.Close() |
| names := make([]string, 0, len(files)) |
| @@ -173,24 +277,24 @@ func installBaseGates(ctx context.Context, tree workspace.TaskTree, candidate st |
| } |
| slices.Sort(names) |
| for name := range listing { |
| - if gatePathCovered(files, name) { |
| + if files.Covers(name) { |
| if err := root.RemoveAll(name); err != nil { |
| - return gate{}, err |
| + return Gate{}, err |
| } |
| } |
| } |
| - pins := make([]provider.Mount, 0, len(files)) |
| + pins := make([]gate.Mount, 0, len(files)) |
| for _, name := range names { |
| f := files[name] |
| if f.mode.IsDir() { |
| if err := root.RemoveAll(name); err != nil { |
| - return gate{}, err |
| + return Gate{}, err |
| } |
| if err := root.MkdirAll(name, 0700); err != nil { |
| - return gate{}, err |
| + return Gate{}, err |
| } |
| if err := os.MkdirAll(filepath.Join(trusted, name), 0700); err != nil { |
| - return gate{}, err |
| + return Gate{}, err |
| } |
| continue |
| } |
| @@ -205,43 +309,43 @@ func installBaseGates(ctx context.Context, tree workspace.TaskTree, candidate st |
| if os.IsNotExist(err) { |
| err = root.Mkdir(parent, 0700) |
| } else if err == nil && !info.IsDir() { |
| - return gate{}, errBaseGate |
| + return Gate{}, errBaseGate |
| } |
| if err != nil { |
| - return gate{}, err |
| + return Gate{}, err |
| } |
| } |
| if err := root.RemoveAll(name); err != nil { |
| - return gate{}, err |
| + return Gate{}, err |
| } |
| if err := root.WriteFile(name, f.body, f.mode); err != nil { |
| - return gate{}, err |
| + return Gate{}, err |
| } |
| src := filepath.Join(trusted, filepath.FromSlash(name)) |
| if err := os.MkdirAll(filepath.Dir(src), 0700); err != nil { |
| - return gate{}, err |
| + return Gate{}, err |
| } |
| if err := os.WriteFile(src, f.body, f.mode); err != nil { |
| - return gate{}, err |
| + return Gate{}, err |
| } |
| if !gateDirectoryContains(files, name) { |
| - pins = append(pins, provider.Mount{Source: src, Target: "/workspace/" + name, ReadOnly: true}) |
| + pins = append(pins, gate.Mount{Source: src, Target: "/workspace/" + name}) |
| } |
| } |
| for _, name := range names { |
| if files[name].mode.IsDir() && !gateDirectoryContains(files, name) { |
| if err := provider.SealTree(filepath.Join(trusted, name)); err != nil { |
| - return gate{}, err |
| + return Gate{}, err |
| } |
| - pins = append(pins, provider.Mount{Source: filepath.Join(trusted, name), Target: "/workspace/" + name, ReadOnly: true}) |
| + pins = append(pins, gate.Mount{Source: filepath.Join(trusted, name), Target: "/workspace/" + name}) |
| } |
| } |
| - g, ok := findGate(trusted) |
| + g, ok := FindGate(trusted) |
| if !ok { |
| - return gate{}, errBaseGate |
| + return Gate{}, errBaseGate |
| } |
| - g.pins = pins |
| - if g.name == ".amadan/ci.d" { |
| + g.Pins = pins |
| + if g.Name == ".amadan/ci.d" { |
| // A candidate cannot add a new step after preparation and have a glob run it. |
| var script strings.Builder |
| script.WriteString("set -eu\n") |
| @@ -250,14 +354,14 @@ func installBaseGates(ctx context.Context, tree workspace.TaskTree, candidate st |
| fmt.Fprintf(&script, "%s\n", shellGatePath("./"+name)) |
| } |
| } |
| - g.argv = []string{"/usr/bin/bash", "-c", script.String()} |
| + g.Argv = []string{"/usr/bin/bash", "-c", script.String()} |
| } |
| return g, nil |
| } |
| func shellGatePath(name string) string { return "'" + strings.ReplaceAll(name, "'", "'\"'\"'") + "'" } |
| -func gateDirectoryContains(files map[string]baseGateFile, name string) bool { |
| +func gateDirectoryContains(files BaseGates, name string) bool { |
| for dir, f := range files { |
| if f.mode.IsDir() && strings.HasPrefix(name, dir+"/") { |
| return true |
| @@ -265,12 +369,16 @@ func gateDirectoryContains(files map[string]baseGateFile, name string) bool { |
| } |
| return false |
| } |
| -func gatePathCovered(files map[string]baseGateFile, name string) bool { |
| + |
| +// Covers reports whether name is one of the base's gate files: listed, |
| +// a standard selector, or inside a gate directory. |
| +func (files BaseGates) Covers(name string) bool { |
| _, listed := files[name] |
| return listed || standardGate(name) || gateDirectoryContains(files, name) |
| } |
| -func removeBaseGates(dir string) { |
| +// RemoveBaseGates removes the trusted copies, sealed read-only or not. |
| +func RemoveBaseGates(dir string) { |
| _ = filepath.WalkDir(dir, func(p string, d os.DirEntry, err error) error { |
| if err == nil && d.IsDir() { |
| _ = os.Chmod(p, 0700) |
diff --git a/internal/runner/checkrun/run.go b/internal/runner/checkrun/run.go| new file mode 100644 |
| index 00000000..70318c6a |
| --- /dev/null |
| +++ b/internal/runner/checkrun/run.go |
| @@ -0,0 +1,315 @@ |
| +// Package checkrun is a checks step's run, wherever it runs: the gates |
| +// from the base commit (the candidate cannot choose what judges it), the |
| +// toolchain check, Equipo's own dependency stage, the gate in a |
| +// gate.Runner, and what the outcome says, needs_network included. The |
| +// primary (internal/runner/thin) and a hosted worker share it; how a gate |
| +// is confined is the runner's business. |
| +package checkrun |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "maps" |
| + "os" |
| + "path/filepath" |
| + "runtime" |
| + "slices" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/checks" |
| + "amadan.net/oficina/equipo/internal/runner/gate" |
| + "amadan.net/oficina/equipo/internal/runner/workspace" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// Inputs is one checks run's tree and commits. |
| +type Inputs struct { |
| + // Workspace is the candidate's tree; repo holds its objects. |
| + Workspace, BaseSHA, CandidateSHA string |
| + // GoRoot is the runner's Go (empty: none, so no toolchain check and |
| + // no dependency stage). ModuleCache is the cache the runner's gate |
| + // mounts; the runner resolves it, so Run does not read it. |
| + GoRoot, ModuleCache string |
| + // Limit bounds each gate (0: the runner's default). |
| + Limit time.Duration |
| + // Attempt names every gate run; Record persists each run's process |
| + // record before it starts (gate.Runner.Run). |
| + Attempt string |
| + Record func(id string) error |
| + // Prepare, when set, gives a tree about to be checked a .git of its |
| + // own at the candidate (the judged tree, and a diagnostic's). |
| + Prepare func(ctx context.Context, dir string) error |
| + // Diagnostic, when set, checks the candidate out afresh into a tree of |
| + // its own, where its own gate runs as a diagnostic when it changed a |
| + // base gate file (nil: no diagnostic). |
| + Diagnostic func(ctx context.Context) (dir string, err error) |
| + // Hosted is hosted CI's verdict on the candidate, when there is one: |
| + // useful feedback, never a certificate. |
| + Hosted *Hosted |
| + // Log, when set, hears what went wrong on the way. |
| + Log func(what string, err error) |
| +} |
| + |
| +// Hosted is hosted CI's verdict on the candidate: its diagnostic output |
| +// and whether it failed. |
| +type Hosted struct { |
| + Output string |
| + Failed bool |
| +} |
| + |
| +// Outcome is how the run ended, as the step reports it. |
| +type Outcome struct { |
| + Checks, BaseChecks, Reason, Output string |
| + // BaseChecksSHA is the base, set only when the base's own gates |
| + // passed on the candidate (certified). |
| + BaseChecksSHA string |
| + Sandbox string |
| + Evidence *checks.Evidence |
| + // State is the step's end (wire.StepDone, StepFailed, StepCancelled); |
| + // Terminated says the ends of everything it ran were observed. |
| + State string |
| + Terminated bool |
| + // Gate is the gate the verdict came from; LogTail the output's last |
| + // lines (or why nothing ran); ExitCode the gate's, once it counts. |
| + Gate, LogTail string |
| + ExitCode *int |
| +} |
| + |
| +// tailLines is how many lines of output a step's log tail keeps. |
| +const tailLines = 30 |
| + |
| +// Run runs the checks of in.CandidateSHA in g: the base's gates when its |
| +// commit certifies them, the dependency stage, the gate, and the mapping |
| +// of what they said to an outcome. A candidate without a gate, its base |
| +// certifying none, ends wire.ChecksNone before anything runs. |
| +func Run(ctx context.Context, g gate.Runner, repo checks.Repo, in Inputs) Outcome { |
| + var out Outcome |
| + done := func(outcome, reason string) Outcome { |
| + out.State, out.Terminated, out.Checks, out.Reason = wire.StepDone, true, outcome, reason |
| + return out |
| + } |
| + run := func(ctx context.Context, dir string, argv []string, limit time.Duration) gate.Result { |
| + return g.Run(ctx, in.Attempt, dir, argv, limit, in.Record) |
| + } |
| + files, baseErr := ReadBaseGates(ctx, repo, in.BaseSHA) |
| + changed, err := (workspace.TaskTree{Dir: in.Workspace, GitDir: repo.GitDir, Git: repo.Git, Base: in.BaseSHA}).ChangedFiles(ctx, in.CandidateSHA) |
| + if err != nil { |
| + return done(wire.ChecksCannotRun, "base_gate_unavailable") |
| + } |
| + changedGate := false |
| + for _, name := range changed { |
| + changedGate = changedGate || files.Covers(name) |
| + } |
| + candidateGate, candidateOK := FindGate(in.Workspace) |
| + 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 { |
| + return done(wire.ChecksCannotRun, "base_gate_unavailable") |
| + } |
| + defer RemoveBaseGates(trusted) |
| + chosen, err = InstallBaseGates(ctx, repo, in.Workspace, in.CandidateSHA, files, trusted) |
| + if err != nil { |
| + return done(wire.ChecksCannotRun, "base_gate_unavailable") |
| + } |
| + } else if !candidateOK { |
| + return done(wire.ChecksNone, "") |
| + } |
| + if runtime.GOOS != "darwin" && checks.NeedsMacOS(changed, chosen.Text) { |
| + out.LogTail = "Not run: " + chosen.Name + " needs macOS to check this change, and this runner is " + runtime.GOOS + "." |
| + return done(wire.ChecksCannotRun, "needs_macos") |
| + } |
| + if goUnmet(ctx, repo, in.BaseSHA, in.GoRoot, in.Log) { |
| + return done(wire.ChecksCannotRun, "checks_unavailable") |
| + } |
| + if in.Prepare != nil { |
| + if err := in.Prepare(ctx, in.Workspace); err != nil { |
| + out.State, out.Reason, out.Terminated = wire.StepFailed, "workspace_refused", true |
| + return out |
| + } |
| + } |
| + stage, staged := dependencyStage(ctx, in, run) |
| + if !staged.Terminated { |
| + // Its namespace's exit was not observed: no gate launches over |
| + // it, and its namespace stays recorded for recovery. |
| + out.State, out.Reason, out.Terminated = wire.StepFailed, firstNonEmpty(staged.Reason, "provider_failed"), false |
| + return out |
| + } |
| + res := run(gate.WithPins(ctx, chosen.Pins), in.Workspace, chosen.Argv, in.Limit) |
| + baseResult, baseGate := res, chosen |
| + if certified { |
| + out.BaseChecks = wire.ChecksCannotRun |
| + if res.Terminated && res.Reason == "" && (res.Code == 0 || !checks.NeedsNetwork(stage, checks.Run{Code: res.Code, Output: res.Output, Evidence: res.Evidence})) { |
| + out.BaseChecks = wire.ChecksFailed |
| + if res.Code == 0 { |
| + out.BaseChecks = wire.ChecksPassed |
| + } |
| + } |
| + } |
| + gateOutput := res.Output |
| + if certified && res.Terminated && res.Reason == "" && res.Code == 0 { |
| + out.BaseChecksSHA = in.BaseSHA |
| + } |
| + if certified && changedGate { |
| + 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 { |
| + if err := in.Prepare(ctx, diagnostic); err != nil { |
| + return done(wire.ChecksCannotRun, "checks_unavailable") |
| + } |
| + } |
| + res = run(ctx, diagnostic, candidateGate.Argv, in.Limit) |
| + chosen = candidateGate |
| + gateOutput = res.Output |
| + res.Output = "Candidate gate diagnostic:\n" + tailBytes(res.Output, wire.MaxChecksOutput/3) + "\n" + baseOutput |
| + } |
| + } |
| + if !certified { |
| + res.Output = "Uncertified candidate gate diagnostic:\n" + tailBytes(res.Output, wire.MaxChecksOutput/3) |
| + } |
| + if in.Hosted != nil { |
| + res.Output = CombinedOutput(res.Output, in.Hosted.Output) |
| + if in.Hosted.Failed && res.Reason == "" && res.Terminated { |
| + res.Code = 1 |
| + } |
| + } |
| + out.Gate, out.Output, out.LogTail = chosen.Name, res.Output, lastLines(res.Output, tailLines, wire.MaxLogTail) |
| + // Diagnostics keep their output, but cannot replace a trusted gate failure. |
| + if certified && out.BaseChecks != wire.ChecksPassed && res.Terminated { |
| + res, gateOutput, out.Gate = baseResult, baseResult.Output, baseGate.Name |
| + } |
| + out.Sandbox, out.Evidence = res.Sandbox, res.Evidence |
| + if !res.Terminated { |
| + out.State, out.Reason, out.Terminated = wire.StepFailed, firstNonEmpty(res.Reason, "provider_failed"), false |
| + return out |
| + } |
| + if ctx.Err() != nil { |
| + out.State, out.Reason, out.Terminated = wire.StepCancelled, "cancelled", true |
| + return out |
| + } |
| + switch { |
| + case res.Reason == "checks_timeout": |
| + out.Gate = "" |
| + return done(wire.ChecksCannotRun, "checks_timeout") |
| + case res.Reason != "": |
| + out.Gate, out.Output = "", "" |
| + return done(wire.ChecksCannotRun, "checks_unavailable") |
| + case res.Code != 0 && checks.NeedsNetwork(stage, checks.Run{Code: res.Code, Output: gateOutput, Evidence: res.Evidence}): |
| + // A gate that needs the network cannot pass or fail honestly here. |
| + out.Gate = "" |
| + return done(wire.ChecksCannotRun, "needs_network") |
| + } |
| + code := res.Code |
| + out.ExitCode = &code |
| + if code == 0 { |
| + return done(wire.ChecksPassed, "") |
| + } |
| + if out.BaseChecks == wire.ChecksFailed { |
| + return done(wire.ChecksFailed, "base_checks_failed") |
| + } |
| + return done(wire.ChecksFailed, "") |
| +} |
| + |
| +// goUnmet reports whether the runner's Go cannot honour what the base's |
| +// own go.mod files and gate files ask (checks.GoRequirement), read from |
| +// base objects the candidate cannot change. Unknown is not unmet: the |
| +// gate runs, and Go says why it cannot. |
| +func goUnmet(ctx context.Context, repo checks.Repo, base, goRoot string, log func(string, error)) bool { |
| + local, err := checks.RunnerGoVersion(goRoot) |
| + if goRoot == "" || err != nil { |
| + return false |
| + } |
| + listing, err := gateListing(ctx, repo.Git, repo.GitDir, base) |
| + if err != nil { |
| + if log != nil { |
| + log("checks go requirement", err) |
| + } |
| + return false |
| + } |
| + files := map[string][]byte{} |
| + for _, name := range slices.Sorted(maps.Keys(listing)) { |
| + if mode := listing[name]; checks.GoRequirementFile(name) && (mode == "100644" || mode == "100755") && len(files) < 512 { |
| + if raw, err := gateGit(ctx, repo.Git, repo.GitDir, 1<<20, "cat-file", "blob", base+":"+name); err == nil { |
| + files[name] = raw |
| + } |
| + } |
| + } |
| + return checks.ReadGoRequirement(files).Unmet(local) |
| +} |
| + |
| +// dependencyStage runs Equipo's own `go mod download` for the tree's |
| +// modules in the gate's runner (checks.DependencyStage), before the gate. |
| +// Its exit code and Go's own lines are the only evidence that a gate |
| +// needed the network; a stage that did not run, or did not finish, gives |
| +// none. The result says whether its exit was observed: when it was not, |
| +// the caller must stop. |
| +func dependencyStage(ctx context.Context, in Inputs, run func(context.Context, string, []string, time.Duration) gate.Result) (checks.Run, gate.Result) { |
| + dirs := checks.GoModuleDirs(in.Workspace) |
| + if existingDir(in.GoRoot) == "" || len(dirs) == 0 { |
| + return checks.Run{}, gate.Result{Terminated: true} |
| + } |
| + res := run(ctx, in.Workspace, checks.DependencyStage(dirs), 5*time.Minute) |
| + if !res.Terminated || res.Reason != "" { |
| + return checks.Run{}, res |
| + } |
| + return checks.Run{Code: res.Code, Output: res.Output, Evidence: res.Evidence}, res |
| +} |
| + |
| +func existingDir(p string) string { |
| + if p == "" { |
| + return "" |
| + } |
| + if info, err := os.Stat(p); err == nil && info.IsDir() { |
| + return p |
| + } |
| + return "" |
| +} |
| + |
| +func firstNonEmpty(a, b string) string { |
| + if a != "" { |
| + return a |
| + } |
| + return b |
| +} |
| + |
| +// CombinedOutput is a local gate's output with hosted CI's diagnostic |
| +// after it, within the bound the instance keeps: the hosted part (every |
| +// failing unit's share, wire.ClipCIOutput) in its third, the local |
| +// output's tail in the rest. |
| +func CombinedOutput(local, hosted string) string { |
| + part := "\nHosted CI diagnostic:\n" + wire.ClipCIOutput(hosted, wire.MaxChecksOutput/3) |
| + return tailBytes(local, wire.MaxChecksOutput-len(part)) + part |
| +} |
| + |
| +// tailBytes is the end of s within limit bytes, starting on a line. |
| +func tailBytes(s string, limit int) string { |
| + if limit <= 0 { |
| + return "" |
| + } |
| + if len(s) <= limit { |
| + return s |
| + } |
| + s = s[len(s)-limit:] |
| + if i := strings.IndexByte(s, '\n'); i >= 0 { |
| + s = s[i+1:] |
| + } |
| + return strings.ToValidUTF8(s, "") |
| +} |
| + |
| +// lastLines is the last n lines of s within limit bytes. |
| +func lastLines(s string, n, limit int) string { |
| + lines := strings.Split(strings.TrimRight(s, "\n"), "\n") |
| + out := strings.Join(lines[max(0, len(lines)-n):], "\n") |
| + for len(out) > limit { |
| + _, out, _ = strings.Cut(out, "\n") |
| + } |
| + return out |
| +} |
diff --git a/internal/runner/checkrun/run_test.go b/internal/runner/checkrun/run_test.go| new file mode 100644 |
| index 00000000..fa52129c |
| --- /dev/null |
| +++ b/internal/runner/checkrun/run_test.go |
| @@ -0,0 +1,197 @@ |
| +package checkrun |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/checks" |
| + "amadan.net/oficina/equipo/internal/runner/gate" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// execGate runs each gate as a plain process in its tree (no sandbox) and |
| +// keeps what it was asked: the argv, the tree and the pins. The |
| +// dependency stage answers stage instead of running. |
| +type execGate struct { |
| + stage *gate.Result |
| + runs []execRun |
| +} |
| + |
| +type execRun struct { |
| + argv []string |
| + dir string |
| + pins []gate.Mount |
| + attempt string |
| + recorded string |
| +} |
| + |
| +func (g *execGate) Sandbox() string { return wire.SandboxBubblewrap } |
| +func (g *execGate) Verify(string) bool { return true } |
| +func (g *execGate) 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) |
| + run := execRun{argv: argv, dir: dir, pins: gate.Pins(ctx), attempt: attempt, recorded: id} |
| + g.runs = append(g.runs, run) |
| + if err := record(id); err != nil { |
| + return gate.Result{Reason: "checks_unavailable", Terminated: true} |
| + } |
| + if len(argv) > 3 && argv[3] == "equipo-dependencies" { |
| + if g.stage != nil { |
| + return *g.stage |
| + } |
| + return gate.Result{Terminated: true, Evidence: checks.Scan("")} |
| + } |
| + cmd := exec.CommandContext(ctx, argv[0], argv[1:]...) |
| + cmd.Dir = dir |
| + out, err := cmd.CombinedOutput() |
| + code := 0 |
| + if x, ok := err.(*exec.ExitError); ok { |
| + code = x.ExitCode() |
| + } else if err != nil { |
| + return gate.Result{Reason: "checks_unavailable", Terminated: true} |
| + } |
| + return gate.Result{Output: strings.TrimRight(string(out), "\n"), Code: code, Terminated: true, Sandbox: wire.SandboxBubblewrap, Evidence: checks.Scan(string(out))} |
| +} |
| + |
| +// repo is a repository with a base commit and a candidate on it, and a |
| +// fresh checkout of the candidate (the judged tree). |
| +func repo(t *testing.T, base, candidate map[string]string) (checks.Repo, string, string, string) { |
| + t.Helper() |
| + dir := filepath.Join(t.TempDir(), "seed") |
| + git := func(args ...string) string { |
| + t.Helper() |
| + cmd := exec.Command("git", args...) |
| + cmd.Dir = dir |
| + cmd.Env = append(os.Environ(), "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@x", "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@x", "GIT_CONFIG_GLOBAL=/dev/null") |
| + out, err := cmd.CombinedOutput() |
| + if err != nil { |
| + t.Fatalf("git %v: %v %s", args, err, out) |
| + } |
| + return strings.TrimSpace(string(out)) |
| + } |
| + write := func(files map[string]string) { |
| + for name, body := range files { |
| + p := filepath.Join(dir, name) |
| + if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(p, []byte(body), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + } |
| + if err := os.MkdirAll(dir, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + git("init", "-q", "-b", "main") |
| + write(map[string]string{"README.md": "readme\n"}) |
| + write(base) |
| + git("add", "-A") |
| + git("commit", "-qm", "base") |
| + baseSHA := git("rev-parse", "HEAD") |
| + write(candidate) |
| + git("add", "-A") |
| + git("commit", "-qm", "candidate", "--allow-empty") |
| + candidateSHA := git("rev-parse", "HEAD") |
| + tree := filepath.Join(t.TempDir(), "tree") |
| + if err := os.MkdirAll(tree, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + git("--work-tree="+tree, "checkout", "-q", candidateSHA, "--", ".") |
| + return checks.Repo{Git: "/usr/bin/git", GitDir: filepath.Join(dir, ".git")}, tree, baseSHA, candidateSHA |
| +} |
| + |
| +const contract = `{"version":1,"files":["budgets.txt"]}` |
| +const budgetGate = "ci:\n\t@test \"$$(cat size.txt)\" -le \"$$(cat budgets.txt)\" || { echo over budget; exit 3; }\n" |
| + |
| +// TestChecksRunBaseGatesFromBase: a candidate that edits its gate and its gate |
| +// files still runs the base's, pinned read-only; the base failing is the |
| +// verdict and BaseChecksSHA stays unset. |
| +func TestChecksRunBaseGatesFromBase(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", "budgets.txt": "9\n", "size.txt": "2\n", ".equipo/gates.json": `{"version":1,"files":[]}`}) |
| + g := &execGate{} |
| + recorded := []string{} |
| + 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 }}) |
| + if out.State != wire.StepDone || !out.Terminated || out.Checks != wire.ChecksFailed || out.BaseChecks != wire.ChecksFailed || out.Reason != "base_checks_failed" || out.BaseChecksSHA != "" || out.Gate != "make ci" || out.ExitCode == nil || *out.ExitCode != 2 { |
| + t.Fatalf("outcome %+v", out) |
| + } |
| + if len(g.runs) != 1 || g.runs[0].attempt != "checks/k" || g.runs[0].dir != tree || len(recorded) != 1 || recorded[0] != "ns-1" { |
| + t.Fatalf("runs %+v recorded %v", g.runs, recorded) |
| + } |
| + pinned := map[string]bool{} |
| + for _, p := range g.runs[0].pins { |
| + pinned[p.Target] = true |
| + } |
| + if !pinned["/workspace/Makefile"] || !pinned["/workspace/budgets.txt"] || !pinned["/workspace/.equipo/gates.json"] { |
| + t.Fatalf("pins %+v", g.runs[0].pins) |
| + } |
| + if !strings.Contains(out.Output, "over budget") || out.Sandbox != wire.SandboxBubblewrap || out.Evidence == nil { |
| + t.Fatalf("output %q sandbox %q", out.Output, out.Sandbox) |
| + } |
| +} |
| + |
| +// TestChecksRunBaseChecksSHAOnlyOnBasePass: a certified pass names the base; an |
| +// uncertified pass (no gate contract) names nothing and says so. |
| +func TestChecksRunBaseChecksSHAOnlyOnBasePass(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{"NEWS": "news\n"}) |
| + out := Run(context.Background(), &execGate{}, r, Inputs{Workspace: tree, BaseSHA: base, CandidateSHA: candidate, Record: func(string) error { return nil }}) |
| + if out.Checks != wire.ChecksPassed || out.BaseChecks != wire.ChecksPassed || out.BaseChecksSHA != base || out.Reason != "" { |
| + t.Fatalf("certified %+v", out) |
| + } |
| + r, tree, base, candidate = repo(t, map[string]string{"Makefile": "ci:\n\t@echo hi\n"}, map[string]string{"NEWS": "news\n"}) |
| + out = Run(context.Background(), &execGate{}, r, Inputs{Workspace: tree, BaseSHA: base, CandidateSHA: candidate, Record: func(string) error { return nil }}) |
| + if out.Checks != wire.ChecksPassed || out.BaseChecks != "" || out.BaseChecksSHA != "" || out.Output != "Uncertified candidate gate diagnostic:\nhi" { |
| + t.Fatalf("uncertified %+v", out) |
| + } |
| + r, tree, base, candidate = repo(t, nil, map[string]string{"NEWS": "news\n"}) |
| + g := &execGate{} |
| + out = Run(context.Background(), g, r, Inputs{Workspace: tree, BaseSHA: base, CandidateSHA: candidate, Record: func(string) error { return nil }}) |
| + if out.State != wire.StepDone || out.Checks != wire.ChecksNone || len(g.runs) != 0 { |
| + t.Fatalf("no gate %+v ran %+v", out, g.runs) |
| + } |
| +} |
| + |
| +// TestChecksRunNeedsNetworkFromTheStage: only the dependency stage's own |
| +// evidence makes a failed gate needs_network, and a base gate that failed |
| +// that way certifies nothing. |
| +func TestChecksRunNeedsNetworkFromTheStage(t *testing.T) { |
| + files := map[string]string{".equipo/gates.json": `{"version":1,"files":[]}`, "Makefile": "ci:\n\texit 1\n", "go.mod": "module example.com/x\n\ngo 1.21\n"} |
| + refusal := "go: example.invalid/dep@v1.0.0: module lookup disabled by GOPROXY=off" |
| + for _, tc := range []struct { |
| + name string |
| + stage gate.Result |
| + checks, base string |
| + reason, label string |
| + }{ |
| + {"stage refused offline", gate.Result{Code: 1, Terminated: true, Output: refusal, Evidence: checks.Scan(refusal + "\n")}, wire.ChecksCannotRun, wire.ChecksCannotRun, "needs_network", ""}, |
| + {"stage passed", gate.Result{Terminated: true, Evidence: checks.Scan("")}, wire.ChecksFailed, wire.ChecksFailed, "base_checks_failed", "make ci"}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + r, tree, base, candidate := repo(t, files, map[string]string{"NEWS": "news\n"}) |
| + g := &execGate{stage: &tc.stage} |
| + out := Run(context.Background(), g, r, Inputs{Workspace: tree, BaseSHA: base, CandidateSHA: candidate, GoRoot: t.TempDir(), Record: func(string) error { return nil }}) |
| + if out.Checks != tc.checks || out.BaseChecks != tc.base || out.Reason != tc.reason || out.Gate != tc.label || out.BaseChecksSHA != "" { |
| + t.Fatalf("outcome %+v", out) |
| + } |
| + if len(g.runs) != 2 || g.runs[0].argv[3] != "equipo-dependencies" || len(g.runs[0].pins) != 0 || len(g.runs[1].pins) == 0 { |
| + t.Fatalf("runs %+v", g.runs) |
| + } |
| + }) |
| + } |
| + // A stage whose end was not proven stops the step there, unterminated. |
| + r, tree, base, candidate := repo(t, files, map[string]string{"NEWS": "news\n"}) |
| + g := &execGate{stage: &gate.Result{Reason: "cancelled"}} |
| + out := Run(context.Background(), g, r, Inputs{Workspace: tree, BaseSHA: base, CandidateSHA: candidate, GoRoot: t.TempDir(), Record: func(string) error { return nil }}) |
| + if out.State != wire.StepFailed || out.Terminated || out.Reason != "cancelled" || out.Checks != "" || len(g.runs) != 1 { |
| + t.Fatalf("unproven stage %+v runs %d", out, len(g.runs)) |
| + } |
| +} |
diff --git a/internal/runner/checks/repo.go b/internal/runner/checks/repo.go| new file mode 100644 |
| index 00000000..031480fc |
| --- /dev/null |
| +++ b/internal/runner/checks/repo.go |
| @@ -0,0 +1,6 @@ |
| +package checks |
| + |
| +// Repo is the git store a checks run reads its commits from: the git |
| +// binary and the git directory holding the base and the candidate. The |
| +// base's gates are read from its objects, never from the candidate's tree. |
| +type Repo struct{ Git, GitDir string } |
diff --git a/internal/runner/gate/gate.go b/internal/runner/gate/gate.go| new file mode 100644 |
| index 00000000..ce6b13c2 |
| --- /dev/null |
| +++ b/internal/runner/gate/gate.go |
| @@ -0,0 +1,56 @@ |
| +// Package gate is the contract every checks gate runner keeps: the |
| +// primary's containment, a Mac's Seatbelt, a hosted VM's bubblewrap. It |
| +// is a leaf: it knows the wire labels and the checks evidence, nothing of |
| +// how a runner confines what it runs. |
| +package gate |
| + |
| +import ( |
| + "context" |
| + "slices" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/checks" |
| +) |
| + |
| +// Result is how a gate's run ended. |
| +type Result struct { |
| + Output, Reason string |
| + Code int |
| + Terminated bool |
| + // Sandbox is how the gate was confined (wire.Sandbox*). |
| + Sandbox string |
| + // Evidence was read from the whole output (Output is its tail). |
| + Evidence *checks.Evidence |
| +} |
| + |
| +// Runner runs one checks gate and proves its end. |
| +type Runner interface { |
| + // Sandbox is what the runner reports in hello (wire.Sandbox*). |
| + Sandbox() string |
| + // Run runs argv in dir. record persists the attempt's process record |
| + // before it runs (so a restart can verify its end); a record that |
| + // cannot be kept stops the run. When ctx carries Pins (checkrun's |
| + // base gate files), the runner mounts them read-only over dir; a |
| + // runner that cannot must not be given checkrun's gates. |
| + Run(ctx context.Context, attempt, dir string, argv []string, limit time.Duration, record func(id string) error) Result |
| + // Verify reports whether a recorded attempt has ended for sure. |
| + Verify(id string) bool |
| +} |
| + |
| +// Mount is a base gate file or directory, copied outside the tree to |
| +// Source, that the run sees read-only at Target (/workspace/<path>): the |
| +// candidate cannot change the gate it is judged by while it runs. |
| +type Mount struct{ Source, Target string } |
| + |
| +type pinsKey struct{} |
| + |
| +// WithPins is ctx for a run that mounts pins read-only (nil: none). |
| +func WithPins(ctx context.Context, pins []Mount) context.Context { |
| + return context.WithValue(ctx, pinsKey{}, slices.Clone(pins)) |
| +} |
| + |
| +// Pins is what the run in ctx mounts read-only, a copy (nil: nothing). |
| +func Pins(ctx context.Context) []Mount { |
| + pins, _ := ctx.Value(pinsKey{}).([]Mount) |
| + return slices.Clone(pins) |
| +} |
diff --git a/internal/runner/gate/gate_test.go b/internal/runner/gate/gate_test.go| new file mode 100644 |
| index 00000000..a3c4f26b |
| --- /dev/null |
| +++ b/internal/runner/gate/gate_test.go |
| @@ -0,0 +1,61 @@ |
| +package gate |
| + |
| +import ( |
| + "context" |
| + "go/parser" |
| + "go/token" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// TestChecksGateIsALeaf: gate imports only the standard library, wire and |
| +// checks, so any runner (the primary, a Mac, a hosted VM) can keep its |
| +// contract without importing another. |
| +func TestChecksGateIsALeaf(t *testing.T) { |
| + files, _ := filepath.Glob("*.go") |
| + n := 0 |
| + for _, f := range files { |
| + if strings.HasSuffix(f, "_test.go") { |
| + continue |
| + } |
| + file, err := parser.ParseFile(token.NewFileSet(), f, nil, parser.ImportsOnly) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, imp := range file.Imports { |
| + path, _ := strconv.Unquote(imp.Path.Value) |
| + n++ |
| + if strings.Contains(strings.Split(path, "/")[0], ".") && path != "amadan.net/oficina/equipo/internal/wire" && path != "amadan.net/oficina/equipo/internal/runner/checks" { |
| + t.Errorf("%s imports %s", f, path) |
| + } |
| + } |
| + } |
| + if n == 0 { |
| + t.Fatal("no imports read") |
| + } |
| +} |
| + |
| +// TestChecksPinsTravelWithTheContext: the base gate files a run pins reach the |
| +// runner through its context, as a copy the caller cannot change after, |
| +// and a context that pins nothing says so. |
| +func TestChecksPinsTravelWithTheContext(t *testing.T) { |
| + if got := Pins(context.Background()); got != nil { |
| + t.Fatalf("pins from nowhere: %v", got) |
| + } |
| + pins := []Mount{{Source: "/trusted/Makefile", Target: "/workspace/Makefile"}} |
| + ctx := WithPins(context.Background(), pins) |
| + pins[0].Target = "/workspace/elsewhere" |
| + got := Pins(ctx) |
| + if len(got) != 1 || got[0] != (Mount{Source: "/trusted/Makefile", Target: "/workspace/Makefile"}) { |
| + t.Fatalf("pins %v", got) |
| + } |
| + got[0].Source = "/candidate/Makefile" |
| + if Pins(ctx)[0].Source != "/trusted/Makefile" { |
| + t.Fatal("a runner changed the run's pins") |
| + } |
| + if Pins(WithPins(ctx, nil)) != nil { |
| + t.Fatal("an unpinned run inherited pins") |
| + } |
| +} |
diff --git a/internal/runner/thin/base_gates_shim_test.go b/internal/runner/thin/base_gates_shim_test.go| new file mode 100644 |
| index 00000000..e183b7fc |
| --- /dev/null |
| +++ b/internal/runner/thin/base_gates_shim_test.go |
| @@ -0,0 +1,27 @@ |
| +package thin |
| + |
| +import ( |
| + "context" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/checkrun" |
| + "amadan.net/oficina/equipo/internal/runner/checks" |
| + "amadan.net/oficina/equipo/internal/runner/workspace" |
| +) |
| + |
| +// The base gates moved to checkrun (hosted slice 2, Task 11); the gate |
| +// tests here read them through these, their assertions unchanged. |
| + |
| +func readBaseGates(ctx context.Context, git, gitDir, base string) (checkrun.BaseGates, error) { |
| + return checkrun.ReadBaseGates(ctx, checks.Repo{Git: git, GitDir: gitDir}, base) |
| +} |
| + |
| +func installBaseGates(ctx context.Context, tree workspace.TaskTree, candidate string, files checkrun.BaseGates, trusted string) (gate, error) { |
| + g, err := checkrun.InstallBaseGates(ctx, checks.Repo{Git: tree.Git, GitDir: tree.GitDir}, tree.Dir, candidate, files, trusted) |
| + return fromCheckrun(g), err |
| +} |
| + |
| +func removeBaseGates(dir string) { checkrun.RemoveBaseGates(dir) } |
| + |
| +// combinedOutput is checkrun's, as TestCombinedOutputKeepsHostedUnits |
| +// reads it. |
| +var combinedOutput = checkrun.CombinedOutput |
diff --git a/internal/runner/thin/copy_commands.go b/internal/runner/thin/copy_commands.go| index 455f7998..545bd02f 100644 |
| --- a/internal/runner/thin/copy_commands.go |
| +++ b/internal/runner/thin/copy_commands.go |
| @@ -172,11 +172,11 @@ func (e *Engineer) copyCommand(ctx context.Context, r stepRow, w copyWork, argv |
| args[0] = "/usr/bin/python3" |
| args[1] = "/workspace/trusted/" + args[1] |
| result := e.runGate(ctx, r, w.root, gate{jsonOutput: true, name: "copy", argv: args, input: raw, limit: 30 * time.Second}) |
| - if !result.terminated || result.reason != "" || result.code != 0 { |
| + if !result.Terminated || result.Reason != "" || result.Code != 0 { |
| return errors.New("copy: command refused or failed") |
| } |
| if out != nil { |
| - return json.Unmarshal([]byte(result.output), out) |
| + return json.Unmarshal([]byte(result.Output), out) |
| } |
| return nil |
| } |
diff --git a/internal/runner/thin/facts.go b/internal/runner/thin/facts.go| index 792ede6b..f5ef53cd 100644 |
| --- a/internal/runner/thin/facts.go |
| +++ b/internal/runner/thin/facts.go |
| @@ -8,6 +8,8 @@ import ( |
| "strconv" |
| "strings" |
| + "amadan.net/oficina/equipo/internal/runner/checkrun" |
| + "amadan.net/oficina/equipo/internal/runner/checks" |
| "amadan.net/oficina/equipo/internal/runner/workspace" |
| "amadan.net/oficina/equipo/internal/wire" |
| ) |
| @@ -92,13 +94,13 @@ func changeFacts(ctx context.Context, git, gitDir string, r stepRow) *wire.Chang |
| if r.RevertSHA != "" { |
| f.Revert = revertCheck(run, r.CandidateSHA, r.RevertSHA) |
| } |
| - gates, err := readBaseGates(ctx, git, gitDir, r.BaseSHA) |
| + gates, err := checkrun.ReadBaseGates(ctx, checks.Repo{Git: git, GitDir: gitDir}, r.BaseSHA) |
| if err != nil { |
| return f |
| } |
| for _, entry := range entries { |
| for _, name := range []string{entry.Old, entry.New} { |
| - if gatePathCovered(gates, name) { |
| + if gates.Covers(name) { |
| f.GateFilesChanged = true |
| } |
| } |
diff --git a/internal/runner/thin/fakeworker.go b/internal/runner/thin/fakeworker.go| index 93e38ecf..395cf4b8 100644 |
| --- a/internal/runner/thin/fakeworker.go |
| +++ b/internal/runner/thin/fakeworker.go |
| @@ -4,6 +4,7 @@ import ( |
| "context" |
| "amadan.net/oficina/equipo/internal/runner" |
| + rungate "amadan.net/oficina/equipo/internal/runner/gate" |
| "amadan.net/oficina/equipo/internal/wire" |
| ) |
| @@ -15,7 +16,7 @@ type fakeMac interface { |
| // probe is the fixture capability report, for a Mac whose checks |
| // sandbox is sandbox (seatbelt: probe P2 denied). |
| probe(sandbox string) func(context.Context) wire.Capabilities |
| - gate(bin, sandbox string) GateRunner |
| + gate(bin, sandbox string) rungate.Runner |
| // setup is the whole fake Mac worker for c and o: its report and |
| // gate, its credential operations and its Engineering pieces (Mac |
| // runners slice F, task 16). It may change c as a Mac's would be. |
diff --git a/internal/runner/thin/fakeworker_testbuild.go b/internal/runner/thin/fakeworker_testbuild.go| index c83d2dcd..179c9530 100644 |
| --- a/internal/runner/thin/fakeworker_testbuild.go |
| +++ b/internal/runner/thin/fakeworker_testbuild.go |
| @@ -17,6 +17,7 @@ import ( |
| "strings" |
| "amadan.net/oficina/equipo/internal/runner" |
| + rungate "amadan.net/oficina/equipo/internal/runner/gate" |
| "amadan.net/oficina/equipo/internal/runner/mac" |
| "amadan.net/oficina/equipo/internal/runner/mac/creds" |
| "amadan.net/oficina/equipo/internal/runner/mac/proc" |
| @@ -87,7 +88,7 @@ func (fakeWorker) probe(sandbox string) func(context.Context) wire.Capabilities |
| // HOME and TMPDIR the attempt's scratch, CI=1, a fixed PATH (bin first: |
| // the fake xcodebuild). Its label is none (it has no sandbox) unless the |
| // scenario plays a Mac whose probe P2 denied (sandbox seatbelt). |
| -func (fakeWorker) gate(bin, sandbox string) GateRunner { |
| +func (fakeWorker) gate(bin, sandbox string) rungate.Runner { |
| label := wire.SandboxNone |
| if sandbox == wire.SandboxSeatbelt { |
| label = wire.SandboxSeatbelt |
| @@ -146,7 +147,7 @@ func (f fakeWorker) setup(ctx context.Context, c *runner.Config, o Options) (wor |
| if err != nil { |
| return workerSetup{}, err |
| } |
| - return workerSetup{probe: probe, gate: gate, creds: m, engineering: eng}, nil |
| + return workerSetup{probe: probe, kind: macKind(gate), creds: m, engineering: eng}, nil |
| } |
| // fakeSRT is the test build's stand-in for srt, for a fake that plays a |
| @@ -161,7 +162,7 @@ const fakeSRT = "#!/bin/sh\nwhile [ \"$#\" -gt 0 ] && [ \"$1\" != \"--\" ]; do s |
| // check killed mid-run is cleared as a seatbelt Mac's is (the idle |
| // read); otherwise without a sandbox, which only a reboot clears (task |
| // 9). |
| -func (f fakeWorker) checksGate(dir, bin, sandbox string, turns *mac.Turns, entry string) (GateRunner, error) { |
| +func (f fakeWorker) checksGate(dir, bin, sandbox string, turns *mac.Turns, entry string) (rungate.Runner, error) { |
| g := f.gate(bin, sandbox).(macGate) |
| g.g.Env, g.g.Turns = append(g.g.Env, entry), turns |
| if sandbox == wire.SandboxSeatbelt { |
diff --git a/internal/runner/thin/go_checks.go b/internal/runner/thin/go_checks.go| deleted file mode 100644 |
| index 86041542..00000000 |
| --- a/internal/runner/thin/go_checks.go |
| +++ /dev/null |
| @@ -1,54 +0,0 @@ |
| -package thin |
| - |
| -import ( |
| - "context" |
| - "maps" |
| - "slices" |
| - "time" |
| - |
| - "amadan.net/oficina/equipo/internal/runner/checks" |
| - "amadan.net/oficina/equipo/internal/runner/workspace" |
| -) |
| - |
| -// goUnmet reports whether the runner's Go cannot honour what the base's |
| -// own go.mod files and gate files ask (checks.GoRequirement), read from |
| -// base objects the candidate cannot change. Unknown is not unmet: the |
| -// gate runs, and Go says why it cannot. |
| -func (e *Engineer) goUnmet(ctx context.Context, tree workspace.TaskTree, base string) bool { |
| - local, err := checks.RunnerGoVersion(e.O.Runner.GoRoot) |
| - if e.O.Runner.GoRoot == "" || err != nil { |
| - return false |
| - } |
| - listing, err := gateListing(ctx, tree.Git, tree.GitDir, base) |
| - if err != nil { |
| - e.log("checks go requirement", err) |
| - return false |
| - } |
| - files := map[string][]byte{} |
| - for _, name := range slices.Sorted(maps.Keys(listing)) { |
| - if mode := listing[name]; checks.GoRequirementFile(name) && (mode == "100644" || mode == "100755") && len(files) < 512 { |
| - if raw, err := gateGit(ctx, tree.Git, tree.GitDir, 1<<20, "cat-file", "blob", base+":"+name); err == nil { |
| - files[name] = raw |
| - } |
| - } |
| - } |
| - return checks.ReadGoRequirement(files).Unmet(local) |
| -} |
| - |
| -// dependencyStage runs Equipo's own `go mod download` for the tree's |
| -// modules in the check profile (checks.DependencyStage), before the gate. |
| -// Its exit code and Go's own lines are the only evidence that a gate |
| -// needed the network; a stage that did not run, or did not finish, gives |
| -// none. The gateResult says whether its namespace's exit was observed: |
| -// when it was not, the caller must stop. |
| -func (e *Engineer) dependencyStage(ctx context.Context, r stepRow, dir string) (checks.Run, gateResult) { |
| - dirs := checks.GoModuleDirs(dir) |
| - if existingDir(e.O.Runner.GoRoot) == "" || len(dirs) == 0 { |
| - return checks.Run{}, gateResult{terminated: true} |
| - } |
| - res := e.runGate(ctx, r, dir, gate{name: "dependencies", argv: checks.DependencyStage(dirs), limit: 5 * time.Minute}) |
| - if !res.terminated || res.reason != "" { |
| - return checks.Run{}, res |
| - } |
| - return checks.Run{Code: res.code, Output: res.output, Evidence: res.evidence}, res |
| -} |
diff --git a/internal/runner/thin/judge.go b/internal/runner/thin/judge.go| index 1d7ce081..986bffa5 100644 |
| --- a/internal/runner/thin/judge.go |
| +++ b/internal/runner/thin/judge.go |
| @@ -8,12 +8,10 @@ import ( |
| "errors" |
| "fmt" |
| "io" |
| - "io/fs" |
| "os" |
| "os/exec" |
| "path/filepath" |
| "regexp" |
| - "runtime" |
| "slices" |
| "strings" |
| "sync" |
| @@ -21,9 +19,11 @@ import ( |
| "amadan.net/oficina/equipo/internal/copydesk" |
| "amadan.net/oficina/equipo/internal/runner" |
| + "amadan.net/oficina/equipo/internal/runner/checkrun" |
| "amadan.net/oficina/equipo/internal/runner/checks" |
| "amadan.net/oficina/equipo/internal/runner/connect" |
| "amadan.net/oficina/equipo/internal/runner/forge" |
| + rungate "amadan.net/oficina/equipo/internal/runner/gate" |
| "amadan.net/oficina/equipo/internal/runner/provider" |
| "amadan.net/oficina/equipo/internal/runner/provider/claude" |
| "amadan.net/oficina/equipo/internal/runner/workspace" |
| @@ -126,9 +126,9 @@ func judgeReport(r stepRow) wire.StepReport { |
| // --- Checks --- |
| -// gate is how a repository checks itself, in Amadan's order: |
| -// .amadan/ci.d/ (each executable step in order), else .amadan/ci, else |
| -// `make ci`. text is what the gate's files say, for what it needs. |
| +// gate is how a repository checks itself (checkrun.Gate), with what a |
| +// launch of it in the containment takes: pins (read-only base gate |
| +// files), stdin, a structured output and its own limit. |
| type gate struct { |
| pins []provider.Mount |
| jsonOutput bool |
| @@ -139,62 +139,35 @@ type gate struct { |
| text string |
| } |
| -const ciDScript = `set -u |
| -for s in .amadan/ci.d/*; do |
| - [ -f "$s" ] || continue |
| - echo "=== ${s##*/}" |
| - if [ ! -x "$s" ]; then echo "${s##*/} is not executable"; exit 126; fi |
| - "./$s" || exit $? |
| -done` |
| +// makeCI matches a makefile's ci target. |
| +var makeCI = checkrun.MakeCI |
| -var makeCI = regexp.MustCompile(`(?m)^ci[ \t]*:([^=]|$)`) |
| - |
| -// findGate looks for the repository's gate in the tree, reading only |
| -// regular files inside it. |
| +// findGate looks for the repository's gate in the tree (checkrun.FindGate). |
| func findGate(dir string) (gate, bool) { |
| - root, err := os.OpenRoot(dir) |
| - if err != nil { |
| - return gate{}, false |
| - } |
| - defer root.Close() |
| - read := func(name string) (string, bool) { |
| - info, err := root.Lstat(name) |
| - if err != nil || !info.Mode().IsRegular() { |
| - return "", false |
| - } |
| - f, err := root.Open(name) |
| - if err != nil { |
| - return "", false |
| - } |
| - defer f.Close() |
| - raw, _ := io.ReadAll(io.LimitReader(f, 64<<10)) |
| - return string(raw), true |
| - } |
| - if entries, err := fs.ReadDir(root.FS(), ".amadan/ci.d"); err == nil { |
| - var text strings.Builder |
| - n := 0 |
| - for _, ent := range entries { |
| - if s, ok := read(".amadan/ci.d/" + ent.Name()); ok { |
| - text.WriteString(s + "\n") |
| - n++ |
| - } |
| - } |
| - if n > 0 { |
| - return gate{name: ".amadan/ci.d", argv: []string{"/usr/bin/bash", "-c", ciDScript}, text: text.String()}, true |
| - } |
| + g, ok := checkrun.FindGate(dir) |
| + return fromCheckrun(g), ok |
| +} |
| + |
| +func fromCheckrun(g checkrun.Gate) gate { |
| + return gate{name: g.Name, argv: g.Argv, text: g.Text, pins: pinMounts(g.Pins)} |
| +} |
| + |
| +// pinMounts is the containment's read-only mounts for a run's pins. |
| +func pinMounts(pins []rungate.Mount) []provider.Mount { |
| + if pins == nil { |
| + return nil |
| } |
| - if s, ok := read(".amadan/ci"); ok { |
| - return gate{name: ".amadan/ci", argv: []string{"/usr/bin/bash", "-c", "exec ./.amadan/ci"}, text: s}, true |
| + out := make([]provider.Mount, 0, len(pins)) |
| + for _, p := range pins { |
| + out = append(out, provider.Mount{Source: p.Source, Target: p.Target, ReadOnly: true}) |
| } |
| - for _, name := range []string{"GNUmakefile", "makefile", "Makefile"} { |
| - if s, ok := read(name); ok && makeCI.MatchString(s) { |
| - return gate{name: "make ci", argv: []string{"/usr/bin/make", "ci"}, text: s}, true |
| - } |
| - } |
| - return gate{}, false |
| + return out |
| } |
| -// checks runs the repository's gate on the candidate. |
| +// checks runs the repository's gate on the candidate (checkrun.Run), in |
| +// the containment's check profile. What is the primary's alone stays |
| +// here: the judged tree from the project clone, hosted CI's verdict, the |
| +// diagnostic tree, and the hosted phase for a candidate with no gate. |
| func (e *Engineer) checks(ctx context.Context, r stepRow, progress func(wire.StepReport)) wire.StepReport { |
| rep := judgeReport(r) |
| if r.Phase == phaseHosted { |
| @@ -218,10 +191,6 @@ func (e *Engineer) checks(ctx context.Context, r stepRow, progress func(wire.Ste |
| defer os.RemoveAll(tree.GitDir) |
| defer os.RemoveAll(tree.Dir) |
| progress(rep) |
| - done := func(outcome, reason string) wire.StepReport { |
| - rep.State, rep.Termination, rep.Checks, rep.Reason = wire.StepDone, true, outcome, reason |
| - return rep |
| - } |
| // Hosted CI is useful feedback, but its candidate-owned gate is never a certificate. |
| var hosted *wire.StepReport |
| hostedOn := false |
| @@ -237,38 +206,40 @@ func (e *Engineer) checks(ctx context.Context, r stepRow, progress func(wire.Ste |
| } |
| cancel() |
| } |
| - files, baseErr := readBaseGates(ctx, tree.Git, tree.GitDir, r.BaseSHA) |
| - changed, err := (workspace.TaskTree{Dir: tree.Dir, GitDir: tree.GitDir, Git: tree.Git, Base: r.BaseSHA}).ChangedFiles(ctx, r.CandidateSHA) |
| - if err != nil { |
| - return done(wire.ChecksCannotRun, "base_gate_unavailable") |
| - } |
| - changedGate := false |
| - for _, name := range changed { |
| - changedGate = changedGate || gatePathCovered(files, name) |
| - } |
| - candidateGate, candidateOK := findGate(tree.Dir) |
| - g := candidateGate |
| - certified := baseErr == nil |
| var candidateTree workspace.TaskTree |
| - if certified && changedGate { |
| - candidateTree, err = workspace.PrepareTaskTree(ctx, tree.Git, e.Clones.Path(r.Repo), r.CandidateSHA, r.Branch, tree.Dir+"-diagnostic", tree.GitDir+"-diagnostic") |
| - if err != nil { |
| - return done(wire.ChecksCannotRun, "checks_unavailable") |
| + defer func() { |
| + if candidateTree.Dir != "" { |
| + os.RemoveAll(candidateTree.Dir) |
| + os.RemoveAll(candidateTree.GitDir) |
| } |
| - defer os.RemoveAll(candidateTree.Dir) |
| - defer os.RemoveAll(candidateTree.GitDir) |
| + }() |
| + in := checkrun.Inputs{Workspace: tree.Dir, BaseSHA: r.BaseSHA, CandidateSHA: r.CandidateSHA, GoRoot: e.O.Runner.GoRoot, ModuleCache: e.O.Runner.ModuleCache, Limit: e.MaxStep, |
| + Attempt: "checks/" + stepKey(r), Log: e.log, |
| + Record: func(id string) error { return e.O.State.setStepNamespace(context.Background(), r, id) }, |
| + Diagnostic: func(ctx context.Context) (string, error) { |
| + t, err := workspace.PrepareTaskTree(ctx, tree.Git, e.Clones.Path(r.Repo), r.CandidateSHA, r.Branch, tree.Dir+"-diagnostic", tree.GitDir+"-diagnostic") |
| + if err != nil { |
| + return "", err |
| + } |
| + candidateTree = t |
| + return t.Dir, nil |
| + }, |
| + Prepare: func(ctx context.Context, dir string) error { |
| + if dir == candidateTree.Dir { |
| + return e.checkRepository(ctx, candidateTree, r.CandidateSHA) |
| + } |
| + err := e.checkRepository(ctx, tree, r.CandidateSHA) |
| + if err != nil { |
| + e.log("checks repository", err) |
| + } |
| + return err |
| + }} |
| + if hosted != nil { |
| + in.Hosted = &checkrun.Hosted{Output: hosted.Output, Failed: hosted.Checks == wire.ChecksFailed} |
| } |
| - if certified { |
| - trusted, err := os.MkdirTemp(filepath.Dir(tree.Dir), "base-gates-") |
| - if err != nil { |
| - return done(wire.ChecksCannotRun, "base_gate_unavailable") |
| - } |
| - defer removeBaseGates(trusted) |
| - g, err = installBaseGates(ctx, tree, r.CandidateSHA, files, trusted) |
| - if err != nil { |
| - return done(wire.ChecksCannotRun, "base_gate_unavailable") |
| - } |
| - } else if !candidateOK { |
| + out := checkrun.Run(ctx, e.checksGate(r), checks.Repo{Git: tree.Git, GitDir: tree.GitDir}, in) |
| + if out.Checks == wire.ChecksNone { |
| + // Uncertified, and the candidate has no gate of its own. |
| if hosted != nil { |
| return *hosted |
| } |
| @@ -277,99 +248,30 @@ func (e *Engineer) checks(ctx context.Context, r stepRow, progress func(wire.Ste |
| return e.hostedChecks(ctx, r, rep) |
| } |
| } |
| - return done(wire.ChecksNone, "") |
| - } |
| - mac := runtime.GOOS != "darwin" && checks.NeedsMacOS(changed, g.text) |
| - if mac { |
| - rep.LogTail = "Not run: " + g.name + " needs macOS to check this change, and this runner is " + runtime.GOOS + "." |
| - return done(wire.ChecksCannotRun, "needs_macos") |
| - } |
| - if e.goUnmet(ctx, tree, r.BaseSHA) { |
| - return done(wire.ChecksCannotRun, "checks_unavailable") |
| - } |
| - if err := e.checkRepository(ctx, tree, r.CandidateSHA); err != nil { |
| - e.log("checks repository", err) |
| - rep.State, rep.Reason, rep.Termination = wire.StepFailed, "workspace_refused", true |
| - return rep |
| } |
| - stage, staged := e.dependencyStage(ctx, r, tree.Dir) |
| - if !staged.terminated { |
| - // Its namespace's exit was not observed: no gate launches over |
| - // it, and its namespace stays recorded for recovery. |
| - rep.State, rep.Reason, rep.Termination = wire.StepFailed, firstNonEmpty(staged.reason, "provider_failed"), false |
| - return rep |
| - } |
| - res := e.runGate(ctx, r, tree.Dir, g) |
| - baseResult, baseGate := res, g |
| - if certified { |
| - rep.BaseChecks = wire.ChecksCannotRun |
| - if res.terminated && res.reason == "" && (res.code == 0 || !checks.NeedsNetwork(stage, checks.Run{Code: res.code, Output: res.output, Evidence: res.evidence})) { |
| - rep.BaseChecks = wire.ChecksFailed |
| - if res.code == 0 { |
| - rep.BaseChecks = wire.ChecksPassed |
| - } |
| - } |
| - } |
| - gateOutput := res.output |
| - if certified && res.terminated && res.reason == "" && res.code == 0 { |
| - rep.BaseChecksSHA = r.BaseSHA |
| - } |
| - baseOutput := "" |
| - if certified && changedGate { |
| - baseOutput = fmt.Sprintf("Base gate certification (exit %d, %s):\n%s\n", res.code, res.reason, tailBytes(res.output, wire.MaxChecksOutput/3)) |
| - if candidateOK { |
| - if err := e.checkRepository(ctx, candidateTree, r.CandidateSHA); err != nil { |
| - return done(wire.ChecksCannotRun, "checks_unavailable") |
| - } |
| - res = e.runGate(ctx, r, candidateTree.Dir, candidateGate) |
| - g = candidateGate |
| - gateOutput = res.output |
| - res.output = "Candidate gate diagnostic:\n" + tailBytes(res.output, wire.MaxChecksOutput/3) + "\n" + baseOutput |
| - } |
| - } |
| - if !certified { |
| - res.output = "Uncertified candidate gate diagnostic:\n" + tailBytes(res.output, wire.MaxChecksOutput/3) |
| - } |
| - if hosted != nil { |
| - res.output = combinedOutput(res.output, hosted.Output) |
| - if hosted.Checks == wire.ChecksFailed && res.reason == "" && res.terminated { |
| - res.code = 1 |
| - } |
| - } |
| - rep.Gate, rep.Output, rep.LogTail = g.name, res.output, lastLines(res.output, stepTailLines, wire.MaxLogTail) |
| - // Diagnostics keep their output, but cannot replace a trusted gate failure. |
| - if certified && rep.BaseChecks != wire.ChecksPassed && res.terminated { |
| - res, gateOutput, rep.Gate = baseResult, baseResult.output, baseGate.name |
| - } |
| - if !res.terminated { |
| - rep.State, rep.Reason, rep.Termination = wire.StepFailed, firstNonEmpty(res.reason, "provider_failed"), false |
| - return rep |
| - } |
| - if ctx.Err() != nil { |
| - rep.State, rep.Reason, rep.Termination = wire.StepCancelled, "cancelled", true |
| - return rep |
| - } |
| - switch { |
| - case res.reason == "checks_timeout": |
| - rep.Gate = "" |
| - return done(wire.ChecksCannotRun, "checks_timeout") |
| - case res.reason != "": |
| - rep.Gate, rep.Output = "", "" |
| - return done(wire.ChecksCannotRun, "checks_unavailable") |
| - case res.code != 0 && checks.NeedsNetwork(stage, checks.Run{Code: res.code, Output: gateOutput, Evidence: res.evidence}): |
| - // A gate that needs the network cannot pass or fail honestly here. |
| - rep.Gate = "" |
| - return done(wire.ChecksCannotRun, "needs_network") |
| - } |
| - code := res.code |
| - rep.ExitCode = &code |
| - if code == 0 { |
| - return done(wire.ChecksPassed, "") |
| - } |
| - if rep.BaseChecks == wire.ChecksFailed { |
| - return done(wire.ChecksFailed, "base_checks_failed") |
| - } |
| - return done(wire.ChecksFailed, "") |
| + rep.State, rep.Termination, rep.Checks, rep.Reason = out.State, out.Terminated, out.Checks, out.Reason |
| + rep.BaseChecks, rep.BaseChecksSHA = out.BaseChecks, out.BaseChecksSHA |
| + rep.Gate, rep.Output, rep.LogTail, rep.ExitCode = out.Gate, out.Output, out.LogTail, out.ExitCode |
| + return rep |
| +} |
| + |
| +// checksGate is the primary's gate.Runner for r's checks: the |
| +// containment's check profile, attempts recorded as the step's namespace. |
| +func (e *Engineer) checksGate(r stepRow) rungate.Runner { return primaryGate{e: e, r: r} } |
| + |
| +type primaryGate struct { |
| + e *Engineer |
| + r stepRow |
| +} |
| + |
| +func (p primaryGate) Sandbox() string { return wire.SandboxBubblewrap } |
| + |
| +func (p primaryGate) Run(ctx context.Context, attempt, dir string, argv []string, limit time.Duration, record func(id string) error) rungate.Result { |
| + return p.e.runGateAs(ctx, attempt, dir, gate{argv: argv, limit: limit, pins: pinMounts(rungate.Pins(ctx))}, func(_ context.Context, id string) error { return record(id) }) |
| +} |
| + |
| +func (p primaryGate) Verify(id string) bool { |
| + return p.e.O.Manager != nil && verifiedExit(context.Background(), p.e.O.Manager, id) |
| } |
| // checkRepository gives the checks tree a .git of its own at exactly the |
| @@ -510,21 +412,15 @@ func (l *limitReader) Read(p []byte) (int, error) { |
| return k, err |
| } |
| -// gateResult is how a gate's run ended. |
| -type gateResult struct { |
| - output, reason string |
| - code int |
| - terminated bool |
| - // sandbox is how a worker's gate was confined (wire.Sandbox*). |
| - sandbox string |
| - // evidence was read from the whole output (output is its tail). |
| - evidence *checks.Evidence |
| +func (e *Engineer) runGate(ctx context.Context, r stepRow, work string, g gate) rungate.Result { |
| + return e.runGateAs(ctx, "checks/"+stepKey(r), work, g, func(ctx context.Context, id string) error { |
| + return e.O.State.setStepNamespace(ctx, r, id) |
| + }) |
| } |
| -// runGate runs the gate in the containment's check profile: the tree at |
| -// /workspace read-write, private /tmp, no network, no provider home, the |
| -// Go toolchain and module cache read-only when the runner has them. |
| -func (e *Engineer) runGate(ctx context.Context, r stepRow, work string, g gate) gateResult { |
| +// runGateAs runs g as one of attempt's processes, its namespace kept by |
| +// record before it launches. |
| +func (e *Engineer) runGateAs(ctx context.Context, attempt, work string, g gate, record func(context.Context, string) error) rungate.Result { |
| c := e.O.Runner |
| env := map[string]string{"GOCACHE": "/tmp/go-build", "GOTMPDIR": "/tmp/go-tmp", "GOMODCACHE": "/opt/go-mod", "GOROOT": "/opt/go", "GOTOOLCHAIN": "local", "GOWORK": "off", "GOENV": "off", "GOTELEMETRY": "off", "GOPROXY": "off", "GOSUMDB": "off", "CGO_ENABLED": "0", "XDG_CONFIG_HOME": "/tmp/xdg", "PATH": "/opt/go/bin:/usr/bin:/bin"} |
| in := provider.CheckPolicyInputs{Workspace: work, Bwrap: c.BwrapPath, RunnerBinary: c.Executable, GoRoot: existingDir(c.GoRoot), ModuleCache: existingDir(firstNonEmpty(c.ModuleCache, homeModuleCache())), Argv: g.argv, Env: env, GateFiles: g.pins} |
| @@ -534,7 +430,7 @@ func (e *Engineer) runGate(ctx context.Context, r stepRow, work string, g gate) |
| policy, err := provider.BuildCheckPolicy(in) |
| if err != nil { |
| e.log("checks policy", err) |
| - return gateResult{reason: "checks_unavailable", terminated: true} |
| + return rungate.Result{Reason: "checks_unavailable", Terminated: true} |
| } |
| limit := e.MaxStep |
| if g.limit > 0 { |
| @@ -549,12 +445,10 @@ func (e *Engineer) runGate(ctx context.Context, r stepRow, work string, g gate) |
| if e.checkStarter != nil { |
| m = e.checkStarter |
| } |
| - proc, err := recordedStart(pctx, m, provider.Launch{AttemptKey: "checks/" + stepKey(r) + "/" + uuid(), Workspace: work, Policy: policy}, g.argv, func(ctx context.Context, id string) error { |
| - return e.O.State.setStepNamespace(ctx, r, id) |
| - }) |
| + proc, err := recordedStart(pctx, m, provider.Launch{AttemptKey: attempt + "/" + uuid(), Workspace: work, Policy: policy}, g.argv, record) |
| if err != nil { |
| e.log("checks start", err) |
| - return gateResult{reason: "checks_unavailable", terminated: true} |
| + return rungate.Result{Reason: "checks_unavailable", Terminated: true} |
| } |
| out := &lineTail{max: wire.MaxChecksLines} |
| copied := make(chan struct{}, 2) |
| @@ -592,14 +486,14 @@ func (e *Engineer) runGate(ctx context.Context, r stepRow, work string, g gate) |
| codeMu.Unlock() |
| exited <- err |
| }() |
| - res := gateResult{} |
| + res := rungate.Result{} |
| select { |
| case err := <-exited: |
| - res.terminated = err == nil |
| + res.Terminated = err == nil |
| case <-ctx.Done(): |
| - res.reason, res.terminated = "cancelled", stopStep(func() {}, exited, kill, false, 0, 30*time.Second) |
| + res.Reason, res.Terminated = "cancelled", stopStep(func() {}, exited, kill, false, 0, 30*time.Second) |
| case <-time.After(limit): |
| - res.reason, res.terminated = "checks_timeout", stopStep(func() {}, exited, kill, false, 0, 30*time.Second) |
| + res.Reason, res.Terminated = "checks_timeout", stopStep(func() {}, exited, kill, false, 0, 30*time.Second) |
| } |
| for range 2 { |
| select { |
| @@ -608,16 +502,16 @@ func (e *Engineer) runGate(ctx context.Context, r stepRow, work string, g gate) |
| } |
| } |
| codeMu.Lock() |
| - res.code, res.output, res.evidence = code, out.String(), evidence |
| + res.Code, res.Output, res.Evidence = code, out.String(), evidence |
| if g.jsonOutput { |
| var over bool |
| - res.output, over = structured.Result() |
| + res.Output, over = structured.Result() |
| if over { |
| - res.reason = "checks_unavailable" |
| + res.Reason = "checks_unavailable" |
| } |
| } |
| codeMu.Unlock() |
| - if res.terminated { |
| + if res.Terminated { |
| e.forget(proc.ID()) |
| } |
| return res |
| @@ -1090,12 +984,3 @@ func changeDiffEvidence(ctx context.Context, git, gitDir, base, candidate string |
| } |
| return treeDiffEvidence(ctx, git, gitDir, empty, candidate, limit) |
| } |
| - |
| -// combinedOutput is a local gate's output with hosted CI's diagnostic |
| -// after it, within the bound the instance keeps: the hosted part (every |
| -// failing unit's share, wire.ClipCIOutput) in its third, the local |
| -// output's tail in the rest. |
| -func combinedOutput(local, hosted string) string { |
| - part := "\nHosted CI diagnostic:\n" + wire.ClipCIOutput(hosted, wire.MaxChecksOutput/3) |
| - return tailBytes(local, wire.MaxChecksOutput-len(part)) + part |
| -} |
diff --git a/internal/runner/thin/judge_hosted.go b/internal/runner/thin/judge_hosted.go| index 2171a77a..b8258bb8 100644 |
| --- a/internal/runner/thin/judge_hosted.go |
| +++ b/internal/runner/thin/judge_hosted.go |
| @@ -159,19 +159,4 @@ func clipName(s string) string { |
| return s |
| } |
| -// tailBytes is the end of s within limit bytes, starting on a line. |
| -func tailBytes(s string, limit int) string { |
| - if limit <= 0 { |
| - return "" |
| - } |
| - if len(s) <= limit { |
| - return s |
| - } |
| - s = s[len(s)-limit:] |
| - if i := strings.IndexByte(s, '\n'); i >= 0 { |
| - s = s[i+1:] |
| - } |
| - return strings.ToValidUTF8(s, "") |
| -} |
| - |
| func shortSHA(sha string) string { return sha[:min(len(sha), 7)] } |
diff --git a/internal/runner/thin/mac.go b/internal/runner/thin/mac.go| index e0eebeaa..a1951806 100644 |
| --- a/internal/runner/thin/mac.go |
| +++ b/internal/runner/thin/mac.go |
| @@ -23,6 +23,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/release" |
| "amadan.net/oficina/equipo/internal/runner" |
| + rungate "amadan.net/oficina/equipo/internal/runner/gate" |
| "amadan.net/oficina/equipo/internal/runner/mac" |
| "amadan.net/oficina/equipo/internal/wire" |
| ) |
| @@ -32,7 +33,7 @@ import ( |
| // and labelled so (Paul's ruling 2). The pieces are in internal/runner/ |
| // mac; this file wires them to the worker. |
| -// macGate adapts a Mac gate to the worker's GateRunner. |
| +// macGate adapts a Mac gate to the worker's gate.Runner. |
| type macGate struct{ g *mac.Gate } |
| // A Mac launch of the pinned CLI goes through the same starter as a |
| @@ -41,9 +42,9 @@ var _ starter = (*mac.Starter)(nil) |
| func (m macGate) Sandbox() string { return m.g.Sandbox } |
| -func (m macGate) Run(ctx context.Context, attempt, dir string, argv []string, limit time.Duration, record func(string) error) gateResult { |
| +func (m macGate) Run(ctx context.Context, attempt, dir string, argv []string, limit time.Duration, record func(string) error) rungate.Result { |
| r := m.g.Run(ctx, attempt, dir, argv, limit, record) |
| - return gateResult{output: r.Output, reason: r.Reason, code: r.Code, terminated: r.Terminated, sandbox: r.Sandbox} |
| + return rungate.Result{Output: r.Output, Reason: r.Reason, Code: r.Code, Terminated: r.Terminated, Sandbox: r.Sandbox} |
| } |
| func (m macGate) Verify(id string) bool { return m.g.Verify(id) } |
| @@ -53,7 +54,7 @@ func (m macGate) Acknowledge(id string) { m.g.Acknowledge(id, mac.ConsumerStep) |
| // acknowledge tells a gate that keeps evidence for its proofs (a Mac's) |
| // that the step's recovery committed what it proved of id. |
| -func acknowledge(g GateRunner, id string) { |
| +func acknowledge(g rungate.Runner, id string) { |
| if a, ok := g.(interface{ Acknowledge(string) }); ok { |
| a.Acknowledge(id) |
| } |
| @@ -98,10 +99,10 @@ func (m *macChecks) Sandbox() string { return m.pick().Sandbox } |
| // turns back into waiting for the Mac's sandbox. It taints the runner |
| // before a check runs outside the sandbox: what it runs could change |
| // anything this user may. |
| -func (m *macChecks) Run(ctx context.Context, attempt, dir string, argv []string, limit time.Duration, record func(string) error) gateResult { |
| +func (m *macChecks) Run(ctx context.Context, attempt, dir string, argv []string, limit time.Duration, record func(string) error) rungate.Result { |
| g := m.pick() |
| if g.Sandbox != wire.SandboxSeatbelt { |
| - refused := gateResult{reason: wire.ReasonSandboxUnproven, terminated: true, sandbox: g.Sandbox} |
| + refused := rungate.Result{Reason: wire.ReasonSandboxUnproven, Terminated: true, Sandbox: g.Sandbox} |
| if !unsandboxedChosen(ctx) || !m.unsandboxedAllowed(ctx) { |
| return refused |
| } |
| @@ -966,7 +967,7 @@ func serveMac(ctx context.Context, c runner.Config, o Options, h *macHost) error |
| o.Logger.Warn("srt is not installed: checks run outside the sandbox and say so") |
| } |
| up := &macUpdater{origin: c.Origin, version: o.Version, binary: c.Executable, fetch: fetchLimited} |
| - return runWorker(ctx, c, o, hostPlatform(), workerSetup{probe: h.caps, gate: h.checks, find: h.find, ready: h.probes.wait, creds: h.creds, engineering: h.engineering(), fprobes: h.eng, |
| + return runWorker(ctx, c, o, hostPlatform(), workerSetup{probe: h.caps, kind: macKind(h.checks), find: h.find, ready: h.probes.wait, creds: h.creds, engineering: h.engineering(), fprobes: h.eng, |
| started: func(ctx context.Context, refresh func()) { |
| h.taint.changed = refresh |
| h.probes.start(ctx, func() { refresh(); h.eng.soon() }) |
diff --git a/internal/runner/thin/mac_stall_test.go b/internal/runner/thin/mac_stall_test.go| index 13a9c473..47f5d08f 100644 |
| --- a/internal/runner/thin/mac_stall_test.go |
| +++ b/internal/runner/thin/mac_stall_test.go |
| @@ -18,6 +18,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/release" |
| "amadan.net/oficina/equipo/internal/runner" |
| + rungate "amadan.net/oficina/equipo/internal/runner/gate" |
| "amadan.net/oficina/equipo/internal/runner/mac" |
| "amadan.net/oficina/equipo/internal/wire" |
| ) |
| @@ -178,7 +179,7 @@ type heldGate struct { |
| started, release chan struct{} |
| } |
| -func (g heldGate) Run(ctx context.Context, a, dir string, argv []string, l time.Duration, record func(string) error) gateResult { |
| +func (g heldGate) Run(ctx context.Context, a, dir string, argv []string, l time.Duration, record func(string) error) rungate.Result { |
| close(g.started) |
| <-g.release |
| return g.stubGate.Run(ctx, a, dir, argv, l, record) |
diff --git a/internal/runner/thin/mac_test.go b/internal/runner/thin/mac_test.go| index a345c7b1..2da43c48 100644 |
| --- a/internal/runner/thin/mac_test.go |
| +++ b/internal/runner/thin/mac_test.go |
| @@ -18,6 +18,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/release" |
| "amadan.net/oficina/equipo/internal/runner" |
| + rungate "amadan.net/oficina/equipo/internal/runner/gate" |
| "amadan.net/oficina/equipo/internal/runner/mac" |
| "amadan.net/oficina/equipo/internal/wire" |
| ) |
| @@ -395,7 +396,7 @@ type recordingGate struct { |
| before func() |
| } |
| -func (g *recordingGate) Run(ctx context.Context, a, dir string, argv []string, l time.Duration, record func(string) error) gateResult { |
| +func (g *recordingGate) Run(ctx context.Context, a, dir string, argv []string, l time.Duration, record func(string) error) rungate.Result { |
| g.before() |
| return g.stubGate.Run(ctx, a, dir, argv, l, record) |
| } |
| @@ -443,7 +444,7 @@ func TestMacTaintIsSticky(t *testing.T) { |
| } |
| // No report yet: the check the person chose to run outside the |
| // sandbox runs there, which taints. |
| - if res := m.Run(withUnsandboxed(context.Background(), true), "checks-t-1", tree, []string{"/bin/true"}, time.Minute, func(string) error { return nil }); res.sandbox != wire.SandboxNone || !m.taint.Tainted() { |
| + if res := m.Run(withUnsandboxed(context.Background(), true), "checks-t-1", tree, []string{"/bin/true"}, time.Minute, func(string) error { return nil }); res.Sandbox != wire.SandboxNone || !m.taint.Tainted() { |
| t.Fatalf("%+v tainted=%v", res, m.taint.Tainted()) |
| } |
| if _, err := os.Stat(file); err != nil { |
diff --git a/internal/runner/thin/primary_checks_test.go b/internal/runner/thin/primary_checks_test.go| new file mode 100644 |
| index 00000000..af2f5808 |
| --- /dev/null |
| +++ b/internal/runner/thin/primary_checks_test.go |
| @@ -0,0 +1,200 @@ |
| +package thin |
| + |
| +import ( |
| + "context" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/containment" |
| + rungate "amadan.net/oficina/equipo/internal/runner/gate" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// launchRecorder starts through the real containment and keeps what each |
| +// checks launch asked for: its attempt key, tree, argv and the read-only |
| +// mounts over /workspace (the pinned base gate files). |
| +type launchRecorder struct { |
| + m starter |
| + mu sync.Mutex |
| + launches []checkLaunch |
| +} |
| + |
| +type checkLaunch struct { |
| + key, workspace string |
| + argv []string |
| + pins []string |
| +} |
| + |
| +func (s *launchRecorder) StartRecorded(ctx context.Context, l provider.Launch, argv []string, record func(context.Context, containment.Record) error) (provider.Process, error) { |
| + var pins []string |
| + for _, m := range l.Policy.Mounts { |
| + if strings.HasPrefix(m.Target, "/workspace/") && m.ReadOnly { |
| + pins = append(pins, strings.TrimPrefix(m.Target, "/workspace/")) |
| + } |
| + } |
| + slices.Sort(pins) |
| + s.mu.Lock() |
| + s.launches = append(s.launches, checkLaunch{key: l.AttemptKey, workspace: l.Workspace, argv: argv, pins: pins}) |
| + s.mu.Unlock() |
| + return s.m.StartRecorded(ctx, l, argv, record) |
| +} |
| + |
| +// TestPrimaryChecksUnchanged (hosted slice 2, Task 11): the primary's |
| +// checks, now run through checkrun, report what they reported before the |
| +// move, field by field: the base gates from BaseSHA pinned read-only, |
| +// BaseChecks and BaseChecksSHA (the primary-only result the instance reads |
| +// at tasks.go:1831), the candidate gate's diagnostic, the uncertified |
| +// label, no gate at all, and needs_macos. |
| +func TestPrimaryChecksUnchanged(t *testing.T) { |
| + const contract = `{"version":1,"files":["budgets.txt"]}` |
| + gateMake := "ci:\n\t@test \"$$(cat size.txt)\" -le \"$$(cat budgets.txt)\" || { echo over budget; exit 3; }\n" |
| + type want struct { |
| + state, checks, base, reason, gate string |
| + baseSHA, termination bool |
| + exit int // -1: none |
| + output, logTail string |
| + launches int |
| + pins []string |
| + } |
| + for _, tc := range []struct { |
| + name string |
| + base, candidate map[string]string |
| + want want |
| + }{ |
| + {"certified pass", |
| + map[string]string{".equipo/gates.json": contract, "Makefile": gateMake, "size.txt": "1\n", "budgets.txt": "1\n"}, |
| + map[string]string{"NEWS": "candidate\n"}, |
| + want{state: wire.StepDone, checks: wire.ChecksPassed, base: wire.ChecksPassed, gate: "make ci", baseSHA: true, termination: true, exit: 0, launches: 1, pins: []string{".equipo/gates.json", "Makefile", "budgets.txt"}}}, |
| + {"certified base fails, candidate gate passes", |
| + map[string]string{".equipo/gates.json": contract, "Makefile": gateMake, "size.txt": "1\n", "budgets.txt": "1\n"}, |
| + map[string]string{"size.txt": "2\n", "budgets.txt": "2\n"}, |
| + want{state: wire.StepDone, checks: wire.ChecksFailed, base: wire.ChecksFailed, reason: "base_checks_failed", gate: "make ci", termination: true, exit: 2, |
| + output: "Candidate gate diagnostic:\n\nBase gate certification (exit 2, ):\nover budget\nmake: *** [Makefile:2: ci] Error 3\n", logTail: "Candidate gate diagnostic:\n\nBase gate certification (exit 2, ):\nover budget\nmake: *** [Makefile:2: ci] Error 3", launches: 2, pins: []string{".equipo/gates.json", "Makefile", "budgets.txt"}}}, |
| + {"certified, candidate edits the gate and both pass", |
| + map[string]string{".equipo/gates.json": contract, "Makefile": gateMake, "size.txt": "1\n", "budgets.txt": "1\n"}, |
| + map[string]string{"Makefile": "ci:\n\t@echo candidate gate\n"}, |
| + want{state: wire.StepDone, checks: wire.ChecksPassed, base: wire.ChecksPassed, gate: "make ci", baseSHA: true, termination: true, exit: 0, |
| + output: "Candidate gate diagnostic:\ncandidate gate\nBase gate certification (exit 0, ):\n\n", logTail: "Candidate gate diagnostic:\ncandidate gate\nBase gate certification (exit 0, ):", launches: 2, pins: []string{".equipo/gates.json", "Makefile", "budgets.txt"}}}, |
| + {"uncertified candidate gate", |
| + map[string]string{"Makefile": "ci:\n\t@echo hello\n"}, |
| + map[string]string{"NEWS": "candidate\n"}, |
| + want{state: wire.StepDone, checks: wire.ChecksPassed, gate: "make ci", termination: true, exit: 0, |
| + output: "Uncertified candidate gate diagnostic:\nhello", logTail: "Uncertified candidate gate diagnostic:\nhello", launches: 1}}, |
| + {"uncertified candidate gate fails", |
| + map[string]string{"Makefile": "ci:\n\t@echo broken; exit 4\n"}, |
| + map[string]string{"NEWS": "candidate\n"}, |
| + want{state: wire.StepDone, checks: wire.ChecksFailed, gate: "make ci", termination: true, exit: 2, |
| + output: "Uncertified candidate gate diagnostic:\nbroken\nmake: *** [Makefile:2: ci] Error 4", logTail: "Uncertified candidate gate diagnostic:\nbroken\nmake: *** [Makefile:2: ci] Error 4", launches: 1}}, |
| + {"no gate", |
| + map[string]string{}, |
| + map[string]string{"NEWS": "candidate\n"}, |
| + want{state: wire.StepDone, checks: wire.ChecksNone, termination: true, exit: -1}}, |
| + {"needs macOS", |
| + map[string]string{"Makefile": "ci:\n\txcodebuild test\n"}, |
| + map[string]string{"NEWS": "candidate\n"}, |
| + want{state: wire.StepDone, checks: wire.ChecksCannotRun, reason: "needs_macos", termination: true, exit: -1, logTail: "Not run: make ci needs macOS to check this change, and this runner is linux."}}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + e, f, r, _ := hubRig(t) |
| + seed := filepath.Join(filepath.Dir(f.dir), "seed") |
| + for name, body := range tc.base { |
| + writeFile(t, seed, name, body) |
| + } |
| + gitOut(t, seed, "add", "-A") |
| + gitOut(t, seed, "commit", "-qm", "base", "--allow-empty") |
| + r.BaseSHA = gitOut(t, seed, "rev-parse", "HEAD") |
| + gitOut(t, seed, "checkout", "-q", "-B", r.Branch) |
| + for name, body := range tc.candidate { |
| + writeFile(t, seed, name, body) |
| + } |
| + gitOut(t, seed, "add", "-A") |
| + gitOut(t, seed, "commit", "-qm", "candidate") |
| + r.CandidateSHA = gitOut(t, seed, "rev-parse", "HEAD") |
| + gitOut(t, seed, "push", "-q", "--force", f.dir, "main", r.Branch) |
| + r.Specialist = wire.SpecialistChecks |
| + scratch := filepath.Join(filepath.Dir(f.dir), "sandbox") |
| + _ = os.Mkdir(scratch, 0o700) |
| + self, _ := os.Executable() |
| + m, err := containment.New(containment.Config{Binary: "/usr/bin/bwrap", RunnerBinary: self, ScratchRoot: scratch}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rec := &launchRecorder{m: m} |
| + e.O.Manager, e.checkStarter = m, rec |
| + if err := e.O.State.AcceptDispatch(context.Background(), "d", r.DispatchCommand); err != nil { |
| + t.Fatal(err) |
| + } |
| + rep := e.Exec(context.Background(), r, func(wire.StepReport) {}) |
| + w := tc.want |
| + wantSHA := "" |
| + if w.baseSHA { |
| + wantSHA = r.BaseSHA |
| + } |
| + exit := -1 |
| + if rep.ExitCode != nil { |
| + exit = *rep.ExitCode |
| + } |
| + if rep.State != w.state || rep.Checks != w.checks || rep.BaseChecks != w.base || rep.BaseChecksSHA != wantSHA || rep.Reason != w.reason || rep.Gate != w.gate || rep.Termination != w.termination || exit != w.exit || rep.ChecksSandbox != "" || rep.TerminationKind != "" { |
| + t.Fatalf("report changed:\n%+v", rep) |
| + } |
| + if rep.Output != w.output || rep.LogTail != w.logTail { |
| + t.Fatalf("output changed:\n%q\n%q", rep.Output, rep.LogTail) |
| + } |
| + if len(rec.launches) != w.launches { |
| + t.Fatalf("%d launches, want %d: %+v", len(rec.launches), w.launches, rec.launches) |
| + } |
| + for i, l := range rec.launches { |
| + if !strings.HasPrefix(l.key, "checks/"+stepKey(r)+"/") || !slices.Equal(l.argv, []string{"/usr/bin/make", "ci"}) { |
| + t.Fatalf("launch %d: %+v", i, l) |
| + } |
| + // The first runs the chosen gate in the judged tree, base |
| + // files pinned; a diagnostic runs the candidate's own gate |
| + // in a tree of its own, nothing pinned. |
| + if i == 0 && (!slices.Equal(l.pins, w.pins) || strings.HasSuffix(l.workspace, "-diagnostic")) { |
| + t.Fatalf("gate launch %+v, want pins %v", l, w.pins) |
| + } |
| + if i == 1 && (len(l.pins) != 0 || !strings.HasSuffix(l.workspace, "-diagnostic")) { |
| + t.Fatalf("diagnostic launch %+v", l) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestPrimaryChecksGatePins: the primary's gate is a gate.Runner, and the |
| +// base gate files checkrun pins through the context reach the launch as |
| +// read-only mounts over /workspace, under the attempt's key. |
| +func TestPrimaryChecksGatePins(t *testing.T) { |
| + e, f, r, _ := hubRig(t) |
| + scratch := filepath.Join(filepath.Dir(f.dir), "sandbox") |
| + _ = os.Mkdir(scratch, 0o700) |
| + self, _ := os.Executable() |
| + m, err := containment.New(containment.Config{Binary: "/usr/bin/bwrap", RunnerBinary: self, ScratchRoot: scratch}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rec := &launchRecorder{m: m} |
| + e.O.Manager, e.checkStarter = m, rec |
| + dir := filepath.Join(e.O.Runner.WorkspaceRoot, "step-pins") |
| + writeFile(t, dir, "Makefile", "ci:\n\t@echo candidate\n") |
| + trusted := filepath.Join(t.TempDir(), "Makefile") |
| + if err := os.WriteFile(trusted, []byte("ci:\n\t@echo base\n"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + var g rungate.Runner = e.checksGate(r) |
| + recorded := "" |
| + ctx := rungate.WithPins(context.Background(), []rungate.Mount{{Source: trusted, Target: "/workspace/Makefile"}}) |
| + res := g.Run(ctx, "checks/"+stepKey(r), dir, []string{"/usr/bin/make", "ci"}, time.Minute, func(id string) error { recorded = id; return nil }) |
| + if !res.Terminated || res.Code != 0 || res.Reason != "" || strings.TrimSpace(res.Output) != "base" || res.Evidence == nil || recorded == "" || g.Sandbox() != wire.SandboxBubblewrap { |
| + t.Fatalf("gate %+v recorded %q", res, recorded) |
| + } |
| + if len(rec.launches) != 1 || !slices.Equal(rec.launches[0].pins, []string{"Makefile"}) || !strings.HasPrefix(rec.launches[0].key, "checks/"+stepKey(r)+"/") { |
| + t.Fatalf("launches %+v", rec.launches) |
| + } |
| +} |
diff --git a/internal/runner/thin/review_fixes_test.go b/internal/runner/thin/review_fixes_test.go| index f7ad6d86..a779d98d 100644 |
| --- a/internal/runner/thin/review_fixes_test.go |
| +++ b/internal/runner/thin/review_fixes_test.go |
| @@ -225,7 +225,11 @@ func TestOversizedCandidateStaysOutOfMemory(t *testing.T) { |
| func TestRunnerReasonsAreKnown(t *testing.T) { |
| fset := token.NewFileSet() |
| files, _ := filepath.Glob("*.go") |
| - steps := map[string]bool{"engineer.go": true, "judge.go": true, "step.go": true, "merge.go": true} |
| + // The checks run moved to checkrun (hosted slice 2, Task 11): its |
| + // reasons are this runner's too. |
| + moved, _ := filepath.Glob("../checkrun/*.go") |
| + files = append(files, moved...) |
| + steps := map[string]bool{"engineer.go": true, "judge.go": true, "step.go": true, "merge.go": true, "../checkrun/run.go": true} |
| found := map[string]bool{} |
| lit := func(e ast.Expr) { |
| if b, ok := e.(*ast.BasicLit); ok && b.Kind == token.STRING { |
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go| index 1e8d061c..6e000754 100644 |
| --- a/internal/runner/thin/run.go |
| +++ b/internal/runner/thin/run.go |
| @@ -24,6 +24,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/runner" |
| "amadan.net/oficina/equipo/internal/runner/containment" |
| + rungate "amadan.net/oficina/equipo/internal/runner/gate" |
| "amadan.net/oficina/equipo/internal/runner/mac" |
| "amadan.net/oficina/equipo/internal/runner/metered" |
| "amadan.net/oficina/equipo/internal/runner/provider" |
| @@ -104,6 +105,40 @@ type Options struct { |
| // ReadCodexLimits stands in for the Codex reading probe's app-server |
| // read (tests); nil: provider.ReadCodexLimits with the pinned CLI. |
| ReadCodexLimits func(context.Context, provider.Binding) (provider.Identity, json.RawMessage, error) |
| + // HostedWorker is the Linux checks worker a hosted VM runs: set only |
| + // by cmd/equipo-runner (thin never imports it). Unused until the |
| + // hosted worker lands (slice 2, Task 17). |
| + HostedWorker *WorkerKind |
| +} |
| + |
| +// WorkerKind is what a kind of worker proves its gates' ends with: the |
| +// gate, the termination kind its reports name (wire.Termination*), and |
| +// Record, which turns a step's recorded id into the record Gate.Verify |
| +// settles (an error: never proven ended). |
| +type WorkerKind struct { |
| + Gate rungate.Runner |
| + Termination string |
| + Record func(id string) (string, error) |
| +} |
| + |
| +// verify reports whether the attempt recorded as id has ended for sure. |
| +func (k WorkerKind) verify(id string) bool { |
| + rec, err := k.Record(id) |
| + return err == nil && k.Gate.Verify(rec) |
| +} |
| + |
| +// acknowledge tells the gate the step's recovery committed what verify |
| +// proved of id. |
| +func (k WorkerKind) acknowledge(id string) { |
| + if rec, err := k.Record(id); err == nil { |
| + acknowledge(k.Gate, rec) |
| + } |
| +} |
| + |
| +// macKind is a Mac's (and the test build's fake Mac's): process groups, |
| +// settled by workerRecord. |
| +func macKind(g rungate.Runner) WorkerKind { |
| + return WorkerKind{Gate: g, Termination: wire.TerminationProcessGroup, Record: func(id string) (string, error) { return workerRecord(id), nil }} |
| } |
| // OptionsFromEnv reads the runner's optional thin settings. |
| @@ -720,11 +755,11 @@ func enrolledRole(c runner.Config, credential string) string { |
| var ErrNotTestBuild = errors.New("EQUIPO_FAKE_PLATFORM: this runner is not a test build") |
| // workerSetup is what differs between workers: the capability report, |
| -// the gate, how a gate is found in a tree, what must be ready before |
| +// the gate and how its ends are proven (kind), how a gate is found in a tree, what must be ready before |
| // judging, and what runs once the worker holds its roots. |
| type workerSetup struct { |
| probe func(context.Context) wire.Capabilities |
| - gate GateRunner |
| + kind WorkerKind |
| find func(dir string) (gate, string, bool) |
| ready func(context.Context) error |
| // started runs after startup with a function that refreshes the |
| @@ -795,7 +830,7 @@ func runWorker(ctx context.Context, c runner.Config, o Options, platform wire.Pl |
| } |
| link.Hello = func() wire.Hello { |
| report := caps.Get(ctx) |
| - h := wire.Hello{Repos: []string{}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Connections: []wire.HeldConnection{}, Versions: map[string]string{"runner": o.Version}, Platform: &platform, Label: c.MachineLabel, Sandbox: w.gate.Sandbox(), Capabilities: &report} |
| + h := wire.Hello{Repos: []string{}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Connections: []wire.HeldConnection{}, Versions: map[string]string{"runner": o.Version}, Platform: &platform, Label: c.MachineLabel, Sandbox: w.kind.Gate.Sandbox(), Capabilities: &report} |
| spoken, _ := link.Spoken() |
| if own != nil { |
| own.hello(spoken, &h) |
| @@ -822,7 +857,7 @@ func runWorker(ctx context.Context, c runner.Config, o Options, platform wire.Pl |
| if engineer.O.SessionRoot == "" { |
| engineer.O.SessionRoot = SessionRoot(c) |
| } |
| - worker := &Worker{State: state, Engine: engineer, Gate: w.gate, MaxStep: o.MaxStep, StepRoot: filepath.Join(c.ScratchRoot, "worker-steps"), Find: w.find, Ready: w.ready} |
| + worker := &Worker{State: state, Engine: engineer, Gate: w.kind.Gate, MaxStep: o.MaxStep, StepRoot: filepath.Join(c.ScratchRoot, "worker-steps"), Find: w.find, Ready: w.ready} |
| if w.engineering != nil && w.creds != nil && own != nil { |
| eng := *w.engineering |
| eng.Creds = w.creds |
| @@ -874,8 +909,8 @@ func runWorker(ctx context.Context, c runner.Config, o Options, platform wire.Pl |
| // sessions it kept (worker_ask.go). |
| steps := &StepEngine{State: state, Exec: placementGuard(tags, caps.Stale, worker.Exec), Ask: worker.ask, Notify: link.Notify, Logger: o.Logger, |
| Sweep: worker.sweep, |
| - Verify: func(_ context.Context, id string) bool { return w.gate.Verify(workerRecord(id)) }, TerminationKind: wire.TerminationProcessGroup, |
| - Acknowledge: func(_ context.Context, id string) { acknowledge(w.gate, workerRecord(id)) }} |
| + Verify: func(_ context.Context, id string) bool { return w.kind.verify(id) }, TerminationKind: w.kind.Termination, |
| + Acknowledge: func(_ context.Context, id string) { w.kind.acknowledge(id) }} |
| link.Steps = steps |
| if err := steps.Start(ctx); err != nil { |
| return err |
diff --git a/internal/runner/thin/sandbox_consent_test.go b/internal/runner/thin/sandbox_consent_test.go| index 317bc435..1cf7168f 100644 |
| --- a/internal/runner/thin/sandbox_consent_test.go |
| +++ b/internal/runner/thin/sandbox_consent_test.go |
| @@ -8,6 +8,7 @@ import ( |
| "testing" |
| "time" |
| + rungate "amadan.net/oficina/equipo/internal/runner/gate" |
| "amadan.net/oficina/equipo/internal/runner/mac" |
| "amadan.net/oficina/equipo/internal/wire" |
| ) |
| @@ -24,7 +25,7 @@ func TestMacChecksRefuseUnprovenWithoutConsent(t *testing.T) { |
| newChecks := func(t *testing.T, probes *macProbes) *macChecks { |
| return &macChecks{probes: probes, taint: loadTaint(filepath.Join(t.TempDir(), "tainted")), creds: holdsNothing(), srt: "/x/srt", sandboxed: &mac.Gate{Sandbox: wire.SandboxSeatbelt}, unproven: &mac.Gate{SRT: "/x/srt", Sandbox: wire.SandboxNone}, bare: &mac.Gate{Sandbox: wire.SandboxNone, Env: []string{"PATH=/usr/bin:/bin"}}} |
| } |
| - run := func(ctx context.Context, m *macChecks) (gateResult, int) { |
| + run := func(ctx context.Context, m *macChecks) (rungate.Result, int) { |
| recorded := 0 |
| res := m.Run(ctx, "checks-t-1", tree, []string{"/bin/true"}, time.Minute, func(string) error { recorded++; return nil }) |
| return res, recorded |
| @@ -36,7 +37,7 @@ func TestMacChecksRefuseUnprovenWithoutConsent(t *testing.T) { |
| t.Fatal("rig: not bare") |
| } |
| res, recorded := run(context.Background(), bare) |
| - if res.reason != wire.ReasonSandboxUnproven || !res.terminated || recorded != 0 || bare.taint.Tainted() { |
| + if res.Reason != wire.ReasonSandboxUnproven || !res.Terminated || recorded != 0 || bare.taint.Tainted() { |
| t.Fatalf("bare without consent: %+v recorded %d tainted %v", res, recorded, bare.taint.Tainted()) |
| } |
| @@ -49,13 +50,13 @@ func TestMacChecksRefuseUnprovenWithoutConsent(t *testing.T) { |
| t.Fatal("rig: not unproven") |
| } |
| res, recorded = run(context.Background(), unproven) |
| - if res.reason != wire.ReasonSandboxUnproven || recorded != 0 || unproven.taint.Tainted() { |
| + if res.Reason != wire.ReasonSandboxUnproven || recorded != 0 || unproven.taint.Tainted() { |
| t.Fatalf("unproven without consent: %+v recorded %d tainted %v", res, recorded, unproven.taint.Tainted()) |
| } |
| // The person chose it for this attempt: it runs bare and taints. |
| res, recorded = run(withUnsandboxed(context.Background(), true), bare) |
| - if res.reason != "" || res.sandbox != wire.SandboxNone || recorded == 0 || !bare.taint.Tainted() { |
| + if res.Reason != "" || res.Sandbox != wire.SandboxNone || recorded == 0 || !bare.taint.Tainted() { |
| t.Fatalf("bare with consent: %+v recorded %d tainted %v", res, recorded, bare.taint.Tainted()) |
| } |
| if withUnsandboxed(context.Background(), false) != context.Background() || unsandboxedChosen(context.Background()) { |
| @@ -76,10 +77,10 @@ type consentGate struct { |
| chosen []bool |
| } |
| -func (g *consentGate) Run(ctx context.Context, a, dir string, argv []string, l time.Duration, record func(string) error) gateResult { |
| +func (g *consentGate) Run(ctx context.Context, a, dir string, argv []string, l time.Duration, record func(string) error) rungate.Result { |
| g.chosen = append(g.chosen, unsandboxedChosen(ctx)) |
| if !unsandboxedChosen(ctx) { |
| - return gateResult{reason: wire.ReasonSandboxUnproven, terminated: true, sandbox: wire.SandboxNone} |
| + return rungate.Result{Reason: wire.ReasonSandboxUnproven, Terminated: true, Sandbox: wire.SandboxNone} |
| } |
| return g.stubGate.Run(ctx, a, dir, argv, l, record) |
| } |
diff --git a/internal/runner/thin/unsandboxed_d1_test.go b/internal/runner/thin/unsandboxed_d1_test.go| index 9d5b4edc..88b00277 100644 |
| --- a/internal/runner/thin/unsandboxed_d1_test.go |
| +++ b/internal/runner/thin/unsandboxed_d1_test.go |
| @@ -11,6 +11,7 @@ import ( |
| "time" |
| "amadan.net/oficina/equipo/internal/fakeclaude" |
| + rungate "amadan.net/oficina/equipo/internal/runner/gate" |
| "amadan.net/oficina/equipo/internal/runner/mac" |
| "amadan.net/oficina/equipo/internal/runner/provider" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| @@ -36,7 +37,7 @@ func TestWorkerRefusesUnsandboxedWithToken(t *testing.T) { |
| checks := func(creds *macCreds) *macChecks { |
| return &macChecks{probes: newProbeRig(t).p, taint: loadTaint(filepath.Join(t.TempDir(), "tainted")), creds: creds, srt: "/x/srt", sandboxed: &mac.Gate{Sandbox: wire.SandboxSeatbelt}, unproven: &mac.Gate{SRT: "/x/srt", Sandbox: wire.SandboxNone}, bare: &mac.Gate{Sandbox: wire.SandboxNone, Env: []string{"PATH=/usr/bin:/bin"}}} |
| } |
| - run := func(m *macChecks) (gateResult, int) { |
| + run := func(m *macChecks) (rungate.Result, int) { |
| recorded := 0 |
| res := m.Run(withUnsandboxed(context.Background(), true), "checks-t-1", tree, []string{"/bin/true"}, time.Minute, func(string) error { recorded++; return nil }) |
| return res, recorded |
| @@ -47,7 +48,7 @@ func TestWorkerRefusesUnsandboxedWithToken(t *testing.T) { |
| t.Fatalf("%s: rig: not the bare gate", what) |
| } |
| res, recorded := run(m) |
| - if res.reason != wire.ReasonSandboxUnproven || !res.terminated || recorded != 0 || m.taint.Tainted() { |
| + if res.Reason != wire.ReasonSandboxUnproven || !res.Terminated || recorded != 0 || m.taint.Tainted() { |
| t.Fatalf("%s: ran outside the sandbox: %+v recorded %d tainted %v", what, res, recorded, m.taint.Tainted()) |
| } |
| } |
| @@ -58,7 +59,7 @@ func TestWorkerRefusesUnsandboxedWithToken(t *testing.T) { |
| // A Mac that never held a credential: the choice runs, and taints. |
| fresh := checks(r.m) |
| - if res, recorded := run(fresh); res.reason != "" || res.sandbox != wire.SandboxNone || recorded == 0 || !fresh.taint.Tainted() { |
| + if res, recorded := run(fresh); res.Reason != "" || res.Sandbox != wire.SandboxNone || recorded == 0 || !fresh.taint.Tainted() { |
| t.Fatalf("a Mac holding nothing refused the choice: %+v recorded %d", res, recorded) |
| } |
| @@ -115,7 +116,7 @@ func TestWorkerRefusesUnsandboxedWithToken(t *testing.T) { |
| t.Fatal("rig: still held once everything is gone") |
| } |
| free := checks(again.m) |
| - if res, recorded := run(free); res.reason != "" || res.sandbox != wire.SandboxNone || recorded == 0 || !free.taint.Tainted() { |
| + if res, recorded := run(free); res.Reason != "" || res.Sandbox != wire.SandboxNone || recorded == 0 || !free.taint.Tainted() { |
| t.Fatalf("no hold: the choice did not run: %+v recorded %d tainted %v", res, recorded, free.taint.Tainted()) |
| } |
| @@ -125,7 +126,7 @@ func TestWorkerRefusesUnsandboxedWithToken(t *testing.T) { |
| var reads atomic.Int32 |
| racing := checks(&macCreds{held: func(context.Context) bool { return reads.Add(1) > 1 }}) |
| res, recorded := run(racing) |
| - if res.reason != wire.ReasonSandboxUnproven || recorded != 0 || reads.Load() < 2 { |
| + if res.Reason != wire.ReasonSandboxUnproven || recorded != 0 || reads.Load() < 2 { |
| t.Fatalf("a hold that came as the check started: %+v recorded %d reads %d", res, recorded, reads.Load()) |
| } |
| } |
diff --git a/internal/runner/thin/worker.go b/internal/runner/thin/worker.go| index bc874e74..42317189 100644 |
| --- a/internal/runner/thin/worker.go |
| +++ b/internal/runner/thin/worker.go |
| @@ -10,6 +10,7 @@ import ( |
| "time" |
| "amadan.net/oficina/equipo/internal/runner" |
| + rungate "amadan.net/oficina/equipo/internal/runner/gate" |
| "amadan.net/oficina/equipo/internal/runner/mac" |
| "amadan.net/oficina/equipo/internal/runner/workspace" |
| "amadan.net/oficina/equipo/internal/wire" |
| @@ -22,18 +23,6 @@ import ( |
| // runner's business: Seatbelt through srt on a Mac (slice D); the test |
| // build's fake worker runs it in a bare process group. |
| -// GateRunner runs one checks gate and proves its end. |
| -type GateRunner interface { |
| - // Sandbox is what the runner reports in hello (wire.Sandbox*). |
| - Sandbox() string |
| - // Run runs argv in dir. record persists the attempt's process record |
| - // before it runs (so a restart can verify its end); a record that |
| - // cannot be kept stops the run. |
| - Run(ctx context.Context, attempt, dir string, argv []string, limit time.Duration, record func(id string) error) gateResult |
| - // Verify reports whether a recorded attempt has ended for sure. |
| - Verify(id string) bool |
| -} |
| - |
| // placementGuard refuses a dispatch whose needs this runner lacks |
| // (placement_refused, nothing run) and marks its capability report stale, |
| // so the next heartbeat says what it can do now. |
| @@ -54,7 +43,7 @@ type Worker struct { |
| State *State |
| // Engine supplies the git helpers (its O.Runner.GitPath and state). |
| Engine *Engineer |
| - Gate GateRunner |
| + Gate rungate.Runner |
| // PackWait bounds the wait for the relayed candidate (default 10 |
| // minutes); MaxStep bounds the gate. |
| PackWait time.Duration |
diff --git a/internal/runner/thin/worker_checks.go b/internal/runner/thin/worker_checks.go| index 146c8266..1eef4aad 100644 |
| --- a/internal/runner/thin/worker_checks.go |
| +++ b/internal/runner/thin/worker_checks.go |
| @@ -101,15 +101,15 @@ func (w *Worker) checks(ctx context.Context, r stepRow, progress func(wire.StepR |
| res := w.Gate.Run(withUnsandboxed(ctx, r.Unsandboxed), "checks/"+stepKey(r), tree.Dir, g.argv, limit, func(id string) error { |
| return w.State.setStepNamespace(context.WithoutCancel(ctx), r, id) |
| }) |
| - if res.reason == wire.ReasonSandboxUnproven { |
| + if res.Reason == wire.ReasonSandboxUnproven { |
| // Nothing ran: the Mac's sandbox is not proven and nobody chose |
| // to run outside it. The instance puts the step back to wait. |
| return end(wire.StepFailed, wire.ReasonSandboxUnproven) |
| } |
| - rep.TerminationKind, rep.ChecksSandbox = wire.TerminationProcessGroup, res.sandbox |
| - rep.Gate, rep.Output, rep.LogTail = g.name, res.output, lastLines(res.output, stepTailLines, wire.MaxLogTail) |
| - if !res.terminated { |
| - rep.State, rep.Reason, rep.Termination = wire.StepFailed, firstNonEmpty(res.reason, "provider_failed"), false |
| + rep.TerminationKind, rep.ChecksSandbox = wire.TerminationProcessGroup, res.Sandbox |
| + rep.Gate, rep.Output, rep.LogTail = g.name, res.Output, lastLines(res.Output, stepTailLines, wire.MaxLogTail) |
| + if !res.Terminated { |
| + rep.State, rep.Reason, rep.Termination = wire.StepFailed, firstNonEmpty(res.Reason, "provider_failed"), false |
| return rep |
| } |
| if ctx.Err() != nil { |
| @@ -120,14 +120,14 @@ func (w *Worker) checks(ctx context.Context, r stepRow, progress func(wire.StepR |
| return end(wire.StepDone, reason) |
| } |
| switch { |
| - case res.reason == "checks_timeout": |
| + case res.Reason == "checks_timeout": |
| rep.Gate = "" |
| return done(wire.ChecksCannotRun, "checks_timeout") |
| - case res.reason != "": |
| + case res.Reason != "": |
| rep.Gate, rep.Output = "", "" |
| return done(wire.ChecksCannotRun, "checks_unavailable") |
| } |
| - code := res.code |
| + code := res.Code |
| rep.ExitCode = &code |
| if code == 0 { |
| return done(wire.ChecksPassed, "") |
diff --git a/internal/runner/thin/worker_conns_test.go b/internal/runner/thin/worker_conns_test.go| index 91c014d8..4073161d 100644 |
| --- a/internal/runner/thin/worker_conns_test.go |
| +++ b/internal/runner/thin/worker_conns_test.go |
| @@ -187,7 +187,7 @@ func (r *darwinRig) runWorker(inst *workerInstance, protocol int) (stop func()) |
| ctx, cancel := context.WithCancel(r.ctx) |
| done := make(chan error, 1) |
| go func() { |
| - done <- runWorker(ctx, c, r.workerOptions(protocol), wire.Platform{OS: "darwin", Arch: "arm64"}, workerSetup{probe: fake.probe(""), gate: fake.gate("", ""), creds: r.m}) |
| + done <- runWorker(ctx, c, r.workerOptions(protocol), wire.Platform{OS: "darwin", Arch: "arm64"}, workerSetup{probe: fake.probe(""), kind: macKind(fake.gate("", "")), creds: r.m}) |
| }() |
| return func() { |
| r.t.Helper() |
diff --git a/internal/runner/thin/worker_kind_test.go b/internal/runner/thin/worker_kind_test.go| new file mode 100644 |
| index 00000000..e003ed60 |
| --- /dev/null |
| +++ b/internal/runner/thin/worker_kind_test.go |
| @@ -0,0 +1,50 @@ |
| +package thin |
| + |
| +import ( |
| + "errors" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/mac" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// verifyingGate records which ids it was asked to verify and acknowledge. |
| +type verifyingGate struct { |
| + *stubGate |
| + verified, acknowledged []string |
| +} |
| + |
| +func (g *verifyingGate) Verify(id string) bool { g.verified = append(g.verified, id); return true } |
| +func (g *verifyingGate) Acknowledge(id string) { g.acknowledged = append(g.acknowledged, id) } |
| + |
| +// TestMacWorkerUnchanged (hosted slice 2, Task 11): runWorker takes its |
| +// termination kind and record conversion from the worker's setup, and a |
| +// Mac's (the test build's fake Mac uses the same) is today's: process groups, |
| +// an attempt that recorded no group settled by its marker alone. |
| +func TestMacWorkerUnchanged(t *testing.T) { |
| + g := &verifyingGate{stubGate: &stubGate{}} |
| + k := macKind(g) |
| + if k.Gate != g || k.Termination != wire.TerminationProcessGroup { |
| + t.Fatalf("Mac kind %+v", k) |
| + } |
| + key := "tk1/s1/1" |
| + unrecorded := UnrecordedStep(key) |
| + if !k.verify(unrecorded) || !k.verify("pg:7:abc") { |
| + t.Fatal("not verified") |
| + } |
| + k.acknowledge(unrecorded) |
| + k.acknowledge("pg:7:abc") |
| + marker := mac.RecordID(0, attemptMarker(key)) |
| + if len(g.verified) != 2 || g.verified[0] != marker || g.verified[1] != "pg:7:abc" || len(g.acknowledged) != 2 || g.acknowledged[0] != marker || g.acknowledged[1] != "pg:7:abc" { |
| + t.Fatalf("verified %q acknowledged %q", g.verified, g.acknowledged) |
| + } |
| + // A record that cannot be converted is never proven ended, nor |
| + // acknowledged. |
| + k.Record = func(string) (string, error) { return "", errors.New("no record") } |
| + if k.verify("pg:7:abc") || len(g.verified) != 2 { |
| + t.Fatal("an unconvertible record verified") |
| + } |
| + if k.acknowledge("pg:7:abc"); len(g.acknowledged) != 2 { |
| + t.Fatal("an unconvertible record acknowledged") |
| + } |
| +} |
diff --git a/internal/runner/thin/worker_test.go b/internal/runner/thin/worker_test.go| index a697e9db..51422cae 100644 |
| --- a/internal/runner/thin/worker_test.go |
| +++ b/internal/runner/thin/worker_test.go |
| @@ -12,6 +12,7 @@ import ( |
| "testing" |
| "time" |
| + rungate "amadan.net/oficina/equipo/internal/runner/gate" |
| "amadan.net/oficina/equipo/internal/wire" |
| ) |
| @@ -24,12 +25,12 @@ type stubGate struct { |
| } |
| func (g *stubGate) Sandbox() string { return wire.SandboxNone } |
| -func (g *stubGate) Run(_ context.Context, _, dir string, argv []string, _ time.Duration, record func(string) error) gateResult { |
| +func (g *stubGate) Run(_ context.Context, _, dir string, argv []string, _ time.Duration, record func(string) error) rungate.Result { |
| g.ran = append(g.ran, argv) |
| g.dirs = append(g.dirs, dir) |
| record("pg:1:stub") |
| head, _ := os.ReadFile(filepath.Join(dir, "Swipe.swift")) |
| - return gateResult{code: g.code, terminated: true, output: "ran on " + strings.TrimSpace(string(head)), sandbox: g.sandbox} |
| + return rungate.Result{Code: g.code, Terminated: true, Output: "ran on " + strings.TrimSpace(string(head)), Sandbox: g.sandbox} |
| } |
| func (g *stubGate) Verify(string) bool { return true } |