Runner side: start authorization, pack relay, publication, fake worker
The runner asks for each attempt's start authorization at protocol 2 and ends a withdrawn attempt without running it; a dispatch whose needs it lacks is refused (placement_refused). The primary uploads the exact candidate as a one-commit pack and publishes a worker's commit: indexed beside the clone, parent checked against the base, the publication confirmed right before the push, forge's record then reconcile (crash after indexing or after the push pushes once). A worker checks the relayed pack against its own step row and digest, needs exactly the candidate, and runs the gate through a GateRunner. The fake Mac worker (EQUIPO_FAKE_PLATFORM) exists only under the testbuild tag; make release-runner checks its binary, and TestReleaseRunnerHasNoFakeWorker fails if it is compiled in. Index and Engineering report the Apple facts placement uses.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
18 files changed,
+1,749
−32
.rastrillo/budgets.txt+1 −0Makefile+4 −2cmd/equipo-runner/release_guard_test.go+63 −0internal/runner/thin/engine.go+6 −0internal/runner/thin/engineer.go+30 −7internal/runner/thin/fakeworker.go+18 −0internal/runner/thin/fakeworker_testbuild.go+164 −0internal/runner/thin/index.go+17 −0internal/runner/thin/judge.go+18 −6internal/runner/thin/link.go+73 −10internal/runner/thin/mergestep.go+3 −3internal/runner/thin/relay.go+585 −0internal/runner/thin/relay_test.go+240 −0internal/runner/thin/run.go+88 −3internal/runner/thin/state.go+1 −1internal/runner/thin/worker.go+245 −0internal/runner/thin/worker_test.go+184 −0scripts/no-fake-worker.sh+9 −0
CI failed — run details
Intent
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 66578e7a..e19e18cf 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -51,3 +51,4 @@ perf GET /api/v1/tasks/{id} skip Thin v1 person API: bearer-only JSON for device |
| size internal/equipo/chat 8600 - Mac runners slices A and B add per-runner mailboxes, placement, withdrawal, the offline rule, the runners view, transfers and publication (runners.go, transfers.go, about 1000 lines). Thin v1 slice 4c adds the merge policy, the merge card, the rebase round and duplicate reports (merge.go, about 380 lines). Thin v1 instance core: conversation, projects, tasks, review and, from slice 4b, questions to the specialists (questions.go, about 470 lines) share one store, transaction and event log; splitting would export the transaction internals. Measured 5514 source lines; revisit at the slice 7 sweep. |
| perf GET /api/v1/questions/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads questions on /tasks/{id}. |
| perf GET /api/v1/steps/{id}/log skip Thin v1 person API: bearer-only JSON for devices; the browser shows the log tail on /tasks/{id}. |
| +time cmd/equipo-runner 60s Mac runners slice B: TestReleaseRunnerHasNoFakeWorker builds the release runner exactly as make release-runner does and the thin package under the testbuild tag (measured 11.9s locally with a warm cache). |
diff --git a/Makefile b/Makefile| index 54f415c1..528dab19 100644 |
| --- a/Makefile |
| +++ b/Makefile |
| @@ -71,7 +71,7 @@ budget: |
| # CI set); here it reports. |
| # TestCIGateSteps executes CI scripts, so cached test results are insufficient. |
| test: |
| - $(RASTRILLO) budget test -count=1 ./... |
| + $(RASTRILLO) budget test -tags testbuild -count=1 ./... |
| # The perf lane: every GET screen at 150ms to first byte, cold boot at |
| # 500ms. Serial (-p 1 -parallel 1) and uncached (-count=1), because a |
| @@ -82,6 +82,7 @@ perf: |
| vet: |
| go vet ./... |
| + go vet -tags testbuild ./internal/runner/thin ./internal/headless |
| fmt-check: |
| @out=$$(gofmt -l .); if [ -n "$$out" ]; then echo "gofmt needed:"; echo "$$out"; exit 1; fi |
| @@ -113,7 +114,7 @@ export STATICCHECK_CACHE ?= $(GOCACHE)/staticcheck |
| endif |
| staticcheck: |
| - go run $(STATICCHECK) -tags browser,perf ./... |
| + go run $(STATICCHECK) -tags browser,perf,testbuild ./... |
| # govulncheck reports only the vulnerabilities your code can reach: a call |
| # path, not a module that merely sits in go.sum. It reads the live |
| @@ -184,6 +185,7 @@ release-runner: copy-release-check direct-release-check |
| CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath \ |
| -ldflags "-s -w -X amadan.net/rastrillo/rastrillo.BuildVersion=$$(git rev-parse --short HEAD)" \ |
| -o $(RUNNER_RELEASE_DIR)/equipo-runner ./cmd/equipo-runner |
| + scripts/no-fake-worker.sh $(RUNNER_RELEASE_DIR)/equipo-runner |
| cp packaging/equipo-runner.service internal/release/manifest.json $(RUNNER_RELEASE_DIR)/ |
| cp -R internal/release/evidence $(RUNNER_RELEASE_DIR)/evidence |
| cp packaging/install/install-v1.sh $(RUNNER_RELEASE_DIR)/install-v1.sh |
diff --git a/cmd/equipo-runner/release_guard_test.go b/cmd/equipo-runner/release_guard_test.go| new file mode 100644 |
| index 00000000..7561690e |
| --- /dev/null |
| +++ b/cmd/equipo-runner/release_guard_test.go |
| @@ -0,0 +1,63 @@ |
| +package main |
| + |
| +import ( |
| + "bytes" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "regexp" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// marker is the fake worker's marker (internal/runner/thin |
| +// fakeworker_testbuild.go). |
| +const marker = "equipo-fake-worker-unsandboxed-process-group" |
| + |
| +// The test build's fake Mac worker runs checks without a sandbox, so it |
| +// must never be compiled into a release runner: built exactly as `make |
| +// release-runner` builds it, the binary does not contain it (and the |
| +// release recipe passes no build tags and checks the binary itself), |
| +// while a test build of the thin runner does, so this test can see it. |
| +func TestReleaseRunnerHasNoFakeWorker(t *testing.T) { |
| + makefile, err := os.ReadFile("../../Makefile") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + recipe := regexp.MustCompile(`(?s)go build -trimpath \\\s*\n\s*-ldflags "([^"]*)" \\\s*\n\s*-o \$\(RUNNER_RELEASE_DIR\)/equipo-runner \./cmd/equipo-runner\n\s*scripts/no-fake-worker\.sh \$\(RUNNER_RELEASE_DIR\)/equipo-runner`).FindSubmatch(makefile) |
| + if recipe == nil { |
| + t.Fatal("the release-runner recipe changed: build the runner without tags and check it with scripts/no-fake-worker.sh") |
| + } |
| + if strings.Contains(string(makefile[bytes.Index(makefile, []byte("release-runner:")):]), "-tags testbuild") { |
| + t.Fatal("a release recipe builds with the testbuild tag") |
| + } |
| + dir := t.TempDir() |
| + bin := filepath.Join(dir, "equipo-runner") |
| + build := exec.Command("go", "build", "-trimpath", "-ldflags", "-s -w", "-o", bin, ".") |
| + build.Env = append(os.Environ(), "CGO_ENABLED=0") |
| + if out, err := build.CombinedOutput(); err != nil { |
| + t.Fatalf("release build: %v %s", err, out) |
| + } |
| + raw, err := os.ReadFile(bin) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if bytes.Contains(raw, []byte(marker)) { |
| + t.Fatal("the release runner contains the fake worker") |
| + } |
| + if out, err := exec.Command("../../scripts/no-fake-worker.sh", bin).CombinedOutput(); err != nil { |
| + t.Fatalf("the release check refused a clean binary: %s", out) |
| + } |
| + archive := filepath.Join(dir, "thin.a") |
| + test := exec.Command("go", "build", "-tags", "testbuild", "-o", archive, "../../internal/runner/thin") |
| + test.Env = append(os.Environ(), "CGO_ENABLED=0") |
| + if out, err := test.CombinedOutput(); err != nil { |
| + t.Fatalf("test build: %v %s", err, out) |
| + } |
| + if raw, _ := os.ReadFile(archive); !bytes.Contains(raw, []byte(marker)) { |
| + t.Fatal("the test build has no marker: this guard sees nothing") |
| + } |
| + if out, err := exec.Command("../../scripts/no-fake-worker.sh", archive).CombinedOutput(); err == nil { |
| + t.Fatalf("the release check accepted the fake worker: %s", out) |
| + } |
| +} |
diff --git a/internal/runner/thin/engine.go b/internal/runner/thin/engine.go| index aaf683ca..bb4c20cd 100644 |
| --- a/internal/runner/thin/engine.go |
| +++ b/internal/runner/thin/engine.go |
| @@ -115,6 +115,9 @@ func (e *Engine) worker(person string) *worker { |
| // Wake makes sure the person's worker looks for runs. |
| func (e *Engine) Wake(person string) { |
| + if e == nil { |
| + return |
| + } |
| e.mu.Lock() |
| defer e.mu.Unlock() |
| w := e.worker(person) |
| @@ -126,6 +129,9 @@ func (e *Engine) Wake(person string) { |
| // Cancel interrupts the attempt if it is the one running now. |
| func (e *Engine) Cancel(person, turn string, attempt int64) { |
| + if e == nil { |
| + return |
| + } |
| e.mu.Lock() |
| defer e.mu.Unlock() |
| if w := e.workers[person]; w != nil && w.turn == turn && w.attempt == attempt && w.cancel != nil { |
diff --git a/internal/runner/thin/engineer.go b/internal/runner/thin/engineer.go| index e8e4af72..7eca3ae2 100644 |
| --- a/internal/runner/thin/engineer.go |
| +++ b/internal/runner/thin/engineer.go |
| @@ -51,6 +51,12 @@ type Engineer struct { |
| // Authorize confirms the execution lease before the step starts and |
| // right before the push. |
| Authorize func(context.Context) error |
| + // AuthorizeStep is that confirmation for one attempt (protocol 2: the |
| + // start authorization); ErrWithdrawn means the attempt must not run. |
| + AuthorizeStep func(ctx context.Context, step string, attempt int64) error |
| + // ConfirmPublication confirms a worker's commit is still to be |
| + // published, right before the push. |
| + ConfirmPublication func(ctx context.Context, step string, attempt int64, publication string) error |
| // Owners are the persons this runner executes for. |
| Owners []string |
| MaxStep time.Duration |
| @@ -105,8 +111,8 @@ func (e *Engineer) Exec(ctx context.Context, r stepRow, progress func(wire.StepR |
| return fail("policy_rejected", true) |
| } |
| // The generation is an execution lease: nothing runs without it. |
| - if e.lease(ctx) != nil { |
| - rep.State, rep.Reason, rep.Termination = wire.StepCancelled, "cancelled", true |
| + if err := e.lease(ctx, r); err != nil { |
| + rep.State, rep.Reason, rep.Termination = wire.StepCancelled, leaseReason(err), true |
| return rep |
| } |
| if r.Republish { |
| @@ -192,6 +198,8 @@ func (e *Engineer) Exec(ctx context.Context, r stepRow, progress func(wire.StepR |
| return fail("workspace_refused", true) |
| } |
| if files, err := tree.ChangedFiles(ctx, sha); err == nil && len(files) > 0 { |
| + // The instance places its checks on a Mac when it needs one. |
| + rep.Apple = needsMacOS(files, "") |
| rep.LogTail = clip(strings.TrimSpace(rep.LogTail+"\nChanged: "+strings.Join(files[:min(len(files), 20)], ", ")), wire.MaxLogTail) |
| } |
| if err := e.O.State.setStepPhase(ctx, r, phaseCommitted, base, sha); err != nil { |
| @@ -236,7 +244,7 @@ func (e *Engineer) publish(ctx context.Context, r stepRow, rep wire.StepReport) |
| if def, err = e.Clones.DefaultBranch(ctx, r.Repo); err == nil { |
| err = forge.PushBranch(ctx, forge.BranchPush{Root: filepath.Join(e.root(), "publish"), Git: e.O.Runner.GitPath, GitDir: tree.GitDir, Repo: r.Repo, Branch: r.Branch, Default: def, Base: r.Base, Commit: r.Candidate, Key: r.TaskID + "/" + r.key(), Person: r.Person, Owners: e.Owners, |
| Remote: func(ctx context.Context) (workspace.Remote, error) { return e.Forge.Remote(ctx, r.Repo) }, |
| - Confirm: e.confirm}) |
| + Confirm: e.confirmFor(r)}) |
| } |
| if err == nil || errors.Is(err, forge.ErrPushRefused) || errors.Is(err, forge.ErrPushConflict) || ctx.Err() != nil { |
| break |
| @@ -273,11 +281,26 @@ func (e *Engineer) Sweep(ctx context.Context, s *State) { |
| } |
| } |
| -func (e *Engineer) confirm(ctx context.Context) error { |
| - if e.Authorize == nil { |
| - return nil |
| +// confirmFor is the pre-push confirmation of one attempt. |
| +func (e *Engineer) confirmFor(r stepRow) func(context.Context) error { |
| + return func(ctx context.Context) error { |
| + if e.AuthorizeStep != nil { |
| + return e.AuthorizeStep(ctx, r.StepID, r.Attempt) |
| + } |
| + if e.Authorize == nil { |
| + return nil |
| + } |
| + return e.Authorize(ctx) |
| + } |
| +} |
| + |
| +// leaseReason is how an attempt the lease stopped ends: withdrawn by the |
| +// instance, or cancelled. |
| +func leaseReason(err error) string { |
| + if errors.Is(err, ErrWithdrawn) { |
| + return "withdrawn" |
| } |
| - return e.Authorize(ctx) |
| + return "cancelled" |
| } |
| // defaultTip is the default branch's commit in the fresh clone. |
diff --git a/internal/runner/thin/fakeworker.go b/internal/runner/thin/fakeworker.go| new file mode 100644 |
| index 00000000..a9be164d |
| --- /dev/null |
| +++ b/internal/runner/thin/fakeworker.go |
| @@ -0,0 +1,18 @@ |
| +package thin |
| + |
| +import ( |
| + "context" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// fakeMac is the test build's fake Mac worker; nil in every other build |
| +// (fakeworker_testbuild.go sets it), so EQUIPO_FAKE_PLATFORM is refused. |
| +type fakeMac interface { |
| + marker() string |
| + platform(spec string) (wire.Platform, bool) |
| + capabilities(context.Context) wire.Capabilities |
| + gate(bin string) GateRunner |
| +} |
| + |
| +var fake fakeMac |
diff --git a/internal/runner/thin/fakeworker_testbuild.go b/internal/runner/thin/fakeworker_testbuild.go| new file mode 100644 |
| index 00000000..fe5ba415 |
| --- /dev/null |
| +++ b/internal/runner/thin/fakeworker_testbuild.go |
| @@ -0,0 +1,164 @@ |
| +//go:build testbuild |
| + |
| +package thin |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "errors" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "syscall" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// fakeWorkerMarker is in every test build and in no release build: |
| +// TestReleaseRunnerHasNoFakeWorker looks for it in a release binary. |
| +const fakeWorkerMarker = "equipo-fake-worker-unsandboxed-process-group" |
| + |
| +// The test build's fake Mac worker (Mac runners spec §6): the real thin |
| +// runner started with EQUIPO_FAKE_PLATFORM=darwin/arm64 reports a Mac's |
| +// capabilities (a fixture until probe P1 records tito-studio's) and runs |
| +// checks in a process group WITHOUT a sandbox. It exists only under the |
| +// testbuild tag, so no release binary can run anything unsandboxed. |
| +func init() { |
| + fake = &fakeWorker{} |
| +} |
| + |
| +type fakeWorker struct{} |
| + |
| +func (fakeWorker) marker() string { return fakeWorkerMarker } |
| + |
| +func (fakeWorker) platform(spec string) (wire.Platform, bool) { |
| + osName, arch, ok := strings.Cut(spec, "/") |
| + if !ok || osName != "darwin" || arch == "" { |
| + return wire.Platform{}, false |
| + } |
| + return wire.Platform{OS: osName, Arch: arch}, true |
| +} |
| + |
| +// capabilities is the fixture report of a Mac with Xcode and one iPhone |
| +// simulator. |
| +func (fakeWorker) capabilities(context.Context) wire.Capabilities { |
| + return wire.Capabilities{Xcode: wire.Xcode{Version: "16.2", Build: "16C5032a"}, Simulators: []wire.Simulator{{Name: "iPhone 16 Pro", Runtime: "iOS 18.2", UDID: "5C0A1E2B-3D4F-4A5B-9C6D-7E8F90A1B2C3", State: "Shutdown"}}, Toolchains: wire.Toolchains{Swift: "6.0.3", Node: "v22.12.0"}, Harness: wire.Harness{Claude: "2.1.312", SRT: "0.0.81"}, Tags: []string{wire.TagMacOS, wire.TagXcode, wire.TagIOSSimulator, wire.TagClaude}} |
| +} |
| + |
| +func (fakeWorker) gate(bin string) GateRunner { return &groupGate{bin: bin} } |
| + |
| +// groupGate runs a gate in its own session and process group, marked with |
| +// EQUIPO_ATTEMPT, with an environment from scratch: HOME and TMPDIR in |
| +// the attempt's directory, CI=1, a fixed PATH (bin first: the fake |
| +// xcodebuild). Cancel or timeout: SIGTERM to the group, 10 s, SIGKILL, |
| +// then a sweep of marked processes. Termination is the group gone and no |
| +// marked process left, within 30 s. |
| +type groupGate struct{ bin string } |
| + |
| +func (groupGate) Sandbox() string { return wire.SandboxNone } |
| + |
| +func (g *groupGate) Run(ctx context.Context, attempt, dir string, argv []string, limit time.Duration, record func(string)) gateResult { |
| + scratch, err := os.MkdirTemp(filepath.Dir(dir), "attempt-") |
| + if err != nil { |
| + return gateResult{reason: "checks_unavailable", terminated: true} |
| + } |
| + defer os.RemoveAll(scratch) |
| + cmd := exec.Command(argv[0], argv[1:]...) |
| + cmd.Dir = dir |
| + cmd.Env = []string{"HOME=" + scratch, "TMPDIR=" + scratch, "CI=1", "PATH=" + g.bin + ":/usr/local/bin:/usr/bin:/bin", "EQUIPO_ATTEMPT=" + attempt, "LANG=C"} |
| + out := &lineTail{max: wire.MaxChecksLines} |
| + cmd.Stdout, cmd.Stderr = out, out |
| + cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} |
| + if err := cmd.Start(); err != nil { |
| + return gateResult{reason: "checks_unavailable", terminated: true} |
| + } |
| + pgid := cmd.Process.Pid |
| + record("pg:" + strconv.Itoa(pgid) + ":" + attempt) |
| + exited := make(chan error, 1) |
| + go func() { exited <- cmd.Wait() }() |
| + res := gateResult{code: -1} |
| + stop := func(reason string) { |
| + res.reason = reason |
| + _ = syscall.Kill(-pgid, syscall.SIGTERM) |
| + select { |
| + case <-exited: |
| + case <-time.After(10 * time.Second): |
| + _ = syscall.Kill(-pgid, syscall.SIGKILL) |
| + <-exited |
| + } |
| + } |
| + select { |
| + case err := <-exited: |
| + var exit *exec.ExitError |
| + if err == nil { |
| + res.code = 0 |
| + } else if errors.As(err, &exit) { |
| + res.code = exit.ExitCode() |
| + } |
| + case <-ctx.Done(): |
| + stop("cancelled") |
| + case <-time.After(limit): |
| + stop("checks_timeout") |
| + } |
| + res.terminated = g.settle(pgid, attempt) |
| + res.output = out.String() |
| + return res |
| +} |
| + |
| +// settle kills what is left of the group and of the marked processes and |
| +// reports whether, within 30 s, none remains. |
| +func (g *groupGate) settle(pgid int, attempt string) bool { |
| + deadline := time.Now().Add(30 * time.Second) |
| + for time.Now().Before(deadline) { |
| + _ = syscall.Kill(-pgid, syscall.SIGKILL) |
| + marked := markedProcesses(attempt) |
| + for _, pid := range marked { |
| + _ = syscall.Kill(pid, syscall.SIGKILL) |
| + } |
| + if syscall.Kill(-pgid, 0) == syscall.ESRCH && len(marked) == 0 { |
| + return true |
| + } |
| + time.Sleep(100 * time.Millisecond) |
| + } |
| + return false |
| +} |
| + |
| +// Verify: a recorded attempt has ended when its group is gone and no |
| +// process still carries its marker. |
| +func (g *groupGate) Verify(id string) bool { |
| + rest, ok := strings.CutPrefix(id, "pg:") |
| + if !ok { |
| + return false |
| + } |
| + num, attempt, _ := strings.Cut(rest, ":") |
| + pgid, err := strconv.Atoi(num) |
| + if err != nil || pgid <= 1 { |
| + return false |
| + } |
| + return g.settle(pgid, attempt) |
| +} |
| + |
| +// markedProcesses are this user's processes whose environment carries the |
| +// attempt's marker (Linux /proc; the Mac uses ps -E). |
| +func markedProcesses(attempt string) []int { |
| + if attempt == "" { |
| + return nil |
| + } |
| + want := []byte("EQUIPO_ATTEMPT=" + attempt + "\x00") |
| + entries, _ := os.ReadDir("/proc") |
| + var out []int |
| + for _, e := range entries { |
| + pid, err := strconv.Atoi(e.Name()) |
| + if err != nil || pid == os.Getpid() { |
| + continue |
| + } |
| + env, err := os.ReadFile(filepath.Join("/proc", e.Name(), "environ")) |
| + if err == nil && bytes.Contains(append(env, 0), want) { |
| + out = append(out, pid) |
| + } |
| + } |
| + return out |
| +} |
diff --git a/internal/runner/thin/index.go b/internal/runner/thin/index.go| index b6f01cbd..0f3ace48 100644 |
| --- a/internal/runner/thin/index.go |
| +++ b/internal/runner/thin/index.go |
| @@ -264,9 +264,26 @@ func (x *Index) entry(ctx context.Context, repo string) (wire.RepoInfo, error) { |
| names = append(names, appNames(list)...) |
| e.Names = bounded(names, wire.MaxRepoNames) |
| e.Hints = bounded(hints(list, read), wire.MaxRepoHints) |
| + e.NeedsMacOS, e.Simulator = appleFacts(list, read) |
| return e, nil |
| } |
| +// appleFacts is what the instance needs to place a repository's checks: |
| +// its gate calls Xcode's tools (every change's checks need a Mac), and it |
| +// has a shared Xcode scheme (they need the iOS simulator). |
| +func appleFacts(list []string, read func(string) string) (gateNeedsMac, simulator bool) { |
| + gateText := read(".amadan/ci") + "\n" + read("Makefile") |
| + for _, f := range list { |
| + if strings.HasPrefix(f, ".amadan/ci.d/") { |
| + gateText += "\n" + read(f) |
| + } |
| + if strings.Contains(f, "/xcshareddata/xcschemes/") && strings.HasSuffix(f, ".xcscheme") { |
| + simulator = true |
| + } |
| + } |
| + return needsMacOS(nil, gateText), simulator |
| +} |
| + |
| func (x *Index) git(ctx context.Context, dir string, args ...string) ([]byte, error) { |
| return readGit(ctx, x.Clones.Git, dir, args...) |
| } |
diff --git a/internal/runner/thin/judge.go b/internal/runner/thin/judge.go| index 8ccc9da5..bf51f136 100644 |
| --- a/internal/runner/thin/judge.go |
| +++ b/internal/runner/thin/judge.go |
| @@ -39,8 +39,8 @@ func (e *Engineer) judgeTree(ctx context.Context, r stepRow) (workspace.TaskTree |
| if !slices.Contains(e.Owners, r.Person) || !repoKey.MatchString(r.Repo) || !wire.ValidTaskBranch(r.Branch) || !shaPattern.MatchString(r.CandidateSHA) || r.BaseSHA != "" && !shaPattern.MatchString(r.BaseSHA) { |
| return workspace.TaskTree{}, "policy_rejected", errors.New("judge refused") |
| } |
| - if err := e.lease(ctx); err != nil { |
| - return workspace.TaskTree{}, "cancelled", err |
| + if err := e.lease(ctx, r); err != nil { |
| + return workspace.TaskTree{}, leaseReason(err), err |
| } |
| // Preparation as a whole has a deadline, so the serial step worker is |
| // never held by it. |
| @@ -94,12 +94,18 @@ func (e *Engineer) fetch(ctx context.Context, repo string) error { |
| var shaPattern = regexp.MustCompile(`^(?:[0-9a-f]{40}|[0-9a-f]{64})$`) |
| -// lease waits for the execution lease: nothing runs without it. |
| -func (e *Engineer) lease(ctx context.Context) error { |
| - for e.Authorize != nil { |
| - if err := e.Authorize(ctx); err == nil { |
| +// lease waits for the execution lease, or at protocol 2 the attempt's |
| +// start authorization: nothing runs without it, and a withdrawn attempt |
| +// never runs. |
| +func (e *Engineer) lease(ctx context.Context, r stepRow) error { |
| + for e.Authorize != nil || e.AuthorizeStep != nil { |
| + err := e.confirmFor(r)(ctx) |
| + if err == nil { |
| return nil |
| } |
| + if errors.Is(err, ErrWithdrawn) { |
| + return err |
| + } |
| select { |
| case <-ctx.Done(): |
| return ctx.Err() |
| @@ -207,6 +213,9 @@ func (e *Engineer) checks(ctx context.Context, r stepRow, progress func(wire.Ste |
| tree, reason, err := e.judgeTree(ctx, r) |
| if err != nil { |
| rep.State, rep.Reason, rep.Termination = wire.StepFailed, reason, true |
| + if reason == "withdrawn" { |
| + rep.State = wire.StepCancelled |
| + } |
| if ctx.Err() != nil { |
| rep.State, rep.Reason = wire.StepCancelled, "cancelled" |
| } |
| @@ -637,6 +646,9 @@ func (e *Engineer) review(ctx context.Context, r stepRow, progress func(wire.Ste |
| tree, reason, err := e.judgeTree(ctx, r) |
| if err != nil { |
| rep.State, rep.Reason, rep.Termination = wire.StepFailed, reason, true |
| + if reason == "withdrawn" { |
| + rep.State = wire.StepCancelled |
| + } |
| if ctx.Err() != nil { |
| rep.State, rep.Reason = wire.StepCancelled, "cancelled" |
| } |
diff --git a/internal/runner/thin/link.go b/internal/runner/thin/link.go| index f379d8ad..f75a456f 100644 |
| --- a/internal/runner/thin/link.go |
| +++ b/internal/runner/thin/link.go |
| @@ -49,6 +49,8 @@ type Link struct { |
| // Synced runs after every sync sent (the merge and branch watch looks |
| // at once). |
| Synced func() |
| + // Relay uploads packs and publishes workers' commits (protocol 2). |
| + Relay *Relay |
| Hello func() wire.Hello |
| Logger *slog.Logger |
| // Connected is called with true once a generation is granted and false |
| @@ -67,7 +69,7 @@ type Link struct { |
| notify chan struct{} |
| pending []wire.DeltaReport |
| activity []wire.ActivityReport |
| - waiters map[string]chan struct{} |
| + waiters map[string]chan string |
| tools map[string]chan wire.ToolResult |
| leaseSeq int64 |
| helloSoon bool |
| @@ -144,28 +146,59 @@ var ErrNoAuthority = errors.New("runner holds no confirmed lease") |
| // connection that the instance acks only while this connection holds the |
| // generation. It fails at once when disconnected. |
| func (l *Link) Confirm(ctx context.Context) error { |
| + return l.lease(ctx, wire.LeaseCheck{}) |
| +} |
| + |
| +// ErrWithdrawn means the instance refused an attempt's start (or a |
| +// publication): it was withdrawn, superseded or cancelled. Nothing of it |
| +// may run; the runner ends it. |
| +var ErrWithdrawn = errors.New("the instance withdrew this attempt") |
| + |
| +// ConfirmStep is a step attempt's start authorization at protocol 2: the |
| +// instance grants it only while the attempt is placed on this runner and |
| +// not withdrawn (ErrWithdrawn). At protocol 1 it is the plain lease. |
| +func (l *Link) ConfirmStep(ctx context.Context, step string, attempt int64) error { |
| + return l.lease(ctx, wire.LeaseCheck{StepID: step, Attempt: attempt}) |
| +} |
| + |
| +// ConfirmPublication is the primary's confirmation right before it pushes |
| +// a worker's commit: refused (ErrWithdrawn) once the publication is no |
| +// longer pending (cancelled, superseded). |
| +func (l *Link) ConfirmPublication(ctx context.Context, step string, attempt int64, publication string) error { |
| + return l.lease(ctx, wire.LeaseCheck{StepID: step, Attempt: attempt, Publication: publication}) |
| +} |
| + |
| +func (l *Link) lease(ctx context.Context, check wire.LeaseCheck) error { |
| l.init() |
| l.mu.Lock() |
| - c, generation := l.conn, l.generation |
| + c, generation, proto := l.conn, l.generation, l.proto |
| if c == nil { |
| l.mu.Unlock() |
| return ErrNoAuthority |
| } |
| + if proto < wire.Protocol2 { |
| + // A protocol 1 instance knows only the generation. |
| + check = wire.LeaseCheck{} |
| + } |
| + check.Generation = generation |
| l.leaseSeq++ |
| id := l.State.prefix + "-lease-" + itoa(l.leaseSeq) |
| - done := make(chan struct{}) |
| + done := make(chan string, 1) |
| if l.waiters == nil { |
| - l.waiters = map[string]chan struct{}{} |
| + l.waiters = map[string]chan string{} |
| } |
| l.waiters[id] = done |
| l.mu.Unlock() |
| defer func() { l.mu.Lock(); delete(l.waiters, id); l.mu.Unlock() }() |
| - f, _ := wire.NewFrame(id, wire.FrameLease, wire.LeaseCheck{Generation: generation}) |
| + f, _ := wire.NewFrame(id, wire.FrameLease, check) |
| if err := l.send(ctx, c, f); err != nil { |
| return ErrNoAuthority |
| } |
| select { |
| - case <-done: |
| + case refused := <-done: |
| + if refused != "" { |
| + return ErrWithdrawn |
| + } |
| return nil |
| case <-ctx.Done(): |
| return ctx.Err() |
| @@ -174,11 +207,12 @@ func (l *Link) Confirm(ctx context.Context) error { |
| } |
| } |
| -func (l *Link) resolve(id string) bool { |
| +// resolve answers a waiting lease: "" granted, else the refusal. |
| +func (l *Link) resolve(id, refused string) bool { |
| l.mu.Lock() |
| defer l.mu.Unlock() |
| if done, ok := l.waiters[id]; ok { |
| - close(done) |
| + done <- refused |
| delete(l.waiters, id) |
| return true |
| } |
| @@ -470,7 +504,9 @@ func (l *Link) read(ctx context.Context, c *websocket.Conn) (time.Duration, erro |
| if err = l.State.Accept(ctx, f.ID, *v); err != nil { |
| return 0, err |
| } |
| - l.Engine.Wake(v.Person) |
| + if l.Engine != nil { |
| + l.Engine.Wake(v.Person) |
| + } |
| case *wire.ResetCommand: |
| // Recorded durably with the frame id before the ack; the |
| // person's worker applies it before running any later turn |
| @@ -535,8 +571,35 @@ func (l *Link) read(ctx context.Context, c *websocket.Conn) (time.Duration, erro |
| } |
| l.Engine.Cancel(v.Person, v.TurnID, v.Attempt) |
| l.Engine.Wake(v.Person) |
| + case *wire.Refused: |
| + l.resolve(v.ID, firstNonEmpty(v.Reason, "refused")) |
| + continue |
| + case *wire.Blob: |
| + if err = l.State.AcceptChunk(ctx, f.ID, *v); err != nil { |
| + return 0, err |
| + } |
| + if l.Steps != nil { |
| + l.Steps.Wake() |
| + } |
| + if l.Relay != nil { |
| + l.Relay.Wake() |
| + } |
| + case *wire.SendPackCommand: |
| + if err = l.State.AcceptUpload(ctx, f.ID, *v); err != nil { |
| + return 0, err |
| + } |
| + if l.Relay != nil { |
| + l.Relay.Wake() |
| + } |
| + case *wire.PublishCommand: |
| + if err = l.State.AcceptPublish(ctx, f.ID, *v); err != nil { |
| + return 0, err |
| + } |
| + if l.Relay != nil { |
| + l.Relay.Wake() |
| + } |
| case *wire.Ack: |
| - if l.resolve(v.ID) { |
| + if l.resolve(v.ID, "") { |
| continue |
| } |
| if err = l.State.Acked(ctx, v.ID); err != nil { |
diff --git a/internal/runner/thin/mergestep.go b/internal/runner/thin/mergestep.go| index 2f2dfcc0..aadcaeae 100644 |
| --- a/internal/runner/thin/mergestep.go |
| +++ b/internal/runner/thin/mergestep.go |
| @@ -47,8 +47,8 @@ func (e *Engineer) mergeStep(ctx context.Context, r stepRow, progress func(wire. |
| if !slices.Contains(e.Owners, r.Person) || !repoKey.MatchString(r.Repo) || !wire.ValidTaskBranch(r.Branch) || !shaPattern.MatchString(r.CandidateSHA) { |
| return fail("policy_rejected") |
| } |
| - if err := e.lease(ctx); err != nil { |
| - rep.State, rep.Reason = wire.StepCancelled, "cancelled" |
| + if err := e.lease(ctx, r); err != nil { |
| + rep.State, rep.Reason = wire.StepCancelled, leaseReason(err) |
| return rep |
| } |
| progress(rep) |
| @@ -65,7 +65,7 @@ func (e *Engineer) mergeStep(ctx context.Context, r stepRow, progress func(wire. |
| Request: func(ctx context.Context, req forge.HubMergeRequest) (forge.HubMergeResult, error) { |
| return e.Forge.Merge(ctx, r.Repo, r.Branch, req) |
| }, |
| - Confirm: e.confirm} |
| + Confirm: e.confirmFor(r)} |
| var out forge.MergeOutcome |
| var err error |
| uncertain, waited := 0, time.Duration(0) |
diff --git a/internal/runner/thin/relay.go b/internal/runner/thin/relay.go| new file mode 100644 |
| index 00000000..d9ce896d |
| --- /dev/null |
| +++ b/internal/runner/thin/relay.go |
| @@ -0,0 +1,585 @@ |
| +package thin |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/sha256" |
| + "database/sql" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "log/slog" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/forge" |
| + "amadan.net/oficina/equipo/internal/runner/workspace" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// Candidates travel as packs (Mac runners spec §2). The primary uploads |
| +// the exact candidate a worker judges and publishes a worker's commit; a |
| +// worker receives the candidate. Chunks, upload requests and publications |
| +// are durable here, recorded with the frame id before the ack. |
| + |
| +const relaySchema = ` |
| +CREATE TABLE IF NOT EXISTS chunks (transfer TEXT NOT NULL, idx INTEGER NOT NULL, total INTEGER NOT NULL, sha256 TEXT NOT NULL, header TEXT NOT NULL, step_id TEXT NOT NULL, attempt INTEGER NOT NULL, direction TEXT NOT NULL, data BLOB NOT NULL, PRIMARY KEY (transfer, idx)); |
| +CREATE INDEX IF NOT EXISTS chunks_step ON chunks(step_id, attempt); |
| +CREATE TABLE IF NOT EXISTS uploads (transfer TEXT PRIMARY KEY, body TEXT NOT NULL, state TEXT NOT NULL, created_at TEXT NOT NULL); |
| +CREATE TABLE IF NOT EXISTS publications (id TEXT PRIMARY KEY, body TEXT NOT NULL, state TEXT NOT NULL, created_at TEXT NOT NULL); |
| +` |
| + |
| +// Upload and publication states. |
| +const ( |
| + relayPending = "pending" |
| + relaySent = "sent" |
| + relayIndexed = "indexed" |
| + relayReported = "reported" |
| + // relayUnpushed: reported, not pushed; its repository stays for a |
| + // republish of the same commit. |
| + relayUnpushed = "unpushed" |
| +) |
| + |
| +// AcceptChunk records one chunk exactly once; the caller acks after. |
| +func (s *State) AcceptChunk(ctx context.Context, frameID string, b wire.Blob) error { |
| + header, _ := json.Marshal(b.Transfer) |
| + data, err := base64.StdEncoding.DecodeString(b.Data) |
| + if err != nil { |
| + data = nil |
| + } |
| + return s.tx(ctx, func(t *sql.Tx) error { |
| + fresh, err := seen(t, frameID) |
| + if err != nil || !fresh || data == nil { |
| + return err |
| + } |
| + _, err = t.Exec("INSERT INTO chunks(transfer, idx, total, sha256, header, step_id, attempt, direction, data) VALUES(?,?,?,?,?,?,?,?,?) ON CONFLICT DO NOTHING", b.Transfer.ID, b.Index, b.Total, b.SHA256, string(header), b.Transfer.StepID, b.Transfer.Attempt, b.Transfer.Direction, data) |
| + return err |
| + }) |
| +} |
| + |
| +// AcceptUpload records a send_pack request exactly once. |
| +func (s *State) AcceptUpload(ctx context.Context, frameID string, c wire.SendPackCommand) error { |
| + raw, _ := json.Marshal(c) |
| + return s.tx(ctx, func(t *sql.Tx) error { |
| + fresh, err := seen(t, frameID) |
| + if err != nil || !fresh { |
| + return err |
| + } |
| + _, err = t.Exec("INSERT INTO uploads(transfer, body, state, created_at) VALUES(?,?,?,?) ON CONFLICT DO NOTHING", c.Transfer.ID, string(raw), relayPending, now()) |
| + return err |
| + }) |
| +} |
| + |
| +// AcceptPublish records a publish command exactly once. |
| +func (s *State) AcceptPublish(ctx context.Context, frameID string, c wire.PublishCommand) error { |
| + raw, _ := json.Marshal(c) |
| + return s.tx(ctx, func(t *sql.Tx) error { |
| + fresh, err := seen(t, frameID) |
| + if err != nil || !fresh { |
| + return err |
| + } |
| + _, err = t.Exec("INSERT INTO publications(id, body, state, created_at) VALUES(?,?,?,?) ON CONFLICT DO NOTHING", c.Publication, string(raw), relayPending, now()) |
| + return err |
| + }) |
| +} |
| + |
| +// ErrPackIncomplete means not every chunk of a transfer has arrived. |
| +var ErrPackIncomplete = errors.New("pack incomplete") |
| + |
| +// errPackRefused means the pack's chunks disagree or its digest is wrong. |
| +var errPackRefused = errors.New("pack refused") |
| + |
| +// pack reassembles a transfer's pack and checks its digest. want is the |
| +// header the receiver expects (its own step row): any other is refused. |
| +func (s *State) pack(ctx context.Context, want wire.TransferHeader) ([]byte, error) { |
| + rows, err := s.db.QueryContext(ctx, "SELECT idx, total, sha256, header, data FROM chunks WHERE transfer=? ORDER BY idx", want.ID) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var buf bytes.Buffer |
| + n, total, digest := 0, -1, "" |
| + for rows.Next() { |
| + var idx, tot int |
| + var sum, header string |
| + var data []byte |
| + if err := rows.Scan(&idx, &tot, &sum, &header, &data); err != nil { |
| + return nil, err |
| + } |
| + var h wire.TransferHeader |
| + if json.Unmarshal([]byte(header), &h) != nil || h != want { |
| + return nil, errPackRefused |
| + } |
| + if total == -1 { |
| + total, digest = tot, sum |
| + } |
| + if idx != n || tot != total || sum != digest || int64(buf.Len()+len(data)) > wire.MaxTransferBytes { |
| + return nil, errPackRefused |
| + } |
| + buf.Write(data) |
| + n++ |
| + } |
| + if err := rows.Err(); err != nil { |
| + return nil, err |
| + } |
| + if total < 1 || n != total { |
| + return nil, ErrPackIncomplete |
| + } |
| + got := sha256.Sum256(buf.Bytes()) |
| + if hex.EncodeToString(got[:]) != digest { |
| + return nil, errPackRefused |
| + } |
| + return buf.Bytes(), nil |
| +} |
| + |
| +// inboundHeader is the transfer header a worker's step expects, from the |
| +// chunks that name its attempt. |
| +func (s *State) inboundHeader(ctx context.Context, r stepRow) (wire.TransferHeader, bool, error) { |
| + var header string |
| + err := s.db.QueryRowContext(ctx, "SELECT header FROM chunks WHERE step_id=? AND attempt=? AND direction=? ORDER BY idx LIMIT 1", r.StepID, r.Attempt, wire.TransferInbound).Scan(&header) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return wire.TransferHeader{}, false, nil |
| + } |
| + if err != nil { |
| + return wire.TransferHeader{}, false, err |
| + } |
| + var h wire.TransferHeader |
| + return h, true, json.Unmarshal([]byte(header), &h) |
| +} |
| + |
| +// dropChunks forgets a transfer's chunks. |
| +func (s *State) dropChunks(ctx context.Context, transfer string) error { |
| + _, err := s.db.ExecContext(ctx, "DELETE FROM chunks WHERE transfer=?", transfer) |
| + return err |
| +} |
| + |
| +// dropStepChunks forgets every chunk of an attempt. |
| +func (s *State) dropStepChunks(ctx context.Context, step string, attempt int64) error { |
| + _, err := s.db.ExecContext(ctx, "DELETE FROM chunks WHERE step_id=? AND attempt=?", step, attempt) |
| + return err |
| +} |
| + |
| +// queueUpload puts a pack's chunks in the outbox and marks the upload |
| +// sent, in one transaction: resent until acked, never built twice. |
| +func (s *State) queueUpload(ctx context.Context, h wire.TransferHeader, pack []byte) error { |
| + sum := sha256.Sum256(pack) |
| + digest := hex.EncodeToString(sum[:]) |
| + total := (len(pack) + wire.MaxBlobChunk - 1) / wire.MaxBlobChunk |
| + if int64(len(pack)) > wire.MaxTransferBytes { |
| + // Too large to relay: one chunk says so (the instance refuses a |
| + // total past the bound and the checks end as not run). |
| + total = int(wire.MaxTransferBytes/wire.MaxBlobChunk) + 2 |
| + pack = pack[:wire.MaxBlobChunk] |
| + } |
| + return s.tx(ctx, func(t *sql.Tx) error { |
| + res, err := t.Exec("UPDATE uploads SET state=? WHERE transfer=? AND state=?", relaySent, h.ID, relayPending) |
| + if err != nil { |
| + return err |
| + } |
| + if n, _ := res.RowsAffected(); n != 1 { |
| + return nil |
| + } |
| + for i := 0; i*wire.MaxBlobChunk < len(pack); i++ { |
| + part := pack[i*wire.MaxBlobChunk : min(len(pack), (i+1)*wire.MaxBlobChunk)] |
| + if err := s.enqueue(t, wire.FrameBlob, "", wire.Blob{Transfer: h, Index: i, Total: total, SHA256: digest, Data: base64.StdEncoding.EncodeToString(part)}); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| + }) |
| +} |
| + |
| +func (s *State) pendingUploads(ctx context.Context) ([]wire.SendPackCommand, error) { |
| + return relayRows[wire.SendPackCommand](ctx, s, "SELECT body FROM uploads WHERE state=? ORDER BY created_at", relayPending) |
| +} |
| + |
| +func (s *State) openPublications(ctx context.Context) ([]pubRow, error) { |
| + rows, err := s.db.QueryContext(ctx, "SELECT body, state FROM publications WHERE state NOT IN (?,?) ORDER BY created_at", relayReported, relayUnpushed) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var out []pubRow |
| + for rows.Next() { |
| + var body string |
| + var p pubRow |
| + if err := rows.Scan(&body, &p.state); err != nil { |
| + return nil, err |
| + } |
| + if err := json.Unmarshal([]byte(body), &p.PublishCommand); err != nil { |
| + return nil, err |
| + } |
| + out = append(out, p) |
| + } |
| + return out, rows.Err() |
| +} |
| + |
| +type pubRow struct { |
| + wire.PublishCommand |
| + state string |
| +} |
| + |
| +func relayRows[T any](ctx context.Context, s *State, q string, args ...any) ([]T, error) { |
| + rows, err := s.db.QueryContext(ctx, q, args...) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var out []T |
| + for rows.Next() { |
| + var body string |
| + var v T |
| + if err := rows.Scan(&body); err != nil { |
| + return nil, err |
| + } |
| + if err := json.Unmarshal([]byte(body), &v); err != nil { |
| + return nil, err |
| + } |
| + out = append(out, v) |
| + } |
| + return out, rows.Err() |
| +} |
| + |
| +func (s *State) setPublication(ctx context.Context, id, state string) error { |
| + _, err := s.db.ExecContext(ctx, "UPDATE publications SET state=? WHERE id=?", state, id) |
| + return err |
| +} |
| + |
| +// reportPublished queues the published report and marks the publication |
| +// reported, in one transaction. |
| +func (s *State) reportPublished(ctx context.Context, rep wire.PublishedReport) error { |
| + return s.tx(ctx, func(t *sql.Tx) error { |
| + next := relayReported |
| + if !rep.Pushed { |
| + next = relayUnpushed |
| + } |
| + res, err := t.Exec("UPDATE publications SET state=? WHERE id=? AND state NOT IN (?,?)", next, rep.Publication, relayReported, relayUnpushed) |
| + if err != nil { |
| + return err |
| + } |
| + if n, _ := res.RowsAffected(); n != 1 { |
| + return nil |
| + } |
| + return s.enqueue(t, wire.FramePublished, "", rep) |
| + }) |
| +} |
| + |
| +// Relay uploads packs the instance asks for and publishes workers' |
| +// commits, one at a time, from the durable tables. It runs at start (a |
| +// restart picks up where a crash left off) and when a command arrives. |
| +type Relay struct { |
| + State *State |
| + Engine *Engineer |
| + Notify func() |
| + Logger *slog.Logger |
| + retry time.Duration |
| + once sync.Once |
| + wake chan struct{} |
| + stopped chan struct{} |
| +} |
| + |
| +func (x *Relay) init() { x.once.Do(func() { x.wake = make(chan struct{}, 1) }) } |
| + |
| +// Wake makes the relay look for work. |
| +func (x *Relay) Wake() { |
| + x.init() |
| + select { |
| + case x.wake <- struct{}{}: |
| + default: |
| + } |
| +} |
| + |
| +// Loop runs until ctx ends. |
| +func (x *Relay) Loop(ctx context.Context) { |
| + x.init() |
| + every := x.retry |
| + if every <= 0 { |
| + every = 10 * time.Second |
| + } |
| + tick := time.NewTicker(every) |
| + defer tick.Stop() |
| + for { |
| + x.Once(ctx) |
| + select { |
| + case <-ctx.Done(): |
| + return |
| + case <-x.wake: |
| + case <-tick.C: |
| + } |
| + } |
| +} |
| + |
| +// Once does what is pending now. |
| +func (x *Relay) Once(ctx context.Context) { |
| + ups, err := x.State.pendingUploads(ctx) |
| + x.log("relay uploads", err) |
| + for _, u := range ups { |
| + pack, err := x.Engine.packCandidate(ctx, u.Transfer) |
| + if err != nil { |
| + x.log("relay pack", err) |
| + continue |
| + } |
| + x.log("relay upload", x.State.queueUpload(ctx, u.Transfer, pack)) |
| + x.notify() |
| + } |
| + pubs, err := x.State.openPublications(ctx) |
| + x.log("relay publications", err) |
| + for _, p := range pubs { |
| + rep, done := x.Engine.publishWorker(ctx, p) |
| + if !done { |
| + continue |
| + } |
| + x.log("relay published", x.State.reportPublished(context.WithoutCancel(ctx), rep)) |
| + x.notify() |
| + } |
| +} |
| + |
| +func (x *Relay) notify() { |
| + if x.Notify != nil { |
| + x.Notify() |
| + } |
| +} |
| + |
| +func (x *Relay) log(msg string, err error) { |
| + if x.Logger != nil && err != nil { |
| + x.Logger.Warn(msg, "err", sanitize(err)) |
| + } |
| +} |
| + |
| +// packCandidate is the pack of exactly one commit (the commit, its tree |
| +// and blobs, no history) from the project clone. |
| +func (e *Engineer) packCandidate(ctx context.Context, h wire.TransferHeader) ([]byte, error) { |
| + if !repoKey.MatchString(h.Repo) || !shaPattern.MatchString(h.CandidateSHA) { |
| + return nil, errPackRefused |
| + } |
| + ctx, cancel := context.WithTimeout(ctx, prepTimeout) |
| + defer cancel() |
| + if err := e.fetch(ctx, h.Repo); err != nil { |
| + return nil, err |
| + } |
| + env := workspace.GitEnvironment() |
| + env["HOME"] = "/nonexistent" |
| + list := groupCommand(ctx, e.O.Runner.GitPath, "--git-dir="+e.Clones.Path(h.Repo), "rev-list", "--objects", "--no-walk", h.CandidateSHA) |
| + pack := groupCommand(ctx, e.O.Runner.GitPath, "--git-dir="+e.Clones.Path(h.Repo), "pack-objects", "--stdout", "-q") |
| + for k, v := range env { |
| + list.Env = append(list.Env, k+"="+v) |
| + pack.Env = append(pack.Env, k+"="+v) |
| + } |
| + objects, err := list.StdoutPipe() |
| + if err != nil { |
| + return nil, err |
| + } |
| + pack.Stdin = objects |
| + var out bytes.Buffer |
| + pack.Stdout = &limitWriter{w: &out, n: wire.MaxTransferBytes + 1} |
| + if err := list.Start(); err != nil { |
| + return nil, err |
| + } |
| + err = pack.Run() |
| + errList := list.Wait() |
| + if err := errors.Join(err, errList); err != nil { |
| + return nil, err |
| + } |
| + return out.Bytes(), nil |
| +} |
| + |
| +// limitWriter keeps at most n bytes and drops the rest (the caller sees |
| +// a pack past the bound by its length). |
| +type limitWriter struct { |
| + w io.Writer |
| + n int64 |
| +} |
| + |
| +func (l *limitWriter) Write(p []byte) (int, error) { |
| + if l.n <= 0 { |
| + return len(p), nil |
| + } |
| + k := min(int64(len(p)), l.n) |
| + if _, err := l.w.Write(p[:k]); err != nil { |
| + return 0, err |
| + } |
| + l.n -= k |
| + return len(p), nil |
| +} |
| + |
| +// relayFault, in tests, stops a publication at a named point ("indexed", |
| +// "pushed"), as a crash there would. |
| +var relayFault func(point string) bool |
| + |
| +// publishWorker publishes a worker's commit: its pack goes into a private |
| +// repository beside the clone, the commit must have the dispatched base |
| +// as its parent and a complete tree, the instance confirms the |
| +// publication right before the push, and forge pushes it with every check |
| +// it makes for the primary's own work (record, then reconcile, so a |
| +// repeat after a crash pushes nothing twice). done is false while it must |
| +// be tried again (chunks still arriving, no lease now). |
| +func (e *Engineer) publishWorker(ctx context.Context, p pubRow) (wire.PublishedReport, bool) { |
| + rep := wire.PublishedReport{Publication: p.Publication, TaskID: p.TaskID, StepID: p.StepID, Attempt: p.Attempt, CandidateSHA: p.CandidateSHA} |
| + fail := func(reason string) (wire.PublishedReport, bool) { |
| + rep.Pushed, rep.Reason = false, reason |
| + return rep, true |
| + } |
| + if !slices.Contains(e.Owners, p.Person) || !repoKey.MatchString(p.Repo) || !wire.ValidTaskBranch(p.Branch) || !shaPattern.MatchString(p.CandidateSHA) || !shaPattern.MatchString(p.BaseSHA) { |
| + return fail("policy_rejected") |
| + } |
| + dir := filepath.Join(e.root(), "worker-"+p.TaskID+"-"+p.StepID+"-"+itoa(p.Attempt)) |
| + if p.state != relayIndexed { |
| + pack, err := e.O.State.pack(ctx, wire.TransferHeader{ID: p.Transfer, Direction: wire.TransferOutbound, Repo: p.Repo, TaskID: p.TaskID, StepID: p.StepID, Attempt: p.Attempt, BaseSHA: p.BaseSHA, CandidateSHA: p.CandidateSHA}) |
| + switch { |
| + case errors.Is(err, ErrPackIncomplete): |
| + if _, statErr := os.Stat(dir); statErr != nil { |
| + return rep, false |
| + } |
| + // Indexed before (a republish): the chunks are gone. |
| + case err != nil: |
| + e.log("publication pack", err) |
| + return fail("candidate_unavailable") |
| + default: |
| + if err := e.indexWorkerPack(ctx, p, dir, pack); err != nil { |
| + e.log("publication index", err) |
| + return fail("candidate_unavailable") |
| + } |
| + } |
| + if err := e.O.State.setPublication(ctx, p.Publication, relayIndexed); err != nil { |
| + return rep, false |
| + } |
| + e.log("publication chunks", e.O.State.dropChunks(ctx, p.Transfer)) |
| + } |
| + if relayFault != nil && relayFault("indexed") { |
| + return rep, false |
| + } |
| + if err := e.verifyWorkerCommit(ctx, p, dir); err != nil { |
| + e.log("publication verify", err) |
| + return fail("candidate_unavailable") |
| + } |
| + def, err := e.Clones.DefaultBranch(ctx, p.Repo) |
| + if err != nil { |
| + // The hub is unreachable: a failed push, which Retry publishes again. |
| + e.log("publication default branch", err) |
| + return fail("push_failed") |
| + } |
| + // forge reports any failed confirmation as uncertain: remember why. |
| + var refused error |
| + confirm := func(ctx context.Context) error { |
| + if e.ConfirmPublication == nil { |
| + return nil |
| + } |
| + refused = e.ConfirmPublication(ctx, p.StepID, p.Attempt, p.Publication) |
| + return refused |
| + } |
| + err = forge.PushBranch(ctx, forge.BranchPush{Root: filepath.Join(e.root(), "publish"), Git: e.O.Runner.GitPath, GitDir: dir, Repo: p.Repo, Branch: p.Branch, Default: def, Base: p.BaseSHA, Commit: p.CandidateSHA, Key: p.TaskID + "/" + p.StepID + "/" + itoa(p.Attempt) + "/worker", Person: p.Person, Owners: e.Owners, |
| + Remote: func(ctx context.Context) (workspace.Remote, error) { return e.Forge.Remote(ctx, p.Repo) }, |
| + Confirm: confirm}) |
| + if relayFault != nil && relayFault("pushed") { |
| + return rep, false |
| + } |
| + switch { |
| + case err == nil: |
| + rep.Pushed = true |
| + return rep, true |
| + case errors.Is(refused, ErrWithdrawn): |
| + return fail("cancelled") |
| + case refused != nil: |
| + // No lease now (disconnected): try again later. |
| + return rep, false |
| + case errors.Is(err, forge.ErrPushConflict): |
| + return fail("push_conflict") |
| + default: |
| + e.log("publication push", err) |
| + return fail("push_failed") |
| + } |
| +} |
| + |
| +// indexWorkerPack makes a private repository that sees the clone's |
| +// objects (the base and its history) and indexes the worker's pack. |
| +func (e *Engineer) indexWorkerPack(ctx context.Context, p pubRow, dir string, pack []byte) error { |
| + if !e.hasCommit(ctx, p.Repo, p.BaseSHA) { |
| + if err := e.fetch(ctx, p.Repo); err != nil { |
| + return err |
| + } |
| + } |
| + git := func(stdin io.Reader, args ...string) error { |
| + cmd := exec.CommandContext(ctx, e.O.Runner.GitPath, append([]string{"--git-dir=" + dir}, args...)...) |
| + cmd.Stdin = stdin |
| + for k, v := range workspace.GitEnvironment() { |
| + cmd.Env = append(cmd.Env, k+"="+v) |
| + } |
| + cmd.Env = append(cmd.Env, "HOME=/nonexistent") |
| + return cmd.Run() |
| + } |
| + if err := os.MkdirAll(dir, 0700); err != nil { |
| + return err |
| + } |
| + if err := git(nil, "init", "-q", "--bare", "--template="); err != nil { |
| + return err |
| + } |
| + alt := filepath.Join(dir, "objects", "info", "alternates") |
| + if err := os.MkdirAll(filepath.Dir(alt), 0700); err != nil { |
| + return err |
| + } |
| + if err := os.WriteFile(alt, []byte(filepath.Join(e.Clones.Path(p.Repo), "objects")+"\n"), 0600); err != nil { |
| + return err |
| + } |
| + return git(bytes.NewReader(pack), "index-pack", "--stdin", "--fix-thin") |
| +} |
| + |
| +// hasCommit reports whether the project clone holds a commit. |
| +func (e *Engineer) hasCommit(ctx context.Context, repo, sha string) bool { |
| + cmd := exec.CommandContext(ctx, e.O.Runner.GitPath, "--git-dir="+e.Clones.Path(repo), "cat-file", "-e", sha+"^{commit}") |
| + for k, v := range workspace.GitEnvironment() { |
| + cmd.Env = append(cmd.Env, k+"="+v) |
| + } |
| + return cmd.Run() == nil |
| +} |
| + |
| +// verifyWorkerCommit: exactly the candidate, a commit whose one parent is |
| +// the dispatched base, with every object of its tree present. |
| +func (e *Engineer) verifyWorkerCommit(ctx context.Context, p pubRow, dir string) error { |
| + out := func(args ...string) (string, error) { |
| + cmd := exec.CommandContext(ctx, e.O.Runner.GitPath, append([]string{"--git-dir=" + dir}, args...)...) |
| + for k, v := range workspace.GitEnvironment() { |
| + cmd.Env = append(cmd.Env, k+"="+v) |
| + } |
| + cmd.Env = append(cmd.Env, "HOME=/nonexistent") |
| + raw, err := cmd.Output() |
| + return strings.TrimSpace(string(raw)), err |
| + } |
| + parents, err := out("rev-list", "--parents", "-n", "1", "--end-of-options", p.CandidateSHA) |
| + if err != nil { |
| + return err |
| + } |
| + if fields := strings.Fields(parents); len(fields) != 2 || fields[0] != p.CandidateSHA || fields[1] != p.BaseSHA { |
| + return errors.New("the worker's commit is not on the dispatched base") |
| + } |
| + _, err = out("rev-list", "--objects", "--no-walk", "--end-of-options", p.CandidateSHA) |
| + return err |
| +} |
| + |
| +// SweepPublications removes the private repositories of pushed |
| +// publications whose report the instance acked (an unpushed one keeps |
| +// its commit for Retry). |
| +func (e *Engineer) SweepPublications(ctx context.Context, s *State) { |
| + rows, err := s.db.QueryContext(ctx, "SELECT body FROM publications WHERE state=? AND NOT EXISTS (SELECT 1 FROM outbox WHERE kind=? AND acked=0 AND body LIKE '%' || publications.id || '%')", relayReported, wire.FramePublished) |
| + if err != nil { |
| + return |
| + } |
| + var keep []wire.PublishCommand |
| + for rows.Next() { |
| + var body string |
| + var p wire.PublishCommand |
| + if rows.Scan(&body) == nil && json.Unmarshal([]byte(body), &p) == nil { |
| + keep = append(keep, p) |
| + } |
| + } |
| + rows.Close() |
| + for _, p := range keep { |
| + _ = os.RemoveAll(filepath.Join(e.root(), "worker-"+p.TaskID+"-"+p.StepID+"-"+itoa(p.Attempt))) |
| + } |
| +} |
diff --git a/internal/runner/thin/relay_test.go b/internal/runner/thin/relay_test.go| new file mode 100644 |
| index 00000000..996591f1 |
| --- /dev/null |
| +++ b/internal/runner/thin/relay_test.go |
| @@ -0,0 +1,240 @@ |
| +package thin |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/workspace" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// pushForge is a bare remote on disk; fail makes the next pushes fail. |
| +type pushForge struct { |
| + Forge |
| + dir string |
| + fail int |
| +} |
| + |
| +func (f *pushForge) Remote(context.Context, string) (workspace.Remote, error) { |
| + if f.fail > 0 { |
| + f.fail-- |
| + return workspace.Remote{}, errors.New("hub unavailable") |
| + } |
| + return workspace.Remote{URL: f.dir}, nil |
| +} |
| + |
| +// relayRig: a remote with main at base, a worker's commit on base that |
| +// the remote has never seen (its one-commit pack), and a primary's |
| +// Engineer and Relay over local state. |
| +type relayRig struct { |
| + e *Engineer |
| + f *pushForge |
| + relay *Relay |
| + base, commit string |
| + pack []byte |
| + pushes string |
| + confirm error |
| +} |
| + |
| +const relayBranch = "equipo/tk1-swipe-back" |
| + |
| +func newRelayRig(t *testing.T) *relayRig { |
| + t.Helper() |
| + root := t.TempDir() |
| + seed := filepath.Join(root, "seed") |
| + gitOut(t, root, "init", "-q", "-b", "main", seed) |
| + os.WriteFile(filepath.Join(seed, "Swipe.swift"), []byte("let back = false\n"), 0644) |
| + gitOut(t, seed, "add", "-A") |
| + gitOut(t, seed, "commit", "-q", "-m", "base") |
| + base := gitOut(t, seed, "rev-parse", "HEAD") |
| + remote := filepath.Join(root, "remote.git") |
| + gitOut(t, root, "clone", "-q", "--bare", seed, remote) |
| + pushes := filepath.Join(root, "pushes") |
| + hook := filepath.Join(remote, "hooks", "post-receive") |
| + os.WriteFile(hook, []byte("#!/bin/sh\ncat >> "+pushes+"\n"), 0755) |
| + // The worker's commit, made elsewhere on the base. |
| + os.WriteFile(filepath.Join(seed, "Swipe.swift"), []byte("let back = true\n"), 0644) |
| + gitOut(t, seed, "commit", "-q", "-am", "swipe back") |
| + commit := gitOut(t, seed, "rev-parse", "HEAD") |
| + list := exec.Command("git", "-C", seed, "rev-list", "--objects", "--no-walk", commit) |
| + objects, _ := list.Output() |
| + packer := exec.Command("git", "-C", seed, "pack-objects", "--stdout", "-q") |
| + packer.Stdin = strings.NewReader(string(objects)) |
| + pack, err := packer.Output() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + os.MkdirAll(filepath.Join(root, "state"), 0700) |
| + os.MkdirAll(filepath.Join(root, "work"), 0700) |
| + s, err := OpenState(context.Background(), filepath.Join(root, "state")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { s.Close() }) |
| + f := &pushForge{dir: remote} |
| + r := &relayRig{f: f, base: base, commit: commit, pack: pack, pushes: pushes} |
| + e := &Engineer{Clones: &Clones{Root: filepath.Join(root, "work"), Git: "/usr/bin/git", Forge: f}, Forge: f, Owners: []string{"p@x"}, Host: "test"} |
| + e.O.Runner.GitPath, e.O.Runner.WorkspaceRoot, e.O.Runner.StateDir, e.O.State = "/usr/bin/git", filepath.Join(root, "work"), filepath.Join(root, "state"), s |
| + e.ConfirmPublication = func(context.Context, string, int64, string) error { return r.confirm } |
| + r.e, r.relay = e, &Relay{State: s, Engine: e} |
| + return r |
| +} |
| + |
| +func (r *relayRig) header() wire.TransferHeader { |
| + return wire.TransferHeader{ID: "tr_1", Direction: wire.TransferOutbound, Repo: "amadan.net/oficina/sample", TaskID: "tk1", StepID: "s1", Attempt: 1, BaseSHA: r.base, CandidateSHA: r.commit} |
| +} |
| + |
| +func (r *relayRig) receive(t *testing.T, pack []byte, h wire.TransferHeader) { |
| + t.Helper() |
| + sum := sha256.Sum256(pack) |
| + if err := r.e.O.State.AcceptChunk(context.Background(), "chunk-"+h.ID, wire.Blob{Transfer: h, Index: 0, Total: 1, SHA256: hex.EncodeToString(sum[:]), Data: base64.StdEncoding.EncodeToString(pack)}); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func (r *relayRig) publish(t *testing.T, id string) { |
| + t.Helper() |
| + h := r.header() |
| + if err := r.e.O.State.AcceptPublish(context.Background(), "pub-"+id, wire.PublishCommand{Publication: id, TaskID: h.TaskID, StepID: h.StepID, Attempt: h.Attempt, Repo: h.Repo, Branch: relayBranch, Person: "p@x", BaseSHA: r.base, CandidateSHA: r.commit, Transfer: h.ID}); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// reports are the published reports in the outbox. |
| +func (r *relayRig) reports(t *testing.T) []wire.PublishedReport { |
| + t.Helper() |
| + frames, _, err := r.e.O.State.Unacked(context.Background(), 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var out []wire.PublishedReport |
| + for _, f := range frames { |
| + if f.Type == wire.FramePublished { |
| + var p wire.PublishedReport |
| + json.Unmarshal(f.Data, &p) |
| + out = append(out, p) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +func (r *relayRig) pushCount() int { |
| + raw, _ := os.ReadFile(r.pushes) |
| + return strings.Count(string(raw), "refs/heads/"+relayBranch) |
| +} |
| + |
| +func (r *relayRig) head(t *testing.T) string { |
| + out, _ := exec.Command("git", "--git-dir="+r.f.dir, "rev-parse", "--verify", "--quiet", "refs/heads/"+relayBranch).Output() |
| + return strings.TrimSpace(string(out)) |
| +} |
| + |
| +// The primary publishes a worker's commit from its pack: indexed beside |
| +// the clone, the branch pushed at exactly the commit, then published. |
| +func TestRelayPublishesAWorkersCommit(t *testing.T) { |
| + r := newRelayRig(t) |
| + r.receive(t, r.pack, r.header()) |
| + r.publish(t, "pb_1") |
| + r.relay.Once(context.Background()) |
| + reps := r.reports(t) |
| + if len(reps) != 1 || !reps[0].Pushed || reps[0].CandidateSHA != r.commit || r.head(t) != r.commit || r.pushCount() != 1 { |
| + t.Fatalf("reports %+v head %s pushes %d", reps, r.head(t), r.pushCount()) |
| + } |
| + // Run again: nothing more. |
| + r.relay.Once(context.Background()) |
| + if len(r.reports(t)) != 1 || r.pushCount() != 1 { |
| + t.Fatal("published twice") |
| + } |
| +} |
| + |
| +// A failed push is reported (not pushed); Retry's new publication of the |
| +// same commit pushes it once, from the commit kept for it. |
| +func TestRelayRetryAfterPushFailure(t *testing.T) { |
| + r := newRelayRig(t) |
| + r.receive(t, r.pack, r.header()) |
| + r.publish(t, "pb_1") |
| + if err := r.e.Clones.Ensure(context.Background(), "amadan.net/oficina/sample"); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.f.fail = 10 |
| + r.relay.Once(context.Background()) |
| + reps := r.reports(t) |
| + if len(reps) != 1 || reps[0].Pushed || reps[0].Reason != "push_failed" || r.pushCount() != 0 { |
| + t.Fatalf("after a failed push %+v", reps) |
| + } |
| + r.f.fail = 0 |
| + r.publish(t, "pb_2") |
| + r.relay.Once(context.Background()) |
| + reps = r.reports(t) |
| + if len(reps) != 2 || !reps[1].Pushed || reps[1].Publication != "pb_2" || r.head(t) != r.commit || r.pushCount() != 1 { |
| + t.Fatalf("republish %+v pushes %d", reps, r.pushCount()) |
| + } |
| +} |
| + |
| +// SIGKILLed after indexing and before the push: restarted, it pushes |
| +// exactly once. SIGKILLed after the push and before published: restarted, |
| +// it reconciles from the remote and reports pushed without pushing again. |
| +func TestRelayCrashes(t *testing.T) { |
| + defer func() { relayFault = nil }() |
| + for _, point := range []string{"indexed", "pushed"} { |
| + t.Run(point, func(t *testing.T) { |
| + r := newRelayRig(t) |
| + r.receive(t, r.pack, r.header()) |
| + r.publish(t, "pb_1") |
| + relayFault = func(p string) bool { return p == point } |
| + r.relay.Once(context.Background()) |
| + relayFault = nil |
| + if len(r.reports(t)) != 0 { |
| + t.Fatal("reported before the crash point") |
| + } |
| + // A new process over the same state and directories. |
| + again := &Relay{State: r.e.O.State, Engine: r.e} |
| + again.Once(context.Background()) |
| + reps := r.reports(t) |
| + if len(reps) != 1 || !reps[0].Pushed || r.head(t) != r.commit || r.pushCount() != 1 { |
| + t.Fatalf("after restart %+v pushes %d", reps, r.pushCount()) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Cancel after the pack arrived and before the push: the instance refuses |
| +// the confirmation, nothing is pushed, the publication reports cancelled. |
| +func TestRelayCancelledBeforePush(t *testing.T) { |
| + r := newRelayRig(t) |
| + r.receive(t, r.pack, r.header()) |
| + r.publish(t, "pb_1") |
| + r.confirm = ErrWithdrawn |
| + r.relay.Once(context.Background()) |
| + reps := r.reports(t) |
| + if len(reps) != 1 || reps[0].Pushed || reps[0].Reason != "cancelled" || r.pushCount() != 0 || r.head(t) != "" { |
| + t.Fatalf("cancelled %+v pushes %d head %s", reps, r.pushCount(), r.head(t)) |
| + } |
| +} |
| + |
| +// A pack that is not the worker's commit on the dispatched base is never |
| +// pushed: another commit under the header, or a commit on another base. |
| +func TestRelayRefusesAWrongCommit(t *testing.T) { |
| + r := newRelayRig(t) |
| + // The transfer and the publication agree, but the commit's parent is |
| + // not the base they name. |
| + h := r.header() |
| + h.BaseSHA = strings.Repeat("e", 40) |
| + r.receive(t, r.pack, h) |
| + if err := r.e.O.State.AcceptPublish(context.Background(), "pub-x", wire.PublishCommand{Publication: "pb_x", TaskID: "tk1", StepID: "s1", Attempt: 1, Repo: h.Repo, Branch: relayBranch, Person: "p@x", BaseSHA: h.BaseSHA, CandidateSHA: r.commit, Transfer: "tr_1"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.relay.Once(context.Background()) |
| + reps := r.reports(t) |
| + if len(reps) != 1 || reps[0].Pushed || reps[0].Reason != "candidate_unavailable" || r.pushCount() != 0 { |
| + t.Fatalf("wrong commit %+v", reps) |
| + } |
| +} |
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go| index c9824685..cd69dbe9 100644 |
| --- a/internal/runner/thin/run.go |
| +++ b/internal/runner/thin/run.go |
| @@ -55,11 +55,15 @@ type Options struct { |
| // Protocol caps the runner stream protocol offered (tests: 1 acts as |
| // a slice 4 runner); 0 is the current one. |
| Protocol int |
| + // FakePlatform (EQUIPO_FAKE_PLATFORM=darwin/arm64) starts the test |
| + // build's fake Mac worker; any other build refuses it. FakeBin is put |
| + // first on its gates' PATH (the fake xcodebuild). |
| + FakePlatform, FakeBin string |
| } |
| // OptionsFromEnv reads the runner's optional thin settings. |
| func OptionsFromEnv(getenv func(string) string) Options { |
| - return Options{NoCreate: getenv("EQUIPO_RUNNER_CREATE_REPOS") == "0", Home: getenv("EQUIPO_RUNNER_HOME_NAMESPACE"), NoMoveIn: getenv("EQUIPO_RUNNER_MOVE_IN") == "0", IndexPace: 4 * time.Second} |
| + return Options{FakePlatform: getenv("EQUIPO_FAKE_PLATFORM"), FakeBin: getenv("EQUIPO_FAKE_BIN"), NoCreate: getenv("EQUIPO_RUNNER_CREATE_REPOS") == "0", Home: getenv("EQUIPO_RUNNER_HOME_NAMESPACE"), NoMoveIn: getenv("EQUIPO_RUNNER_MOVE_IN") == "0", IndexPace: 4 * time.Second} |
| } |
| // SessionRoot is where durable coordinator transcripts live by default: |
| @@ -71,6 +75,19 @@ func Run(ctx context.Context, c runner.Config, o Options) error { |
| if err := c.Validate(); err != nil { |
| return err |
| } |
| + if o.FakePlatform != "" { |
| + if fake == nil { |
| + return ErrNotTestBuild |
| + } |
| + platform, ok := fake.platform(o.FakePlatform) |
| + if !ok { |
| + return ErrNotTestBuild |
| + } |
| + if o.Logger != nil { |
| + o.Logger.Warn("test build: the fake Mac worker runs checks in a process group without a sandbox", "build", fake.marker()) |
| + } |
| + return runWorker(ctx, c, o, platform, fake.capabilities, fake.gate(o.FakeBin)) |
| + } |
| // Ownership first: the state lock, then the scratch and workspace |
| // roots. Only then may recovery touch namespaces or scratch. |
| var manager *containment.Manager |
| @@ -186,7 +203,7 @@ func Run(ctx context.Context, c runner.Config, o Options) error { |
| if err = engine.Start(ctx); err != nil { |
| return err |
| } |
| - engineer := &Engineer{O: o.Claude, Clones: clones, Forge: fg, Authorize: link.Confirm, Owners: coordinatorPersons(c)(), MaxStep: o.MaxStep, Note: o.StepNote, Healthy: health.ok, Delta: link.Delta, Activity: link.Activity, Retention: o.KeptRetention, Host: c.MachineLabel} |
| + engineer := &Engineer{O: o.Claude, Clones: clones, Forge: fg, Authorize: link.Confirm, AuthorizeStep: link.ConfirmStep, ConfirmPublication: link.ConfirmPublication, Owners: coordinatorPersons(c)(), MaxStep: o.MaxStep, Note: o.StepNote, Healthy: health.ok, Delta: link.Delta, Activity: link.Activity, Retention: o.KeptRetention, Host: c.MachineLabel} |
| link.Forget = engineer.RemoveKept |
| merges := &MergeWatch{State: state, Clones: clones, Git: c.GitPath, Notify: link.Notify, Logger: o.Logger, Every: o.MergeEvery} |
| if merges.Every <= 0 { |
| @@ -197,8 +214,16 @@ func Run(ctx context.Context, c runner.Config, o Options) error { |
| if engineer.MaxStep == 0 { |
| engineer.MaxStep = DefaultMaxStep |
| } |
| - steps := &StepEngine{State: state, Exec: engineer.Exec, Ask: engineer.ask, Notify: link.Notify, Logger: o.Logger, Sweep: func(ctx context.Context) { engineer.Sweep(ctx, state); engineer.sweepKept(ctx, state) }, Verify: func(ctx context.Context, id string) bool { return verifiedExit(ctx, manager, id) }} |
| + tags := func() []string { return caps.Get(ctx).Tags } |
| + steps := &StepEngine{State: state, Exec: placementGuard(tags, caps.Stale, engineer.Exec), Ask: engineer.ask, Notify: link.Notify, Logger: o.Logger, Sweep: func(ctx context.Context) { |
| + engineer.Sweep(ctx, state) |
| + engineer.sweepKept(ctx, state) |
| + engineer.SweepPublications(ctx, state) |
| + }, Verify: func(ctx context.Context, id string) bool { return verifiedExit(ctx, manager, id) }} |
| link.Steps = steps |
| + relay := &Relay{State: state, Engine: engineer, Notify: link.Notify, Logger: o.Logger} |
| + link.Relay = relay |
| + go relay.Loop(ctx) |
| if err = steps.Start(ctx); err != nil { |
| return err |
| } |
| @@ -467,3 +492,63 @@ func verifiedExit(ctx context.Context, m *containment.Manager, id string) bool { |
| } |
| return true |
| } |
| + |
| +// ErrNotTestBuild refuses EQUIPO_FAKE_PLATFORM outside the test build: |
| +// no release binary runs the unsandboxed fake worker. |
| +var ErrNotTestBuild = errors.New("EQUIPO_FAKE_PLATFORM: this runner is not a test build") |
| + |
| +// runWorker serves the instance as a worker: it runs the steps placed on |
| +// it and nothing else (no coordinator, no clone, no forge credential). |
| +func runWorker(ctx context.Context, c runner.Config, o Options, platform wire.Platform, probe func(context.Context) wire.Capabilities, gate GateRunner) error { |
| + release, err := startup(ctx, c, func(context.Context) error { return nil }) |
| + if err != nil { |
| + return err |
| + } |
| + defer release() |
| + creds, err := runner.ReadCredentials(filepath.Join(c.StateDir, "credentials.json")) |
| + if err != nil { |
| + return err |
| + } |
| + state, err := OpenState(ctx, c.StateDir) |
| + if err != nil { |
| + return err |
| + } |
| + defer state.Close() |
| + ctx, cancel := context.WithCancel(ctx) |
| + defer cancel() |
| + caps := &Capabilities{Probe: probe} |
| + link := &Link{Origin: c.Origin, Token: creds.Bearer.Token, State: state, Logger: o.Logger, Connected: o.Connected, Protocol: o.Protocol, WorkerOnly: true} |
| + link.Hello = func() wire.Hello { |
| + report := caps.Get(ctx) |
| + return wire.Hello{Repos: []string{}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Accounts: []wire.Account{}, Versions: map[string]string{"runner": o.Version}, Platform: &platform, Label: c.MachineLabel, Sandbox: gate.Sandbox(), Capabilities: &report} |
| + } |
| + engineer := &Engineer{O: o.Claude, Authorize: link.Confirm, AuthorizeStep: link.ConfirmStep, Owners: coordinatorPersons(c)(), MaxStep: o.MaxStep, Host: c.MachineLabel} |
| + engineer.O.Runner, engineer.O.State, engineer.O.Logger = c, state, o.Logger |
| + worker := &Worker{State: state, Engine: engineer, Gate: gate, MaxStep: o.MaxStep} |
| + tags := func() []string { return caps.Get(ctx).Tags } |
| + steps := &StepEngine{State: state, Exec: placementGuard(tags, caps.Stale, worker.Exec), Notify: link.Notify, Logger: o.Logger, |
| + Sweep: func(ctx context.Context) { |
| + keys, err := state.finishedSteps(ctx) |
| + if err == nil { |
| + for _, r := range keys { |
| + _ = os.RemoveAll(filepath.Join(worker.root(), "steps", stepKey(r))) |
| + } |
| + } |
| + }, |
| + Verify: func(_ context.Context, id string) bool { return id == "" || gate.Verify(id) }} |
| + link.Steps = steps |
| + if err := steps.Start(ctx); err != nil { |
| + return err |
| + } |
| + err = link.Run(ctx) |
| + cancel() |
| + steps.Wait() |
| + if errors.Is(err, ErrSuperseded) { |
| + _ = state.Supersede(context.Background()) |
| + return err |
| + } |
| + if ctx.Err() != nil && !errors.Is(err, ErrRevoked) { |
| + return nil |
| + } |
| + return err |
| +} |
diff --git a/internal/runner/thin/state.go b/internal/runner/thin/state.go| index 8d3825ab..41be0b69 100644 |
| --- a/internal/runner/thin/state.go |
| +++ b/internal/runner/thin/state.go |
| @@ -54,7 +54,7 @@ func OpenState(ctx context.Context, dir string) (*State, error) { |
| return nil, err |
| } |
| d.SetMaxOpenConns(1) |
| - if _, err = d.ExecContext(ctx, schema+stepSchema+watchSchema+askSchema); err != nil { |
| + if _, err = d.ExecContext(ctx, schema+stepSchema+watchSchema+askSchema+relaySchema); err != nil { |
| d.Close() |
| return nil, err |
| } |
diff --git a/internal/runner/thin/worker.go b/internal/runner/thin/worker.go| new file mode 100644 |
| index 00000000..c9d12b9d |
| --- /dev/null |
| +++ b/internal/runner/thin/worker.go |
| @@ -0,0 +1,245 @@ |
| +package thin |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "io" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/workspace" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// A worker runs the steps placed on it (Mac runners spec §1.4): in this |
| +// release, checks of a candidate the primary relays as a pack. It holds |
| +// no clone and no forge credential. How a gate is confined is the gate |
| +// runner's business: Seatbelt through srt on a Mac (slice D); the test |
| +// build's fake worker runs it in a bare process group. |
| + |
| +// GateRunner runs one checks gate and proves its end. |
| +type GateRunner interface { |
| + // Sandbox is what the runner reports in hello (wire.Sandbox*). |
| + Sandbox() string |
| + // Run runs argv in dir. record is called with the attempt's process |
| + // record before it runs (so a restart can verify its end). |
| + Run(ctx context.Context, attempt, dir string, argv []string, limit time.Duration, record func(id string)) gateResult |
| + // Verify reports whether a recorded attempt has ended for sure. |
| + Verify(id string) bool |
| +} |
| + |
| +// placementGuard refuses a dispatch whose needs this runner lacks |
| +// (placement_refused, nothing run) and marks its capability report stale, |
| +// so the next heartbeat says what it can do now. |
| +func placementGuard(tags func() []string, stale func(), inner StepFunc) StepFunc { |
| + return func(ctx context.Context, r stepRow, progress func(wire.StepReport)) wire.StepReport { |
| + if len(r.Needs) > 0 && !wire.Covers(tags(), r.Needs) { |
| + if stale != nil { |
| + stale() |
| + } |
| + return wire.StepReport{TaskID: r.TaskID, StepID: r.StepID, Attempt: r.Attempt, State: wire.StepFailed, Reason: "placement_refused", Termination: true, Findings: []wire.Finding{}} |
| + } |
| + return inner(ctx, r, progress) |
| + } |
| +} |
| + |
| +// Worker executes checks placed on a worker. |
| +type Worker struct { |
| + State *State |
| + // Engine supplies the git helpers (its O.Runner.GitPath and state). |
| + Engine *Engineer |
| + Gate GateRunner |
| + // PackWait bounds the wait for the relayed candidate (default 10 |
| + // minutes); MaxStep bounds the gate. |
| + PackWait time.Duration |
| + MaxStep time.Duration |
| +} |
| + |
| +func (w *Worker) root() string { return filepath.Join(w.Engine.O.Runner.StateDir, "worker") } |
| + |
| +// objects is the worker's object store for a repository: relayed packs |
| +// stay there, so a repository's objects move once. |
| +func (w *Worker) objects(repo string) string { |
| + return filepath.Join(w.root(), "objects", strings.NewReplacer("/", "_", ".", "_").Replace(repo)+".git") |
| +} |
| + |
| +// Exec runs one attempt placed on this worker. |
| +func (w *Worker) Exec(ctx context.Context, r stepRow, progress func(wire.StepReport)) wire.StepReport { |
| + rep := judgeReport(r) |
| + rep.Findings = []wire.Finding{} |
| + end := func(state, reason string) wire.StepReport { |
| + rep.State, rep.Reason, rep.Termination = state, reason, true |
| + return rep |
| + } |
| + if r.Specialist != wire.SpecialistChecks || !repoKey.MatchString(r.Repo) || !shaPattern.MatchString(r.CandidateSHA) { |
| + // Only checks are placed on workers until slice F. |
| + return end(wire.StepFailed, "placement_refused") |
| + } |
| + if err := w.Engine.lease(ctx, r); err != nil { |
| + return end(wire.StepCancelled, leaseReason(err)) |
| + } |
| + defer func() { _ = w.State.dropStepChunks(context.WithoutCancel(ctx), r.StepID, r.Attempt) }() |
| + pack, err := w.awaitPack(ctx, r) |
| + switch { |
| + case ctx.Err() != nil: |
| + return end(wire.StepCancelled, "cancelled") |
| + case err != nil: |
| + w.Engine.log("worker pack", err) |
| + return end(wire.StepFailed, "candidate_unavailable") |
| + } |
| + store := w.objects(r.Repo) |
| + if err := w.index(ctx, store, pack, r.CandidateSHA); err != nil { |
| + w.Engine.log("worker index", err) |
| + return end(wire.StepFailed, "candidate_unavailable") |
| + } |
| + rep.Have = []string{r.CandidateSHA} |
| + dir := filepath.Join(w.root(), "steps", stepKey(r)) |
| + defer os.RemoveAll(dir) |
| + 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) |
| + return end(wire.StepFailed, "workspace_refused") |
| + } |
| + progress(rep) |
| + g, ok := findGate(tree.Dir) |
| + if !ok { |
| + rep.LogTail = "No checks found: no .amadan/ci.d, .amadan/ci or make ci target." |
| + rep.Checks = wire.ChecksNone |
| + return end(wire.StepDone, "") |
| + } |
| + if err := w.Engine.checkRepository(ctx, tree, r.CandidateSHA); err != nil { |
| + w.Engine.log("worker checks repository", err) |
| + return end(wire.StepFailed, "workspace_refused") |
| + } |
| + limit := w.MaxStep |
| + if limit <= 0 { |
| + limit = DefaultMaxStep |
| + } |
| + res := w.Gate.Run(ctx, "checks/"+stepKey(r), tree.Dir, g.argv, limit, func(id string) { |
| + _ = w.State.setStepNamespace(context.WithoutCancel(ctx), r, id) |
| + }) |
| + rep.TerminationKind = wire.TerminationProcessGroup |
| + rep.Gate, rep.Output, rep.LogTail = g.name, res.output, lastLines(res.output, stepTailLines, wire.MaxLogTail) |
| + if !res.terminated { |
| + rep.State, rep.Reason, rep.Termination = wire.StepFailed, firstNonEmpty(res.reason, "provider_failed"), false |
| + return rep |
| + } |
| + if ctx.Err() != nil { |
| + return end(wire.StepCancelled, "cancelled") |
| + } |
| + done := func(outcome, reason string) wire.StepReport { |
| + rep.Checks = outcome |
| + return end(wire.StepDone, reason) |
| + } |
| + switch { |
| + case res.reason == "checks_timeout": |
| + rep.Gate = "" |
| + return done(wire.ChecksCannotRun, "checks_timeout") |
| + case res.reason != "": |
| + rep.Gate, rep.Output = "", "" |
| + return done(wire.ChecksCannotRun, "checks_unavailable") |
| + case res.code != 0 && offline.MatchString(res.output): |
| + rep.Gate = "" |
| + return done(wire.ChecksCannotRun, "needs_network") |
| + } |
| + code := res.code |
| + rep.ExitCode = &code |
| + if code == 0 { |
| + return done(wire.ChecksPassed, "") |
| + } |
| + return done(wire.ChecksFailed, "") |
| +} |
| + |
| +// awaitPack waits for every chunk of the attempt's inbound transfer and |
| +// checks its header against the step row before reassembling it. |
| +func (w *Worker) awaitPack(ctx context.Context, r stepRow) ([]byte, error) { |
| + wait := w.PackWait |
| + if wait <= 0 { |
| + wait = 10 * time.Minute |
| + } |
| + deadline := time.Now().Add(wait) |
| + for { |
| + h, ok, err := w.State.inboundHeader(ctx, r) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if ok { |
| + want := wire.TransferHeader{ID: h.ID, Direction: wire.TransferInbound, Repo: r.Repo, TaskID: r.TaskID, StepID: r.StepID, Attempt: r.Attempt, BaseSHA: r.BaseSHA, CandidateSHA: r.CandidateSHA} |
| + if h != want { |
| + return nil, errPackRefused |
| + } |
| + pack, err := w.State.pack(ctx, want) |
| + if !errors.Is(err, ErrPackIncomplete) { |
| + return pack, err |
| + } |
| + } |
| + if time.Now().After(deadline) { |
| + return nil, ErrPackIncomplete |
| + } |
| + select { |
| + case <-ctx.Done(): |
| + return nil, ctx.Err() |
| + case <-time.After(200 * time.Millisecond): |
| + } |
| + } |
| +} |
| + |
| +func (w *Worker) git(ctx context.Context, stdin io.Reader, args ...string) (string, error) { |
| + cmd := exec.CommandContext(ctx, w.Engine.O.Runner.GitPath, args...) |
| + cmd.Stdin = stdin |
| + for k, v := range workspace.GitEnvironment() { |
| + cmd.Env = append(cmd.Env, k+"="+v) |
| + } |
| + cmd.Env = append(cmd.Env, "HOME=/nonexistent") |
| + out, err := cmd.Output() |
| + return strings.TrimSpace(string(out)), err |
| +} |
| + |
| +// index adds the pack to the repository's store and requires that it |
| +// yields exactly the candidate, a commit whose whole tree is present. |
| +func (w *Worker) index(ctx context.Context, store string, pack []byte, sha string) error { |
| + if _, err := os.Stat(store); err != nil { |
| + if err := os.MkdirAll(store, 0700); err != nil { |
| + return err |
| + } |
| + if _, err := w.git(ctx, nil, "init", "-q", "--bare", "--template=", "--object-format="+map[bool]string{true: "sha256", false: "sha1"}[len(sha) == 64], store); err != nil { |
| + return err |
| + } |
| + } |
| + if _, err := w.git(ctx, strings.NewReader(string(pack)), "--git-dir="+store, "index-pack", "--stdin"); err != nil { |
| + return err |
| + } |
| + if kind, err := w.git(ctx, nil, "--git-dir="+store, "cat-file", "-t", "--end-of-options", sha); err != nil || kind != "commit" { |
| + return errors.New("the pack does not hold the candidate") |
| + } |
| + _, err := w.git(ctx, nil, "--git-dir="+store, "rev-list", "--objects", "--no-walk", "--end-of-options", sha) |
| + return err |
| +} |
| + |
| +// checkout writes the candidate's tree into a fresh directory. |
| +func (w *Worker) checkout(ctx context.Context, t workspace.TaskTree, sha string) error { |
| + if err := os.MkdirAll(t.Dir, 0700); err != nil { |
| + return err |
| + } |
| + index := filepath.Join(filepath.Dir(t.Dir), "index") |
| + env := []string{"GIT_INDEX_FILE=" + index} |
| + run := func(args ...string) error { |
| + cmd := exec.CommandContext(ctx, w.Engine.O.Runner.GitPath, append([]string{"--git-dir=" + t.GitDir, "--work-tree=" + t.Dir}, args...)...) |
| + for k, v := range workspace.GitEnvironment() { |
| + cmd.Env = append(cmd.Env, k+"="+v) |
| + } |
| + cmd.Env = append(cmd.Env, append(env, "HOME=/nonexistent")...) |
| + cmd.Dir = t.Dir |
| + return cmd.Run() |
| + } |
| + if err := run("read-tree", "--end-of-options", sha); err != nil { |
| + return err |
| + } |
| + if err := run("checkout-index", "-a", "-f"); err != nil { |
| + return err |
| + } |
| + return os.Remove(index) |
| +} |
diff --git a/internal/runner/thin/worker_test.go b/internal/runner/thin/worker_test.go| new file mode 100644 |
| index 00000000..83e07626 |
| --- /dev/null |
| +++ b/internal/runner/thin/worker_test.go |
| @@ -0,0 +1,184 @@ |
| +package thin |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// stubGate records what it was asked to run and answers code. |
| +type stubGate struct { |
| + ran [][]string |
| + dirs []string |
| + code int |
| +} |
| + |
| +func (g *stubGate) Sandbox() string { return wire.SandboxNone } |
| +func (g *stubGate) Run(_ context.Context, _, dir string, argv []string, _ time.Duration, record func(string)) gateResult { |
| + g.ran = append(g.ran, argv) |
| + g.dirs = append(g.dirs, dir) |
| + record("pg:1:stub") |
| + head, _ := os.ReadFile(filepath.Join(dir, "Swipe.swift")) |
| + return gateResult{code: g.code, terminated: true, output: "ran on " + strings.TrimSpace(string(head))} |
| +} |
| +func (g *stubGate) Verify(string) bool { return true } |
| + |
| +type workerRig struct { |
| + w *Worker |
| + gate *stubGate |
| + r stepRow |
| + base, commit string |
| + pack, other []byte |
| +} |
| + |
| +func onePack(t *testing.T, dir, sha string) []byte { |
| + t.Helper() |
| + objects, err := exec.Command("git", "-C", dir, "rev-list", "--objects", "--no-walk", sha).Output() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + packer := exec.Command("git", "-C", dir, "pack-objects", "--stdout", "-q") |
| + packer.Stdin = strings.NewReader(string(objects)) |
| + pack, err := packer.Output() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return pack |
| +} |
| + |
| +func newWorkerRig(t *testing.T) *workerRig { |
| + t.Helper() |
| + root := t.TempDir() |
| + seed := filepath.Join(root, "seed") |
| + gitOut(t, root, "init", "-q", "-b", "main", seed) |
| + os.MkdirAll(filepath.Join(seed, ".amadan"), 0755) |
| + os.WriteFile(filepath.Join(seed, ".amadan", "ci"), []byte("#!/bin/sh\nxcodebuild test\n"), 0755) |
| + os.WriteFile(filepath.Join(seed, "Swipe.swift"), []byte("let back = false\n"), 0644) |
| + gitOut(t, seed, "add", "-A") |
| + gitOut(t, seed, "commit", "-q", "-m", "base") |
| + base := gitOut(t, seed, "rev-parse", "HEAD") |
| + os.WriteFile(filepath.Join(seed, "Swipe.swift"), []byte("let back = true\n"), 0644) |
| + gitOut(t, seed, "commit", "-q", "-am", "swipe") |
| + commit := gitOut(t, seed, "rev-parse", "HEAD") |
| + state := filepath.Join(root, "state") |
| + os.MkdirAll(state, 0700) |
| + s, err := OpenState(context.Background(), state) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { s.Close() }) |
| + e := &Engineer{} |
| + e.O.Runner.GitPath, e.O.Runner.StateDir, e.O.State = "/usr/bin/git", state, s |
| + g := &stubGate{} |
| + r := stepRow{DispatchCommand: wire.DispatchCommand{Person: "p@x", TaskID: "tk1", StepID: "s2", Attempt: 1, Specialist: wire.SpecialistChecks, Repo: "amadan.net/woodstar/woodstar", Branch: "equipo/tk1-swipe", BaseSHA: base, CandidateSHA: commit, Needs: []string{wire.TagMacOS, wire.TagXcode}}} |
| + return &workerRig{w: &Worker{State: s, Engine: e, Gate: g, PackWait: 300 * time.Millisecond}, gate: g, r: r, base: base, commit: commit, pack: onePack(t, seed, commit), other: onePack(t, seed, base)} |
| +} |
| + |
| +func (x *workerRig) header() wire.TransferHeader { |
| + return wire.TransferHeader{ID: "tr_1", Direction: wire.TransferInbound, Repo: x.r.Repo, TaskID: x.r.TaskID, StepID: x.r.StepID, Attempt: x.r.Attempt, BaseSHA: x.r.BaseSHA, CandidateSHA: x.r.CandidateSHA} |
| +} |
| + |
| +func (x *workerRig) chunk(t *testing.T, id string, h wire.TransferHeader, data []byte, index, total int, digest string) { |
| + t.Helper() |
| + if digest == "" { |
| + sum := sha256.Sum256(data) |
| + digest = hex.EncodeToString(sum[:]) |
| + } |
| + if err := x.w.State.AcceptChunk(context.Background(), id, wire.Blob{Transfer: h, Index: index, Total: total, SHA256: digest, Data: base64.StdEncoding.EncodeToString(data)}); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func (x *workerRig) run() wire.StepReport { |
| + return x.w.Exec(context.Background(), x.r, func(wire.StepReport) {}) |
| +} |
| + |
| +// The relayed candidate is checked out at exactly its SHA and the gate |
| +// runs there; the report proves termination by process group and says |
| +// the worker now holds the commit. |
| +func TestWorkerRunsChecksOnTheRelayedCandidate(t *testing.T) { |
| + x := newWorkerRig(t) |
| + x.chunk(t, "c1", x.header(), x.pack, 0, 1, "") |
| + rep := x.run() |
| + if rep.State != wire.StepDone || rep.Checks != wire.ChecksPassed || rep.Gate != ".amadan/ci" || rep.ExitCode == nil || *rep.ExitCode != 0 || !rep.Termination || rep.TerminationKind != wire.TerminationProcessGroup || len(rep.Have) != 1 || rep.Have[0] != x.commit { |
| + t.Fatalf("report %+v", rep) |
| + } |
| + if len(x.gate.ran) != 1 || !strings.Contains(rep.Output, "let back = true") { |
| + t.Fatalf("gate %v output %q", x.gate.ran, rep.Output) |
| + } |
| + if _, err := os.Stat(x.gate.dirs[0]); !os.IsNotExist(err) { |
| + t.Fatal("the checks tree was kept") |
| + } |
| + x.gate.code = 65 |
| + x.r.Attempt = 2 |
| + h := x.header() |
| + h.ID = "tr_2" |
| + x.chunk(t, "c2", h, x.pack, 0, 1, "") |
| + if rep = x.run(); rep.State != wire.StepDone || rep.Checks != wire.ChecksFailed || *rep.ExitCode != 65 { |
| + t.Fatalf("failing gate %+v", rep) |
| + } |
| +} |
| + |
| +// M7 at the receiver: a pack whose digest is wrong, a pack that does not |
| +// hold the dispatched SHA, chunks under another task's header, and a |
| +// missing chunk are all refused before the gate runs. |
| +func TestWorkerRefusesTamperedPacks(t *testing.T) { |
| + for name, feed := range map[string]func(*testing.T, *workerRig){ |
| + "bad sha256": func(t *testing.T, x *workerRig) { |
| + x.chunk(t, "c1", x.header(), x.pack, 0, 1, strings.Repeat("0", 64)) |
| + }, |
| + "wrong SHA": func(t *testing.T, x *workerRig) { x.chunk(t, "c1", x.header(), x.other, 0, 1, "") }, |
| + "another task's header": func(t *testing.T, x *workerRig) { |
| + h := x.header() |
| + h.TaskID = "tkother" |
| + x.chunk(t, "c1", h, x.pack, 0, 1, "") |
| + }, |
| + "missing chunk": func(t *testing.T, x *workerRig) { |
| + half := len(x.pack) / 2 |
| + sum := sha256.Sum256(x.pack) |
| + x.chunk(t, "c1", x.header(), x.pack[:half], 0, 2, hex.EncodeToString(sum[:])) |
| + }, |
| + "bytes changed": func(t *testing.T, x *workerRig) { |
| + bad := append([]byte{}, x.pack...) |
| + bad[len(bad)/2] ^= 0xff |
| + sum := sha256.Sum256(x.pack) |
| + x.chunk(t, "c1", x.header(), bad, 0, 1, hex.EncodeToString(sum[:])) |
| + }, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + x := newWorkerRig(t) |
| + feed(t, x) |
| + rep := x.run() |
| + if rep.State != wire.StepFailed || rep.Reason != "candidate_unavailable" || !rep.Termination || len(x.gate.ran) != 0 { |
| + t.Fatalf("%s: %+v gate %v", name, rep, x.gate.ran) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// A withdrawn attempt never runs: the start authorization is refused and |
| +// it ends cancelled (withdrawn) with nothing run. A dispatch whose needs |
| +// the runner lacks is refused (placement_refused) and marks the |
| +// capability report stale. |
| +func TestWorkerStartAndPlacement(t *testing.T) { |
| + x := newWorkerRig(t) |
| + x.chunk(t, "c1", x.header(), x.pack, 0, 1, "") |
| + x.w.Engine.AuthorizeStep = func(context.Context, string, int64) error { return ErrWithdrawn } |
| + if rep := x.run(); rep.State != wire.StepCancelled || rep.Reason != "withdrawn" || !rep.Termination || len(x.gate.ran) != 0 { |
| + t.Fatalf("withdrawn %+v", rep) |
| + } |
| + stale := false |
| + guard := placementGuard(func() []string { return []string{wire.TagLinux} }, func() { stale = true }, x.w.Exec) |
| + if rep := guard(context.Background(), x.r, func(wire.StepReport) {}); rep.State != wire.StepFailed || rep.Reason != "placement_refused" || !rep.Termination || !stale || len(x.gate.ran) != 0 { |
| + t.Fatalf("placement %+v stale %v", rep, stale) |
| + } |
| +} |
diff --git a/scripts/no-fake-worker.sh b/scripts/no-fake-worker.sh| new file mode 100755 |
| index 00000000..b968e4fd |
| --- /dev/null |
| +++ b/scripts/no-fake-worker.sh |
| @@ -0,0 +1,9 @@ |
| +#!/bin/sh |
| +# Refuse a runner binary that contains the test build's fake Mac worker, |
| +# which runs checks without a sandbox (internal/runner/thin |
| +# fakeworker_testbuild.go). Release builds never pass -tags testbuild. |
| +set -eu |
| +if grep -q 'equipo-fake-worker-unsandboxed-process-group' "$1"; then |
| + echo "refusing $1: it contains the test build's fake worker" >&2 |
| + exit 1 |
| +fi |