package thintest import ( "fmt" "slices" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo/chat" "amadan.net/oficina/equipo/internal/wire" ) // Mac Engineering (Mac runners slice F, plan task 3): Engineering for a // repository whose gate needs Xcode is placed on a Mac worker that can // take it, behind EQUIPO_MAC_ENGINEERING. The primary resolves the // attempt's base first (prepare_base, then its base report), and only // then is the attempt dispatched to the worker with the inbound // Engineering transfer, in one transaction. The task is pinned to that // worker; review stays on the primary, and a Mac-made candidate is never // merged by policy. // sha is a distinct full SHA for n. func sha(n int) string { return fmt.Sprintf("%040x", n) } // macEngineerHello is a Mac worker's hello at protocol: seatbelt, the Mac // tags, and the Engineering status state (claude only when ready). With // f5, probe F5 is denied (Xcode's services denied under Claude's own // sandbox). func macEngineerHello(label, state string, protocol int, f5 bool) wire.Hello { h := WorkerHello(0) h.Protocol, h.Label, h.Sandbox = protocol, label, wire.SandboxSeatbelt caps := *h.Capabilities caps.Tags = []string{wire.TagMacOS, wire.TagXcode, wire.TagIOSSimulator} if state == wire.EngineeringReady { caps.Tags = append(caps.Tags, wire.TagClaude) } caps.Probes = []wire.Probe{{ID: "P1", Verdict: wire.ProbePassed}, {ID: "P2", Verdict: wire.ProbeDenied}, {ID: "P4", Verdict: wire.ProbePassed}} if protocol >= wire.ProtocolMacEngineering { caps.Engineering = &wire.EngineeringStatus{State: state} for _, id := range wire.EngineeringProbeIDs { verdict := wire.EngineeringProbeSuccess(id) if id == "F5" && !f5 { verdict = wire.ProbeFailed } caps.Probes = append(caps.Probes, wire.Probe{ID: id, Verdict: verdict}) } } h.Capabilities = &caps return h } // newMacRig is the runners rig with its primary at protocol 37, the // sample repository's gate needing Xcode, and the switch on. func newMacRig(t *testing.T) *runnersRig { return newMacRigAt(t, wire.ProtocolMacEngineering) } func newMacRigAt(t *testing.T, protocol int) *runnersRig { r := newRunnersRigAt(t, protocol) h := primaryHello(0) h.Protocol = protocol h.Catalog[0].NeedsMacOS = true r.primary.heartbeat(h) r.macEngineering(true) return r } // macEngineering is EQUIPO_MAC_ENGINEERING, for this process and the next. func (r *runnersRig) macEngineering(on bool) { r.inst.MacEngineering = on r.inst.Store.Chat().SetMacEngineering(on) } // newMacEngineer enrols and connects a Mac worker at protocol 37 whose // Engineering status is state. func (r *runnersRig) newMacEngineer(label, state string) *peer { return r.newMacEngineerAt(label, state, wire.ProtocolMacEngineering, false) } func (r *runnersRig) newMacEngineerAt(label, state string, protocol int, f5 bool) *peer { r.t.Helper() token := r.inst.EnrolRunner(r.t).Token fr, err := DialRunnerHello(r.ctx, r.inst.URL, token, macEngineerHello(label, state, protocol, f5)) if err != nil { r.t.Fatal(err) } r.t.Cleanup(fr.Close) r.creds[fr] = [2]string{token, label} return &peer{t: r.t, r: r.toolRig, fr: fr} } // macState says a new Engineering status (and tags) in w's hello. func (r *runnersRig) macState(w *peer, state string, f5 bool) { r.t.Helper() w.heartbeat(macEngineerHello(r.creds[w.fr][1], state, wire.ProtocolMacEngineering, f5)) } // fromPrimary is the next frame of kind sent to the primary, whichever of // the rig's readers took it off the socket, acked. func (r *runnersRig) fromPrimary(kind string) any { r.t.Helper() for i, h := range r.held { if h.f.Type == kind { r.held = append(r.held[:i:i], r.held[i+1:]...) r.primary.ack(h.f) return h.body } } _, body := r.primary.expect(kind) return body } // mailbox counts a runner's commands of kind, acked or not. func (r *runnersRig) mailbox(runner, kind string) int { r.t.Helper() var n int if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM runner_commands WHERE runner_id = ? AND kind = ?", runner, kind).Scan(&n); err != nil { r.t.Fatal(err) } return n } // mailboxHas counts a runner's commands whose body contains text. func (r *runnersRig) mailboxHas(runner, text string) int { r.t.Helper() var n int if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM runner_commands WHERE runner_id = ? AND instr(body, ?) > 0", runner, text).Scan(&n); err != nil { r.t.Fatal(err) } return n } // macTask records and starts a task in the Mac repository. func (r *runnersRig) macTask(title string) string { r.t.Helper() task := taskID(r.t, r.call("c-"+title, wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": title, "brief": "b"})) r.call("s-"+title, wire.ToolStartTask, map[string]string{"task": task, "brief": "go"}) return task } // prepared is the primary's prepare_base for the task's newest // Engineering attempt. func (r *runnersRig) prepared(task string) *wire.PrepareBaseCommand { r.t.Helper() pb := r.fromPrimary(wire.FramePrepareBase).(*wire.PrepareBaseCommand) if pb.TaskID != task || !pb.Valid() || !strings.HasSuffix(pb.Repo, "oficina/sample") { r.t.Fatalf("prepare_base %+v", pb) } return pb } // based answers prepare_base from the primary's connection. func (r *runnersRig) based(pb *wire.PrepareBaseCommand, base string) { r.t.Helper() r.primary.send(wire.FrameBase, wire.BaseReport{TaskID: pb.TaskID, StepID: pb.StepID, Attempt: pb.Attempt, BaseSHA: base}) } // newestEngineering is the task's newest Engineering step. func (r *runnersRig) newestEngineering(task string) wire.Step { r.t.Helper() k, err := r.client.Task(r.ctx, task) if err != nil { r.t.Fatal(err) } for i := len(k.Steps) - 1; i >= 0; i-- { if k.Steps[i].Specialist == wire.SpecialistEngineering { return k.Steps[i] } } r.t.Fatalf("no engineering step: %+v", k.Steps) return wire.Step{} } func (r *runnersRig) task(id string) wire.Task { r.t.Helper() k, err := r.client.Task(r.ctx, id) if err != nil { r.t.Fatal(err) } return k } // engineeringTransfer is the inbound Engineering transfer the primary is // asked to upload for an attempt on w. func (r *runnersRig) engineeringTransfer(w *peer, d *wire.DispatchCommand) wire.TransferHeader { r.t.Helper() h := r.fromPrimary(wire.FrameSendPack).(*wire.SendPackCommand).Transfer if h.Kind != wire.TransferKindEngineering || h.Direction != wire.TransferInbound || h.StepID != d.StepID || h.Attempt != d.Attempt || h.BaseSHA != d.BaseSHA || !h.Valid() { r.t.Fatalf("engineering transfer %+v for %+v", h, d) } return h } // workerCommitted runs w's Engineering attempt d to a commit: started, // committed (the outbound transfer opens for exactly that candidate), its // pack sent, which reaches the primary with a publish command. With done, // the worker's final report comes before the pack. func (r *runnersRig) workerCommitted(w *peer, d *wire.DispatchCommand, cand string, done bool) *wire.PublishCommand { r.t.Helper() if !w.lease(d.StepID, d.Attempt) { r.t.Fatal("start refused") } w.send(wire.FrameStep, wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepRunning, BaseSHA: d.BaseSHA, Findings: []wire.Finding{}}) w.send(wire.FrameStep, wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepRunning, CandidateSHA: cand, Phase: wire.OutcomeCommitted, Findings: []wire.Finding{}}) _, body := w.expect(wire.FrameSendPack) h := body.(*wire.SendPackCommand).Transfer if h.Direction != wire.TransferOutbound || h.CandidateSHA != cand || h.BaseSHA != d.BaseSHA || h.Kind != "" || h.Attempt != d.Attempt { r.t.Fatalf("outbound header %+v", h) } if done { w.send(wire.FrameStep, wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepDone, CandidateSHA: cand, Termination: true, TerminationKind: wire.TerminationProcessGroup, Findings: []wire.Finding{}}) } w.send(wire.FrameBlob, chunk(h, []byte("PACK commit"))) r.fromPrimary(wire.FrameBlob) pub := r.fromPrimary(wire.FramePublish).(*wire.PublishCommand) if pub.CandidateSHA != cand || pub.Transfer != h.ID || pub.StepID != d.StepID || pub.Attempt != d.Attempt { r.t.Fatalf("publish %+v", pub) } return pub } // macDispatch is the first Engineering attempt of a new Mac task on w: // prepared, based on base, dispatched with its transfer. func (r *runnersRig) macDispatch(w *peer, title, base string) (string, *wire.DispatchCommand) { r.t.Helper() task := r.macTask(title) r.based(r.prepared(task), base) _, body := w.expect(wire.FrameDispatch) d := body.(*wire.DispatchCommand) if d.TaskID != task || d.Specialist != wire.SpecialistEngineering || d.BaseSHA != base || d.RunnerID != w.fr.Welcome.RunnerID { r.t.Fatalf("dispatch %+v", d) } r.engineeringTransfer(w, d) return task, d } // macCandidate is a Mac task whose first Engineering attempt ran on w and // whose candidate cand the primary published. func (r *runnersRig) macCandidate(w *peer, title, base, cand string) (string, *wire.DispatchCommand) { r.t.Helper() task, d := r.macDispatch(w, title, base) pub := r.workerCommitted(w, d, cand, true) r.primary.send(wire.FramePublished, wire.PublishedReport{Publication: pub.Publication, TaskID: task, StepID: d.StepID, Attempt: d.Attempt, CandidateSHA: cand, Pushed: true}) if k := r.task(task); k.CandidateSHA != cand || k.EngineeringRunner != w.fr.Welcome.RunnerID { r.t.Fatalf("published %+v", k) } return task, d } // peerOf is the peer runner id is, of those given. func peerOf(id string, ps ...*peer) *peer { for _, p := range ps { if p.fr.Welcome.RunnerID == id { return p } } return nil } // macChecked takes the checks dispatch of the task from whichever of ws // it was placed on, with its relay. func (r *runnersRig) macChecked(task string, ws ...*peer) (*peer, *wire.DispatchCommand) { r.t.Helper() s := r.newest(task, wire.SpecialistChecks) w := peerOf(s.RunnerID, ws...) if w == nil { r.t.Fatalf("checks not on a Mac worker: %+v", s) } _, body := w.expect(wire.FrameDispatch) c := body.(*wire.DispatchCommand) if c.Specialist != wire.SpecialistChecks || c.TaskID != task || c.StepID != s.ID || c.Attempt != s.Attempt { r.t.Fatalf("checks dispatch %+v for %+v", c, s) } r.fromPrimary(wire.FrameSendPack) return w, c } // 1. The first Engineering step of Mac work: prepare_base to the primary // first, nothing else; on its base, the dispatch to the worker and the // inbound Engineering transfer (base only) are written in one // transaction, and the task is pinned to the worker. func TestContractMacEngineeringPlacedOnWorker(t *testing.T) { r := newMacRig(t) w := r.newMacEngineer("Tito Studio", wire.EngineeringReady) task := r.macTask("iOS settings") pb := r.prepared(task) if pb.Attempt != 1 || pb.Rebase || pb.FromBase != "" || pb.CandidateSHA != "" { t.Fatalf("prepare_base %+v", pb) } s := r.engineeringStep(task) if s.State != wire.StepQueued || s.Placement != wire.PlacementBase || s.RunnerID != "" || s.BaseSHA != "" || s.ID != pb.StepID { t.Fatalf("waiting for the base: %+v", s) } // Nothing goes to the worker, and no transfer opens, before the base // is bound. w.none(wire.FrameDispatch, 150*time.Millisecond) r.primary.none(wire.FrameSendPack, 0) if n := r.mailbox(r.primary.fr.Welcome.RunnerID, wire.FrameSendPack) + r.mailbox(w.fr.Welcome.RunnerID, wire.FrameDispatch); n != 0 { t.Fatalf("%d commands before the base", n) } if n := r.mailbox(r.primary.fr.Welcome.RunnerID, wire.FrameDispatch); n != 0 { t.Fatal("Mac engineering dispatched to the Linux primary") } base := sha(1) r.based(pb, base) // The base report's transaction wrote both: they are there once it is // acked. if n, m := r.mailbox(r.primary.fr.Welcome.RunnerID, wire.FrameSendPack), r.mailbox(w.fr.Welcome.RunnerID, wire.FrameDispatch); n != 1 || m != 1 { t.Fatalf("after the base: %d send_pack, %d dispatch", n, m) } _, body := w.expect(wire.FrameDispatch) d := body.(*wire.DispatchCommand) if d.Specialist != wire.SpecialistEngineering || d.StepID != pb.StepID || d.Attempt != 1 || d.BaseSHA != base || d.RunnerID != w.fr.Welcome.RunnerID || strings.Join(d.Needs, ",") != "macos,xcode,claude" || d.XcodeAccess != "" { t.Fatalf("dispatch %+v", d) } h := r.engineeringTransfer(w, d) if h.OldBaseSHA != "" || h.CandidateSHA != "" || !slices.Equal(h.Commits(), []string{base}) || h.TaskID != task { t.Fatalf("transfer %+v", h) } k := r.task(task) if k.EngineeringRunner != w.fr.Welcome.RunnerID || k.BaseSHA != base { t.Fatalf("not pinned: %+v", k) } if s := r.engineeringStep(task); s.RunnerID != w.fr.Welcome.RunnerID || s.Placement != "" || s.BaseSHA != base || s.RunnerLabel != "Tito Studio" { t.Fatalf("placed %+v", s) } if !w.lease(d.StepID, 1) { t.Fatal("the worker's start was refused") } r.primary.none(wire.FrameDispatch, 0) } // 2. Unset, Mac Engineering waits exactly as mac-placement-wait left it, // with a Mac that could take it; set, the minute's placement takes it // from there. func TestContractMacEngineeringSwitchOff(t *testing.T) { r := newMacRig(t) r.macEngineering(false) w := r.newMacEngineer("Tito Studio", wire.EngineeringReady) task := r.macTask("iOS switch") w.none(wire.FrameDispatch, 150*time.Millisecond) r.primary.none(wire.FramePrepareBase, 0) r.primary.none(wire.FrameDispatch, 0) s := r.engineeringStep(task) if s.State != wire.StepQueued || s.Placement != wire.PlacementMacEngineering || s.RunnerID != "" || strings.Join(s.Needs, ",") != "macos,xcode" { t.Fatalf("switch off: %+v", s) } if got := r.needsYou(task); got != wire.NeedsMacEngineering { t.Fatalf("needs you %q", got) } r.macEngineering(true) if err := r.inst.Store.Chat().Place(r.ctx); err != nil { t.Fatal(err) } r.prepared(task) if s := r.engineeringStep(task); s.Placement != wire.PlacementBase { t.Fatalf("switch on: %+v", s) } } // 3. A Mac that fits all but claude: each Engineering status is its own // wait (waiting_mac_connection, read from the Mac's status now) and // Needs-you line; once the status is ready, the step is placed. func TestContractMacEngineeringStatusWaits(t *testing.T) { r := newMacRig(t) w := r.newMacEngineer("Tito Studio", wire.EngineeringNoConnection) task := r.macTask("iOS status") for _, state := range wire.EngineeringStates[1:] { r.macState(w, state, false) k := r.task(task) s := r.engineeringStep(task) if s.State != wire.StepQueued || s.Placement != wire.PlacementMacConnection || s.RunnerID != "" || s.RunnerLabel != "Tito Studio" || s.EngineeringStatus == nil || s.EngineeringStatus.State != state { t.Fatalf("%s: %+v", state, s) } if k.NeedsYou != wire.NeedsMacConnection { t.Fatalf("%s: needs you %q", state, k.NeedsYou) } w.none(wire.FrameDispatch, 50*time.Millisecond) r.primary.none(wire.FramePrepareBase, 0) } r.macState(w, wire.EngineeringReady, false) pb := r.prepared(task) if s := r.engineeringStep(task); s.Placement != wire.PlacementBase || s.EngineeringStatus != nil || r.needsYou(task) != "" { t.Fatalf("ready: %+v", s) } r.based(pb, sha(3)) _, body := w.expect(wire.FrameDispatch) if d := body.(*wire.DispatchCommand); d.TaskID != task || d.BaseSHA != sha(3) { t.Fatalf("dispatch %+v", d) } } // 4. A worker below protocol 37 waits waiting_mac_update, naming the // worker; nothing of protocol 37 reaches either runner. func TestContractMacEngineeringOldWorker(t *testing.T) { r := newMacRig(t) w := r.newMacEngineerAt("Tito Studio", wire.EngineeringReady, wire.ProtocolChangeDiffs, false) task := r.macTask("iOS old worker") w.none(wire.FrameDispatch, 150*time.Millisecond) s := r.engineeringStep(task) if s.State != wire.StepQueued || s.Placement != wire.PlacementMacUpdate || s.RunnerLabel != "Tito Studio" || s.RunnerID != "" { t.Fatalf("old worker: %+v", s) } if got := r.needsYou(task); got != wire.NeedsMacUpdate { t.Fatalf("needs you %q", got) } for _, id := range []string{w.fr.Welcome.RunnerID, r.primary.fr.Welcome.RunnerID} { if n := r.mailbox(id, wire.FramePrepareBase) + r.mailbox(id, wire.FrameDispatch) + r.mailboxHas(id, `"xcode_access"`) + r.mailboxHas(id, `"kind":"engineering"`); n != 0 { t.Fatalf("%d protocol 37 commands for %s", n, id) } } } // 4. A primary below protocol 37 cannot prepare a base: waiting_mac_update, // naming the primary, and it is sent nothing it cannot carry. func TestContractMacEngineeringOldPrimary(t *testing.T) { r := newMacRigAt(t, wire.ProtocolChangeDiffs) w := r.newMacEngineer("Tito Studio", wire.EngineeringReady) task := r.macTask("iOS old primary") w.none(wire.FrameDispatch, 150*time.Millisecond) s := r.engineeringStep(task) if s.State != wire.StepQueued || s.Placement != wire.PlacementMacUpdate || s.RunnerLabel != "docs-t1" || s.RunnerID != "" { t.Fatalf("old primary: %+v", s) } if got := r.needsYou(task); got != wire.NeedsMacUpdate { t.Fatalf("needs you %q", got) } for _, id := range []string{w.fr.Welcome.RunnerID, r.primary.fr.Welcome.RunnerID} { if n := r.mailbox(id, wire.FramePrepareBase) + r.mailbox(id, wire.FrameDispatch) + r.mailboxHas(id, `"xcode_access"`) + r.mailboxHas(id, `"kind":"engineering"`); n != 0 { t.Fatalf("%d protocol 37 commands for %s", n, id) } } } // 5. The only Mac that fits is offline: the step waits for it // (waiting_runner), raises Needs you runner_offline after 30 minutes and // keeps waiting; Cancel works; it never moves to Linux. func TestContractMacEngineeringOffline(t *testing.T) { r := newMacRig(t) w := r.newMacEngineer("Tito Studio", wire.EngineeringReady) w.fr.Close() deadline := time.Now().Add(5 * time.Second) for { runners, err := r.client.Runners(r.ctx) offline := false for _, x := range runners.Items { offline = offline || x.ID == w.fr.Welcome.RunnerID && !x.Online } if err == nil && offline { break } if time.Now().After(deadline) { t.Fatalf("worker still online: %+v %v", runners, err) } time.Sleep(50 * time.Millisecond) } task := r.macTask("iOS offline") s := r.engineeringStep(task) if s.State != wire.StepQueued || s.Placement != wire.PlacementWaiting || s.RunnerLabel != "Tito Studio" || r.needsYou(task) != "" { t.Fatalf("waiting for the Mac: %+v needs %q", s, r.needsYou(task)) } clock := time.Now().UTC().Add(chat.OfflineLimit + time.Minute) r.inst.Store.Chat().SetClock(func() time.Time { return clock }) if err := r.inst.Store.Chat().Place(r.ctx); err != nil { t.Fatal(err) } if s := r.engineeringStep(task); s.State != wire.StepQueued || s.Placement != wire.PlacementWaiting || s.Attempt != 1 { t.Fatalf("after the limit: %+v", s) } if got := r.needsYou(task); got != wire.NeedsRunnerOffline { t.Fatalf("needs you %q", got) } r.primary.none(wire.FrameDispatch, 50*time.Millisecond) r.primary.none(wire.FramePrepareBase, 0) if _, err := r.client.CancelTask(r.ctx, task); err != nil { t.Fatal(err) } if k := r.task(task); k.Stage != wire.StageCancelled || k.NeedsYou != "" { t.Fatalf("not cancelled: %+v", k) } if n := r.mailbox(r.primary.fr.Welcome.RunnerID, wire.FrameDispatch); n != 0 { t.Fatal("Mac engineering went to Linux") } } // 6. A fix round, a Retry, a republish and a rebase round all go to the // pinned worker while a second worker fits too. The fix round's base is // the published tip (no prepare_base); the rebase round's base comes from // the primary, and its transfer carries base, old base and candidate. func TestContractMacEngineeringPinHolds(t *testing.T) { r := newMacRig(t) r.shipsNo(r.project()) a := r.newMacEngineer("Mac A", wire.EngineeringReady) base, c1, c2, tip := sha(1), sha(0xc1), sha(0xc2), sha(0x71) task, _ := r.macCandidate(a, "iOS pinned", base, c1) b := r.newMacEngineer("Mac B", wire.EngineeringReady) // Checks of c1 fail: a fix round, on c1, on Mac A. cw, c := r.macChecked(task, a, b) cw.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: c.StepID, Attempt: c.Attempt, State: wire.StepDone, CandidateSHA: c1, Checks: wire.ChecksFailed, Gate: "xcodebuild test", ExitCode: exit(65), Output: "FAILED", Termination: true, TerminationKind: wire.TerminationProcessGroup, Findings: []wire.Finding{}}) _, body := a.expect(wire.FrameDispatch) fix := body.(*wire.DispatchCommand) if fix.Specialist != wire.SpecialistEngineering || fix.Round != 1 || fix.BaseSHA != c1 || fix.Attempt != 1 { t.Fatalf("fix round %+v", fix) } if h := r.engineeringTransfer(a, fix); !slices.Equal(h.Commits(), []string{c1}) { t.Fatalf("fix transfer %+v", h) } if n := r.mailbox(r.primary.fr.Welcome.RunnerID, wire.FramePrepareBase); n != 1 { t.Fatalf("a fix round prepared a base: %d", n) } // It fails; Retry: Mac A again, from the same base. if !a.lease(fix.StepID, 1) { t.Fatal("fix round refused") } a.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: fix.StepID, Attempt: 1, State: wire.StepFailed, Reason: "provider_failed", Termination: true, TerminationKind: wire.TerminationProcessGroup, Findings: []wire.Finding{}}) if acc, err := r.client.RetryTask(r.ctx, task); err != nil || acc.Attempt != 2 { t.Fatalf("retry %+v %v", acc, err) } _, body = a.expect(wire.FrameDispatch) retry := body.(*wire.DispatchCommand) if retry.StepID != fix.StepID || retry.Attempt != 2 || retry.BaseSHA != c1 { t.Fatalf("retry %+v", retry) } r.engineeringTransfer(a, retry) // Its push fails; Retry publishes the same commit again, on the // primary, running nothing on any Mac. pub := r.workerCommitted(a, retry, c2, true) if !r.primary.leasePublication(retry.StepID, 2, pub.Publication) { t.Fatal("publication refused") } r.primary.send(wire.FramePublished, wire.PublishedReport{Publication: pub.Publication, TaskID: task, StepID: retry.StepID, Attempt: 2, CandidateSHA: c2, Pushed: false, Reason: "push_failed"}) if acc, err := r.client.RetryTask(r.ctx, task); err != nil || acc.Attempt != 2 { t.Fatalf("republish %+v %v", acc, err) } again := r.fromPrimary(wire.FramePublish).(*wire.PublishCommand) if again.CandidateSHA != c2 || again.Transfer != pub.Transfer { t.Fatalf("republish %+v", again) } a.none(wire.FrameDispatch, 50*time.Millisecond) b.none(wire.FrameDispatch, 0) r.primary.send(wire.FramePublished, wire.PublishedReport{Publication: again.Publication, TaskID: task, StepID: retry.StepID, Attempt: 2, CandidateSHA: c2, Pushed: true}) // Checks pass on a Mac, review approves on the primary, the person // merges, and the merge conflicts: a rebase round, on Mac A. cw, c = r.macChecked(task, a, b) cw.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: c.StepID, Attempt: c.Attempt, State: wire.StepDone, CandidateSHA: c2, Checks: wire.ChecksPassed, Gate: "xcodebuild test", ExitCode: exit(0), Output: "ok", Termination: true, TerminationKind: wire.TerminationProcessGroup, ChecksSandbox: wire.SandboxSeatbelt, Findings: []wire.Finding{}}) rv := r.fromPrimary(wire.FrameDispatch).(*wire.DispatchCommand) if rv.Specialist != wire.SpecialistReview || rv.RunnerID != r.primary.fr.Welcome.RunnerID { t.Fatalf("review %+v", rv) } r.primary.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: rv.StepID, Attempt: rv.Attempt, State: wire.StepDone, BaseSHA: rv.BaseSHA, CandidateSHA: c2, Termination: true, Family: "codex", Account: "codex-a", Verdict: wire.VerdictApprove, ReviewLabel: wire.ReviewOtherFamily, Change: facts(rv), Findings: []wire.Finding{}, Summary: "Read it."}) card := r.mergeCardFor(task) if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceMerge, card.Revision); err != nil { t.Fatal(err) } m := r.fromPrimary(wire.FrameDispatch).(*wire.DispatchCommand) if m.Specialist != wire.SpecialistMerge || m.CandidateSHA != c2 { t.Fatalf("merge %+v", m) } r.primary.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: m.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, CandidateSHA: c2}) r.primary.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: m.StepID, Attempt: 1, State: wire.StepFailed, Reason: "merge_conflict", BaseSHA: base, CandidateSHA: c2, Termination: true}) pb := r.prepared(task) if !pb.Rebase || pb.FromBase != base || pb.CandidateSHA != c2 || pb.Attempt != 1 { t.Fatalf("rebase prepare_base %+v", pb) } r.based(pb, tip) _, body = a.expect(wire.FrameDispatch) rb := body.(*wire.DispatchCommand) if !rb.Rebase || rb.BaseSHA != tip || rb.FromBase != base || rb.CandidateSHA != c2 { t.Fatalf("rebase round %+v", rb) } h := r.engineeringTransfer(a, rb) if h.OldBaseSHA != base || h.CandidateSHA != c2 || !slices.Equal(h.Commits(), []string{tip, base, c2}) { t.Fatalf("rebase transfer %+v", h) } b.none(wire.FrameDispatch, 50*time.Millisecond) if n := r.mailboxHas(b.fr.Welcome.RunnerID, `"specialist":"engineering"`); n != 0 { t.Fatalf("Mac B got %d engineering dispatches", n) } for _, s := range r.task(task).Steps { if s.Specialist == wire.SpecialistEngineering && s.RunnerID != a.fr.Welcome.RunnerID { t.Fatalf("an engineering step off the pinned Mac: %+v", s) } } } // mergeCardFor waits for the task's open merge card. func (r *runnersRig) mergeCardFor(task string) wire.Card { r.t.Helper() deadline := time.Now().Add(5 * time.Second) for time.Now().Before(deadline) { for _, c := range r.mergeCards(task) { if c.State == wire.CardOpen { return c } } time.Sleep(20 * time.Millisecond) } r.t.Fatalf("no merge card for %s: %+v", task, r.task(task)) return wire.Card{} } // 7. The pinned worker loses claude mid-task: the next round waits for // it (waiting_mac_connection, naming it) and is never placed on the // second worker that fits; once it is ready again, it runs there. func TestContractMacEngineeringPinnedLostTag(t *testing.T) { r := newMacRig(t) a := r.newMacEngineer("Mac A", wire.EngineeringReady) b := r.newMacEngineer("Mac B", wire.EngineeringReady) c1 := sha(0xc1) task, _ := r.macCandidate(a, "iOS lost tag", sha(1), c1) r.macState(a, wire.EngineeringSignedOut, false) cw, c := r.macChecked(task, a, b) cw.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: c.StepID, Attempt: c.Attempt, State: wire.StepDone, CandidateSHA: c1, Checks: wire.ChecksFailed, Gate: "xcodebuild test", ExitCode: exit(65), Output: "FAILED", Termination: true, TerminationKind: wire.TerminationProcessGroup, Findings: []wire.Finding{}}) s := r.newestEngineering(task) if s.Round != 1 || s.State != wire.StepQueued || s.Placement != wire.PlacementMacConnection || s.RunnerLabel != "Mac A" || s.EngineeringStatus == nil || s.EngineeringStatus.State != wire.EngineeringSignedOut { t.Fatalf("fix round with the pinned Mac signed out: %+v", s) } if got := r.needsYou(task); got != wire.NeedsMacConnection { t.Fatalf("needs you %q", got) } if err := r.inst.Store.Chat().Place(r.ctx); err != nil { t.Fatal(err) } b.none(wire.FrameDispatch, 100*time.Millisecond) a.none(wire.FrameDispatch, 0) r.macState(a, wire.EngineeringReady, false) _, body := a.expect(wire.FrameDispatch) if d := body.(*wire.DispatchCommand); d.StepID != s.ID || d.BaseSHA != c1 { t.Fatalf("fix round %+v", d) } b.none(wire.FrameDispatch, 0) } // 8. The pinned worker is removed while its fix round may run: the step // is quarantined (machine_removed) until the creator recovers it; Retry // then re-pins to a fitting Mac, or waits for one (waiting_mac), and is // never placed on the Linux primary. func TestContractMacEngineeringPinnedRemoved(t *testing.T) { r := newMacRig(t) a := r.newMacEngineer("Mac A", wire.EngineeringReady) c1 := sha(0xc1) task, _ := r.macCandidate(a, "iOS removed", sha(1), c1) cw, c := r.macChecked(task, a) cw.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: c.StepID, Attempt: c.Attempt, State: wire.StepDone, CandidateSHA: c1, Checks: wire.ChecksFailed, Gate: "xcodebuild test", ExitCode: exit(65), Output: "FAILED", Termination: true, TerminationKind: wire.TerminationProcessGroup, Findings: []wire.Finding{}}) _, body := a.expect(wire.FrameDispatch) fix := body.(*wire.DispatchCommand) r.engineeringTransfer(a, fix) if !a.lease(fix.StepID, fix.Attempt) { t.Fatal("fix round refused") } r.remove(a.fr.Welcome.RunnerID, true) if s := r.newestEngineering(task); s.State != wire.StepFailed || s.Reason != "machine_removed" || r.needsYou(task) != wire.NeedsMachineRemoved { t.Fatalf("not quarantined: %+v", s) } if _, err := r.client.RecoverTask(r.ctx, task); err != nil { t.Fatal(err) } // The primary's catalog no longer names the repository: the task was // made on a Mac, so it still needs one. h := primaryHello(0) h.Protocol, h.Catalog = wire.ProtocolMacEngineering, []wire.RepoInfo{} r.primary.heartbeat(h) if acc, err := r.client.RetryTask(r.ctx, task); err != nil || acc.Attempt != 2 { t.Fatalf("retry %+v %v", acc, err) } s := r.newestEngineering(task) if s.State != wire.StepQueued || s.Placement != wire.PlacementMac || s.RunnerID != "" || r.needsYou(task) != wire.NeedsMacRunner { t.Fatalf("after recovery, no Mac: %+v", s) } r.primary.none(wire.FrameDispatch, 100*time.Millisecond) b := r.newMacEngineer("Mac B", wire.EngineeringReady) _, body = b.expect(wire.FrameDispatch) d := body.(*wire.DispatchCommand) if d.StepID != fix.StepID || d.Attempt != 2 || d.BaseSHA != c1 { t.Fatalf("re-pinned %+v", d) } r.engineeringTransfer(b, d) if k := r.task(task); k.EngineeringRunner != b.fr.Welcome.RunnerID { t.Fatalf("pin %q", k.EngineeringRunner) } for _, s := range r.task(task).Steps { if s.Specialist == wire.SpecialistEngineering && s.RunnerID == r.primary.fr.Welcome.RunnerID { t.Fatalf("engineering on the Linux primary: %+v", s) } } r.primary.none(wire.FrameDispatch, 0) } // 9. Only the primary's base report for the attempt waiting for it binds: // one from the worker, for an older attempt, after the attempt was // withdrawn, or after Cancel is refused and logged; a second report for // the same attempt does nothing; base_unavailable ends the attempt // failed, Needs you retry. func TestContractPrepareBase(t *testing.T) { r := newMacRig(t) w := r.newMacEngineer("Tito Studio", wire.EngineeringReady) task := r.macTask("iOS base") pb := r.prepared(task) waiting := func(what string, attempt int64) { t.Helper() s := r.engineeringStep(task) if s.Placement != wire.PlacementBase || s.Attempt != attempt || s.BaseSHA != "" || s.RunnerID != "" { t.Fatalf("%s: %+v", what, s) } w.none(wire.FrameDispatch, 50*time.Millisecond) r.primary.none(wire.FrameSendPack, 0) } // From the worker's connection. w.send(wire.FrameBase, wire.BaseReport{TaskID: task, StepID: pb.StepID, Attempt: 1, BaseSHA: sha(1)}) waiting("worker's report", 1) if !strings.Contains(r.inst.Logs(), "base_refused: not the primary") { t.Fatalf("worker's report not logged: %s", r.inst.Logs()) } // The primary cannot resolve it: the attempt fails, Needs you retry. r.primary.send(wire.FrameBase, wire.BaseReport{TaskID: task, StepID: pb.StepID, Attempt: 1, Reason: wire.ReasonBaseUnavailable}) s := r.engineeringStep(task) if s.State != wire.StepFailed || s.Reason != wire.ReasonBaseUnavailable || !s.Terminated || s.Placement != "" || r.needsYou(task) != wire.NeedsRetry { t.Fatalf("base unavailable: %+v needs %q", s, r.needsYou(task)) } if acc, err := r.client.RetryTask(r.ctx, task); err != nil || acc.Attempt != 2 { t.Fatalf("retry %+v %v", acc, err) } pb2 := r.prepared(task) if pb2.Attempt != 2 || pb2.StepID != pb.StepID { t.Fatalf("second prepare_base %+v", pb2) } // A late report for the older attempt. r.based(pb, sha(2)) waiting("older attempt", 2) if !strings.Contains(r.inst.Logs(), "base_refused: attempt not current") { t.Fatal("older attempt's report not logged") } // The Mac is removed while the attempt waits for its base: the attempt // is withdrawn (the next waits for a Mac), and its report is refused. r.remove(w.fr.Welcome.RunnerID, false) if s := r.engineeringStep(task); s.Attempt != 3 || s.Placement != wire.PlacementMac { t.Fatalf("withdrawn: %+v", s) } r.based(pb2, sha(3)) if s := r.engineeringStep(task); s.Attempt != 3 || s.BaseSHA != "" || s.Placement != wire.PlacementMac { t.Fatalf("withdrawn attempt's base bound: %+v", s) } if strings.Count(r.inst.Logs(), "base_refused: attempt not current") < 2 { t.Fatal("withdrawn attempt's report not logged") } // A Mac that fits enrols: the waiting attempt is prepared for it. w2 := r.newMacEngineer("Mac B", wire.EngineeringReady) if pb3 := r.prepared(task); pb3.Attempt != 3 { t.Fatalf("third prepare_base %+v", pb3) } // After Cancel. other := r.macTask("iOS cancelled") pc := r.prepared(other) if _, err := r.client.CancelTask(r.ctx, other); err != nil { t.Fatal(err) } r.based(pc, sha(4)) if k := r.task(other); k.Stage != wire.StageCancelled || k.Steps[0].BaseSHA != "" { t.Fatalf("cancelled task's base bound: %+v", k) } if !strings.Contains(r.inst.Logs(), "base_refused: task ended") { t.Fatal("cancelled task's report not logged") } w2.none(wire.FrameDispatch, 50*time.Millisecond) // A second report for the same attempt changes nothing. third := r.macTask("iOS twice") pt := r.prepared(third) r.based(pt, sha(5)) w2.expect(wire.FrameDispatch) r.based(pt, sha(6)) if s := r.engineeringStep(third); s.BaseSHA != sha(5) || s.Attempt != 1 { t.Fatalf("second report rebound: %+v", s) } w2.none(wire.FrameDispatch, 50*time.Millisecond) if n := r.mailbox(r.primary.fr.Welcome.RunnerID, wire.FrameSendPack); n != 1 { t.Fatalf("%d transfers", n) } } // 10. Xcode access for Engineering follows the proof: sent only to a Mac // the instance holds sandbox-proven (seatbelt, untainted) whose probe F5 // is denied. Without F5, with the sandbox not proven, or tainted, none. func TestContractMacEngineeringXcodeAccess(t *testing.T) { r := newMacRig(t) w := r.newMacEngineerAt("Tito Studio", wire.EngineeringReady, wire.ProtocolMacEngineering, true) access := func(title string) string { t.Helper() task := r.macTask(title) r.based(r.prepared(task), sha(1)) _, body := w.expect(wire.FrameDispatch) r.fromPrimary(wire.FrameSendPack) return body.(*wire.DispatchCommand).XcodeAccess } if got := access("iOS proven"); got != wire.XcodeAccessSandboxed { t.Fatalf("proven with F5 denied: %q", got) } r.macState(w, wire.EngineeringReady, false) if got := access("iOS no F5"); got != "" { t.Fatalf("without F5: %q", got) } h := macEngineerHello("Tito Studio", wire.EngineeringReady, wire.ProtocolMacEngineering, true) h.Sandbox = wire.SandboxNone w.heartbeat(h) if got := access("iOS unproven"); got != "" { t.Fatalf("sandbox not proven: %q", got) } r.macState(w, wire.EngineeringReady, true) if _, err := r.inst.DB.Writer().Exec("UPDATE runners SET tainted_at = ? WHERE id = ?", time.Now().UTC(), w.fr.Welcome.RunnerID); err != nil { t.Fatal(err) } if got := access("iOS tainted"); got != "" { t.Fatalf("tainted: %q", got) } } // 11. A worker's Engineering reports: pushed is refused; committed opens // the outbound transfer for exactly that candidate; done waits for the // primary's published, in either order. func TestContractWorkerEngineeringReports(t *testing.T) { r := newMacRig(t) w := r.newMacEngineer("Mac A", wire.EngineeringReady) base, cand := sha(1), sha(0xc1) task, d := r.macDispatch(w, "iOS reports", base) if !w.lease(d.StepID, 1) { t.Fatal("start refused") } w.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, Findings: []wire.Finding{}}) // A worker claiming it pushed is refused: the step does not end. w.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d.StepID, Attempt: 1, State: wire.StepDone, CandidateSHA: cand, Pushed: true, Termination: true, Findings: []wire.Finding{}}) if s := r.engineeringStep(task); s.State != wire.StepRunning || s.Pushed || s.CandidateSHA != "" { t.Fatalf("a worker's pushed counted: %+v", s) } w.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, CandidateSHA: cand, Phase: wire.OutcomeCommitted, Findings: []wire.Finding{}}) _, body := w.expect(wire.FrameSendPack) h := body.(*wire.SendPackCommand).Transfer if h.Direction != wire.TransferOutbound || h.CandidateSHA != cand || h.BaseSHA != base || h.Kind != "" || h.Attempt != 1 { t.Fatalf("outbound %+v", h) } // Another committed, for another commit, opens nothing more. w.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, CandidateSHA: sha(0xbad), Phase: wire.OutcomeCommitted, Findings: []wire.Finding{}}) w.none(wire.FrameSendPack, 50*time.Millisecond) if s := r.engineeringStep(task); s.CandidateSHA != cand { t.Fatalf("candidate moved: %+v", s) } // Done first: nothing is judged until the primary has published. w.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d.StepID, Attempt: 1, State: wire.StepDone, CandidateSHA: cand, Termination: true, TerminationKind: wire.TerminationProcessGroup, Findings: []wire.Finding{}}) w.send(wire.FrameBlob, chunk(h, []byte("PACK commit"))) r.fromPrimary(wire.FrameBlob) pub := r.fromPrimary(wire.FramePublish).(*wire.PublishCommand) if k := r.task(task); k.Steps[0].Pushed || k.CandidateSHA != "" || len(k.Steps) != 1 { t.Fatalf("judged before publication: %+v", k) } r.primary.send(wire.FramePublished, wire.PublishedReport{Publication: pub.Publication, TaskID: task, StepID: d.StepID, Attempt: 1, CandidateSHA: cand, Pushed: true}) if k := r.task(task); !k.Steps[0].Pushed || k.CandidateSHA != cand { t.Fatalf("after publication %+v", k) } r.macChecked(task, w) } // The primary may publish before the worker's final report: that report // keeps the primary's publication, and checks follow. func TestContractPublishedBeforeWorkerDone(t *testing.T) { r := newMacRig(t) w := r.newMacEngineer("Mac A", wire.EngineeringReady) cand := sha(0xc) task, d := r.macDispatch(w, "Published early", sha(1)) pub := r.workerCommitted(w, d, cand, false) r.primary.send(wire.FramePublished, wire.PublishedReport{Publication: pub.Publication, TaskID: task, StepID: d.StepID, Attempt: 1, CandidateSHA: cand, Pushed: true}) w.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d.StepID, Attempt: 1, State: wire.StepDone, CandidateSHA: cand, Termination: true, Findings: []wire.Finding{}}) k := r.task(task) if !k.Steps[0].Pushed || k.Steps[0].Publication != wire.PublicationPublished || k.CandidateSHA != cand { t.Fatalf("the worker's report cleared the publication: %+v", k.Steps[0]) } if _, c := r.macChecked(task, w); c.CandidateSHA != cand { t.Fatalf("checks %+v", c) } } // 12. Review of a Mac-made candidate is placed on the primary after // publication, never on a Mac. func TestContractReviewStaysOnPrimary(t *testing.T) { r := newMacRig(t) w := r.newMacEngineer("Mac A", wire.EngineeringReady) cand := sha(0xc1) task, _ := r.macCandidate(w, "iOS review", sha(1), cand) cw, c := r.macChecked(task, w) cw.send(wire.FrameStep, passed(task, c.StepID, c.Attempt, cand)) rv := r.fromPrimary(wire.FrameDispatch).(*wire.DispatchCommand) if rv.Specialist != wire.SpecialistReview || rv.RunnerID != r.primary.fr.Welcome.RunnerID || rv.CandidateSHA != cand || len(rv.Needs) != 0 { t.Fatalf("review %+v", rv) } w.none(wire.FrameDispatch, 50*time.Millisecond) for _, s := range r.task(task).Steps { if s.Specialist == wire.SpecialistReview && s.RunnerID != r.primary.fr.Welcome.RunnerID { t.Fatalf("review off the primary %+v", s) } } } // 12. Ready to merge never merges a Mac-made candidate by policy (a // worker cannot run certified base gates): work that would merge on its // own from the primary asks; the person's Merge acts. func TestContractMacMadeNeverAutoMerges(t *testing.T) { r := newMacRig(t) r.shipsNo(r.project()) w := r.newMacEngineer("Mac A", wire.EngineeringReady) cand := sha(0xc1) task, _ := r.macCandidate(w, "iOS swipe", sha(1), cand) cw, c := r.macChecked(task, w) // Not run, for an environment reason: small, ordinary, approved work // that would merge on its own were it made on the primary. cw.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: c.StepID, Attempt: c.Attempt, State: wire.StepDone, CandidateSHA: cand, Checks: wire.ChecksCannotRun, Reason: "needs_macos", Termination: true, TerminationKind: wire.TerminationProcessGroup, Findings: []wire.Finding{}}) rv := r.fromPrimary(wire.FrameDispatch).(*wire.DispatchCommand) r.primary.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: rv.StepID, Attempt: rv.Attempt, State: wire.StepDone, BaseSHA: rv.BaseSHA, CandidateSHA: cand, Termination: true, Family: "codex", Account: "codex-a", Verdict: wire.VerdictApprove, ReviewLabel: wire.ReviewOtherFamily, Change: facts(rv), Findings: []wire.Finding{}, Summary: "Read it."}) card := r.mergeCardFor(task) k := r.task(task) if k.Stage != wire.StageReadyToMerge || k.MergeDecision == nil || k.MergeDecision.Class != "ask" { t.Fatalf("a Mac-made candidate was not asked about: %+v", k.MergeDecision) } made := false for _, c := range k.MergeDecision.Reasons { made = made || c.Name == "made_on_primary" && !c.OK } if !made { t.Fatalf("decision %+v", k.MergeDecision) } if n := r.mailbox(r.primary.fr.Welcome.RunnerID, wire.FrameDispatch); n != 1 { // Review, then nothing: no merge was dispatched. t.Fatalf("%d dispatches to the primary", n) } if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceMerge, card.Revision); err != nil { t.Fatal(err) } if m := r.fromPrimary(wire.FrameDispatch).(*wire.DispatchCommand); m.Specialist != wire.SpecialistMerge || m.CandidateSHA != cand { t.Fatalf("the person's merge %+v", m) } } // A primary replaced after it acked prepare_base: the preparation it can // no longer answer is invalidated (the attempt moves on) and asked of the // replacement, which must speak 37 (until then waiting_mac_update naming // it). The old primary's report, and a report for the invalidated // request, are refused and logged. func TestContractPrepareBaseAfterPrimaryReplaced(t *testing.T) { r := newMacRig(t) w := r.newMacEngineer("Tito Studio", wire.EngineeringReady) // Work the old primary may have started (a Linux change), so its // removal waits for that proof and it stays connected, removing. plain := primaryHello(0) plain.Protocol = wire.ProtocolMacEngineering r.primary.heartbeat(plain) started := r.macTask("Linux change") d0 := r.fromPrimary(wire.FrameDispatch).(*wire.DispatchCommand) if d0.TaskID != started || !r.primary.lease(d0.StepID, d0.Attempt) { t.Fatalf("plain engineering %+v", d0) } mac := primaryHello(0) mac.Protocol = wire.ProtocolMacEngineering mac.Catalog[0].NeedsMacOS = true r.primary.heartbeat(mac) task := r.macTask("iOS replaced primary") pb := r.prepared(task) old := r.primary.fr.Welcome.RunnerID r.ackedBy(old, wire.FramePrepareBase) r.remove(old, false) if r.revokedAt(old) { t.Fatal("revoked before its proof") } token := r.inst.EnrolRunner(t).Token h := primaryHello(0) // A Linux replacement whose catalog does not name the repository: the // task's Mac need outlives that. h.Protocol, h.Label, h.Catalog = wire.ProtocolChangeDiffs, "docs-t2", []wire.RepoInfo{} p35, err := DialRunnerHello(r.ctx, r.inst.URL, token, h) if err != nil || p35.Welcome.Role != wire.RolePrimary { t.Fatalf("replacement %+v %v", p35, err) } s := r.engineeringStep(task) if s.Attempt != 2 || s.State != wire.StepQueued || s.Placement != wire.PlacementMacUpdate || s.RunnerLabel != "docs-t2" || r.needsYou(task) != wire.NeedsMacUpdate { t.Fatalf("with a replacement below 37: %+v needs %q", s, r.needsYou(task)) } if n := r.unacked(p35.Welcome.RunnerID, wire.FramePrepareBase); n != 0 { t.Fatalf("%d prepare_base for a primary below 37", n) } // The old primary's late answer, on its own connection. r.primary.send(wire.FrameBase, wire.BaseReport{TaskID: task, StepID: pb.StepID, Attempt: 1, BaseSHA: sha(1)}) if s := r.engineeringStep(task); s.BaseSHA != "" || s.Attempt != 2 { t.Fatalf("the old primary's base bound: %+v", s) } if !strings.Contains(r.inst.Logs(), "base_refused: not the primary") { t.Fatal("the old primary's report not logged") } // The replacement updated: asked afresh, for the new attempt. p35.Close() h.Protocol = wire.ProtocolMacEngineering p37, err := DialRunnerHello(r.ctx, r.inst.URL, token, h) if err != nil { t.Fatal(err) } t.Cleanup(p37.Close) np := &peer{t: t, r: r.toolRig, fr: p37} _, body := np.expect(wire.FramePrepareBase) pb2 := body.(*wire.PrepareBaseCommand) if pb2.StepID != pb.StepID || pb2.Attempt != 2 || !pb2.Valid() { t.Fatalf("fresh prepare_base %+v", pb2) } // A report for the invalidated request. np.send(wire.FrameBase, wire.BaseReport{TaskID: task, StepID: pb.StepID, Attempt: 1, BaseSHA: sha(1)}) if s := r.engineeringStep(task); s.BaseSHA != "" || s.Placement != wire.PlacementBase { t.Fatalf("the invalidated request bound: %+v", s) } if !strings.Contains(r.inst.Logs(), "base_refused: attempt not current") { t.Fatal("the invalidated request's report not logged") } np.send(wire.FrameBase, wire.BaseReport{TaskID: task, StepID: pb2.StepID, Attempt: 2, BaseSHA: sha(2)}) _, body = w.expect(wire.FrameDispatch) if d := body.(*wire.DispatchCommand); d.Attempt != 2 || d.BaseSHA != sha(2) { t.Fatalf("dispatch %+v", d) } if n := r.mailboxHas(p37.Welcome.RunnerID, `"specialist":"engineering"`); n != 0 { t.Fatalf("%d engineering dispatches to the Linux replacement", n) } } // ackedBy waits until runner's commands of kind are all acked. func (r *runnersRig) ackedBy(runner, kind string) { r.t.Helper() deadline := time.Now().Add(5 * time.Second) for r.unacked(runner, kind) != 0 { if time.Now().After(deadline) { r.t.Fatalf("%s not acked by %s", kind, runner) } time.Sleep(20 * time.Millisecond) } } func (r *runnersRig) unacked(runner, kind string) int { r.t.Helper() var n int if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM runner_commands WHERE runner_id = ? AND kind = ? AND acked_at IS NULL", runner, kind).Scan(&n); err != nil { r.t.Fatal(err) } return n } // The same primary back below protocol 37 after it acked prepare_base // cannot answer it: invalidated, and the attempt waits for its update. func TestContractPrepareBasePrimaryDowngraded(t *testing.T) { r := newMacRig(t) r.newMacEngineer("Tito Studio", wire.EngineeringReady) task := r.macTask("iOS downgraded primary") r.prepared(task) r.ackedBy(r.primary.fr.Welcome.RunnerID, wire.FramePrepareBase) r.primary.fr.Close() h := primaryHello(0) h.Protocol = wire.ProtocolChangeDiffs h.Catalog[0].NeedsMacOS = true p, err := DialRunnerHello(r.ctx, r.inst.URL, r.rig.runner, h) if err != nil { t.Fatal(err) } t.Cleanup(p.Close) if s := r.engineeringStep(task); s.Attempt != 2 || s.Placement != wire.PlacementMacUpdate || s.RunnerLabel != "docs-t1" || r.needsYou(task) != wire.NeedsMacUpdate { t.Fatalf("after the downgrade: %+v", s) } } // Pinned to a Mac that is removed before anything it made was published: // the task still needs a Mac when the catalog no longer says so. func TestContractMacEngineeringPinnedBeforeCommit(t *testing.T) { r := newMacRig(t) a := r.newMacEngineer("Mac A", wire.EngineeringReady) task, d := r.macDispatch(a, "iOS early removal", sha(1)) if !a.lease(d.StepID, d.Attempt) { t.Fatal("start refused") } r.remove(a.fr.Welcome.RunnerID, true) if _, err := r.client.RecoverTask(r.ctx, task); err != nil { t.Fatal(err) } h := primaryHello(0) h.Protocol, h.Catalog = wire.ProtocolMacEngineering, []wire.RepoInfo{} r.primary.heartbeat(h) if acc, err := r.client.RetryTask(r.ctx, task); err != nil || acc.Attempt != 2 { t.Fatalf("retry %+v %v", acc, err) } if s := r.engineeringStep(task); s.State != wire.StepQueued || s.Placement != wire.PlacementMac || s.RunnerID != "" { t.Fatalf("after recovery: %+v", s) } r.primary.none(wire.FrameDispatch, 100*time.Millisecond) } // macPrimaryHello is the rig's primary become a Mac: every tag Mac // Engineering needs. func macPrimaryHello() wire.Hello { h := primaryHello(0) h.Protocol, h.Platform = wire.ProtocolMacEngineering, &wire.Platform{OS: "darwin", Arch: "arm64"} h.Capabilities.Tags = []string{wire.TagMacOS, wire.TagXcode, wire.TagIOSSimulator, wire.TagClaude} h.Catalog[0].NeedsMacOS = true return h } // macNeedOutlivesPins: the task's Engineering, quarantined on Mac A // (step at attempt), re-pins on Recover and Retry to a primary that is a // Mac; that primary is removed too, and the Linux primary that replaces // it has catalog (one without the repository, or naming it as not // needing a Mac). Retry still waits for a Mac: // the task's Mac need is its own record, not its current pin or its // publications. func (r *runnersRig) macNeedOutlivesPins(task, step string, attempt int64, a *peer, catalog []wire.RepoInfo) { r.t.Helper() r.remove(a.fr.Welcome.RunnerID, true) if _, err := r.client.RecoverTask(r.ctx, task); err != nil { r.t.Fatal(err) } r.primary.heartbeat(macPrimaryHello()) if acc, err := r.client.RetryTask(r.ctx, task); err != nil || acc.Attempt != attempt+1 { r.t.Fatalf("retry %+v %v", acc, err) } d := r.fromPrimary(wire.FrameDispatch).(*wire.DispatchCommand) if d.StepID != step || d.Attempt != attempt+1 || d.Specialist != wire.SpecialistEngineering { r.t.Fatalf("on the Mac primary %+v", d) } if k := r.task(task); k.EngineeringRunner != r.primary.fr.Welcome.RunnerID { r.t.Fatalf("not re-pinned to the Mac primary: %q", k.EngineeringRunner) } if !r.primary.lease(d.StepID, d.Attempt) { r.t.Fatal("start refused") } r.remove(r.primary.fr.Welcome.RunnerID, true) token := r.inst.EnrolRunner(r.t).Token h := primaryHello(0) h.Protocol, h.Label, h.Catalog = wire.ProtocolMacEngineering, "docs-t2", catalog np, err := DialRunnerHello(r.ctx, r.inst.URL, token, h) if err != nil || np.Welcome.Role != wire.RolePrimary { r.t.Fatalf("replacement %+v %v", np, err) } r.t.Cleanup(np.Close) if _, err := r.client.RecoverTask(r.ctx, task); err != nil { r.t.Fatal(err) } if acc, err := r.client.RetryTask(r.ctx, task); err != nil || acc.Attempt != attempt+2 { r.t.Fatalf("second retry %+v %v", acc, err) } if s := r.newestEngineering(task); s.State != wire.StepQueued || s.Placement != wire.PlacementMac || s.RunnerID != "" { r.t.Fatalf("after the Linux replacement: %+v", s) } time.Sleep(100 * time.Millisecond) if n := r.mailboxHas(np.Welcome.RunnerID, `"specialist":"engineering"`); n != 0 { r.t.Fatalf("%d engineering dispatches to the Linux primary", n) } } // Before anything was published: Mac A removed while its first attempt // may run, then the Mac primary that took it over. func TestContractMacNeedOutlivesPinsBeforePublication(t *testing.T) { r := newMacRig(t) a := r.newMacEngineer("Mac A", wire.EngineeringReady) task, d := r.macDispatch(a, "iOS twice removed", sha(1)) if !a.lease(d.StepID, d.Attempt) { t.Fatal("start refused") } r.macNeedOutlivesPins(task, d.StepID, d.Attempt, a, []wire.RepoInfo{}) } // After a published round: Mac A removed during the fix round, then the // Mac primary that took it over. func TestContractMacNeedOutlivesPinsAfterPublication(t *testing.T) { r := newMacRig(t) a := r.newMacEngineer("Mac A", wire.EngineeringReady) c1 := sha(0xc1) task, _ := r.macCandidate(a, "iOS fixed, twice removed", sha(1), c1) cw, c := r.macChecked(task, a) cw.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: c.StepID, Attempt: c.Attempt, State: wire.StepDone, CandidateSHA: c1, Checks: wire.ChecksFailed, Gate: "xcodebuild test", ExitCode: exit(65), Output: "FAILED", Termination: true, TerminationKind: wire.TerminationProcessGroup, Findings: []wire.Finding{}}) _, body := a.expect(wire.FrameDispatch) fix := body.(*wire.DispatchCommand) r.engineeringTransfer(a, fix) if !a.lease(fix.StepID, fix.Attempt) { t.Fatal("fix round refused") } // The replacement's catalog names the repository, as not needing a // Mac: a catalog only adds needs. r.macNeedOutlivesPins(task, fix.StepID, fix.Attempt, a, primaryHello(0).Catalog) } // A task whose Engineering never needed a Mac records no Mac need, and // stays on the Linux primary when the catalog later omits its repository. func TestContractNeverMacTaskUnaffected(t *testing.T) { r := newMacRig(t) r.newMacEngineer("Mac A", wire.EngineeringReady) h := primaryHello(0) h.Protocol = wire.ProtocolMacEngineering r.primary.heartbeat(h) task := r.macTask("Linux fix") d := r.fromPrimary(wire.FrameDispatch).(*wire.DispatchCommand) if d.Specialist != wire.SpecialistEngineering || d.RunnerID != r.primary.fr.Welcome.RunnerID { t.Fatalf("engineering %+v", d) } var needs string if err := r.inst.DB.Writer().QueryRow("SELECT coalesce(mac_needs, '') FROM chat_tasks WHERE id = ?", task).Scan(&needs); err != nil || needs != "" { t.Fatalf("mac_needs %q %v", needs, err) } r.primary.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d.StepID, Attempt: 1, State: wire.StepFailed, Reason: "provider_failed", Termination: true, TerminationKind: wire.TerminationNamespace, Findings: []wire.Finding{}}) h.Catalog = []wire.RepoInfo{} r.primary.heartbeat(h) if acc, err := r.client.RetryTask(r.ctx, task); err != nil || acc.Attempt != 2 { t.Fatalf("retry %+v %v", acc, err) } if d := r.fromPrimary(wire.FrameDispatch).(*wire.DispatchCommand); d.Specialist != wire.SpecialistEngineering || d.Attempt != 2 || d.RunnerID != r.primary.fr.Welcome.RunnerID { t.Fatalf("retry %+v", d) } } // forget_task reaches every runner that holds the task's steps: the // primary, as before, and the Mac worker that kept the task's // Engineering session and candidate (Mac runners slice F, task 12). func TestContractForgetReachesWorkers(t *testing.T) { r := newMacRig(t) w := r.newMacEngineer("Tito Studio", wire.EngineeringReady) task, _ := r.macCandidate(w, "iOS forget", sha(1), sha(0xf1)) _, c := r.macChecked(task, w) if res := r.call("c-forget", wire.ToolCancelTask, map[string]string{"task": task}); res.IsError { t.Fatalf("cancel: %+v", res) } w.expect(wire.FrameCancelStep) w.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: c.StepID, Attempt: c.Attempt, State: wire.StepCancelled, Reason: "cancelled", Termination: true, TerminationKind: wire.TerminationProcessGroup, Findings: []wire.Finding{}}) _, body := w.expect(wire.FrameForgetTask) if f := body.(*wire.ForgetTaskCommand); f.TaskID != task || f.KeepUntil != nil { t.Fatalf("the worker's forget %+v", f) } if f := r.fromPrimary(wire.FrameForgetTask).(*wire.ForgetTaskCommand); f.TaskID != task || f.KeepUntil != nil { t.Fatalf("the primary's forget %+v", f) } if n := r.mailbox(w.fr.Welcome.RunnerID, wire.FrameForgetTask); n != 1 { t.Fatalf("%d forgets to the worker", n) } }