runner: Linux checks worker on the containment manager
linuxworker: the bubblewrap gate (pins read-only, the attempt's staged module cache at /opt/go-mod, one sandbox policy shared with certification), namespace proof and record conversion, and the hosted checks: deps conflicts, new modules and staging, then checkrun with the base's gates. thin runs it only from hosted-run (a Linux worker refuses otherwise), over the session's in-memory credential and proxy client; a failed renewal reports token_renewal_failed. hosted-run renews while it serves and exits non-zero on ErrRenewal. New reasons registered with pending words; deps transfers valid and accepted up to their limit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
24 files changed,
+1,881
−49
.rastrillo/budgets.txt+4 −3cmd/equipo-runner/hosted.go+86 −8cmd/equipo-runner/hosted_certify_linux.go+6 −5cmd/equipo-runner/hosted_test.go+98 −8docs/superpowers/plans/2026-11-30-hosted-slice-2-copy.json+35 −0docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+5 −0docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md+34 −0internal/equipo/copy.go+5 −0internal/runner/checkrun/run.go+9 −6internal/runner/gate/gate.go+16 −0internal/runner/hosted/bootstrap.go+9 −0internal/runner/hosted/renew.go+1 −1internal/runner/linuxworker/gate.go+286 −0internal/runner/linuxworker/worker.go+209 −0internal/runner/linuxworker/worker_test.go+745 −0internal/runner/thin/hosted_worker.go+177 −0internal/runner/thin/hosted_worker_test.go+80 −0internal/runner/thin/relay.go+4 −3internal/runner/thin/run.go+34 −6internal/runner/thin/worker.go+5 −2internal/runner/thin/worker_checks.go+6 −2internal/wire/hosted.go+14 −0internal/wire/mac_engineering.go+5 −3internal/wire/tasks.go+8 −2
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 811f2a44..d927dfda 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -14,8 +14,8 @@ perf GET /* skip Unknown private paths render 404; this fallback contains no scr |
| time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial reruns measured 18.079s and 22.031s. Keep migration, recovery, accounting and concurrency assertions; 60s leaves 30 percent headroom above loaded CI. |
| time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage. |
| -size internal/equipo 24736 - Preview, retry, merges, kept work, check-db, notifications, places, GitHub routes, installer, abilities, lookups, Mac waits, slice F codes, D1, probe details, Design's copy, /api/team; measured 24735. Hosted slice 2 Task 15 review 1: work.reason.pack_incomplete (pending); 24736. |
| -size internal/wire 9862 - Protocols 31 to 35 (facts, diffs, evidence, CI units, files, places), abilities, 36 lookups, 37 Mac Engineering, 38 Design, unproven and probe detail codes, 39 hosted runners (hosted.go: placement, hosted_pack and deps transfer limits, enrolment types); measured 9848. Task 15 opened TransferHeader.Valid to hosted_pack (inbound, base then candidate) and added ReasonPackIncomplete; 9860. Its review round 1 registered it in StepReasons; 9862. |
| +size internal/equipo 24741 - Preview, retry, merges, kept work, check-db, notifications, places, GitHub routes, installer, abilities, lookups, Mac waits, slice F codes, D1, probe details, Design's copy, /api/team; measured 24735. Hosted slice 2 Task 15 review 1: work.reason.pack_incomplete (pending); 24736. Task 17: work.reason.deps_conflict, deps_new_module, deps_missing, deps_too_large and token_renewal_failed (pending); 24741. |
| +size internal/wire 9884 - Protocols 31 to 35 (facts, diffs, evidence, CI units, files, places), abilities, 36 lookups, 37 Mac Engineering, 38 Design, unproven and probe detail codes, 39 hosted runners (hosted.go: placement, hosted_pack and deps transfer limits, enrolment types); measured 9848. Task 15 opened TransferHeader.Valid to hosted_pack (inbound, base then candidate) and added ReasonPackIncomplete; 9860. Its review round 1 registered it in StepReasons; 9862. Task 17: the hosted worker's reasons (deps_conflict, deps_new_module, deps_missing, deps_too_large, token_renewal_failed) registered in StepReasons, and TransferHeader.Valid opened to deps with the hosted_pack rules (the worker accepts the bundle; Task 23 sends it); 9884. |
| size internal/equipotest - 12693 GitHub connect value search, lifecycle and sweep-log contracts; Task 21 migration fixtures, Rastrillo asset contract, renderer archive link; measured 0/12693 source/test lines. |
| time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded); |
| time internal/runner 330s Plan 3 CI repair measured 292.120s for the full package (controller CI 472.184s). |
| @@ -39,7 +39,8 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full |
| perf GET /releases/* skip Verified runner release file downloads, not browser GET screens. |
| perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen. |
| time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s; |
| -size internal/runner/thin 35863 35688 Protocols 31-35, merge credential, publication guards, kept work, scans, 36 lookups; Mac pin, Engineering, asks, F probes, D1, P2, held reports; 38 Design step, renderer; hosted slice 2 Task 11 moved the base-gate checks to checkrun (source down) and pinned the primary and Mac behaviour with tests (test up), and its round 1 fixes added the worker step-engine wiring test; Task 12 added Link.TokenSource and Link.HTTPClient (a hosted runner's bearer is read at each dial and its dial goes through the proxy) and their two tests; 35831/35453. Task 14 review round 1 added Link.ReconnectWait (the wait between connections, a fake clock's in the hosted renewal tests, which drive the real Link through certificate rotation and bearer renewal); 35839/35453. Task 15: the hosted pack (inboundHeader selects by attempt and kind, Worker.Hosted indexes the base and the candidate into an empty store, pack_incomplete) and hosted_pack_test.go; 35863/35688. |
| +time internal/runner/linuxworker 30s Hosted slice 2 Task 17: each test starts real bubblewrap namespaces through the containment manager over real git stores (base gates, pins, restart and cancel proof, offline, staged cache, six dependency outcomes); measured 11.6 to 14.5s on a loaded docs-t1. |
| +size internal/runner/thin 36073 35768 Protocols 31-35, merge credential, publication guards, kept work, scans, 36 lookups; Mac pin, Engineering, asks, F probes, D1, P2, held reports; 38 Design step, renderer; hosted slice 2 Task 11 moved the base-gate checks to checkrun (source down) and pinned the primary and Mac behaviour with tests (test up), and its round 1 fixes added the worker step-engine wiring test; Task 12 added Link.TokenSource and Link.HTTPClient (a hosted runner's bearer is read at each dial and its dial goes through the proxy) and their two tests; 35831/35453. Task 14 review round 1 added Link.ReconnectWait (the wait between connections, a fake clock's in the hosted renewal tests, which drive the real Link through certificate rotation and bearer renewal); 35839/35453. Task 15: the hosted pack (inboundHeader selects by attempt and kind, Worker.Hosted indexes the base and the candidate into an empty store, pack_incomplete) and hosted_pack_test.go; 35863/35688. Task 17 wiring for the Linux checks worker (hosted_worker.go): Options.Hosted (HostedLink: the session's in-memory credential, proxy client, Work context, Flush on a failed renewal and token_renewal_failed), WorkerKind.Checks and Probe, runHosted, the Linux worker refusal outside hosted-run, the hand-off of an indexed hosted attempt and its deps bundle to the kind's checks, the receiver's per-kind transfer limits; its two tests; 36073/35768. |
| time internal/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/cmd/equipo-runner/hosted.go b/cmd/equipo-runner/hosted.go| index 907f22d9..5ddfa832 100644 |
| --- a/cmd/equipo-runner/hosted.go |
| +++ b/cmd/equipo-runner/hosted.go |
| @@ -6,30 +6,38 @@ import ( |
| "fmt" |
| "io" |
| "log/slog" |
| + "os" |
| "path/filepath" |
| + "time" |
| "amadan.net/oficina/equipo/internal/equipo" |
| "amadan.net/oficina/equipo/internal/hostedwire" |
| + "amadan.net/oficina/equipo/internal/runner" |
| + "amadan.net/oficina/equipo/internal/runner/containment" |
| "amadan.net/oficina/equipo/internal/runner/hosted" |
| + "amadan.net/oficina/equipo/internal/runner/linuxworker" |
| + "amadan.net/oficina/equipo/internal/runner/thin" |
| + "amadan.net/rastrillo/rastrillo" |
| ) |
| -// startHosted is hosted.Start, and certifyHosted certify; tests replace |
| -// them. |
| +// startHosted is hosted.Start, certifyHosted certify and serveHosted |
| +// serveChecks; tests replace them. |
| var ( |
| startHosted = hosted.Start |
| certifyHosted = certify |
| + serveHosted = serveChecks |
| ) |
| -// errNotWired is a hosted subcommand whose work has not arrived yet: the |
| -// checks worker loop (Task 17). |
| -var errNotWired = errors.New("equipo-runner: started, but this hosted subcommand is not yet wired") |
| +// The hosted image's git (hostedimage pins /usr/bin/git's digest). |
| +const hostedGit = "/usr/bin/git" |
| // hostedMain runs hosted-run or hosted-certify as vm-init starts it: the |
| // environment names the bootstrap file (in the state directory) and the |
| // results directory. It reads and deletes the bootstrap, checks that its |
| // purpose is the subcommand's, and runs hosted.Start. hosted-certify then |
| -// runs the certification probes and sends the report (certify); what |
| -// follows Start for hosted-run is not built yet, so it then refuses. |
| +// runs the certification probes and sends the report (certify); hosted-run |
| +// serves the job's checks (serveChecks) and exits non-zero when its |
| +// credentials could not be renewed. |
| func hostedMain(ctx context.Context, sub string, errorOutput io.Writer, getenv func(string) string) int { |
| logger := slog.New(slog.NewTextHandler(errorOutput, nil)) |
| fail := func(code, variable string, err error) int { |
| @@ -67,5 +75,75 @@ func hostedMain(ctx context.Context, sub string, errorOutput io.Writer, getenv f |
| logger.Info("certification report sent", "launch", b.LaunchID) |
| return 0 |
| } |
| - return fail("runner.hosted.not_wired", "-", errNotWired) |
| + if err := serveHosted(ctx, s, filepath.Dir(path), logger); err != nil { |
| + return fail("runner.hosted.run", "-", err) |
| + } |
| + return 0 |
| +} |
| + |
| +// serveChecks serves a checks VM's instance as its Linux checks worker |
| +// (thin, with linuxworker's kind) over the session's link, from |
| +// directories under the state directory state, while the session renews |
| +// its credentials (renewing). |
| +func serveChecks(ctx context.Context, s *hosted.Session, state string, logger *slog.Logger) error { |
| + self, err := os.Executable() |
| + if err != nil { |
| + return err |
| + } |
| + c := runner.Config{Origin: s.Origin(), StateDir: filepath.Join(state, "runner"), ScratchRoot: filepath.Join(state, "scratch"), |
| + WorkspaceRoot: filepath.Join(state, "work"), GitPath: hostedGit, Executable: self, GoRoot: linuxworker.GoRoot, BwrapPath: linuxworker.Bwrap} |
| + deps := filepath.Join(state, "deps") |
| + for _, d := range []string{c.ScratchRoot, c.WorkspaceRoot, deps} { |
| + if err := os.MkdirAll(d, 0o700); err != nil { |
| + return err |
| + } |
| + } |
| + m, err := containment.New(containment.Config{Binary: linuxworker.Bwrap, RunnerBinary: self, ScratchRoot: c.ScratchRoot}) |
| + if err != nil { |
| + return err |
| + } |
| + o := thin.OptionsFromEnv(func(string) string { return "" }) |
| + o.Version, o.Logger = rastrillo.BuildVersion, logger |
| + o.HostedWorker = linuxworker.Kind(m, linuxworker.GoRoot, linuxworker.StagedUnder(deps)) |
| + o.Hosted = &thin.HostedLink{Credential: s.Credential, Client: s.HTTPClient(), Work: s.Work} |
| + return renewing(ctx, s, o.Hosted.Flush, func(ctx context.Context) error { return thin.Run(ctx, c, o) }) |
| +} |
| + |
| +// renewer is a hosted session's renewal (hosted.Session). |
| +type renewer interface { |
| + Run(ctx context.Context, clock func() time.Time) error |
| + OnRenewalFailed(report func(reason string)) |
| +} |
| + |
| +// renewing runs serve while job renews the credentials. A renewal that |
| +// fails has already stopped the attempt's work (Session.Work); flush |
| +// lets its token_renewal_failed report leave, then serve is stopped and |
| +// the error (hosted.ErrRenewal) returned. Run returning nil means only |
| +// that nothing is left to renew: serve goes on. |
| +func renewing(ctx context.Context, job renewer, flush func(), serve func(context.Context) error) error { |
| + ctx, cancel := context.WithCancel(ctx) |
| + defer cancel() |
| + job.OnRenewalFailed(func(string) { flush() }) |
| + renewed, served := make(chan error, 1), make(chan error, 1) |
| + go func() { renewed <- job.Run(ctx, time.Now) }() |
| + go func() { served <- serve(ctx) }() |
| + for { |
| + select { |
| + case err := <-renewed: |
| + renewed = nil |
| + if errors.Is(err, hosted.ErrRenewal) { |
| + cancel() |
| + <-served |
| + return err |
| + } |
| + case err := <-served: |
| + cancel() |
| + if renewed != nil { |
| + if rerr := <-renewed; errors.Is(rerr, hosted.ErrRenewal) { |
| + return rerr |
| + } |
| + } |
| + return err |
| + } |
| + } |
| } |
diff --git a/cmd/equipo-runner/hosted_certify_linux.go b/cmd/equipo-runner/hosted_certify_linux.go| index f76669af..720a1192 100644 |
| --- a/cmd/equipo-runner/hosted_certify_linux.go |
| +++ b/cmd/equipo-runner/hosted_certify_linux.go |
| @@ -19,17 +19,17 @@ import ( |
| "amadan.net/oficina/equipo/internal/hostedcert" |
| "amadan.net/oficina/equipo/internal/runner/containment" |
| "amadan.net/oficina/equipo/internal/runner/hosted" |
| + "amadan.net/oficina/equipo/internal/runner/linuxworker" |
| "amadan.net/oficina/equipo/internal/runner/provider" |
| - "amadan.net/oficina/equipo/internal/runner/provider/gotoolchain" |
| ) |
| // Where the hosted image installs what certification runs (hostedimage's |
| // PathBwrap and PathContainmentTest; a test holds them equal) and the Go |
| // tree (the Dockerfile unpacks the toolchain into /usr/local). |
| const ( |
| - hostedBwrap = "/usr/bin/bwrap" |
| + hostedBwrap = linuxworker.Bwrap |
| hostedContainmentTest = "/usr/local/libexec/equipo/containment.test" |
| - hostedGoRoot = "/usr/local/go" |
| + hostedGoRoot = linuxworker.GoRoot |
| ) |
| // Inside the checks sandbox: the probe binary (a copy of this runner in |
| @@ -140,8 +140,9 @@ func checksSandbox(state string) hostedcert.SandboxRunner { |
| if err != nil { |
| return nil, -1, fmt.Errorf("the containment manager: %w", err) |
| } |
| - policy, err := provider.BuildCheckPolicy(provider.CheckPolicyInputs{Workspace: work, Bwrap: hostedBwrap, RunnerBinary: self, |
| - GoRoot: hostedGoRoot, Argv: argv, Env: gotoolchain.Environment()}) |
| + // The hosted checks gate's own policy (linuxworker.Policy): what |
| + // the probes prove of the sandbox is what the checks run in. |
| + policy, err := linuxworker.CertificationPolicy(work, self, hostedGoRoot, argv) |
| if err != nil { |
| return nil, -1, fmt.Errorf("the check policy: %w", err) |
| } |
diff --git a/cmd/equipo-runner/hosted_test.go b/cmd/equipo-runner/hosted_test.go| index c74026aa..8159abc2 100644 |
| --- a/cmd/equipo-runner/hosted_test.go |
| +++ b/cmd/equipo-runner/hosted_test.go |
| @@ -5,11 +5,15 @@ import ( |
| "context" |
| "encoding/json" |
| "errors" |
| + "fmt" |
| + "log/slog" |
| "net/netip" |
| "os" |
| "path/filepath" |
| "strings" |
| + "sync/atomic" |
| "testing" |
| + "time" |
| "amadan.net/oficina/equipo/internal/hostedwire" |
| "amadan.net/oficina/equipo/internal/isolatedjob" |
| @@ -39,20 +43,22 @@ func hostedBootstrap(t *testing.T, purpose string) string { |
| // The hosted subcommands read vm-init's environment and bootstrap and |
| // run Start. hosted-certify then certifies (Task 13), with the session, |
| // the state directory and the results directory, and exits 0 only once |
| -// its report is sent; hosted-run, until its work arrives (Task 17), |
| -// refuses with "not yet wired", never a silent success. |
| -func TestHostedSubcommandsNotYetWired(t *testing.T) { |
| +// its report is sent; hosted-run serves the job's checks (Task 17) with |
| +// the session and the state directory, and exits non-zero when that |
| +// ends in an error (a failed renewal among them). |
| +func TestHostedSubcommands(t *testing.T) { |
| defer func(f func(context.Context, hostedwire.BootstrapV2, isolatedjob.Ref, string) (*hosted.Session, error), |
| - c func(context.Context, *hosted.Session, string, string) error) { |
| - startHosted, certifyHosted = f, c |
| - }(startHosted, certifyHosted) |
| + c func(context.Context, *hosted.Session, string, string) error, s func(context.Context, *hosted.Session, string, *slog.Logger) error) { |
| + startHosted, certifyHosted, serveHosted = f, c, s |
| + }(startHosted, certifyHosted, serveHosted) |
| for _, tc := range []struct { |
| sub, purpose string |
| certifyErr error |
| code int |
| want string |
| }{ |
| - {hostedwire.SubcommandChecks, hostedwire.PurposeChecks, nil, 1, "runner.hosted.not_wired"}, |
| + {hostedwire.SubcommandChecks, hostedwire.PurposeChecks, nil, 0, ""}, |
| + {hostedwire.SubcommandChecks, hostedwire.PurposeChecks, fmt.Errorf("%w: bearer", hosted.ErrRenewal), 1, "runner.hosted.run"}, |
| {hostedwire.SubcommandCertify, hostedwire.PurposeCertification, nil, 0, ""}, |
| {hostedwire.SubcommandCertify, hostedwire.PurposeCertification, errors.New("report refused"), 1, "runner.hosted.certify"}, |
| } { |
| @@ -71,6 +77,13 @@ func TestHostedSubcommandsNotYetWired(t *testing.T) { |
| } |
| return tc.certifyErr |
| } |
| + var served []string |
| + serveHosted = func(_ context.Context, s *hosted.Session, state string, _ *slog.Logger) error { |
| + if s == session { |
| + served = append(served, state) |
| + } |
| + return tc.certifyErr |
| + } |
| var out, errOut bytes.Buffer |
| code := run(context.Background(), []string{tc.sub}, strings.NewReader(""), &out, &errOut, func(k string) string { return env[k] }) |
| want := tc.purpose + " vm-1 " + filepath.Dir(path) |
| @@ -81,6 +94,9 @@ func TestHostedSubcommandsNotYetWired(t *testing.T) { |
| wantCertified && certified[0] != filepath.Dir(path)+" "+results { |
| t.Errorf("%s: certified %q", tc.sub, certified) |
| } |
| + if wantServed := tc.sub == hostedwire.SubcommandChecks; wantServed != (len(served) == 1) || wantServed && served[0] != filepath.Dir(path) { |
| + t.Errorf("%s: served %q", tc.sub, served) |
| + } |
| if _, err := os.Lstat(path); !errors.Is(err, os.ErrNotExist) { |
| t.Errorf("%s: the bootstrap file was left behind", tc.sub) |
| } |
| @@ -116,8 +132,82 @@ func TestHostedSubcommandsNotYetWired(t *testing.T) { |
| } |
| var out, errOut bytes.Buffer |
| code := run(context.Background(), []string{tc.sub}, strings.NewReader(""), &out, &errOut, func(k string) string { return env[k] }) |
| - if code != 1 || calls != tc.calls || !strings.Contains(errOut.String(), tc.want) || strings.Contains(errOut.String(), "not_wired") { |
| + if code != 1 || calls != tc.calls || !strings.Contains(errOut.String(), tc.want) || strings.Contains(errOut.String(), "runner.hosted.run") { |
| t.Errorf("%s with a %s bootstrap: exit %d, %d starts, stderr %q; want %q", tc.sub, tc.purpose, code, calls, errOut.String(), tc.want) |
| } |
| } |
| } |
| + |
| +// fakeRenewer is a session's renewal: Run waits for ret, calling the |
| +// failure hook first when ret carries hosted.ErrRenewal. |
| +type fakeRenewer struct { |
| + ret chan error |
| + failed func(string) |
| +} |
| + |
| +func (f *fakeRenewer) OnRenewalFailed(report func(string)) { f.failed = report } |
| +func (f *fakeRenewer) Run(ctx context.Context, _ func() time.Time) error { |
| + select { |
| + case <-ctx.Done(): |
| + return nil |
| + case err := <-f.ret: |
| + if errors.Is(err, hosted.ErrRenewal) { |
| + f.failed(hosted.ReasonRenewalFailed) |
| + } |
| + return err |
| + } |
| +} |
| + |
| +// TestHostedRunRenewal (Task 17, requirement D): hosted-run serves while |
| +// its session renews. Run returning nil means nothing is left to renew, |
| +// and the job goes on; a failed renewal lets the stopped attempt's report |
| +// leave (flush), then stops serving and returns ErrRenewal, so hosted-run |
| +// exits non-zero. |
| +func TestHostedRunRenewal(t *testing.T) { |
| + job := &fakeRenewer{ret: make(chan error, 1)} |
| + var flushed atomic.Int32 |
| + stop := make(chan error) |
| + done := make(chan error, 1) |
| + var servedCtx atomic.Pointer[context.Context] |
| + go func() { |
| + done <- renewing(context.Background(), job, func() { flushed.Add(1) }, func(ctx context.Context) error { |
| + servedCtx.Store(&ctx) |
| + select { |
| + case err := <-stop: |
| + return err |
| + case <-ctx.Done(): |
| + return nil |
| + } |
| + }) |
| + }() |
| + job.ret <- nil |
| + select { |
| + case err := <-done: |
| + t.Fatalf("serving stopped when nothing was left to renew: %v", err) |
| + case <-time.After(200 * time.Millisecond): |
| + } |
| + stop <- nil |
| + if err := <-done; err != nil || flushed.Load() != 0 { |
| + t.Fatalf("a job that ended: %v, %d flushes", err, flushed.Load()) |
| + } |
| + |
| + job = &fakeRenewer{ret: make(chan error, 1)} |
| + go func() { |
| + done <- renewing(context.Background(), job, func() { flushed.Add(1) }, func(ctx context.Context) error { |
| + servedCtx.Store(&ctx) |
| + <-ctx.Done() |
| + return nil |
| + }) |
| + }() |
| + time.Sleep(50 * time.Millisecond) |
| + job.ret <- fmt.Errorf("%w: bearer", hosted.ErrRenewal) |
| + var err error |
| + select { |
| + case err = <-done: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("hosted-run carried on serving after a failed renewal") |
| + } |
| + if !errors.Is(err, hosted.ErrRenewal) || flushed.Load() != 1 || (*servedCtx.Load()).Err() == nil { |
| + t.Fatalf("after a failed renewal: %v, %d flushes, serving still on", err, flushed.Load()) |
| + } |
| +} |
diff --git a/docs/superpowers/plans/2026-11-30-hosted-slice-2-copy.json b/docs/superpowers/plans/2026-11-30-hosted-slice-2-copy.json| index 4bdba38b..e21c5399 100644 |
| --- a/docs/superpowers/plans/2026-11-30-hosted-slice-2-copy.json |
| +++ b/docs/superpowers/plans/2026-11-30-hosted-slice-2-copy.json |
| @@ -5,5 +5,40 @@ |
| "draft": "the hosted machine did not receive both commits it needed", |
| "paul_sees": true, |
| "reviewed": "" |
| + }, |
| + { |
| + "key": "work.reason.deps_conflict", |
| + "where": "Task view, why checks did not run: on a hosted checks VM, a candidate go.sum line changes a module version the base commit pins (Task 17)", |
| + "draft": "the change alters a dependency version the base commit pins", |
| + "paul_sees": true, |
| + "reviewed": "" |
| + }, |
| + { |
| + "key": "work.reason.deps_new_module", |
| + "where": "Task view, why checks did not run: on a hosted checks VM, the candidate adds a module the base commit does not pin, which would need the network (Task 17)", |
| + "draft": "the change adds a dependency the hosted machine cannot fetch", |
| + "paul_sees": true, |
| + "reviewed": "" |
| + }, |
| + { |
| + "key": "work.reason.deps_missing", |
| + "where": "Task view, why checks did not run: on a hosted checks VM, a module the base pins was not in the dependency bundle the primary sent (Task 17)", |
| + "draft": "a dependency the checks need did not reach the hosted machine", |
| + "paul_sees": true, |
| + "reviewed": "" |
| + }, |
| + { |
| + "key": "work.reason.deps_too_large", |
| + "where": "Task view, why checks did not run: on a hosted checks VM, the dependency bundle is over its size or file limits (Task 17)", |
| + "draft": "the dependencies were too large to send to the hosted machine", |
| + "paul_sees": true, |
| + "reviewed": "" |
| + }, |
| + { |
| + "key": "work.reason.token_renewal_failed", |
| + "where": "Task view, why a hosted step stopped: the hosted VM could not renew its credential, so its work was stopped (Task 17)", |
| + "draft": "the hosted machine could not renew its sign-in before the checks finished", |
| + "paul_sees": true, |
| + "reviewed": "" |
| } |
| ] |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index 6eb03cc3..92bfa905 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -7220,6 +7220,11 @@ records remain unchanged. |
| | `api.direction_note` | Say which option to build. Open this card on the web to add your note. | Direction card (dynamic specialists slice 1, 2026-11-29) | COPY APPROVED (Paul, 2026-11-29, copy-review v4fsltihakfhehduzju7dgu47m, unchanged) | |
| | `work.explore.build_note` | %s said which option to build in their own words: %s | Build task brief (dynamic specialists slice 1, 2026-11-29) | COPY ACCEPTED BY DELEGATION (Luna, 2026-11-29) | |
| | `work.reason.pack_incomplete` | the hosted machine did not receive both commits it needed | Copy specialist | COPY REVIEW PENDING | |
| +| `work.reason.deps_conflict` | the change alters a dependency version the base commit pins | Copy specialist | COPY REVIEW PENDING | |
| +| `work.reason.deps_new_module` | the change adds a dependency the hosted machine cannot fetch | Copy specialist | COPY REVIEW PENDING | |
| +| `work.reason.deps_missing` | a dependency the checks need did not reach the hosted machine | Copy specialist | COPY REVIEW PENDING | |
| +| `work.reason.deps_too_large` | the dependencies were too large to send to the hosted machine | Copy specialist | COPY REVIEW PENDING | |
| +| `work.reason.token_renewal_failed` | the hosted machine could not renew its sign-in before the checks finished | Copy specialist | COPY REVIEW PENDING | |
| ## Task 21 |
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md| index 018763fb..ca432217 100644 |
| --- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| +++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| @@ -1263,3 +1263,37 @@ Red: `go test ./internal/runner/depsbundle -run TestZipSizeCapIsTooLarge -count= |
| Green: `go test ./internal/runner/depsbundle -count=3`: ok. `make budget build vet`: exit 0. staticcheck v0.7.0, gofmt and `git diff --check`: clean. |
| 193. SizeError not told apart (`if cf.SizeError != nil {` → `if cf.SizeError != nil && false {`). `-run TestZipSizeCapIsTooLarge`: FAIL `depsbundle_test.go:842: ... depsbundle: unsafe path in the dependencies: total uncompressed size of module contents too large (max size is 524288000 bytes); want ErrTooLarge before the hash`. Restored (checked with `cmp`). |
| + |
| +## Task 17 |
| + |
| +The Linux checks worker on the containment manager: `internal/runner/linuxworker` (gate.go, worker.go, worker_test.go), thin's hosted wiring (`internal/runner/thin/hosted_worker.go` and small edits), hosted-run in `cmd/equipo-runner/hosted.go`. |
| + |
| +Red (linuxworker stubs: `NewGate` and `Kind` returning zero results; thin, wire, copy and cmd already as built), `CGO_ENABLED=0 go test ./internal/runner/linuxworker -count=1` FAIL on assertions: |
| +- `TestHostedBaseGatesFromBase` (3 subtests), `TestHostedBasePinMounted`, `TestHostedStagedCacheReadOnly`, `TestHostedDeps` (6 subtests): `worker_test.go:...: report {... State:failed Reason:provider_failed ...}` (the stub's empty outcome). |
| +- `TestHostedChecksNamespaceProof`: `kind "", sandbox ""`. `TestHostedRestartProof`, `TestHostedCancel`: `the attempt's namespace was never recorded`. `TestHostedChecksOffline`: `result {Output: Reason: Code:0 Terminated:false ...}`. `TestHostedGatePolicyMatchesCertification`: `gate launches [], certification's policy `. |
| +- The thin tests (`TestHostedRenewalFailureReported`, `TestHostedFlushWaitsForReports`) and the cmd tests (`TestHostedSubcommands`, `TestHostedRunRenewal`) were written after their code; mutations 205 to 209 stand as their failing evidence. `TestHostedGateCacheStagedForAttempt` was added with mutation 201. |
| + |
| +Green: `CGO_ENABLED=0 go test ./internal/runner/linuxworker ./internal/runner/thin -run 'TestHosted|TestLinuxWorker' -count=1`: ok (linuxworker 14.5s, thin 7.3s). Also ok: thin `-run 'TestPrimaryChecks|TestMacWorker|TestWorker|TestHosted|TestEmptyStore|TestMissingBase|TestInboundSelects|TestRunnerReasonsAreKnown|TestRelay|TestPack|TestTransfer|TestEngineeringTransfer|TestLinuxWorker'`; thintest `-run 'TestContractTransfer|TestReview|TestContractWorker|TestWorker'`; whole packages wire, gate, checkrun, hosted, depsbundle, cmd/equipo-runner; `./internal/equipo -run 'TestStepReasons|Copy'`. `make budget build vet` (darwin build of cmd/equipo-runner included): exit 0. `make lanes-check`: ok. staticcheck v0.7.0 on linuxworker, thin, cmd/equipo-runner, gate, checkrun: only the old `mac_fprobe.go:182 xcode is unused`. gofmt and `git diff --check`: clean. |
| + |
| +`make runner-namespace-test` on docs-t1, once: FAIL only `TestNamespaceOpenCodeBinaryAfterAttestation/second_name` (`listen unix .../tool/equipo.sock: bind: invalid argument`: the socket path under `$TMPDIR=/home/paulca/.cache/tmp` is too long). Task 11 recorded the same failure at 51eec914; containment is unchanged here. Every other `^TestNamespace` test passed. |
| + |
| +Mutations (each applied by an exact-string replace from a script under `$TMPDIR`, one at a time, the named test run, the file restored from a copy and checked with `cmp`): |
| +- **194** read gates from the candidate tree (the hosted worker hands checkrun the candidate as the base). In `internal/runner/linuxworker/worker.go`, `checkrun.Inputs{Workspace: tree, BaseSHA: hc.BaseSHA,` became `checkrun.Inputs{Workspace: tree, BaseSHA: hc.CandidateSHA,`. `CGO_ENABLED=0 go test ./internal/runner/linuxworker -run TestHostedBaseGatesFromBase -count=1`: exit 1, `worker_test.go:308: report {ChangeDiffs: ChangeFiles:<nil> BaseChecks:passed BaseChecksSHA:3b4ac93b844cd886b4615614776a49c5a98084d8 Failure:<nil> Copy:<nil> TaskID:tk1 StepID:s1 Attempt:1 State:done R...`. Restored (`cp`, `cmp` identical). |
| +- **195** set BaseChecksSHA on a candidate-gate pass (checkrun drops the certified condition). In `internal/runner/checkrun/run.go`, `if certified && res.Terminated && res.Reason == "" && res.Code == 0 {` became `if res.Terminated && res.Reason == "" && res.Code == 0 {`. `CGO_ENABLED=0 go test ./internal/runner/linuxworker -run TestHostedBaseGatesFromBase -count=1`: exit 1, `worker_test.go:308: report {ChangeDiffs: ChangeFiles:<nil> BaseChecks: BaseChecksSHA:a612249e8a2e67bd868837ee2e26cd602144e3c5 Failure:<nil> Copy:<nil> TaskID:tk1 StepID:s1 Attempt:1 State:done Reason:...`. Restored (`cp`, `cmp` identical). |
| +- **196** the gate drops the base gate pin mounts. In `internal/runner/linuxworker/gate.go`, `GateFiles: pinMounts(gate.Pins(ctx)), Argv: argv})` became `GateFiles: nil, Argv: argv})`. `CGO_ENABLED=0 go test ./internal/runner/linuxworker -run TestHostedBasePinMounted -count=1`: exit 1, `worker_test.go:329: a candidate wrote over a pinned base gate file: {ChangeDiffs: ChangeFiles:<nil> BaseChecks:failed BaseChecksSHA: Failure:<nil> Copy:<nil> TaskID:tk1 StepID:s1 Attempt:1 State:done ...`. Restored (`cp`, `cmp` identical). |
| +- **197** the gate builds its own policy (no Go environment) instead of linuxworker.Policy. In `internal/runner/linuxworker/gate.go`, `policy, err := Policy(SandboxInputs{Workspace: dir, RunnerBinary: g.self, GoRoot: goRoot, ModuleCache: cache, ` became `policy, err := provider.BuildCheckPolicy(provider.CheckPolicyInputs{Workspace: dir, Bwrap: Bwrap, RunnerBinary`. `CGO_ENABLED=0 go test ./internal/runner/linuxworker -run TestHostedGatePolicyMatchesCertification -count=1`: exit 1, `worker_test.go:585: gate launches [{Mode: ToolSocket: AttemptKey:checks/policy/IH2HLKCO36Q5OGMEC6NQNAY3LP Workspace:/home/paulca/.cache/tmp/TestHostedGatePolicyMatchesCertification91891995/001/work Re...`. Restored (`cp`, `cmp` identical). |
| +- **198** no conflict check (a changed base pin goes on to staging). In `internal/runner/linuxworker/worker.go`, `if len(conflicts) > 0 {` became `if len(conflicts) > 99 {`. `CGO_ENABLED=0 go test ./internal/runner/linuxworker -run TestHostedDeps -count=1`: exit 1, `worker_test.go:724: report {ChangeDiffs: ChangeFiles:<nil> BaseChecks: BaseChecksSHA: Failure:<nil> Copy:<nil> TaskID:tk1 StepID:s1 Attempt:1 State:done Reason:deps_missing BaseSHA:9eb4e4e6ee448dc17af...`. Restored (`cp`, `cmp` identical). |
| +- **199** every missing module reported deps_missing (an unpinned requirement is not deps_new_module). In `internal/runner/linuxworker/worker.go`, `if _, pinned := pins[m]; !pinned {` became `if _, pinned := pins[m]; pinned && !pinned {`. `CGO_ENABLED=0 go test ./internal/runner/linuxworker -run TestHostedDeps -count=1`: exit 1, `worker_test.go:724: report {ChangeDiffs: ChangeFiles:<nil> BaseChecks: BaseChecksSHA: Failure:<nil> Copy:<nil> TaskID:tk1 StepID:s1 Attempt:1 State:done Reason:deps_missing BaseSHA:4322c476c614aabf3dc...`. Restored (`cp`, `cmp` identical). |
| +- **200** checkrun leaves Inputs.ModuleCache unused (no gate.WithModuleCache). In `internal/runner/checkrun/run.go`, `if in.ModuleCache != "" {` became `(nothing: deleted)`. `CGO_ENABLED=0 go test ./internal/runner/linuxworker -run TestHostedStagedCacheReadOnly -count=1`: exit 1, `worker_test.go:679: report {ChangeDiffs: ChangeFiles:<nil> BaseChecks: BaseChecksSHA: Failure:<nil> Copy:<nil> TaskID:tk1 StepID:s1 Attempt:1 State:done Reason: BaseSHA:4f8cfcf355be52c54c2a96b9f118c4c...`. Restored (`cp`, `cmp` identical). |
| +- **201** the gate mounts a cache not staged for the attempt (no staging-root check). In `internal/runner/linuxworker/gate.go`, `return dir, err == nil && root != "" && filepath.IsAbs(dir) && filepath.Dir(filepath.Clean(dir)) == filepath.C` became `return dir, (err == nil && root == root && filepath.IsAbs(dir)) || true`. `CGO_ENABLED=0 go test ./internal/runner/linuxworker -run TestHostedGateCacheStagedForAttempt -count=1`: exit 1, `worker_test.go:622: mounted ["/home/paulca/.cache/tmp/TestHostedGateCacheStagedForAttempt3188675511/001/deps/0cde1ed31d458f8d/deps-1" "/home/paulca/.cache/tmp/TestHostedGateCacheStagedForAttempt318867...`. Restored (`cp`, `cmp` identical). |
| +- **202** the hosted kind names process groups. In `internal/runner/linuxworker/worker.go`, `Termination: wire.TerminationNamespace, Record: Record` became `Termination: wire.TerminationProcessGroup, Record: Record`. `CGO_ENABLED=0 go test ./internal/runner/linuxworker -run TestHostedChecksNamespaceProof -count=1`: exit 1, `worker_test.go:342: kind "process_group", sandbox "bubblewrap"`. Restored (`cp`, `cmp` identical). |
| +- **203** recovery's Verify takes a recorded namespace as ended without proving it (no Forget). In `internal/runner/linuxworker/gate.go`, `proven = g.m.Forget(ctx, r) == nil && proven` became `proven = proven || r.ID == ""`. `CGO_ENABLED=0 go test ./internal/runner/linuxworker -run TestHostedRestartProof -count=1`: exit 1, `worker_test.go:428: the old namespace (pid 1185557) is still there after recovery reported it: <nil>`. Restored (`cp`, `cmp` identical). |
| +- **204** a cancelled run is not stopped (no kill on cancel or return). In `internal/runner/linuxworker/gate.go`, `pctx, kill := context.WithCancel(context.Background())` became `pctx, _ := context.WithCancel(context.Background())`. `CGO_ENABLED=0 go test ./internal/runner/linuxworker -run TestHostedCancel -count=1`: exit 1, `worker_test.go:462: cancelled report {ChangeDiffs: ChangeFiles:<nil> BaseChecks: BaseChecksSHA: Failure:<nil> Copy:<nil> TaskID:tk1 StepID:s1 Attempt:1 State:cancelled Reason:cancelled BaseSHA:db76ffd...`. Restored (`cp`, `cmp` identical). |
| +- **205** thin.Run lets a Linux worker start outside hosted-run. In `internal/runner/thin/run.go`, `if runtime.GOOS == "linux" && o.FakePlatform == "" && enrolledWorker(c) {` became `if false && enrolledWorker(c) {`. `CGO_ENABLED=0 go test ./internal/runner/linuxworker -run TestLinuxWorkerRefusedOutsideHosted -count=1`: exit 1, `worker_test.go:496: role file: runner.config.origin:EQUIPO_ORIGIN, want refused`. Restored (`cp`, `cmp` identical). |
| +- **206** a step stopped by a failed renewal keeps its own reason. In `internal/runner/thin/hosted_worker.go`, `rep.State, rep.Reason = wire.StepFailed, wire.ReasonTokenRenewalFailed` became `(nothing: deleted)`. `CGO_ENABLED=0 go test ./internal/runner/thin -run TestHostedRenewalFailureReported -count=1`: exit 1, `hosted_worker_test.go:33: after a failed renewal: {ChangeDiffs: ChangeFiles:<nil> BaseChecks: BaseChecksSHA: Failure:<nil> Copy:<nil> TaskID: StepID: Attempt:0 State:cancelled Reason:cancelled BaseSHA...`. Restored (`cp`, `cmp` identical). |
| +- **207** Flush does not wait for the report to leave. In `internal/runner/thin/hosted_worker.go`, `h.flush.Store(&f)` became `_ = f`. `CGO_ENABLED=0 go test ./internal/runner/thin -run TestHostedFlushWaitsForReports -count=1`: exit 1, `hosted_worker_test.go:66: Flush returned before the report was acked`. Restored (`cp`, `cmp` identical). |
| +- **208** hosted-run carries on after a failed renewal. In `cmd/equipo-runner/hosted.go`, `if errors.Is(err, hosted.ErrRenewal) {` became `if false {`. `CGO_ENABLED=0 go test ./cmd/equipo-runner -run TestHostedRunRenewal -count=1`: exit 1, `hosted_test.go:208: hosted-run carried on serving after a failed renewal`. Restored (`cp`, `cmp` identical). |
| +- **209** hosted-run stops when Run returns nil (nothing left to renew). In `cmd/equipo-runner/hosted.go`, `if errors.Is(err, hosted.ErrRenewal) {` became `cancel()`. `CGO_ENABLED=0 go test ./cmd/equipo-runner -run TestHostedRunRenewal -count=1`: exit 1, `hosted_test.go:186: serving stopped when nothing was left to renew: <nil>`. Restored (`cp`, `cmp` identical). |
| +- **210** the worker refuses the deps transfer (Valid closed to deps again). In `internal/wire/mac_engineering.go`, `case TransferKindHostedPack, TransferKindDeps:` became `case TransferKindHostedPack:`. `CGO_ENABLED=0 go test ./internal/runner/linuxworker -run TestHostedBaseGatesFromBase -count=1`: exit 1, `worker_test.go:308: report {ChangeDiffs: ChangeFiles:<nil> BaseChecks: BaseChecksSHA: Failure:<nil> Copy:<nil> TaskID:tk1 StepID:s1 Attempt:1 State:failed Reason:placement_refused BaseSHA:87b34786f707...`. Restored (`cp`, `cmp` identical). |
| + |
| +Mutations 197 and 201 first failed to build (an unused variable); they were rewritten as above and then failed on their assertions. 204 first removed only the kill on cancel and survived, because `Run`'s deferred `kill` still ended the namespace; it was rewritten to remove every kill. 208 first hung its test until the go test timeout; `TestHostedRunRenewal` now bounds that wait and fails with the line above. |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index 9c441243..5fbbddb0 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -982,6 +982,11 @@ var pageCopy = map[string]string{ |
| "work.reason.checks_timeout": "the checks ran out of time", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) |
| "work.reason.checks_unavailable": "this runner cannot run the checks", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) |
| "work.reason.needs_network": "the checks need a network connection", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) |
| + "work.reason.deps_conflict": "the change alters a dependency version the base commit pins", // COPY REVIEW PENDING |
| + "work.reason.deps_new_module": "the change adds a dependency the hosted machine cannot fetch", // COPY REVIEW PENDING |
| + "work.reason.deps_missing": "a dependency the checks need did not reach the hosted machine", // COPY REVIEW PENDING |
| + "work.reason.deps_too_large": "the dependencies were too large to send to the hosted machine", // COPY REVIEW PENDING |
| + "work.reason.token_renewal_failed": "the hosted machine could not renew its sign-in before the checks finished", // COPY REVIEW PENDING |
| "work.reason.pack_incomplete": "the hosted machine did not receive both commits it needed", // COPY REVIEW PENDING |
| "work.reason.placement_refused": "no runner could take it", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) |
| "work.reason.withdrawn": "it was withdrawn before it started", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) |
diff --git a/internal/runner/checkrun/run.go b/internal/runner/checkrun/run.go| index 9688e574..f3b4e3ca 100644 |
| --- a/internal/runner/checkrun/run.go |
| +++ b/internal/runner/checkrun/run.go |
| @@ -9,9 +9,8 @@ |
| // Attempt and Record. A run missing any of them is refused before |
| // anything starts (StepFailed, policy_rejected, terminated: nothing ran). |
| // Optional: BaseSHA (none: nothing certifies, the candidate's own gate is |
| -// a diagnostic), GoRoot, Limit, Prepare, Diagnostic, Hosted and Log, each |
| -// documented on its field. ModuleCache is the runner's: the gate.Runner's |
| -// constructor gives it its cache, and Run does not read it. |
| +// a diagnostic), GoRoot, ModuleCache, Limit, Prepare, Diagnostic, Hosted |
| +// and Log, each documented on its field. |
| // |
| // The gate.Runner must mount gate.Pins(ctx) read-only over the tree (the |
| // base's gate files); a runner that cannot (a Mac's) must not be given |
| @@ -41,9 +40,10 @@ 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 gate.Runner's constructor owns it, so Run does not read |
| - // it. |
| + // no dependency stage). ModuleCache, when set, is a module cache the |
| + // runner staged for this attempt (a hosted worker's dependencies): |
| + // every gate run carries it (gate.WithModuleCache), so the gate.Runner |
| + // mounts it read-only; empty, the runner mounts its own (the primary). |
| GoRoot, ModuleCache string |
| // Limit bounds each gate (0: the runner's default). |
| Limit time.Duration |
| @@ -109,6 +109,9 @@ func Run(ctx context.Context, g gate.Runner, repo checks.Repo, in Inputs) Outcom |
| return out |
| } |
| run := func(ctx context.Context, dir string, argv []string, limit time.Duration) gate.Result { |
| + if in.ModuleCache != "" { |
| + ctx = gate.WithModuleCache(ctx, in.ModuleCache) |
| + } |
| return g.Run(ctx, in.Attempt, dir, argv, limit, in.Record) |
| } |
| files, baseErr := ReadBaseGates(ctx, repo, in.BaseSHA) |
diff --git a/internal/runner/gate/gate.go b/internal/runner/gate/gate.go| index ce6b13c2..838e6cb5 100644 |
| --- a/internal/runner/gate/gate.go |
| +++ b/internal/runner/gate/gate.go |
| @@ -54,3 +54,19 @@ func Pins(ctx context.Context) []Mount { |
| pins, _ := ctx.Value(pinsKey{}).([]Mount) |
| return slices.Clone(pins) |
| } |
| + |
| +type cacheKey struct{} |
| + |
| +// WithModuleCache is ctx for a run that mounts dir, a module cache the |
| +// runner staged outside the sandbox, read-only as its Go module cache |
| +// ("": none). |
| +func WithModuleCache(ctx context.Context, dir string) context.Context { |
| + return context.WithValue(ctx, cacheKey{}, dir) |
| +} |
| + |
| +// ModuleCache is the module cache the run in ctx mounts ("": none). A |
| +// runner that stages caches checks it is one it staged for the attempt. |
| +func ModuleCache(ctx context.Context) string { |
| + dir, _ := ctx.Value(cacheKey{}).(string) |
| + return dir |
| +} |
diff --git a/internal/runner/hosted/bootstrap.go b/internal/runner/hosted/bootstrap.go| index 253790d6..99665d0c 100644 |
| --- a/internal/runner/hosted/bootstrap.go |
| +++ b/internal/runner/hosted/bootstrap.go |
| @@ -106,6 +106,15 @@ func (s *Session) Token() string { |
| return "" |
| } |
| +// Credential is the current bearer credential (zero before enrolment, |
| +// and for a certification launch). |
| +func (s *Session) Credential() runnerproto.RunnerCredential { |
| + if c := s.bearer.Load(); c != nil { |
| + return *c |
| + } |
| + return runnerproto.RunnerCredential{} |
| +} |
| + |
| // Origin is the instance's origin, its one host on port 443. |
| func (s *Session) Origin() string { return s.origin } |
diff --git a/internal/runner/hosted/renew.go b/internal/runner/hosted/renew.go| index 372d34b8..097b215b 100644 |
| --- a/internal/runner/hosted/renew.go |
| +++ b/internal/runner/hosted/renew.go |
| @@ -28,7 +28,7 @@ const ( |
| ) |
| // ReasonRenewalFailed is the step report's reason when a renewal fails. |
| -const ReasonRenewalFailed = "token_renewal_failed" |
| +const ReasonRenewalFailed = wire.ReasonTokenRenewalFailed |
| // ErrRenewal is a credential the session could not renew: the job's work |
| // is stopped and hosted-run exits non-zero. |
diff --git a/internal/runner/linuxworker/gate.go b/internal/runner/linuxworker/gate.go| new file mode 100644 |
| index 00000000..15b09745 |
| --- /dev/null |
| +++ b/internal/runner/linuxworker/gate.go |
| @@ -0,0 +1,286 @@ |
| +package linuxworker |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/rand" |
| + "io" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "time" |
| + "unicode/utf8" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/checks" |
| + "amadan.net/oficina/equipo/internal/runner/containment" |
| + "amadan.net/oficina/equipo/internal/runner/gate" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/runner/provider/gotoolchain" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// Where the hosted image installs bubblewrap (hostedimage.PathBwrap, the |
| +// file measured.json's sandbox_policy digests) and Go. |
| +const ( |
| + Bwrap = "/usr/bin/bwrap" |
| + GoRoot = "/usr/local/go" |
| +) |
| + |
| +// SandboxInputs are what one hosted check's sandbox varies by: its tree, |
| +// the runner, the Go tree, the staged module cache, the base's gate files |
| +// and the argv. Everything else (bubblewrap, the environment) is fixed. |
| +type SandboxInputs struct { |
| + Workspace, RunnerBinary, GoRoot, ModuleCache string |
| + GateFiles []provider.Mount |
| + Argv []string |
| +} |
| + |
| +// Policy is a hosted check's sandbox: the checks policy (no network, no |
| +// provider home, no writable host cache) over the image's bubblewrap, |
| +// with Go's fixed environment. The gate and certification's sandbox |
| +// probes both build theirs here, so what certification proved of the |
| +// sandbox is what the checks run in. |
| +func Policy(in SandboxInputs) (provider.Policy, error) { |
| + return provider.BuildCheckPolicy(provider.CheckPolicyInputs{Workspace: in.Workspace, Bwrap: Bwrap, RunnerBinary: in.RunnerBinary, |
| + GoRoot: in.GoRoot, ModuleCache: in.ModuleCache, GateFiles: in.GateFiles, Argv: in.Argv, Env: gotoolchain.Environment()}) |
| +} |
| + |
| +// CertificationPolicy is the policy certification's sandbox probes run |
| +// under: a check's, with no staged cache and no gate files. |
| +func CertificationPolicy(work, runnerBinary, goRoot string, argv []string) (provider.Policy, error) { |
| + return Policy(SandboxInputs{Workspace: work, RunnerBinary: runnerBinary, GoRoot: goRoot, Argv: argv}) |
| +} |
| + |
| +// defaultLimit bounds a gate run given none. |
| +const defaultLimit = 20 * time.Minute |
| + |
| +// maxStream bounds what is read of each of a gate's output streams. |
| +const maxStream = 256 << 20 |
| + |
| +type bwrapGate struct { |
| + m *containment.Manager |
| + goRoot string |
| + staged func(attempt string) (string, error) |
| + self string |
| + // start launches a contained process, its record kept first |
| + // (containment.Manager.StartRecorded; tests watch the launch). |
| + start func(context.Context, provider.Launch, []string, func(context.Context, containment.Record) error) (provider.Process, error) |
| +} |
| + |
| +// NewGate is a hosted VM's checks gate: each run in its own containment |
| +// namespace under Policy, the base's gate files (gate.Pins) mounted |
| +// read-only over the tree, and the module cache staged for the attempt |
| +// (gate.ModuleCache, which must lie in staged(attempt)) read-only at |
| +// /opt/go-mod. goRoot is the Go tree mounted at /opt/go ("": none). |
| +func NewGate(m *containment.Manager, goRoot string, staged func(attempt string) (string, error)) gate.Runner { |
| + self, _ := os.Executable() |
| + g := &bwrapGate{m: m, goRoot: goRoot, staged: staged, self: self} |
| + if m != nil { |
| + g.start = m.StartRecorded |
| + } |
| + return g |
| +} |
| + |
| +func (g *bwrapGate) Sandbox() string { return wire.SandboxBubblewrap } |
| + |
| +// cache is the module cache a run in ctx mounts: "" for none, or one |
| +// staged for attempt (a directory directly under staged(attempt)). |
| +func (g *bwrapGate) cache(ctx context.Context, attempt string) (string, bool) { |
| + dir := gate.ModuleCache(ctx) |
| + if dir == "" { |
| + return "", true |
| + } |
| + root, err := g.staged(attempt) |
| + return dir, err == nil && root != "" && filepath.IsAbs(dir) && filepath.Dir(filepath.Clean(dir)) == filepath.Clean(root) |
| +} |
| + |
| +// Run runs argv in dir in its own namespace. The namespace is recorded |
| +// (record) before it starts; a run that ended is proven ended, and its |
| +// record released, before Run returns Terminated. |
| +func (g *bwrapGate) Run(ctx context.Context, attempt, dir string, argv []string, limit time.Duration, record func(id string) error) gate.Result { |
| + unavailable := gate.Result{Reason: "checks_unavailable", Terminated: true, Sandbox: wire.SandboxBubblewrap} |
| + cache, ok := g.cache(ctx, attempt) |
| + if !ok || g.start == nil { |
| + return unavailable |
| + } |
| + goRoot := "" |
| + if info, err := os.Stat(g.goRoot); g.goRoot != "" && err == nil && info.IsDir() { |
| + goRoot = g.goRoot |
| + } |
| + policy, err := Policy(SandboxInputs{Workspace: dir, RunnerBinary: g.self, GoRoot: goRoot, ModuleCache: cache, GateFiles: pinMounts(gate.Pins(ctx)), Argv: argv}) |
| + if err != nil { |
| + return unavailable |
| + } |
| + if limit <= 0 { |
| + limit = defaultLimit |
| + } |
| + pctx, kill := context.WithCancel(context.Background()) |
| + defer kill() |
| + proc, err := g.start(pctx, provider.Launch{AttemptKey: attempt + "/" + rand.Text(), Workspace: dir, Policy: policy}, argv, |
| + func(_ context.Context, r containment.Record) error { return record(r.ID) }) |
| + if err != nil { |
| + return unavailable |
| + } |
| + out := &lineTail{max: wire.MaxChecksLines} |
| + evidence, streams := checks.NewEvidence(2) |
| + copied := make(chan struct{}, 2) |
| + for i, rd := range []io.Reader{proc.Stdout(), proc.Stderr()} { |
| + go func() { |
| + // The whole stream is classified as it is copied; one cut |
| + // short leaves the evidence incomplete. |
| + if n, err := io.Copy(io.MultiWriter(out, streams[i]), io.LimitReader(rd, maxStream)); err != nil || n == maxStream { |
| + streams[i].Abort() |
| + } else { |
| + streams[i].Close() |
| + } |
| + copied <- struct{}{} |
| + }() |
| + } |
| + _ = proc.Stdin().Close() |
| + type exit struct { |
| + code int |
| + err error |
| + } |
| + exited := make(chan exit, 1) |
| + go func() { |
| + x, err := proc.Wait(context.Background()) |
| + exited <- exit{x.Code, err} |
| + }() |
| + res := gate.Result{Code: -1, Sandbox: wire.SandboxBubblewrap} |
| + stop := func(reason string) { |
| + // Cancelling the launch's context kills the namespace; its exit |
| + // is still awaited, so the result says whether it was seen. |
| + kill() |
| + res.Reason = reason |
| + select { |
| + case x := <-exited: |
| + res.Code, res.Terminated = x.code, x.err == nil |
| + case <-time.After(30 * time.Second): |
| + } |
| + } |
| + select { |
| + case x := <-exited: |
| + res.Code, res.Terminated = x.code, x.err == nil |
| + case <-ctx.Done(): |
| + stop("cancelled") |
| + case <-time.After(limit): |
| + stop("checks_timeout") |
| + } |
| + for range 2 { |
| + select { |
| + case <-copied: |
| + case <-time.After(5 * time.Second): |
| + } |
| + } |
| + res.Output, res.Evidence = out.String(), evidence |
| + if res.Terminated { |
| + g.forget(proc.ID()) |
| + } |
| + return res |
| +} |
| + |
| +// forget releases an ended namespace's record (its exit proven again). |
| +func (g *bwrapGate) forget(id string) { |
| + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| + defer cancel() |
| + records, err := g.m.Records(ctx) |
| + if err != nil { |
| + return |
| + } |
| + for _, r := range records { |
| + if r.ID == id { |
| + _ = g.m.Forget(ctx, r) |
| + } |
| + } |
| +} |
| + |
| +// Verify reports whether the namespace recorded as id has ended for |
| +// sure: its record is gone (released only after proof), or recovery |
| +// proves it ended now, killing it if it had not. "" is an attempt that |
| +// recorded no namespace: proven only once none of this runner's remains. |
| +func (g *bwrapGate) Verify(id string) bool { |
| + if g.m == nil { |
| + return false |
| + } |
| + ctx := context.Background() |
| + records, err := g.m.Records(ctx) |
| + if err != nil { |
| + return false |
| + } |
| + proven := true |
| + for _, r := range records { |
| + if id == "" || r.ID == id { |
| + proven = g.m.Forget(ctx, r) == nil && proven |
| + } |
| + } |
| + return proven |
| +} |
| + |
| +func pinMounts(pins []gate.Mount) []provider.Mount { |
| + if pins == nil { |
| + return nil |
| + } |
| + out := make([]provider.Mount, 0, len(pins)) |
| + for _, p := range pins { |
| + out = append(out, provider.Mount{Source: p.Source, Target: p.Target, ReadOnly: true}) |
| + } |
| + return out |
| +} |
| + |
| +// lineTail keeps the last max lines written to it, each clipped, within |
| +// wire.MaxChecksOutput bytes. |
| +type lineTail struct { |
| + mu sync.Mutex |
| + max int |
| + lines []string |
| + partial []byte |
| +} |
| + |
| +func (t *lineTail) Write(p []byte) (int, error) { |
| + t.mu.Lock() |
| + defer t.mu.Unlock() |
| + t.partial = append(t.partial, p...) |
| + for { |
| + i := bytes.IndexByte(t.partial, '\n') |
| + if i < 0 { |
| + break |
| + } |
| + t.add(string(t.partial[:i])) |
| + t.partial = t.partial[i+1:] |
| + } |
| + if len(t.partial) > 4<<10 { |
| + t.add(string(t.partial)) |
| + t.partial = nil |
| + } |
| + return len(p), nil |
| +} |
| + |
| +func (t *lineTail) add(line string) { |
| + line = strings.ToValidUTF8(strings.TrimRight(line, "\r"), "?") |
| + if len(line) > 500 { |
| + line = line[:500] |
| + for !utf8.ValidString(line) { |
| + line = line[:len(line)-1] |
| + } |
| + } |
| + t.lines = append(t.lines, line) |
| + if len(t.lines) > t.max { |
| + t.lines = t.lines[len(t.lines)-t.max:] |
| + } |
| +} |
| + |
| +func (t *lineTail) String() string { |
| + t.mu.Lock() |
| + defer t.mu.Unlock() |
| + lines := t.lines |
| + if len(t.partial) > 0 { |
| + lines = append(slices.Clone(lines), string(t.partial)) |
| + } |
| + out := strings.Join(lines, "\n") |
| + for len(out) > wire.MaxChecksOutput { |
| + _, out, _ = strings.Cut(out, "\n") |
| + } |
| + return out |
| +} |
diff --git a/internal/runner/linuxworker/worker.go b/internal/runner/linuxworker/worker.go| new file mode 100644 |
| index 00000000..27000506 |
| --- /dev/null |
| +++ b/internal/runner/linuxworker/worker.go |
| @@ -0,0 +1,209 @@ |
| +// Package linuxworker is a hosted VM's checks worker (hosted runners |
| +// slice 2): thin's worker with this kind runs the one checks attempt |
| +// placed on the VM. Its checks are the base's gates (checkrun, from |
| +// BaseSHA) in a bubblewrap namespace of the containment manager, over the |
| +// dependencies the primary sent, staged outside the sandbox against the |
| +// base's go.sum pins and mounted read-only. Each run's namespace is |
| +// recorded before it starts, and every end is proven (wire.TerminationNamespace). |
| +// cmd/equipo-runner hosted-run sets it as thin.Options.HostedWorker; |
| +// thin never imports this package. |
| +package linuxworker |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "errors" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "regexp" |
| + "strings" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/checkrun" |
| + "amadan.net/oficina/equipo/internal/runner/checks" |
| + "amadan.net/oficina/equipo/internal/runner/containment" |
| + "amadan.net/oficina/equipo/internal/runner/depsbundle" |
| + "amadan.net/oficina/equipo/internal/runner/gate" |
| + "amadan.net/oficina/equipo/internal/runner/thin" |
| + "amadan.net/oficina/equipo/internal/runner/workspace" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// stageLimits bound a bundle's staging (tests lower them). |
| +var stageLimits = depsbundle.DefaultLimits |
| + |
| +// Kind is the hosted worker thin runs: the bubblewrap gate (NewGate), |
| +// namespaces as proof, the containment record conversion (Record), the |
| +// hosted checks and the capability report. |
| +func Kind(m *containment.Manager, goRoot string, staged func(attempt string) (string, error)) *thin.WorkerKind { |
| + w := &worker{gate: NewGate(m, goRoot, staged), goRoot: goRoot, staged: staged} |
| + return &thin.WorkerKind{Gate: w.gate, Termination: wire.TerminationNamespace, Record: Record, Checks: w.checks, Probe: w.probe} |
| +} |
| + |
| +var namespaceID = regexp.MustCompile(`^[0-9a-f]{32}$`) |
| + |
| +// errNotNamespace: a recorded attempt that names no namespace of this |
| +// runner (a Mac's process group) is never proven ended here. |
| +var errNotNamespace = errors.New("not a namespace record") |
| + |
| +// Record turns a step's recorded id into what the gate's Verify settles: |
| +// a namespace record is itself; an attempt that recorded none |
| +// (thin.UnrecordedStep) is "", proven only once no namespace remains. |
| +func Record(id string) (string, error) { |
| + switch { |
| + case namespaceID.MatchString(id): |
| + return id, nil |
| + case strings.HasPrefix(id, thin.UnrecordedStep("")): |
| + return "", nil |
| + } |
| + return "", errNotNamespace |
| +} |
| + |
| +// StagedUnder is the staging directory of each attempt's dependencies: |
| +// root/<a digest of the attempt>, made 0700. A gate mounts only a cache |
| +// staged directly in it. |
| +func StagedUnder(root string) func(attempt string) (string, error) { |
| + return func(attempt string) (string, error) { |
| + sum := sha256.Sum256([]byte(attempt)) |
| + dir := filepath.Join(root, hex.EncodeToString(sum[:8])) |
| + return dir, os.MkdirAll(dir, 0o700) |
| + } |
| +} |
| + |
| +type worker struct { |
| + gate gate.Runner |
| + goRoot string |
| + staged func(attempt string) (string, error) |
| +} |
| + |
| +// probe is the hosted worker's capability report: Linux, and Go when |
| +// its tree is there. |
| +func (w *worker) probe(context.Context) wire.Capabilities { |
| + c := wire.Capabilities{Simulators: []wire.Simulator{}, Tags: []string{wire.TagLinux}} |
| + if v, err := checks.RunnerGoVersion(w.goRoot); w.goRoot != "" && err == nil { |
| + c.Toolchains.Go = v |
| + c.Tags = append(c.Tags, wire.TagGo) |
| + } |
| + return c |
| +} |
| + |
| +// checks runs a hosted attempt: the base and the candidate checked out |
| +// of the attempt's store; the candidate's go.sum against the base's pins |
| +// (deps_conflict, deps_new_module); the bundle staged outside the |
| +// sandbox (deps_missing, deps_new_module, deps_too_large); then checkrun |
| +// with the base's gates and the staged cache. Nothing runs in a sandbox |
| +// before the dependencies are settled. |
| +func (w *worker) checks(ctx context.Context, hc thin.HostedChecks) checkrun.Outcome { |
| + cannot := func(reason, why string) checkrun.Outcome { |
| + return checkrun.Outcome{State: wire.StepDone, Terminated: true, Checks: wire.ChecksCannotRun, Reason: reason, LogTail: why} |
| + } |
| + failed := func(state, reason string) checkrun.Outcome { |
| + return checkrun.Outcome{State: state, Terminated: true, Reason: reason} |
| + } |
| + stopped := func(err error) (checkrun.Outcome, bool) { |
| + if ctx.Err() != nil { |
| + return failed(wire.StepCancelled, "cancelled"), true |
| + } |
| + switch { |
| + case errors.Is(err, depsbundle.ErrTooLarge): |
| + return cannot(wire.ReasonDepsTooLarge, ""), true |
| + case errors.Is(err, depsbundle.ErrMalformed), errors.Is(err, depsbundle.ErrUnsafePath), errors.Is(err, depsbundle.ErrHashMismatch): |
| + return cannot("checks_unavailable", "Not run: the dependencies were refused ("+err.Error()+")."), true |
| + case err != nil: |
| + return cannot("checks_unavailable", ""), true |
| + } |
| + return checkrun.Outcome{}, false |
| + } |
| + tree, base := filepath.Join(hc.Dir, "tree"), filepath.Join(hc.Dir, "base") |
| + for dir, sha := range map[string]string{base: hc.BaseSHA, tree: hc.CandidateSHA} { |
| + if err := checkout(ctx, hc.Repo, dir, sha); err != nil { |
| + if ctx.Err() != nil { |
| + return failed(wire.StepCancelled, "cancelled") |
| + } |
| + return failed(wire.StepFailed, "workspace_refused") |
| + } |
| + } |
| + baseRoot, err := os.OpenRoot(base) |
| + if err != nil { |
| + return failed(wire.StepFailed, "workspace_refused") |
| + } |
| + defer baseRoot.Close() |
| + candidateRoot, err := os.OpenRoot(tree) |
| + if err != nil { |
| + return failed(wire.StepFailed, "workspace_refused") |
| + } |
| + defer candidateRoot.Close() |
| + // Read through roots: a tree's symlink out of it is refused, never |
| + // followed. |
| + baseFS, candidateFS := baseRoot.FS(), candidateRoot.FS() |
| + conflicts, err := depsbundle.Conflicts(baseFS, candidateFS) |
| + if out, stop := stopped(err); stop { |
| + return out |
| + } |
| + if len(conflicts) > 0 { |
| + return cannot(wire.ReasonDepsConflict, "") |
| + } |
| + fresh, err := depsbundle.NewModules(baseFS, candidateFS) |
| + if out, stop := stopped(err); stop { |
| + return out |
| + } |
| + if len(fresh) > 0 { |
| + return cannot(wire.ReasonDepsNewModule, "") |
| + } |
| + pins, err := depsbundle.Pins(baseFS) |
| + if out, stop := stopped(err); stop { |
| + return out |
| + } |
| + root, err := w.staged(hc.Attempt) |
| + if out, stop := stopped(err); stop { |
| + return out |
| + } |
| + staged, err := depsbundle.Stage(ctx, bytes.NewReader(hc.Bundle), pins, root, stageLimits) |
| + if out, stop := stopped(err); stop { |
| + return out |
| + } |
| + defer func() { |
| + _ = staged.Remove() |
| + _ = os.Remove(root) |
| + }() |
| + if len(staged.Missing) > 0 { |
| + for _, m := range staged.Missing { |
| + if _, pinned := pins[m]; !pinned { |
| + return cannot(wire.ReasonDepsNewModule, "") |
| + } |
| + } |
| + return cannot(wire.ReasonDepsMissing, "") |
| + } |
| + // The base's own tree is not checked; only its objects judge. |
| + _ = os.RemoveAll(base) |
| + return checkrun.Run(ctx, w.gate, hc.Repo, checkrun.Inputs{Workspace: tree, BaseSHA: hc.BaseSHA, CandidateSHA: hc.CandidateSHA, |
| + GoRoot: w.goRoot, ModuleCache: staged.Dir, Limit: hc.Limit, Attempt: hc.Attempt, Record: hc.Record, Prepare: hc.Prepare, |
| + Diagnostic: func(ctx context.Context) (string, error) { |
| + dir := tree + "-diagnostic" |
| + return dir, checkout(ctx, hc.Repo, dir, hc.CandidateSHA) |
| + }}) |
| +} |
| + |
| +// checkout writes sha's tree from repo's store into a fresh dir. |
| +func checkout(ctx context.Context, repo checks.Repo, dir, sha string) error { |
| + if err := os.MkdirAll(dir, 0o700); err != nil { |
| + return err |
| + } |
| + index := dir + ".index" |
| + defer os.Remove(index) |
| + run := func(args ...string) error { |
| + cmd := exec.CommandContext(ctx, repo.Git, append([]string{"--git-dir=" + repo.GitDir, "--work-tree=" + dir}, args...)...) |
| + for k, v := range workspace.GitEnvironment() { |
| + cmd.Env = append(cmd.Env, k+"="+v) |
| + } |
| + cmd.Env = append(cmd.Env, "GIT_INDEX_FILE="+index, "HOME=/nonexistent") |
| + cmd.Dir = dir |
| + return cmd.Run() |
| + } |
| + if err := run("read-tree", "--end-of-options", sha); err != nil { |
| + return err |
| + } |
| + return run("checkout-index", "-a", "-f") |
| +} |
diff --git a/internal/runner/linuxworker/worker_test.go b/internal/runner/linuxworker/worker_test.go| new file mode 100644 |
| index 00000000..2cf7e0fb |
| --- /dev/null |
| +++ b/internal/runner/linuxworker/worker_test.go |
| @@ -0,0 +1,745 @@ |
| +package linuxworker |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "regexp" |
| + "runtime" |
| + "slices" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedimage" |
| + "amadan.net/oficina/equipo/internal/runner" |
| + "amadan.net/oficina/equipo/internal/runner/containment" |
| + "amadan.net/oficina/equipo/internal/runner/depsbundle" |
| + "amadan.net/oficina/equipo/internal/runner/gate" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/runner/thin" |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "amadan.net/rastrillo/rastrillo/budget" |
| + "golang.org/x/mod/module" |
| + "golang.org/x/mod/sumdb/dirhash" |
| + modzip "golang.org/x/mod/zip" |
| +) |
| + |
| +func TestMain(m *testing.M) { |
| + if len(os.Args) > 1 && os.Args[1] == "__namespace" { |
| + os.Exit(containment.NamespaceMain(os.Args[2:])) |
| + } |
| + if len(os.Args) > 1 && os.Args[1] == "__dial" { |
| + os.Exit(dialMain(os.Args[2:])) |
| + } |
| + os.Exit(budget.Main(m)) |
| +} |
| + |
| +// dialMain is the probe run inside the sandbox: it dials each address and |
| +// prints whether it connected; it exits 1 if any did. |
| +func dialMain(addrs []string) int { |
| + code := 0 |
| + for _, a := range addrs { |
| + c, err := net.DialTimeout("tcp", a, 3*time.Second) |
| + if err == nil { |
| + c.Close() |
| + fmt.Printf("connected %s\n", a) |
| + code = 1 |
| + continue |
| + } |
| + fmt.Printf("failed %s\n", a) |
| + } |
| + return code |
| +} |
| + |
| +const sampleRepo = "amadan.net/oficina/sample" |
| + |
| +// gitRun runs git in dir with a fixed identity and no user config. |
| +func gitRun(t *testing.T, dir string, stdin io.Reader, args ...string) string { |
| + t.Helper() |
| + cmd := exec.Command("/usr/bin/git", args...) |
| + cmd.Dir, cmd.Stdin = dir, stdin |
| + cmd.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL=/dev/null", "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@example.com", "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@example.com") |
| + var out, errOut bytes.Buffer |
| + cmd.Stdout, cmd.Stderr = &out, &errOut |
| + if err := cmd.Run(); err != nil { |
| + t.Fatalf("git %v: %v %s", args, err, errOut.String()) |
| + } |
| + return strings.TrimSpace(out.String()) |
| +} |
| + |
| +// rig is a hosted worker on real bubblewrap: a containment manager, the |
| +// hosted kind, a thin worker and its step engine over a state, and the |
| +// commits and transfers one hosted checks attempt receives. |
| +type rig struct { |
| + t *testing.T |
| + root, seed, scratch, deps string |
| + m *containment.Manager |
| + kind *thin.WorkerKind |
| + st *thin.State |
| + w *thin.Worker |
| + d wire.DispatchCommand |
| +} |
| + |
| +func newRig(t *testing.T) *rig { |
| + t.Helper() |
| + if runtime.GOOS != "linux" { |
| + t.Skip("the hosted worker is Linux only") |
| + } |
| + root := t.TempDir() |
| + // The check policy refuses directories under the home directory. |
| + t.Setenv("HOME", filepath.Join(root, "home")) |
| + r := &rig{t: t, root: root, seed: filepath.Join(root, "seed"), scratch: filepath.Join(root, "scratch"), deps: filepath.Join(root, "deps")} |
| + for _, d := range []string{r.scratch, r.deps, filepath.Join(root, "state"), filepath.Join(root, "steps")} { |
| + if err := os.MkdirAll(d, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + self, err := os.Executable() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if r.m, err = containment.New(containment.Config{Binary: Bwrap, RunnerBinary: self, ScratchRoot: r.scratch}); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.kind = Kind(r.m, "", StagedUnder(r.deps)) |
| + if r.st, err = thin.OpenState(context.Background(), filepath.Join(root, "state")); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { r.st.Close() }) |
| + e := &thin.Engineer{} |
| + e.O.Runner.GitPath, e.O.Runner.StateDir, e.O.State = "/usr/bin/git", filepath.Join(root, "state"), r.st |
| + r.w = &thin.Worker{State: r.st, Engine: e, Gate: r.kind.Gate, PackWait: 5 * time.Second, MaxStep: 2 * time.Minute, StepRoot: filepath.Join(root, "steps"), Hosted: true, HostedChecks: r.kind.Checks} |
| + return r |
| +} |
| + |
| +// commits makes the base from base and the candidate from the base with |
| +// candidate's files changed, and returns both. |
| +func (r *rig) commits(base, candidate map[string]string) (string, string) { |
| + t := r.t |
| + gitRun(t, r.root, nil, "init", "-q", "-b", "main", r.seed) |
| + write := func(files map[string]string) { |
| + for name, body := range files { |
| + p := filepath.Join(r.seed, name) |
| + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(p, []byte(body), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + gitRun(t, r.seed, nil, "add", "-A") |
| + } |
| + write(base) |
| + gitRun(t, r.seed, nil, "commit", "-q", "--allow-empty", "-m", "base") |
| + b := gitRun(t, r.seed, nil, "rev-parse", "HEAD") |
| + write(candidate) |
| + gitRun(t, r.seed, nil, "commit", "-q", "--allow-empty", "-m", "candidate") |
| + return b, gitRun(t, r.seed, nil, "rev-parse", "HEAD") |
| +} |
| + |
| +// dispatch places a hosted checks attempt of the two commits and relays |
| +// its hosted pack (both commits, no history) and bundle. |
| +func (r *rig) dispatch(base, candidate map[string]string, bundle []byte) { |
| + t := r.t |
| + b, c := r.commits(base, candidate) |
| + r.d = wire.DispatchCommand{Person: "p@x", TaskID: "tk1", StepID: "s1", Attempt: 1, Specialist: wire.SpecialistChecks, Repo: sampleRepo, Branch: "equipo/tk1-change", BaseSHA: b, CandidateSHA: c} |
| + objects := gitRun(t, r.seed, nil, "rev-list", "--objects", "--no-walk", b, c) |
| + var names bytes.Buffer |
| + for _, line := range strings.Split(objects, "\n") { |
| + names.WriteString(strings.Fields(line)[0] + "\n") |
| + } |
| + cmd := exec.Command("/usr/bin/git", "pack-objects", "--stdout", "-q") |
| + cmd.Dir, cmd.Stdin = r.seed, &names |
| + pack, err := cmd.Output() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + h := wire.TransferHeader{Direction: wire.TransferInbound, Repo: sampleRepo, TaskID: "tk1", StepID: "s1", Attempt: 1, BaseSHA: b, CandidateSHA: c} |
| + pk, dp := h, h |
| + pk.ID, pk.Kind = "tr_pack", wire.TransferKindHostedPack |
| + dp.ID, dp.Kind = "tr_deps", wire.TransferKindDeps |
| + r.relay(pk, pack) |
| + r.relay(dp, bundle) |
| +} |
| + |
| +func (r *rig) relay(h wire.TransferHeader, data []byte) { |
| + sum := sha256.Sum256(data) |
| + total := max(1, (len(data)+wire.MaxBlobChunk-1)/wire.MaxBlobChunk) |
| + for i := range total { |
| + part := data[i*wire.MaxBlobChunk : min(len(data), (i+1)*wire.MaxBlobChunk)] |
| + b := wire.Blob{Transfer: h, Index: i, Total: total, SHA256: hex.EncodeToString(sum[:]), Data: base64.StdEncoding.EncodeToString(part)} |
| + if err := r.st.AcceptChunk(context.Background(), fmt.Sprintf("%s-%d", h.ID, i), b); err != nil { |
| + r.t.Fatal(err) |
| + } |
| + } |
| +} |
| + |
| +// engine is the worker's step engine over kind: recovery proves a |
| +// recorded attempt ended through kind's record conversion and gate. |
| +func (r *rig) engine(kind *thin.WorkerKind, exec thin.StepFunc) *thin.StepEngine { |
| + if exec == nil { |
| + exec = r.w.Exec |
| + } |
| + return &thin.StepEngine{State: r.st, Exec: exec, Notify: func() {}, |
| + Verify: func(_ context.Context, id string) bool { |
| + rec, err := kind.Record(id) |
| + return err == nil && kind.Gate.Verify(rec) |
| + }, TerminationKind: kind.Termination} |
| +} |
| + |
| +// start starts e, then gives it the dispatch, as the link does. |
| +func (r *rig) start(ctx context.Context, e *thin.StepEngine) { |
| + r.t.Helper() |
| + if err := e.Start(ctx); err != nil { |
| + r.t.Fatal(err) |
| + } |
| + if err := r.st.AcceptDispatch(ctx, "d1", r.d); err != nil { |
| + r.t.Fatal(err) |
| + } |
| + e.Wake() |
| +} |
| + |
| +// run runs the dispatched attempt to its final report. |
| +func (r *rig) run() wire.StepReport { |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + e := r.engine(r.kind, nil) |
| + r.start(ctx, e) |
| + defer func() { cancel(); e.Wait() }() |
| + return r.final(2 * time.Minute) |
| +} |
| + |
| +// final waits for the attempt's final step report in the outbox. |
| +func (r *rig) final(wait time.Duration) wire.StepReport { |
| + r.t.Helper() |
| + deadline := time.Now().Add(wait) |
| + for time.Now().Before(deadline) { |
| + frames, _, err := r.st.Unacked(context.Background(), 0) |
| + if err != nil { |
| + r.t.Fatal(err) |
| + } |
| + for _, f := range frames { |
| + var rep wire.StepReport |
| + if f.Type != wire.FrameStep || json.Unmarshal(f.Data, &rep) != nil { |
| + continue |
| + } |
| + if rep.State == wire.StepDone || rep.State == wire.StepFailed || rep.State == wire.StepCancelled { |
| + return rep |
| + } |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| + r.t.Fatal("no final step report") |
| + return wire.StepReport{} |
| +} |
| + |
| +// waitRecorded waits until the attempt's namespace is recorded and |
| +// returns its record. |
| +func (r *rig) waitRecorded(m *containment.Manager) containment.Record { |
| + r.t.Helper() |
| + for range 600 { |
| + recs, err := m.Records(context.Background()) |
| + if err == nil && len(recs) == 1 && recs[0].HostPID > 0 { |
| + return recs[0] |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| + r.t.Fatal("the attempt's namespace was never recorded") |
| + return containment.Record{} |
| +} |
| + |
| +func emptyBundle(t *testing.T, want ...depsbundle.Module) []byte { |
| + t.Helper() |
| + b, err := depsbundle.Build(context.Background(), t.TempDir(), want, wire.DepsTransferMax) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return b.Bytes() |
| +} |
| + |
| +const contract = `{"version":1,"files":["budgets.txt"]}` |
| + |
| +var gateMake = "ci:\n\t@test \"$$(cat size.txt)\" -le \"$$(cat budgets.txt)\" || { echo over budget; exit 3; }\n" |
| + |
| +// TestHostedBaseGatesFromBase: a hosted attempt is judged by the base's |
| +// gates (Task 11's checkrun, from BaseSHA's objects): a candidate that |
| +// edits .equipo/gates.json and the Makefile still runs the base's gate, |
| +// and BaseChecksSHA is set only when that base gate passed. The report |
| +// says bubblewrap and names the namespace as its proof. |
| +func TestHostedBaseGatesFromBase(t *testing.T) { |
| + base := map[string]string{".equipo/gates.json": contract, "Makefile": gateMake, "size.txt": "1\n", "budgets.txt": "1\n"} |
| + for _, tc := range []struct { |
| + name string |
| + base, candidate map[string]string |
| + checks, baseChecks string |
| + reason string |
| + certified bool |
| + }{ |
| + {"candidate rewrites the gate and its budget", base, |
| + map[string]string{".equipo/gates.json": `{"version":1,"files":[]}`, "Makefile": "ci:\n\t@echo candidate gate\n", "size.txt": "2\n", "budgets.txt": "2\n"}, |
| + wire.ChecksFailed, wire.ChecksFailed, "base_checks_failed", false}, |
| + {"candidate edits the contract, base gate passes", base, |
| + map[string]string{".equipo/gates.json": `{"version":1,"files":["budgets.txt","size.txt"]}`, "NEWS": "news\n"}, |
| + wire.ChecksPassed, wire.ChecksPassed, "", true}, |
| + {"base certifies nothing, candidate gate passes", map[string]string{"Makefile": "ci:\n\t@echo hello\n"}, |
| + map[string]string{"NEWS": "news\n"}, |
| + wire.ChecksPassed, "", "", false}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + r := newRig(t) |
| + r.dispatch(tc.base, tc.candidate, emptyBundle(t)) |
| + rep := r.run() |
| + wantSHA := "" |
| + if tc.certified { |
| + wantSHA = r.d.BaseSHA |
| + } |
| + if rep.State != wire.StepDone || rep.Checks != tc.checks || rep.BaseChecks != tc.baseChecks || rep.Reason != tc.reason || rep.BaseChecksSHA != wantSHA { |
| + t.Fatalf("report %+v", rep) |
| + } |
| + if !rep.Termination || rep.TerminationKind != wire.TerminationNamespace || rep.ChecksSandbox != wire.SandboxBubblewrap || rep.Gate != "make ci" { |
| + t.Fatalf("proof %v %q, sandbox %q, gate %q", rep.Termination, rep.TerminationKind, rep.ChecksSandbox, rep.Gate) |
| + } |
| + if recs, err := r.m.Records(context.Background()); err != nil || len(recs) != 0 { |
| + t.Fatalf("namespaces left recorded: %v %v", recs, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestHostedBasePinMounted (requirement A): the base's gate files are |
| +// mounted read-only over the candidate's tree, so a candidate's check |
| +// that writes to one is refused and the gate reads the base's bytes. |
| +func TestHostedBasePinMounted(t *testing.T) { |
| + r := newRig(t) |
| + base := map[string]string{".equipo/gates.json": contract, "Makefile": "ci:\n\t@sh check.sh\n\t@test \"$$(cat budgets.txt)\" = 1 && echo budget kept\n", "check.sh": "true\n", "budgets.txt": "1\n"} |
| + r.dispatch(base, map[string]string{"check.sh": "echo 9 > budgets.txt || echo write refused\n"}, emptyBundle(t)) |
| + rep := r.run() |
| + if rep.State != wire.StepDone || rep.Checks != wire.ChecksPassed || rep.BaseChecksSHA != r.d.BaseSHA { |
| + t.Fatalf("a candidate wrote over a pinned base gate file: %+v", rep) |
| + } |
| + if !strings.Contains(rep.Output, "write refused") || !strings.Contains(rep.Output, "budget kept") { |
| + t.Fatalf("output %q", rep.Output) |
| + } |
| +} |
| + |
| +// TestHostedChecksNamespaceProof: the hosted kind proves ends with |
| +// namespaces, and the gate keeps each run's namespace record before the |
| +// run starts; a record that cannot be kept starts nothing. |
| +func TestHostedChecksNamespaceProof(t *testing.T) { |
| + r := newRig(t) |
| + if r.kind.Termination != wire.TerminationNamespace || r.kind.Gate.Sandbox() != wire.SandboxBubblewrap { |
| + t.Fatalf("kind %q, sandbox %q", r.kind.Termination, r.kind.Gate.Sandbox()) |
| + } |
| + // The record conversion: a namespace is itself, an unrecorded attempt |
| + // is "" (no namespace of this runner may remain), anything else (a |
| + // Mac's process group) is never proven here. |
| + if rec, err := r.kind.Record("0123456789abcdef0123456789abcdef"); err != nil || rec != "0123456789abcdef0123456789abcdef" { |
| + t.Fatalf("namespace record %q %v", rec, err) |
| + } |
| + if rec, err := r.kind.Record(thin.UnrecordedStep("tk1/s1/1")); err != nil || rec != "" { |
| + t.Fatalf("unrecorded %q %v", rec, err) |
| + } |
| + if _, err := r.kind.Record("pg:0:checks/abc"); err == nil { |
| + t.Fatal("a process group record converted") |
| + } |
| + work := filepath.Join(r.root, "work") |
| + if err := os.Mkdir(work, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx := context.Background() |
| + var id string |
| + var recorded, started bool |
| + res := r.kind.Gate.Run(ctx, "checks/proof", work, []string{"/usr/bin/touch", "started"}, time.Minute, func(got string) error { |
| + id = got |
| + recs, _ := r.m.Records(ctx) |
| + recorded = slices.ContainsFunc(recs, func(c containment.Record) bool { return c.ID == got }) |
| + _, err := os.Stat(filepath.Join(work, "started")) |
| + started = err == nil |
| + return nil |
| + }) |
| + if !regexp.MustCompile(`^[0-9a-f]{32}$`).MatchString(id) || !recorded || started { |
| + t.Fatalf("record %q (durable %v) when the run had started %v", id, recorded, started) |
| + } |
| + if !res.Terminated || res.Code != 0 || res.Reason != "" || res.Sandbox != wire.SandboxBubblewrap { |
| + t.Fatalf("result %+v", res) |
| + } |
| + if _, err := os.Stat(filepath.Join(work, "started")); err != nil { |
| + t.Fatalf("the run did not run: %v", err) |
| + } |
| + if !r.kind.Gate.Verify(id) { |
| + t.Fatal("an ended, forgotten namespace is not verified") |
| + } |
| + // A record that cannot be kept: nothing starts. |
| + if err := os.Remove(filepath.Join(work, "started")); err != nil { |
| + t.Fatal(err) |
| + } |
| + res = r.kind.Gate.Run(ctx, "checks/proof", work, []string{"/usr/bin/touch", "started"}, time.Minute, func(string) error { return errors.New("disk full") }) |
| + if !res.Terminated || res.Reason != "checks_unavailable" { |
| + t.Fatalf("unrecorded run %+v", res) |
| + } |
| + if _, err := os.Stat(filepath.Join(work, "started")); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatal("a run whose record failed started") |
| + } |
| +} |
| + |
| +var sleepGate = map[string]string{"Makefile": "ci:\n\t@sleep 300\n"} |
| + |
| +// TestHostedRestartProof: the runner stops mid-check and a new one |
| +// starts. Its recovery proves the old namespace ended (killing it if it |
| +// had not) before it reports the attempt, naming the namespace. |
| +func TestHostedRestartProof(t *testing.T) { |
| + r := newRig(t) |
| + r.dispatch(sleepGate, map[string]string{"NEWS": "news\n"}, emptyBundle(t)) |
| + // The first runner never reports: it stands for one that died. |
| + hold := make(chan struct{}) |
| + ctx1, stop1 := context.WithCancel(context.Background()) |
| + first := r.engine(r.kind, never(r.w.Exec, hold)) |
| + r.start(ctx1, first) |
| + t.Cleanup(func() { stop1(); close(hold); first.Wait() }) |
| + old := r.waitRecorded(r.m) |
| + // The new process: its own manager over the same scratch root. |
| + self, _ := os.Executable() |
| + m2, err := containment.New(containment.Config{Binary: Bwrap, RunnerBinary: self, ScratchRoot: r.scratch}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + second := r.engine(Kind(m2, "", StagedUnder(r.deps)), refusing(r.w.Exec, t)) |
| + ctx2, stop2 := context.WithCancel(context.Background()) |
| + defer func() { stop2(); second.Wait() }() |
| + if err := second.Start(ctx2); err != nil { |
| + t.Fatal(err) |
| + } |
| + rep := r.final(time.Minute) |
| + if rep.State != wire.StepFailed || rep.Reason != "runner_restarted" || !rep.Termination || rep.TerminationKind != wire.TerminationNamespace { |
| + t.Fatalf("recovery report %+v", rep) |
| + } |
| + if err := syscall.Kill(old.HostPID, 0); !errors.Is(err, syscall.ESRCH) { |
| + t.Fatalf("the old namespace (pid %d) is still there after recovery reported it: %v", old.HostPID, err) |
| + } |
| +} |
| + |
| +// never runs inner, then holds its report until hold closes. |
| +func never[R any](inner func(context.Context, R, func(wire.StepReport)) wire.StepReport, hold <-chan struct{}) func(context.Context, R, func(wire.StepReport)) wire.StepReport { |
| + return func(ctx context.Context, r R, p func(wire.StepReport)) wire.StepReport { |
| + rep := inner(ctx, r, p) |
| + <-hold |
| + return rep |
| + } |
| +} |
| + |
| +// refusing fails the test if an attempt runs. |
| +func refusing[R any](_ func(context.Context, R, func(wire.StepReport)) wire.StepReport, t *testing.T) func(context.Context, R, func(wire.StepReport)) wire.StepReport { |
| + return func(context.Context, R, func(wire.StepReport)) wire.StepReport { |
| + t.Error("the recovered attempt ran again") |
| + return wire.StepReport{} |
| + } |
| +} |
| + |
| +// TestHostedCancel: a cancelled hosted step stops its sandbox and reports |
| +// cancelled with the namespace's end as proof. |
| +func TestHostedCancel(t *testing.T) { |
| + r := newRig(t) |
| + r.dispatch(sleepGate, map[string]string{"NEWS": "news\n"}, emptyBundle(t)) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + e := r.engine(r.kind, nil) |
| + r.start(ctx, e) |
| + defer func() { cancel(); e.Wait() }() |
| + rec := r.waitRecorded(r.m) |
| + e.Cancel("s1", 1) |
| + rep := r.final(time.Minute) |
| + if rep.State != wire.StepCancelled || !rep.Termination || rep.TerminationKind != wire.TerminationNamespace { |
| + t.Fatalf("cancelled report %+v", rep) |
| + } |
| + if err := syscall.Kill(rec.HostPID, 0); !errors.Is(err, syscall.ESRCH) { |
| + t.Fatalf("the sandbox (pid %d) outlived its cancelled step: %v", rec.HostPID, err) |
| + } |
| + if recs, err := r.m.Records(context.Background()); err != nil || len(recs) != 0 { |
| + t.Fatalf("namespaces left recorded: %v %v", recs, err) |
| + } |
| +} |
| + |
| +// TestLinuxWorkerRefusedOutsideHosted: a Linux runner enrolled as a |
| +// worker (its role file, or its credential) that hosted-run did not |
| +// start refuses to start; hosted-run's kind without its link is refused. |
| +func TestLinuxWorkerRefusedOutsideHosted(t *testing.T) { |
| + if runtime.GOOS != "linux" { |
| + t.Skip("Linux only") |
| + } |
| + ctx := context.Background() |
| + state := func(name string, body any) string { |
| + dir := filepath.Join(t.TempDir(), "state") |
| + if err := os.Mkdir(dir, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + raw, _ := json.Marshal(body) |
| + if err := os.WriteFile(filepath.Join(dir, name), raw, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + return dir |
| + } |
| + for name, dir := range map[string]string{ |
| + "role file": state(runner.RoleFile, wire.RoleWorker), |
| + "credential": state("credentials.json", map[string]any{"bearer": map[string]string{"token": "t", "role": wire.RoleWorker}}), |
| + } { |
| + if err := thin.Run(ctx, runner.Config{StateDir: dir}, thin.Options{}); !errors.Is(err, thin.ErrLinuxWorker) { |
| + t.Errorf("%s: %v, want refused", name, err) |
| + } |
| + } |
| + if err := thin.Run(ctx, runner.Config{StateDir: state(runner.RoleFile, wire.RolePrimary)}, thin.Options{}); errors.Is(err, thin.ErrLinuxWorker) { |
| + t.Error("a primary refused as a worker") |
| + } |
| + kind := &thin.WorkerKind{Gate: NewGate(nil, "", StagedUnder(t.TempDir())), Termination: wire.TerminationNamespace, Record: Record} |
| + if err := thin.Run(ctx, runner.Config{StateDir: state(runner.RoleFile, wire.RoleWorker)}, thin.Options{HostedWorker: kind}); !errors.Is(err, thin.ErrHostedSetup) { |
| + t.Errorf("a hosted kind without its link or checks: %v", err) |
| + } |
| +} |
| + |
| +// TestHostedChecksOffline: from inside the hosted sandbox neither a |
| +// listener on the host's loopback (where a proxy port would be) nor a |
| +// public address can be reached, though the host reaches the first. |
| +func TestHostedChecksOffline(t *testing.T) { |
| + r := newRig(t) |
| + ln, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer ln.Close() |
| + go func() { |
| + for { |
| + c, err := ln.Accept() |
| + if err != nil { |
| + return |
| + } |
| + c.Close() |
| + } |
| + }() |
| + if c, err := net.DialTimeout("tcp", ln.Addr().String(), 3*time.Second); err != nil { |
| + t.Fatalf("the host cannot reach its own listener: %v", err) |
| + } else { |
| + c.Close() |
| + } |
| + work := filepath.Join(r.root, "work") |
| + if err := os.Mkdir(work, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + self, _ := os.Executable() |
| + raw, err := os.ReadFile(self) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(filepath.Join(work, "probe"), raw, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + res := r.kind.Gate.Run(context.Background(), "checks/offline", work, []string{"/workspace/probe", "__dial", ln.Addr().String(), "1.1.1.1:443", "[2606:4700:4700::1111]:443"}, time.Minute, func(string) error { return nil }) |
| + if !res.Terminated || res.Reason != "" || res.Code != 0 { |
| + t.Fatalf("result %+v", res) |
| + } |
| + for _, want := range []string{"failed " + ln.Addr().String(), "failed 1.1.1.1:443", "failed [2606:4700:4700::1111]:443"} { |
| + if !strings.Contains(res.Output, want) { |
| + t.Fatalf("output %q, want %q", res.Output, want) |
| + } |
| + } |
| +} |
| + |
| +// TestHostedGatePolicyMatchesCertification (requirement B): the gate |
| +// builds its sandbox with the policy certification's sandbox probes use, |
| +// so for the same workspace, Go tree and argv its digest is theirs; and |
| +// the bubblewrap it names is the image's, which measured.json's |
| +// sandbox_policy digests. |
| +func TestHostedGatePolicyMatchesCertification(t *testing.T) { |
| + r := newRig(t) |
| + if Bwrap != hostedimage.PathBwrap { |
| + t.Fatalf("bwrap %s, the image installs %s", Bwrap, hostedimage.PathBwrap) |
| + } |
| + goRoot, work := filepath.Join(r.root, "go"), filepath.Join(r.root, "work") |
| + for _, d := range []string{goRoot, work} { |
| + if err := os.Mkdir(d, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + g := NewGate(r.m, goRoot, StagedUnder(r.deps)).(*bwrapGate) |
| + var launched []provider.Launch |
| + g.start = func(_ context.Context, l provider.Launch, _ []string, _ func(context.Context, containment.Record) error) (provider.Process, error) { |
| + launched = append(launched, l) |
| + return nil, errors.New("not started") |
| + } |
| + argv := []string{"/workspace/equipo-probes", "hosted-sandbox-probes", "{}"} |
| + g.Run(context.Background(), "checks/policy", work, argv, time.Minute, func(string) error { return nil }) |
| + self, _ := os.Executable() |
| + want, err := CertificationPolicy(work, self, goRoot, argv) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(launched) != 1 || want.Hash == "" || launched[0].Policy.Hash != want.Hash || launched[0].Workspace != work { |
| + t.Fatalf("gate launches %+v, certification's policy %s", launched, want.Hash) |
| + } |
| +} |
| + |
| +// TestHostedGateCacheStagedForAttempt: the gate mounts a module cache |
| +// only when it was staged for the attempt (directly in staged(attempt)); |
| +// any other directory is refused before anything launches. |
| +func TestHostedGateCacheStagedForAttempt(t *testing.T) { |
| + r := newRig(t) |
| + work := filepath.Join(r.root, "work") |
| + if err := os.Mkdir(work, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + staged, err := StagedUnder(r.deps)("checks/cache") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + g := NewGate(r.m, "", StagedUnder(r.deps)).(*bwrapGate) |
| + var mounted []string |
| + g.start = func(_ context.Context, l provider.Launch, _ []string, _ func(context.Context, containment.Record) error) (provider.Process, error) { |
| + for _, m := range l.Policy.Mounts { |
| + if m.Target == "/opt/go-mod" && m.ReadOnly { |
| + mounted = append(mounted, m.Source) |
| + } |
| + } |
| + return nil, errors.New("not started") |
| + } |
| + other := filepath.Join(r.root, "elsewhere", "deps-1") |
| + for _, dir := range []string{filepath.Join(staged, "deps-1"), other} { |
| + if err := os.MkdirAll(dir, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + for _, dir := range []string{filepath.Join(staged, "deps-1"), other, staged} { |
| + g.Run(gate.WithModuleCache(context.Background(), dir), "checks/cache", work, []string{"/usr/bin/true"}, time.Minute, func(string) error { return nil }) |
| + } |
| + if !slices.Equal(mounted, []string{filepath.Join(staged, "deps-1")}) { |
| + t.Fatalf("mounted %q, want only the attempt's staged cache", mounted) |
| + } |
| +} |
| + |
| +// fixtureModule zips files as module m into cache's cache/download and |
| +// returns its go.sum lines. |
| +func fixtureModule(t *testing.T, cache string, m depsbundle.Module, files map[string]string) string { |
| + t.Helper() |
| + src := t.TempDir() |
| + for name, body := range files { |
| + if err := os.WriteFile(filepath.Join(src, name), []byte(body), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + esc, _ := module.EscapePath(m.Path) |
| + at := filepath.Join(cache, "cache", "download", filepath.FromSlash(esc), "@v") |
| + if err := os.MkdirAll(at, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + var z bytes.Buffer |
| + if err := modzip.CreateFromDir(&z, module.Version{Path: m.Path, Version: m.Version}, src); err != nil { |
| + t.Fatal(err) |
| + } |
| + base := filepath.Join(at, m.Version) |
| + for ext, data := range map[string][]byte{".zip": z.Bytes(), ".mod": []byte(files["go.mod"]), ".info": []byte(`{"Version":"` + m.Version + `"}`)} { |
| + if err := os.WriteFile(base+ext, data, 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + zh, err := dirhash.HashZip(base+".zip", dirhash.Hash1) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + mh, err := dirhash.Hash1([]string{"go.mod"}, func(string) (io.ReadCloser, error) { return io.NopCloser(strings.NewReader(files["go.mod"])), nil }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return fmt.Sprintf("%s %s %s\n%s %s/go.mod %s\n", m.Path, m.Version, zh, m.Path, m.Version, mh) |
| +} |
| + |
| +// TestHostedStagedCacheReadOnly (requirement C): the bundle is staged |
| +// outside the sandbox against the base's pins, and the gate sees exactly |
| +// that staged cache, read-only, at /opt/go-mod (checkrun's ModuleCache). |
| +func TestHostedStagedCacheReadOnly(t *testing.T) { |
| + r := newRig(t) |
| + cache := t.TempDir() |
| + m := depsbundle.Module{Path: "example.com/m", Version: "v1.0.0"} |
| + sum := fixtureModule(t, cache, m, map[string]string{"go.mod": "module example.com/m\n", "m.go": "package m\n"}) |
| + bundle, err := depsbundle.Build(context.Background(), cache, []depsbundle.Module{m}, wire.DepsTransferMax) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + base := map[string]string{"go.mod": "module example.com/app\n\nrequire example.com/m v1.0.0\n", "go.sum": sum, |
| + "Makefile": "ci:\n\t@test -f /opt/go-mod/example.com/m@v1.0.0/m.go && echo staged\n\t@touch /opt/go-mod/x 2>/dev/null && echo writable || echo read-only\n"} |
| + r.dispatch(base, map[string]string{"NEWS": "news\n"}, bundle.Bytes()) |
| + rep := r.run() |
| + if rep.State != wire.StepDone || rep.Checks != wire.ChecksPassed || !strings.Contains(rep.Output, "staged") || !strings.Contains(rep.Output, "read-only") || strings.Contains(rep.Output, "writable") { |
| + t.Fatalf("report %+v", rep) |
| + } |
| + if entries, err := os.ReadDir(r.deps); err != nil || len(entries) != 0 { |
| + t.Fatalf("staged dependencies left behind: %v %v", entries, err) |
| + } |
| +} |
| + |
| +// fakeSum is a well-formed h1 hash of s. |
| +func fakeSum(s string) string { |
| + h := sha256.Sum256([]byte(s)) |
| + return "h1:" + base64.StdEncoding.EncodeToString(h[:]) |
| +} |
| + |
| +// TestHostedDeps (requirement C): the dependency outcomes, each before |
| +// any gate runs: cannot_run with deps_conflict, deps_new_module (from |
| +// the go.sum comparison, or a requirement the base does not pin), |
| +// deps_missing, deps_too_large, and a malformed go.sum. |
| +func TestHostedDeps(t *testing.T) { |
| + m := depsbundle.Module{Path: "example.com/m", Version: "v1.0.0"} |
| + n := depsbundle.Module{Path: "example.com/n", Version: "v1.0.0"} |
| + pins := "example.com/m v1.0.0 " + fakeSum("zip") + "\nexample.com/m v1.0.0/go.mod " + fakeSum("mod") + "\n" |
| + base := map[string]string{"go.mod": "module example.com/app\n\nrequire example.com/m v1.0.0\n", "go.sum": pins, "Makefile": "ci:\n\t@echo ran\n"} |
| + for _, tc := range []struct { |
| + name string |
| + candidate map[string]string |
| + want []depsbundle.Module |
| + limits depsbundle.Limits |
| + reason string |
| + }{ |
| + {"a changed pin", map[string]string{"go.sum": "example.com/m v1.0.0 " + fakeSum("other") + "\n"}, []depsbundle.Module{m}, depsbundle.Limits{}, wire.ReasonDepsConflict}, |
| + {"a new tree line", map[string]string{"go.sum": pins + "example.com/n v1.0.0 " + fakeSum("n") + "\n"}, []depsbundle.Module{m}, depsbundle.Limits{}, wire.ReasonDepsNewModule}, |
| + {"an unpinned requirement", map[string]string{"go.mod": "module example.com/app\n\nrequire (\n\texample.com/m v1.0.0\n\texample.com/n v1.0.0\n)\n"}, []depsbundle.Module{m, n}, depsbundle.Limits{}, wire.ReasonDepsNewModule}, |
| + {"a pinned module the bundle lacks", map[string]string{"NEWS": "news\n"}, []depsbundle.Module{m}, depsbundle.Limits{}, wire.ReasonDepsMissing}, |
| + {"a bundle past its limit", map[string]string{"NEWS": "news\n"}, []depsbundle.Module{m}, depsbundle.Limits{Bundle: 16}, wire.ReasonDepsTooLarge}, |
| + {"a malformed go.sum", map[string]string{"go.sum": "not a go.sum line\n"}, []depsbundle.Module{m}, depsbundle.Limits{}, "checks_unavailable"}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + r := newRig(t) |
| + if tc.limits != (depsbundle.Limits{}) { |
| + defer func(l depsbundle.Limits) { stageLimits = l }(stageLimits) |
| + stageLimits = tc.limits |
| + } |
| + r.dispatch(base, tc.candidate, emptyBundle(t, tc.want...)) |
| + rep := r.run() |
| + if rep.State != wire.StepDone || rep.Checks != wire.ChecksCannotRun || rep.Reason != tc.reason || !rep.Termination || rep.Gate != "" || rep.ChecksSandbox != "" { |
| + t.Fatalf("report %+v", rep) |
| + } |
| + if tc.reason == "checks_unavailable" && !strings.Contains(rep.LogTail, "go.sum") { |
| + t.Fatalf("log tail %q does not say why", rep.LogTail) |
| + } |
| + if recs, err := r.m.Records(context.Background()); err != nil || len(recs) != 0 { |
| + t.Fatalf("a gate ran: %v %v", recs, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestHostedReasonsRegistered: every reason the hosted worker reports is |
| +// one the instance records (with words), and the session's renewal |
| +// failure reason is the wire's. |
| +func TestHostedReasonsRegistered(t *testing.T) { |
| + for _, reason := range []string{wire.ReasonDepsConflict, wire.ReasonDepsNewModule, wire.ReasonDepsMissing, wire.ReasonDepsTooLarge, wire.ReasonTokenRenewalFailed, wire.ReasonPackIncomplete} { |
| + if !wire.StepReasons[reason] { |
| + t.Errorf("%s is not a step reason", reason) |
| + } |
| + } |
| +} |
diff --git a/internal/runner/thin/hosted_worker.go b/internal/runner/thin/hosted_worker.go| new file mode 100644 |
| index 00000000..173ba7ff |
| --- /dev/null |
| +++ b/internal/runner/thin/hosted_worker.go |
| @@ -0,0 +1,177 @@ |
| +package thin |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + "path/filepath" |
| + "runtime" |
| + "sync/atomic" |
| + "time" |
| + |
| + "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/mac" |
| + "amadan.net/oficina/equipo/internal/runner/workspace" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// A hosted VM's runner (hosted slice 2) is a Linux checks worker: it |
| +// runs the one checks step placed on it, in the kind cmd/equipo-runner |
| +// gives it (internal/runner/linuxworker; thin never imports it), over |
| +// the link its hosted session holds. |
| + |
| +// ErrLinuxWorker refuses a Linux runner enrolled as a worker that was |
| +// not started as a hosted VM's runner (equipo-runner hosted-run). |
| +var ErrLinuxWorker = errors.New("a Linux worker runs only as a hosted VM's runner (equipo-runner hosted-run)") |
| + |
| +// ErrHostedSetup refuses a hosted worker missing its link or its kind's |
| +// checks. |
| +var ErrHostedSetup = errors.New("a hosted worker needs its link and its kind's checks") |
| + |
| +// HostedLink is a hosted VM's standing with its instance, from its |
| +// hosted.Session: the credential stays in memory, renewed, and is read |
| +// at each dial; every connection goes through Client (the proxy). |
| +type HostedLink struct { |
| + Credential func() runnerproto.RunnerCredential |
| + Client *http.Client |
| + // Work is an attempt's context (hosted.Session.Work): it ends when a |
| + // renewal fails, and the attempt then reports token_renewal_failed. |
| + Work func(context.Context) (context.Context, context.CancelFunc) |
| + // flush waits until no attempt runs and every report was acked. |
| + flush atomic.Pointer[func(context.Context)] |
| +} |
| + |
| +// hostedFlushWait bounds Flush: past it the runner exits regardless. |
| +var hostedFlushWait = 60 * time.Second |
| + |
| +// Flush is the session's OnRenewalFailed: the attempt the failure |
| +// stopped reports token_renewal_failed (steps), and Flush waits, at most |
| +// hostedFlushWait, until that report has been acked. |
| +func (h *HostedLink) Flush() { |
| + if f := h.flush.Load(); f != nil { |
| + ctx, cancel := context.WithTimeout(context.Background(), hostedFlushWait) |
| + defer cancel() |
| + (*f)(ctx) |
| + } |
| +} |
| + |
| +// steps runs each attempt in its Work context: one that context ended |
| +// while the runner's own did not was stopped by a failed renewal. |
| +func (h *HostedLink) steps(inner StepFunc) StepFunc { |
| + return func(ctx context.Context, r stepRow, progress func(wire.StepReport)) wire.StepReport { |
| + work, release := h.Work(ctx) |
| + defer release() |
| + rep := inner(work, r, progress) |
| + if work.Err() != nil && ctx.Err() == nil { |
| + rep.State, rep.Reason = wire.StepFailed, wire.ReasonTokenRenewalFailed |
| + } |
| + return rep |
| + } |
| +} |
| + |
| +// settle gives Flush its wait: until no step runs and the outbox is |
| +// empty, or ctx ends. |
| +func (h *HostedLink) settle(state *State) { |
| + f := func(ctx context.Context) { |
| + for { |
| + var n int |
| + err := state.db.QueryRowContext(ctx, "SELECT (SELECT count(*) FROM steps WHERE state=?) + (SELECT count(*) FROM outbox WHERE acked=0)", runRunning).Scan(&n) |
| + if err == nil && n == 0 { |
| + return |
| + } |
| + select { |
| + case <-ctx.Done(): |
| + return |
| + case <-time.After(100 * time.Millisecond): |
| + } |
| + } |
| + } |
| + h.flush.Store(&f) |
| +} |
| + |
| +// HostedChecks is a hosted attempt's checks (WorkerKind.Checks), once |
| +// its hosted pack is indexed and its dependency bundle has arrived. |
| +type HostedChecks struct { |
| + // Repo is the attempt's own store, holding both commits; Dir is the |
| + // attempt's directory, removed after it. |
| + Repo checks.Repo |
| + Dir string |
| + // BaseSHA judges CandidateSHA: its gates and its go.sum pins. |
| + BaseSHA, CandidateSHA string |
| + // Attempt names the attempt's gate runs; Record keeps each run's |
| + // namespace before it starts. |
| + Attempt string |
| + Record func(id string) error |
| + // Bundle is the dependency bundle the primary sent (depsbundle). |
| + Bundle []byte |
| + // Prepare gives a checked tree a .git of its own at the candidate. |
| + Prepare func(ctx context.Context, dir string) error |
| + Limit time.Duration |
| +} |
| + |
| +// enrolledWorker reports whether the runner in c was enrolled as a |
| +// worker (enrolledRole), from its role file or its credential. |
| +func enrolledWorker(c runner.Config) bool { |
| + creds, _ := runner.ReadCredentials(filepath.Join(c.StateDir, "credentials.json")) |
| + return enrolledRole(c, creds.Bearer.Role) == wire.RoleWorker |
| +} |
| + |
| +// runHosted serves a hosted VM's instance as its checks worker. |
| +func runHosted(ctx context.Context, c runner.Config, o Options) error { |
| + k, h := o.HostedWorker, o.Hosted |
| + if runtime.GOOS != "linux" || h == nil || h.Credential == nil || h.Client == nil || h.Work == nil || k.Gate == nil || k.Record == nil || k.Checks == nil || k.Probe == nil { |
| + return ErrHostedSetup |
| + } |
| + return runWorker(ctx, c, o, hostPlatform(), workerSetup{probe: k.Probe, kind: *k}) |
| +} |
| + |
| +// markAttempt records a worker attempt's marker as its process group |
| +// before anything of it runs; a hosted attempt records only its |
| +// namespaces, each before it starts, so until then it is unrecorded. |
| +func (w *Worker) markAttempt(ctx context.Context, r stepRow) error { |
| + if w.Hosted && w.HostedChecks != nil { |
| + return nil |
| + } |
| + return w.State.setStepNamespace(ctx, r, mac.RecordID(0, w.marker)) |
| +} |
| + |
| +// hosted ends a hosted attempt's checks: it waits for the dependency |
| +// bundle, then runs the kind's checks over the indexed store. |
| +func (w *Worker) hosted(ctx context.Context, r stepRow, rep wire.StepReport, store, dir string, progress func(wire.StepReport)) wire.StepReport { |
| + end := func(state, reason string) wire.StepReport { |
| + rep.State, rep.Reason, rep.Termination = state, reason, true |
| + return rep |
| + } |
| + want := wire.TransferHeader{Direction: wire.TransferInbound, Kind: wire.TransferKindDeps, Repo: r.Repo, TaskID: r.TaskID, StepID: r.StepID, Attempt: r.Attempt, BaseSHA: r.BaseSHA, CandidateSHA: r.CandidateSHA} |
| + if !want.Valid() { |
| + return end(wire.StepFailed, "placement_refused") |
| + } |
| + bundle, err := w.awaitPack(ctx, r, want) |
| + switch { |
| + case ctx.Err() != nil: |
| + return end(wire.StepCancelled, "cancelled") |
| + case err != nil: |
| + w.Engine.log("worker deps", err) |
| + return end(wire.StepFailed, "candidate_unavailable") |
| + } |
| + progress(rep) |
| + git := w.Engine.O.Runner.GitPath |
| + out := w.HostedChecks(ctx, HostedChecks{Repo: checks.Repo{Git: git, GitDir: store}, Dir: dir, BaseSHA: r.BaseSHA, CandidateSHA: r.CandidateSHA, |
| + Attempt: "checks/" + stepKey(r), Bundle: bundle, Limit: w.MaxStep, |
| + Record: func(id string) error { return w.State.setStepNamespace(context.WithoutCancel(ctx), r, id) }, |
| + Prepare: func(ctx context.Context, d string) error { |
| + return w.Engine.checkRepository(ctx, workspace.TaskTree{Dir: d, GitDir: store, Git: git, Branch: r.Branch}, r.CandidateSHA) |
| + }}) |
| + return hostedReport(rep, out) |
| +} |
| + |
| +// hostedReport is the step report of a hosted attempt's outcome. |
| +func hostedReport(rep wire.StepReport, out checkrun.Outcome) wire.StepReport { |
| + rep.State, rep.Termination, rep.Checks, rep.Reason = out.State, out.Terminated, out.Checks, out.Reason |
| + rep.BaseChecks, rep.BaseChecksSHA, rep.ChecksSandbox = out.BaseChecks, out.BaseChecksSHA, out.Sandbox |
| + rep.Gate, rep.Output, rep.LogTail, rep.ExitCode = out.Gate, out.Output, out.LogTail, out.ExitCode |
| + return rep |
| +} |
diff --git a/internal/runner/thin/hosted_worker_test.go b/internal/runner/thin/hosted_worker_test.go| new file mode 100644 |
| index 00000000..958de34d |
| --- /dev/null |
| +++ b/internal/runner/thin/hosted_worker_test.go |
| @@ -0,0 +1,80 @@ |
| +package thin |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// TestHostedRenewalFailureReported (Task 17, requirement D): a hosted |
| +// attempt runs in its session's Work context. When a failed renewal ends |
| +// that context, the attempt reports token_renewal_failed, keeping its |
| +// proof; the runner's own cancel stays a plain cancel. |
| +func TestHostedRenewalFailureReported(t *testing.T) { |
| + renewal := errors.New("renewal failed") |
| + var fail context.CancelCauseFunc |
| + h := &HostedLink{Work: func(parent context.Context) (context.Context, context.CancelFunc) { |
| + ctx, cancel := context.WithCancelCause(parent) |
| + fail = cancel |
| + return ctx, func() { cancel(context.Canceled) } |
| + }} |
| + stopped := func(stop func()) StepFunc { |
| + return func(ctx context.Context, r stepRow, _ func(wire.StepReport)) wire.StepReport { |
| + stop() |
| + <-ctx.Done() |
| + return wire.StepReport{State: wire.StepCancelled, Reason: "cancelled", Termination: true} |
| + } |
| + } |
| + rep := h.steps(stopped(func() { fail(renewal) }))(context.Background(), stepRow{}, nil) |
| + if rep.State != wire.StepFailed || rep.Reason != wire.ReasonTokenRenewalFailed || !rep.Termination { |
| + t.Fatalf("after a failed renewal: %+v", rep) |
| + } |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + rep = h.steps(stopped(cancel))(ctx, stepRow{}, nil) |
| + if rep.State != wire.StepCancelled || rep.Reason != "cancelled" { |
| + t.Fatalf("after the runner's own cancel: %+v", rep) |
| + } |
| +} |
| + |
| +// TestHostedFlushWaitsForReports: Flush (the session's OnRenewalFailed) |
| +// returns once every report was acked, and gives up after its bound. |
| +func TestHostedFlushWaitsForReports(t *testing.T) { |
| + defer func(d time.Duration) { hostedFlushWait = d }(hostedFlushWait) |
| + hostedFlushWait = 300 * time.Millisecond |
| + s, err := OpenState(context.Background(), t.TempDir()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer s.Close() |
| + h := &HostedLink{} |
| + h.Flush() // not serving yet: nothing to wait for |
| + h.settle(s) |
| + start := time.Now() |
| + h.Flush() |
| + if time.Since(start) > 200*time.Millisecond { |
| + t.Fatal("Flush waited with nothing to send") |
| + } |
| + if err := s.SendNotebook(context.Background(), wire.NotebookReport{}); err != nil { |
| + t.Fatal(err) |
| + } |
| + start = time.Now() |
| + h.Flush() |
| + if time.Since(start) < 300*time.Millisecond { |
| + t.Fatal("Flush returned before the report was acked") |
| + } |
| + frames, _, err := s.Unacked(context.Background(), 0) |
| + if err != nil || len(frames) != 1 { |
| + t.Fatalf("unacked %v %v", frames, err) |
| + } |
| + if err := s.Acked(context.Background(), frames[0].ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + start = time.Now() |
| + h.Flush() |
| + if time.Since(start) > 200*time.Millisecond { |
| + t.Fatal("Flush waited after every report was acked") |
| + } |
| +} |
diff --git a/internal/runner/thin/relay.go b/internal/runner/thin/relay.go| index e36ec882..db64576c 100644 |
| --- a/internal/runner/thin/relay.go |
| +++ b/internal/runner/thin/relay.go |
| @@ -171,11 +171,11 @@ func (s *State) pack(ctx context.Context, want wire.TransferHeader) ([]byte, err |
| if total == -1 { |
| total, digest = tot, sum |
| } |
| - if tot > wire.MaxTransferChunks { |
| + if tot > wire.MaxChunks(want.Kind) { |
| // Declared too large to relay. |
| return nil, errPackRefused |
| } |
| - if idx != n || tot != total || sum != digest || int64(buf.Len()+len(data)) > wire.MaxTransferBytes { |
| + if idx != n || tot != total || sum != digest || int64(buf.Len()+len(data)) > wire.MaxBytes(want.Kind) { |
| return nil, errPackRefused |
| } |
| buf.Write(data) |
| @@ -502,7 +502,8 @@ func (e *Engineer) prepareBase(ctx context.Context, c wire.PrepareBaseCommand) ( |
| // the fresh clone does not have is refused before the pack is built. |
| func (e *Engineer) packCommits(ctx context.Context, h wire.TransferHeader) ([]byte, error) { |
| commits := h.Commits() |
| - if !forgekey.ValidHub(h.Repo) || !h.Valid() || len(commits) == 0 { |
| + // A deps transfer is a dependency bundle, never a git pack (Task 23). |
| + if !forgekey.ValidHub(h.Repo) || !h.Valid() || h.Kind == wire.TransferKindDeps || len(commits) == 0 { |
| return nil, errPackRefused |
| } |
| for _, c := range commits { |
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go| index 1cc6f784..02067e20 100644 |
| --- a/internal/runner/thin/run.go |
| +++ b/internal/runner/thin/run.go |
| @@ -23,6 +23,7 @@ import ( |
| "time" |
| "amadan.net/oficina/equipo/internal/runner" |
| + "amadan.net/oficina/equipo/internal/runner/checkrun" |
| "amadan.net/oficina/equipo/internal/runner/containment" |
| rungate "amadan.net/oficina/equipo/internal/runner/gate" |
| "amadan.net/oficina/equipo/internal/runner/mac" |
| @@ -105,10 +106,11 @@ 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 is the Linux checks worker a hosted VM runs, and Hosted |
| + // its link (hosted_worker.go): set only by cmd/equipo-runner |
| + // hosted-run (thin never imports linuxworker). |
| HostedWorker *WorkerKind |
| + Hosted *HostedLink |
| } |
| // WorkerKind is what a kind of worker proves its gates' ends with: the |
| @@ -119,6 +121,10 @@ type WorkerKind struct { |
| Gate rungate.Runner |
| Termination string |
| Record func(id string) (string, error) |
| + // Checks runs a hosted attempt's checks, and Probe is the hosted |
| + // worker's capability report (a hosted kind's only). |
| + Checks func(context.Context, HostedChecks) checkrun.Outcome |
| + Probe func(context.Context) wire.Capabilities |
| } |
| // verify reports whether the attempt recorded as id has ended for sure. |
| @@ -180,6 +186,12 @@ func SessionRoot(c runner.Config) string { return filepath.Join(filepath.Dir(c.S |
| // Run serves the instance until ctx ends or a newer generation takes over. |
| func Run(ctx context.Context, c runner.Config, o Options) error { |
| + if o.HostedWorker != nil { |
| + return runHosted(ctx, c, o) |
| + } |
| + if runtime.GOOS == "linux" && o.FakePlatform == "" && enrolledWorker(c) { |
| + return ErrLinuxWorker |
| + } |
| if err := c.Validate(); err != nil { |
| return err |
| } |
| @@ -816,7 +828,15 @@ func runWorker(ctx context.Context, c runner.Config, o Options, platform wire.Pl |
| return err |
| } |
| defer release() |
| - creds, state, err := openRunner(ctx, c, o.Logger) |
| + var creds runnerproto.CredentialRotation |
| + var state *State |
| + if o.Hosted != nil { |
| + // A hosted VM's credential is its session's, in memory. |
| + creds.Bearer = o.Hosted.Credential() |
| + state, err = OpenState(ctx, c.StateDir) |
| + } else { |
| + creds, state, err = openRunner(ctx, c, o.Logger) |
| + } |
| if err != nil { |
| return err |
| } |
| @@ -825,6 +845,9 @@ func runWorker(ctx context.Context, c runner.Config, o Options, platform wire.Pl |
| defer cancel(nil) |
| caps := &Capabilities{Probe: w.probe, Logger: o.Logger} |
| link := &Link{Origin: c.Origin, Token: creds.Bearer.Token, State: state, Logger: o.Logger, Connected: o.Connected, Protocol: o.Protocol, WorkerOnly: true, Role: enrolledRole(c, creds.Bearer.Role)} |
| + if h := o.Hosted; h != nil { |
| + link.TokenSource, link.HTTPClient = func() string { return h.Credential().Token }, h.Client |
| + } |
| // A Mac's own Claude connections (slice F task 11): said in hello |
| // only once the welcome says 37. |
| var own *workerConns |
| @@ -868,7 +891,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.kind.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, Hosted: w.kind.Checks != nil, HostedChecks: w.kind.Checks} |
| if w.engineering != nil && w.creds != nil && own != nil { |
| eng := *w.engineering |
| eng.Creds = w.creds |
| @@ -918,7 +941,12 @@ func runWorker(ctx context.Context, c runner.Config, o Options, platform wire.Pl |
| tags := func() []string { return caps.Get(ctx).Tags } |
| // Questions about the Engineering it ran are answered here, from the |
| // sessions it kept (worker_ask.go). |
| - steps := workerSteps(state, worker, w.kind, placementGuard(tags, caps.Stale, worker.Exec), link.Notify, o.Logger) |
| + exec := placementGuard(tags, caps.Stale, worker.Exec) |
| + if h := o.Hosted; h != nil { |
| + exec = h.steps(exec) |
| + h.settle(state) |
| + } |
| + steps := workerSteps(state, worker, w.kind, exec, link.Notify, o.Logger) |
| link.Steps = steps |
| if err := steps.Start(ctx); err != nil { |
| return err |
diff --git a/internal/runner/thin/worker.go b/internal/runner/thin/worker.go| index c7f402bc..85c960a6 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" |
| + "amadan.net/oficina/equipo/internal/runner/checkrun" |
| rungate "amadan.net/oficina/equipo/internal/runner/gate" |
| "amadan.net/oficina/equipo/internal/runner/mac" |
| "amadan.net/oficina/equipo/internal/runner/workspace" |
| @@ -61,8 +62,10 @@ type Worker struct { |
| // none; worker_engineering.go). |
| Eng *WorkerEngineering |
| // Hosted: a hosted VM's worker (slice 2), whose checks take a |
| - // hosted_pack of the base and the candidate into an empty store. |
| - Hosted bool |
| + // hosted_pack of the base and the candidate into an empty store, and |
| + // the dependency bundle, then run HostedChecks (hosted_worker.go). |
| + Hosted bool |
| + HostedChecks func(context.Context, HostedChecks) checkrun.Outcome |
| // mine, in tests, stands in for Engine.Conns.Mine (the person's |
| // connections, read from the bindings file). |
| mine func(person string) []runner.AccountBinding |
diff --git a/internal/runner/thin/worker_checks.go b/internal/runner/thin/worker_checks.go| index a0f942fa..b85c8a23 100644 |
| --- a/internal/runner/thin/worker_checks.go |
| +++ b/internal/runner/thin/worker_checks.go |
| @@ -9,7 +9,6 @@ import ( |
| "strings" |
| "time" |
| - "amadan.net/oficina/equipo/internal/runner/mac" |
| "amadan.net/oficina/equipo/internal/runner/workspace" |
| "amadan.net/oficina/equipo/internal/wire" |
| "amadan.net/oficina/equipo/internal/wire/forgekey" |
| @@ -50,7 +49,9 @@ func (w *Worker) checks(ctx context.Context, r stepRow, progress func(wire.StepR |
| // restarted runner can find them even if no group was recorded. |
| w.marker = "checks/" + stepKey(r) |
| defer func() { w.marker = "" }() |
| - if err := w.State.setStepNamespace(ctx, r, mac.RecordID(0, w.marker)); err != nil { |
| + // A hosted attempt records only its namespaces, each before it starts |
| + // (the gate's record): until then it is unrecorded. |
| + if err := w.markAttempt(ctx, r); err != nil { |
| w.Engine.log("worker record", err) |
| return end(wire.StepFailed, "workspace_refused") |
| } |
| @@ -85,6 +86,9 @@ func (w *Worker) checks(ctx context.Context, r stepRow, progress func(wire.StepR |
| return end(wire.StepFailed, "candidate_unavailable") |
| } |
| rep.Have = []string{r.CandidateSHA} |
| + if w.Hosted && w.HostedChecks != nil { |
| + return w.hosted(ctx, r, rep, store, dir, progress) |
| + } |
| tree := workspace.TaskTree{Dir: filepath.Join(dir, "tree"), GitDir: store, Git: w.Engine.O.Runner.GitPath, Branch: r.Branch, Base: r.BaseSHA} |
| if err := w.checkout(ctx, tree, r.CandidateSHA); err != nil { |
| w.Engine.log("worker tree", err) |
diff --git a/internal/wire/hosted.go b/internal/wire/hosted.go| index 4b320130..6a260c12 100644 |
| --- a/internal/wire/hosted.go |
| +++ b/internal/wire/hosted.go |
| @@ -31,6 +31,20 @@ const ( |
| // candidate; the checks end cannot_run. |
| const ReasonPackIncomplete = "pack_incomplete" |
| +// A hosted worker's checks that end cannot_run over their dependencies |
| +// (depsbundle): a candidate go.sum line changes a base pin; the |
| +// candidate adds a module the base does not pin (it needs the network); |
| +// a pinned module did not arrive in the bundle; the bundle is past its |
| +// limits. ReasonTokenRenewalFailed: the job's credential could not be |
| +// renewed, so its work stopped. |
| +const ( |
| + ReasonDepsConflict = "deps_conflict" |
| + ReasonDepsNewModule = "deps_new_module" |
| + ReasonDepsMissing = "deps_missing" |
| + ReasonDepsTooLarge = "deps_too_large" |
| + ReasonTokenRenewalFailed = "token_renewal_failed" |
| +) |
| + |
| // DepsTransferMax is a deps transfer's own byte limit. Every other kind |
| // keeps MaxTransferBytes. |
| const DepsTransferMax = 256 << 20 |
diff --git a/internal/wire/mac_engineering.go b/internal/wire/mac_engineering.go| index 393d4f17..dec3c762 100644 |
| --- a/internal/wire/mac_engineering.go |
| +++ b/internal/wire/mac_engineering.go |
| @@ -143,7 +143,8 @@ func (h TransferHeader) Commits() []string { |
| // transfer has a candidate (and its base, when known) and no old base. |
| // An Engineering transfer is inbound and has a base, and either nothing |
| // else (a first step or a fix round) or both an old base and a candidate |
| -// (a rebase round). A deps transfer is not valid yet (Task 23). |
| +// (a rebase round). A hosted pack or a deps bundle is inbound and names |
| +// both the base and the candidate, which differ. |
| func (h TransferHeader) Valid() bool { |
| switch h.Kind { |
| case "": |
| @@ -154,8 +155,9 @@ func (h TransferHeader) Valid() bool { |
| if h.Direction != TransferInbound || h.BaseSHA == "" || (h.OldBaseSHA == "") != (h.CandidateSHA == "") { |
| return false |
| } |
| - case TransferKindHostedPack: |
| - // Inbound, exactly two commits: the base, then the candidate. |
| + case TransferKindHostedPack, TransferKindDeps: |
| + // Inbound, exactly two commits: the base, then the candidate (a |
| + // deps bundle names the attempt's two, and carries no objects). |
| if h.Direction != TransferInbound || h.OldBaseSHA != "" || h.BaseSHA == "" || h.CandidateSHA == "" || h.BaseSHA == h.CandidateSHA { |
| return false |
| } |
diff --git a/internal/wire/tasks.go b/internal/wire/tasks.go| index fecbcfd3..81d39e81 100644 |
| --- a/internal/wire/tasks.go |
| +++ b/internal/wire/tasks.go |
| @@ -1125,8 +1125,14 @@ var StepReasons = map[string]bool{ |
| "preview_public_disabled": true, |
| "preview_host": true, |
| "needs_network": true, |
| - // A hosted worker's pack lacked the base or the candidate. |
| - ReasonPackIncomplete: true, |
| + // A hosted worker's pack lacked the base or the candidate; its |
| + // dependencies could not be staged; its credential was not renewed. |
| + ReasonPackIncomplete: true, |
| + ReasonDepsConflict: true, |
| + ReasonDepsNewModule: true, |
| + ReasonDepsMissing: true, |
| + ReasonDepsTooLarge: true, |
| + ReasonTokenRenewalFailed: true, |
| // Merge: the branch conflicts with the default branch; the branch is |
| // no longer at the judged SHA; the hub's own CI on the commit is not |
| // green (still running, or failed); the agent may not merge here; or |