oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package thintest
2
3import (
4 "fmt"
5 "slices"
6 "strings"
7 "testing"
8 "time"
9
10 "amadan.net/oficina/equipo/internal/equipo/chat"
11 "amadan.net/oficina/equipo/internal/wire"
12)
13
14// Mac Engineering (Mac runners slice F, plan task 3): Engineering for a
15// repository whose gate needs Xcode is placed on a Mac worker that can
16// take it, behind EQUIPO_MAC_ENGINEERING. The primary resolves the
17// attempt's base first (prepare_base, then its base report), and only
18// then is the attempt dispatched to the worker with the inbound
19// Engineering transfer, in one transaction. The task is pinned to that
20// worker; review stays on the primary, and a Mac-made candidate is never
21// merged by policy.
22
23// sha is a distinct full SHA for n.
24func sha(n int) string { return fmt.Sprintf("%040x", n) }
25
26// macEngineerHello is a Mac worker's hello at protocol: seatbelt, the Mac
27// tags, and the Engineering status state (claude only when ready). With
28// f5, probe F5 is denied (Xcode's services denied under Claude's own
29// sandbox).
30func macEngineerHello(label, state string, protocol int, f5 bool) wire.Hello {
31 h := WorkerHello(0)
32 h.Protocol, h.Label, h.Sandbox = protocol, label, wire.SandboxSeatbelt
33 caps := *h.Capabilities
34 caps.Tags = []string{wire.TagMacOS, wire.TagXcode, wire.TagIOSSimulator}
35 if state == wire.EngineeringReady {
36 caps.Tags = append(caps.Tags, wire.TagClaude)
37 }
38 caps.Probes = []wire.Probe{{ID: "P1", Verdict: wire.ProbePassed}, {ID: "P2", Verdict: wire.ProbeDenied}, {ID: "P4", Verdict: wire.ProbePassed}}
39 if protocol >= wire.ProtocolMacEngineering {
40 caps.Engineering = &wire.EngineeringStatus{State: state}
41 for _, id := range wire.EngineeringProbeIDs {
42 verdict := wire.EngineeringProbeSuccess(id)
43 if id == "F5" && !f5 {
44 verdict = wire.ProbeFailed
45 }
46 caps.Probes = append(caps.Probes, wire.Probe{ID: id, Verdict: verdict})
47 }
48 }
49 h.Capabilities = &caps
50 return h
51}
52
53// newMacRig is the runners rig with its primary at protocol 37, the
54// sample repository's gate needing Xcode, and the switch on.
55func newMacRig(t *testing.T) *runnersRig { return newMacRigAt(t, wire.ProtocolMacEngineering) }
56
57func newMacRigAt(t *testing.T, protocol int) *runnersRig {
58 r := newRunnersRigAt(t, protocol)
59 h := primaryHello(0)
60 h.Protocol = protocol
61 h.Catalog[0].NeedsMacOS = true
62 r.primary.heartbeat(h)
63 r.macEngineering(true)
64 return r
65}
66
67// macEngineering is EQUIPO_MAC_ENGINEERING, for this process and the next.
68func (r *runnersRig) macEngineering(on bool) {
69 r.inst.MacEngineering = on
70 r.inst.Store.Chat().SetMacEngineering(on)
71}
72
73// newMacEngineer enrols and connects a Mac worker at protocol 37 whose
74// Engineering status is state.
75func (r *runnersRig) newMacEngineer(label, state string) *peer {
76 return r.newMacEngineerAt(label, state, wire.ProtocolMacEngineering, false)
77}
78
79func (r *runnersRig) newMacEngineerAt(label, state string, protocol int, f5 bool) *peer {
80 r.t.Helper()
81 token := r.inst.EnrolRunner(r.t).Token
82 fr, err := DialRunnerHello(r.ctx, r.inst.URL, token, macEngineerHello(label, state, protocol, f5))
83 if err != nil {
84 r.t.Fatal(err)
85 }
86 r.t.Cleanup(fr.Close)
87 r.creds[fr] = [2]string{token, label}
88 return &peer{t: r.t, r: r.toolRig, fr: fr}
89}
90
91// macState says a new Engineering status (and tags) in w's hello.
92func (r *runnersRig) macState(w *peer, state string, f5 bool) {
93 r.t.Helper()
94 w.heartbeat(macEngineerHello(r.creds[w.fr][1], state, wire.ProtocolMacEngineering, f5))
95}
96
97// fromPrimary is the next frame of kind sent to the primary, whichever of
98// the rig's readers took it off the socket, acked.
99func (r *runnersRig) fromPrimary(kind string) any {
100 r.t.Helper()
101 for i, h := range r.held {
102 if h.f.Type == kind {
103 r.held = append(r.held[:i:i], r.held[i+1:]...)
104 r.primary.ack(h.f)
105 return h.body
106 }
107 }
108 _, body := r.primary.expect(kind)
109 return body
110}
111
112// mailbox counts a runner's commands of kind, acked or not.
113func (r *runnersRig) mailbox(runner, kind string) int {
114 r.t.Helper()
115 var n int
116 if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM runner_commands WHERE runner_id = ? AND kind = ?", runner, kind).Scan(&n); err != nil {
117 r.t.Fatal(err)
118 }
119 return n
120}
121
122// mailboxHas counts a runner's commands whose body contains text.
123func (r *runnersRig) mailboxHas(runner, text string) int {
124 r.t.Helper()
125 var n int
126 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 {
127 r.t.Fatal(err)
128 }
129 return n
130}
131
132// macTask records and starts a task in the Mac repository.
133func (r *runnersRig) macTask(title string) string {
134 r.t.Helper()
135 task := taskID(r.t, r.call("c-"+title, wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": title, "brief": "b"}))
136 r.call("s-"+title, wire.ToolStartTask, map[string]string{"task": task, "brief": "go"})
137 return task
138}
139
140// prepared is the primary's prepare_base for the task's newest
141// Engineering attempt.
142func (r *runnersRig) prepared(task string) *wire.PrepareBaseCommand {
143 r.t.Helper()
144 pb := r.fromPrimary(wire.FramePrepareBase).(*wire.PrepareBaseCommand)
145 if pb.TaskID != task || !pb.Valid() || !strings.HasSuffix(pb.Repo, "oficina/sample") {
146 r.t.Fatalf("prepare_base %+v", pb)
147 }
148 return pb
149}
150
151// based answers prepare_base from the primary's connection.
152func (r *runnersRig) based(pb *wire.PrepareBaseCommand, base string) {
153 r.t.Helper()
154 r.primary.send(wire.FrameBase, wire.BaseReport{TaskID: pb.TaskID, StepID: pb.StepID, Attempt: pb.Attempt, BaseSHA: base})
155}
156
157// newestEngineering is the task's newest Engineering step.
158func (r *runnersRig) newestEngineering(task string) wire.Step {
159 r.t.Helper()
160 k, err := r.client.Task(r.ctx, task)
161 if err != nil {
162 r.t.Fatal(err)
163 }
164 for i := len(k.Steps) - 1; i >= 0; i-- {
165 if k.Steps[i].Specialist == wire.SpecialistEngineering {
166 return k.Steps[i]
167 }
168 }
169 r.t.Fatalf("no engineering step: %+v", k.Steps)
170 return wire.Step{}
171}
172
173func (r *runnersRig) task(id string) wire.Task {
174 r.t.Helper()
175 k, err := r.client.Task(r.ctx, id)
176 if err != nil {
177 r.t.Fatal(err)
178 }
179 return k
180}
181
182// engineeringTransfer is the inbound Engineering transfer the primary is
183// asked to upload for an attempt on w.
184func (r *runnersRig) engineeringTransfer(w *peer, d *wire.DispatchCommand) wire.TransferHeader {
185 r.t.Helper()
186 h := r.fromPrimary(wire.FrameSendPack).(*wire.SendPackCommand).Transfer
187 if h.Kind != wire.TransferKindEngineering || h.Direction != wire.TransferInbound || h.StepID != d.StepID || h.Attempt != d.Attempt || h.BaseSHA != d.BaseSHA || !h.Valid() {
188 r.t.Fatalf("engineering transfer %+v for %+v", h, d)
189 }
190 return h
191}
192
193// workerCommitted runs w's Engineering attempt d to a commit: started,
194// committed (the outbound transfer opens for exactly that candidate), its
195// pack sent, which reaches the primary with a publish command. With done,
196// the worker's final report comes before the pack.
197func (r *runnersRig) workerCommitted(w *peer, d *wire.DispatchCommand, cand string, done bool) *wire.PublishCommand {
198 r.t.Helper()
199 if !w.lease(d.StepID, d.Attempt) {
200 r.t.Fatal("start refused")
201 }
202 w.send(wire.FrameStep, wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepRunning, BaseSHA: d.BaseSHA, Findings: []wire.Finding{}})
203 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{}})
204 _, body := w.expect(wire.FrameSendPack)
205 h := body.(*wire.SendPackCommand).Transfer
206 if h.Direction != wire.TransferOutbound || h.CandidateSHA != cand || h.BaseSHA != d.BaseSHA || h.Kind != "" || h.Attempt != d.Attempt {
207 r.t.Fatalf("outbound header %+v", h)
208 }
209 if done {
210 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{}})
211 }
212 w.send(wire.FrameBlob, chunk(h, []byte("PACK commit")))
213 r.fromPrimary(wire.FrameBlob)
214 pub := r.fromPrimary(wire.FramePublish).(*wire.PublishCommand)
215 if pub.CandidateSHA != cand || pub.Transfer != h.ID || pub.StepID != d.StepID || pub.Attempt != d.Attempt {
216 r.t.Fatalf("publish %+v", pub)
217 }
218 return pub
219}
220
221// macDispatch is the first Engineering attempt of a new Mac task on w:
222// prepared, based on base, dispatched with its transfer.
223func (r *runnersRig) macDispatch(w *peer, title, base string) (string, *wire.DispatchCommand) {
224 r.t.Helper()
225 task := r.macTask(title)
226 r.based(r.prepared(task), base)
227 _, body := w.expect(wire.FrameDispatch)
228 d := body.(*wire.DispatchCommand)
229 if d.TaskID != task || d.Specialist != wire.SpecialistEngineering || d.BaseSHA != base || d.RunnerID != w.fr.Welcome.RunnerID {
230 r.t.Fatalf("dispatch %+v", d)
231 }
232 r.engineeringTransfer(w, d)
233 return task, d
234}
235
236// macCandidate is a Mac task whose first Engineering attempt ran on w and
237// whose candidate cand the primary published.
238func (r *runnersRig) macCandidate(w *peer, title, base, cand string) (string, *wire.DispatchCommand) {
239 r.t.Helper()
240 task, d := r.macDispatch(w, title, base)
241 pub := r.workerCommitted(w, d, cand, true)
242 r.primary.send(wire.FramePublished, wire.PublishedReport{Publication: pub.Publication, TaskID: task, StepID: d.StepID, Attempt: d.Attempt, CandidateSHA: cand, Pushed: true})
243 if k := r.task(task); k.CandidateSHA != cand || k.EngineeringRunner != w.fr.Welcome.RunnerID {
244 r.t.Fatalf("published %+v", k)
245 }
246 return task, d
247}
248
249// peerOf is the peer runner id is, of those given.
250func peerOf(id string, ps ...*peer) *peer {
251 for _, p := range ps {
252 if p.fr.Welcome.RunnerID == id {
253 return p
254 }
255 }
256 return nil
257}
258
259// macChecked takes the checks dispatch of the task from whichever of ws
260// it was placed on, with its relay.
261func (r *runnersRig) macChecked(task string, ws ...*peer) (*peer, *wire.DispatchCommand) {
262 r.t.Helper()
263 s := r.newest(task, wire.SpecialistChecks)
264 w := peerOf(s.RunnerID, ws...)
265 if w == nil {
266 r.t.Fatalf("checks not on a Mac worker: %+v", s)
267 }
268 _, body := w.expect(wire.FrameDispatch)
269 c := body.(*wire.DispatchCommand)
270 if c.Specialist != wire.SpecialistChecks || c.TaskID != task || c.StepID != s.ID || c.Attempt != s.Attempt {
271 r.t.Fatalf("checks dispatch %+v for %+v", c, s)
272 }
273 r.fromPrimary(wire.FrameSendPack)
274 return w, c
275}
276
277// 1. The first Engineering step of Mac work: prepare_base to the primary
278// first, nothing else; on its base, the dispatch to the worker and the
279// inbound Engineering transfer (base only) are written in one
280// transaction, and the task is pinned to the worker.
281func TestContractMacEngineeringPlacedOnWorker(t *testing.T) {
282 r := newMacRig(t)
283 w := r.newMacEngineer("Tito Studio", wire.EngineeringReady)
284 task := r.macTask("iOS settings")
285 pb := r.prepared(task)
286 if pb.Attempt != 1 || pb.Rebase || pb.FromBase != "" || pb.CandidateSHA != "" {
287 t.Fatalf("prepare_base %+v", pb)
288 }
289 s := r.engineeringStep(task)
290 if s.State != wire.StepQueued || s.Placement != wire.PlacementBase || s.RunnerID != "" || s.BaseSHA != "" || s.ID != pb.StepID {
291 t.Fatalf("waiting for the base: %+v", s)
292 }
293 // Nothing goes to the worker, and no transfer opens, before the base
294 // is bound.
295 w.none(wire.FrameDispatch, 150*time.Millisecond)
296 r.primary.none(wire.FrameSendPack, 0)
297 if n := r.mailbox(r.primary.fr.Welcome.RunnerID, wire.FrameSendPack) + r.mailbox(w.fr.Welcome.RunnerID, wire.FrameDispatch); n != 0 {
298 t.Fatalf("%d commands before the base", n)
299 }
300 if n := r.mailbox(r.primary.fr.Welcome.RunnerID, wire.FrameDispatch); n != 0 {
301 t.Fatal("Mac engineering dispatched to the Linux primary")
302 }
303 base := sha(1)
304 r.based(pb, base)
305 // The base report's transaction wrote both: they are there once it is
306 // acked.
307 if n, m := r.mailbox(r.primary.fr.Welcome.RunnerID, wire.FrameSendPack), r.mailbox(w.fr.Welcome.RunnerID, wire.FrameDispatch); n != 1 || m != 1 {
308 t.Fatalf("after the base: %d send_pack, %d dispatch", n, m)
309 }
310 _, body := w.expect(wire.FrameDispatch)
311 d := body.(*wire.DispatchCommand)
312 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 != "" {
313 t.Fatalf("dispatch %+v", d)
314 }
315 h := r.engineeringTransfer(w, d)
316 if h.OldBaseSHA != "" || h.CandidateSHA != "" || !slices.Equal(h.Commits(), []string{base}) || h.TaskID != task {
317 t.Fatalf("transfer %+v", h)
318 }
319 k := r.task(task)
320 if k.EngineeringRunner != w.fr.Welcome.RunnerID || k.BaseSHA != base {
321 t.Fatalf("not pinned: %+v", k)
322 }
323 if s := r.engineeringStep(task); s.RunnerID != w.fr.Welcome.RunnerID || s.Placement != "" || s.BaseSHA != base || s.RunnerLabel != "Tito Studio" {
324 t.Fatalf("placed %+v", s)
325 }
326 if !w.lease(d.StepID, 1) {
327 t.Fatal("the worker's start was refused")
328 }
329 r.primary.none(wire.FrameDispatch, 0)
330}
331
332// 2. Unset, Mac Engineering waits exactly as mac-placement-wait left it,
333// with a Mac that could take it; set, the minute's placement takes it
334// from there.
335func TestContractMacEngineeringSwitchOff(t *testing.T) {
336 r := newMacRig(t)
337 r.macEngineering(false)
338 w := r.newMacEngineer("Tito Studio", wire.EngineeringReady)
339 task := r.macTask("iOS switch")
340 w.none(wire.FrameDispatch, 150*time.Millisecond)
341 r.primary.none(wire.FramePrepareBase, 0)
342 r.primary.none(wire.FrameDispatch, 0)
343 s := r.engineeringStep(task)
344 if s.State != wire.StepQueued || s.Placement != wire.PlacementMacEngineering || s.RunnerID != "" || strings.Join(s.Needs, ",") != "macos,xcode" {
345 t.Fatalf("switch off: %+v", s)
346 }
347 if got := r.needsYou(task); got != wire.NeedsMacEngineering {
348 t.Fatalf("needs you %q", got)
349 }
350 r.macEngineering(true)
351 if err := r.inst.Store.Chat().Place(r.ctx); err != nil {
352 t.Fatal(err)
353 }
354 r.prepared(task)
355 if s := r.engineeringStep(task); s.Placement != wire.PlacementBase {
356 t.Fatalf("switch on: %+v", s)
357 }
358}
359
360// 3. A Mac that fits all but claude: each Engineering status is its own
361// wait (waiting_mac_connection, read from the Mac's status now) and
362// Needs-you line; once the status is ready, the step is placed.
363func TestContractMacEngineeringStatusWaits(t *testing.T) {
364 r := newMacRig(t)
365 w := r.newMacEngineer("Tito Studio", wire.EngineeringNoConnection)
366 task := r.macTask("iOS status")
367 for _, state := range wire.EngineeringStates[1:] {
368 r.macState(w, state, false)
369 k := r.task(task)
370 s := r.engineeringStep(task)
371 if s.State != wire.StepQueued || s.Placement != wire.PlacementMacConnection || s.RunnerID != "" || s.RunnerLabel != "Tito Studio" || s.EngineeringStatus == nil || s.EngineeringStatus.State != state {
372 t.Fatalf("%s: %+v", state, s)
373 }
374 if k.NeedsYou != wire.NeedsMacConnection {
375 t.Fatalf("%s: needs you %q", state, k.NeedsYou)
376 }
377 w.none(wire.FrameDispatch, 50*time.Millisecond)
378 r.primary.none(wire.FramePrepareBase, 0)
379 }
380 r.macState(w, wire.EngineeringReady, false)
381 pb := r.prepared(task)
382 if s := r.engineeringStep(task); s.Placement != wire.PlacementBase || s.EngineeringStatus != nil || r.needsYou(task) != "" {
383 t.Fatalf("ready: %+v", s)
384 }
385 r.based(pb, sha(3))
386 _, body := w.expect(wire.FrameDispatch)
387 if d := body.(*wire.DispatchCommand); d.TaskID != task || d.BaseSHA != sha(3) {
388 t.Fatalf("dispatch %+v", d)
389 }
390}
391
392// 4. A worker below protocol 37 waits waiting_mac_update, naming the
393// worker; nothing of protocol 37 reaches either runner.
394func TestContractMacEngineeringOldWorker(t *testing.T) {
395 r := newMacRig(t)
396 w := r.newMacEngineerAt("Tito Studio", wire.EngineeringReady, wire.ProtocolChangeDiffs, false)
397 task := r.macTask("iOS old worker")
398 w.none(wire.FrameDispatch, 150*time.Millisecond)
399 s := r.engineeringStep(task)
400 if s.State != wire.StepQueued || s.Placement != wire.PlacementMacUpdate || s.RunnerLabel != "Tito Studio" || s.RunnerID != "" {
401 t.Fatalf("old worker: %+v", s)
402 }
403 if got := r.needsYou(task); got != wire.NeedsMacUpdate {
404 t.Fatalf("needs you %q", got)
405 }
406 for _, id := range []string{w.fr.Welcome.RunnerID, r.primary.fr.Welcome.RunnerID} {
407 if n := r.mailbox(id, wire.FramePrepareBase) + r.mailbox(id, wire.FrameDispatch) + r.mailboxHas(id, `"xcode_access"`) + r.mailboxHas(id, `"kind":"engineering"`); n != 0 {
408 t.Fatalf("%d protocol 37 commands for %s", n, id)
409 }
410 }
411}
412
413// 4. A primary below protocol 37 cannot prepare a base: waiting_mac_update,
414// naming the primary, and it is sent nothing it cannot carry.
415func TestContractMacEngineeringOldPrimary(t *testing.T) {
416 r := newMacRigAt(t, wire.ProtocolChangeDiffs)
417 w := r.newMacEngineer("Tito Studio", wire.EngineeringReady)
418 task := r.macTask("iOS old primary")
419 w.none(wire.FrameDispatch, 150*time.Millisecond)
420 s := r.engineeringStep(task)
421 if s.State != wire.StepQueued || s.Placement != wire.PlacementMacUpdate || s.RunnerLabel != "docs-t1" || s.RunnerID != "" {
422 t.Fatalf("old primary: %+v", s)
423 }
424 if got := r.needsYou(task); got != wire.NeedsMacUpdate {
425 t.Fatalf("needs you %q", got)
426 }
427 for _, id := range []string{w.fr.Welcome.RunnerID, r.primary.fr.Welcome.RunnerID} {
428 if n := r.mailbox(id, wire.FramePrepareBase) + r.mailbox(id, wire.FrameDispatch) + r.mailboxHas(id, `"xcode_access"`) + r.mailboxHas(id, `"kind":"engineering"`); n != 0 {
429 t.Fatalf("%d protocol 37 commands for %s", n, id)
430 }
431 }
432}
433
434// 5. The only Mac that fits is offline: the step waits for it
435// (waiting_runner), raises Needs you runner_offline after 30 minutes and
436// keeps waiting; Cancel works; it never moves to Linux.
437func TestContractMacEngineeringOffline(t *testing.T) {
438 r := newMacRig(t)
439 w := r.newMacEngineer("Tito Studio", wire.EngineeringReady)
440 w.fr.Close()
441 deadline := time.Now().Add(5 * time.Second)
442 for {
443 runners, err := r.client.Runners(r.ctx)
444 offline := false
445 for _, x := range runners.Items {
446 offline = offline || x.ID == w.fr.Welcome.RunnerID && !x.Online
447 }
448 if err == nil && offline {
449 break
450 }
451 if time.Now().After(deadline) {
452 t.Fatalf("worker still online: %+v %v", runners, err)
453 }
454 time.Sleep(50 * time.Millisecond)
455 }
456 task := r.macTask("iOS offline")
457 s := r.engineeringStep(task)
458 if s.State != wire.StepQueued || s.Placement != wire.PlacementWaiting || s.RunnerLabel != "Tito Studio" || r.needsYou(task) != "" {
459 t.Fatalf("waiting for the Mac: %+v needs %q", s, r.needsYou(task))
460 }
461 clock := time.Now().UTC().Add(chat.OfflineLimit + time.Minute)
462 r.inst.Store.Chat().SetClock(func() time.Time { return clock })
463 if err := r.inst.Store.Chat().Place(r.ctx); err != nil {
464 t.Fatal(err)
465 }
466 if s := r.engineeringStep(task); s.State != wire.StepQueued || s.Placement != wire.PlacementWaiting || s.Attempt != 1 {
467 t.Fatalf("after the limit: %+v", s)
468 }
469 if got := r.needsYou(task); got != wire.NeedsRunnerOffline {
470 t.Fatalf("needs you %q", got)
471 }
472 r.primary.none(wire.FrameDispatch, 50*time.Millisecond)
473 r.primary.none(wire.FramePrepareBase, 0)
474 if _, err := r.client.CancelTask(r.ctx, task); err != nil {
475 t.Fatal(err)
476 }
477 if k := r.task(task); k.Stage != wire.StageCancelled || k.NeedsYou != "" {
478 t.Fatalf("not cancelled: %+v", k)
479 }
480 if n := r.mailbox(r.primary.fr.Welcome.RunnerID, wire.FrameDispatch); n != 0 {
481 t.Fatal("Mac engineering went to Linux")
482 }
483}
484
485// 6. A fix round, a Retry, a republish and a rebase round all go to the
486// pinned worker while a second worker fits too. The fix round's base is
487// the published tip (no prepare_base); the rebase round's base comes from
488// the primary, and its transfer carries base, old base and candidate.
489func TestContractMacEngineeringPinHolds(t *testing.T) {
490 r := newMacRig(t)
491 r.shipsNo(r.project())
492 a := r.newMacEngineer("Mac A", wire.EngineeringReady)
493 base, c1, c2, tip := sha(1), sha(0xc1), sha(0xc2), sha(0x71)
494 task, _ := r.macCandidate(a, "iOS pinned", base, c1)
495 b := r.newMacEngineer("Mac B", wire.EngineeringReady)
496 // Checks of c1 fail: a fix round, on c1, on Mac A.
497 cw, c := r.macChecked(task, a, b)
498 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{}})
499 _, body := a.expect(wire.FrameDispatch)
500 fix := body.(*wire.DispatchCommand)
501 if fix.Specialist != wire.SpecialistEngineering || fix.Round != 1 || fix.BaseSHA != c1 || fix.Attempt != 1 {
502 t.Fatalf("fix round %+v", fix)
503 }
504 if h := r.engineeringTransfer(a, fix); !slices.Equal(h.Commits(), []string{c1}) {
505 t.Fatalf("fix transfer %+v", h)
506 }
507 if n := r.mailbox(r.primary.fr.Welcome.RunnerID, wire.FramePrepareBase); n != 1 {
508 t.Fatalf("a fix round prepared a base: %d", n)
509 }
510 // It fails; Retry: Mac A again, from the same base.
511 if !a.lease(fix.StepID, 1) {
512 t.Fatal("fix round refused")
513 }
514 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{}})
515 if acc, err := r.client.RetryTask(r.ctx, task); err != nil || acc.Attempt != 2 {
516 t.Fatalf("retry %+v %v", acc, err)
517 }
518 _, body = a.expect(wire.FrameDispatch)
519 retry := body.(*wire.DispatchCommand)
520 if retry.StepID != fix.StepID || retry.Attempt != 2 || retry.BaseSHA != c1 {
521 t.Fatalf("retry %+v", retry)
522 }
523 r.engineeringTransfer(a, retry)
524 // Its push fails; Retry publishes the same commit again, on the
525 // primary, running nothing on any Mac.
526 pub := r.workerCommitted(a, retry, c2, true)
527 if !r.primary.leasePublication(retry.StepID, 2, pub.Publication) {
528 t.Fatal("publication refused")
529 }
530 r.primary.send(wire.FramePublished, wire.PublishedReport{Publication: pub.Publication, TaskID: task, StepID: retry.StepID, Attempt: 2, CandidateSHA: c2, Pushed: false, Reason: "push_failed"})
531 if acc, err := r.client.RetryTask(r.ctx, task); err != nil || acc.Attempt != 2 {
532 t.Fatalf("republish %+v %v", acc, err)
533 }
534 again := r.fromPrimary(wire.FramePublish).(*wire.PublishCommand)
535 if again.CandidateSHA != c2 || again.Transfer != pub.Transfer {
536 t.Fatalf("republish %+v", again)
537 }
538 a.none(wire.FrameDispatch, 50*time.Millisecond)
539 b.none(wire.FrameDispatch, 0)
540 r.primary.send(wire.FramePublished, wire.PublishedReport{Publication: again.Publication, TaskID: task, StepID: retry.StepID, Attempt: 2, CandidateSHA: c2, Pushed: true})
541 // Checks pass on a Mac, review approves on the primary, the person
542 // merges, and the merge conflicts: a rebase round, on Mac A.
543 cw, c = r.macChecked(task, a, b)
544 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{}})
545 rv := r.fromPrimary(wire.FrameDispatch).(*wire.DispatchCommand)
546 if rv.Specialist != wire.SpecialistReview || rv.RunnerID != r.primary.fr.Welcome.RunnerID {
547 t.Fatalf("review %+v", rv)
548 }
549 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."})
550 card := r.mergeCardFor(task)
551 if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceMerge, card.Revision); err != nil {
552 t.Fatal(err)
553 }
554 m := r.fromPrimary(wire.FrameDispatch).(*wire.DispatchCommand)
555 if m.Specialist != wire.SpecialistMerge || m.CandidateSHA != c2 {
556 t.Fatalf("merge %+v", m)
557 }
558 r.primary.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: m.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, CandidateSHA: c2})
559 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})
560 pb := r.prepared(task)
561 if !pb.Rebase || pb.FromBase != base || pb.CandidateSHA != c2 || pb.Attempt != 1 {
562 t.Fatalf("rebase prepare_base %+v", pb)
563 }
564 r.based(pb, tip)
565 _, body = a.expect(wire.FrameDispatch)
566 rb := body.(*wire.DispatchCommand)
567 if !rb.Rebase || rb.BaseSHA != tip || rb.FromBase != base || rb.CandidateSHA != c2 {
568 t.Fatalf("rebase round %+v", rb)
569 }
570 h := r.engineeringTransfer(a, rb)
571 if h.OldBaseSHA != base || h.CandidateSHA != c2 || !slices.Equal(h.Commits(), []string{tip, base, c2}) {
572 t.Fatalf("rebase transfer %+v", h)
573 }
574 b.none(wire.FrameDispatch, 50*time.Millisecond)
575 if n := r.mailboxHas(b.fr.Welcome.RunnerID, `"specialist":"engineering"`); n != 0 {
576 t.Fatalf("Mac B got %d engineering dispatches", n)
577 }
578 for _, s := range r.task(task).Steps {
579 if s.Specialist == wire.SpecialistEngineering && s.RunnerID != a.fr.Welcome.RunnerID {
580 t.Fatalf("an engineering step off the pinned Mac: %+v", s)
581 }
582 }
583}
584
585// mergeCardFor waits for the task's open merge card.
586func (r *runnersRig) mergeCardFor(task string) wire.Card {
587 r.t.Helper()
588 deadline := time.Now().Add(5 * time.Second)
589 for time.Now().Before(deadline) {
590 for _, c := range r.mergeCards(task) {
591 if c.State == wire.CardOpen {
592 return c
593 }
594 }
595 time.Sleep(20 * time.Millisecond)
596 }
597 r.t.Fatalf("no merge card for %s: %+v", task, r.task(task))
598 return wire.Card{}
599}
600
601// 7. The pinned worker loses claude mid-task: the next round waits for
602// it (waiting_mac_connection, naming it) and is never placed on the
603// second worker that fits; once it is ready again, it runs there.
604func TestContractMacEngineeringPinnedLostTag(t *testing.T) {
605 r := newMacRig(t)
606 a := r.newMacEngineer("Mac A", wire.EngineeringReady)
607 b := r.newMacEngineer("Mac B", wire.EngineeringReady)
608 c1 := sha(0xc1)
609 task, _ := r.macCandidate(a, "iOS lost tag", sha(1), c1)
610 r.macState(a, wire.EngineeringSignedOut, false)
611 cw, c := r.macChecked(task, a, b)
612 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{}})
613 s := r.newestEngineering(task)
614 if s.Round != 1 || s.State != wire.StepQueued || s.Placement != wire.PlacementMacConnection || s.RunnerLabel != "Mac A" || s.EngineeringStatus == nil || s.EngineeringStatus.State != wire.EngineeringSignedOut {
615 t.Fatalf("fix round with the pinned Mac signed out: %+v", s)
616 }
617 if got := r.needsYou(task); got != wire.NeedsMacConnection {
618 t.Fatalf("needs you %q", got)
619 }
620 if err := r.inst.Store.Chat().Place(r.ctx); err != nil {
621 t.Fatal(err)
622 }
623 b.none(wire.FrameDispatch, 100*time.Millisecond)
624 a.none(wire.FrameDispatch, 0)
625 r.macState(a, wire.EngineeringReady, false)
626 _, body := a.expect(wire.FrameDispatch)
627 if d := body.(*wire.DispatchCommand); d.StepID != s.ID || d.BaseSHA != c1 {
628 t.Fatalf("fix round %+v", d)
629 }
630 b.none(wire.FrameDispatch, 0)
631}
632
633// 8. The pinned worker is removed while its fix round may run: the step
634// is quarantined (machine_removed) until the creator recovers it; Retry
635// then re-pins to a fitting Mac, or waits for one (waiting_mac), and is
636// never placed on the Linux primary.
637func TestContractMacEngineeringPinnedRemoved(t *testing.T) {
638 r := newMacRig(t)
639 a := r.newMacEngineer("Mac A", wire.EngineeringReady)
640 c1 := sha(0xc1)
641 task, _ := r.macCandidate(a, "iOS removed", sha(1), c1)
642 cw, c := r.macChecked(task, a)
643 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{}})
644 _, body := a.expect(wire.FrameDispatch)
645 fix := body.(*wire.DispatchCommand)
646 r.engineeringTransfer(a, fix)
647 if !a.lease(fix.StepID, fix.Attempt) {
648 t.Fatal("fix round refused")
649 }
650 r.remove(a.fr.Welcome.RunnerID, true)
651 if s := r.newestEngineering(task); s.State != wire.StepFailed || s.Reason != "machine_removed" || r.needsYou(task) != wire.NeedsMachineRemoved {
652 t.Fatalf("not quarantined: %+v", s)
653 }
654 if _, err := r.client.RecoverTask(r.ctx, task); err != nil {
655 t.Fatal(err)
656 }
657 // The primary's catalog no longer names the repository: the task was
658 // made on a Mac, so it still needs one.
659 h := primaryHello(0)
660 h.Protocol, h.Catalog = wire.ProtocolMacEngineering, []wire.RepoInfo{}
661 r.primary.heartbeat(h)
662 if acc, err := r.client.RetryTask(r.ctx, task); err != nil || acc.Attempt != 2 {
663 t.Fatalf("retry %+v %v", acc, err)
664 }
665 s := r.newestEngineering(task)
666 if s.State != wire.StepQueued || s.Placement != wire.PlacementMac || s.RunnerID != "" || r.needsYou(task) != wire.NeedsMacRunner {
667 t.Fatalf("after recovery, no Mac: %+v", s)
668 }
669 r.primary.none(wire.FrameDispatch, 100*time.Millisecond)
670 b := r.newMacEngineer("Mac B", wire.EngineeringReady)
671 _, body = b.expect(wire.FrameDispatch)
672 d := body.(*wire.DispatchCommand)
673 if d.StepID != fix.StepID || d.Attempt != 2 || d.BaseSHA != c1 {
674 t.Fatalf("re-pinned %+v", d)
675 }
676 r.engineeringTransfer(b, d)
677 if k := r.task(task); k.EngineeringRunner != b.fr.Welcome.RunnerID {
678 t.Fatalf("pin %q", k.EngineeringRunner)
679 }
680 for _, s := range r.task(task).Steps {
681 if s.Specialist == wire.SpecialistEngineering && s.RunnerID == r.primary.fr.Welcome.RunnerID {
682 t.Fatalf("engineering on the Linux primary: %+v", s)
683 }
684 }
685 r.primary.none(wire.FrameDispatch, 0)
686}
687
688// 9. Only the primary's base report for the attempt waiting for it binds:
689// one from the worker, for an older attempt, after the attempt was
690// withdrawn, or after Cancel is refused and logged; a second report for
691// the same attempt does nothing; base_unavailable ends the attempt
692// failed, Needs you retry.
693func TestContractPrepareBase(t *testing.T) {
694 r := newMacRig(t)
695 w := r.newMacEngineer("Tito Studio", wire.EngineeringReady)
696 task := r.macTask("iOS base")
697 pb := r.prepared(task)
698 waiting := func(what string, attempt int64) {
699 t.Helper()
700 s := r.engineeringStep(task)
701 if s.Placement != wire.PlacementBase || s.Attempt != attempt || s.BaseSHA != "" || s.RunnerID != "" {
702 t.Fatalf("%s: %+v", what, s)
703 }
704 w.none(wire.FrameDispatch, 50*time.Millisecond)
705 r.primary.none(wire.FrameSendPack, 0)
706 }
707 // From the worker's connection.
708 w.send(wire.FrameBase, wire.BaseReport{TaskID: task, StepID: pb.StepID, Attempt: 1, BaseSHA: sha(1)})
709 waiting("worker's report", 1)
710 if !strings.Contains(r.inst.Logs(), "base_refused: not the primary") {
711 t.Fatalf("worker's report not logged: %s", r.inst.Logs())
712 }
713 // The primary cannot resolve it: the attempt fails, Needs you retry.
714 r.primary.send(wire.FrameBase, wire.BaseReport{TaskID: task, StepID: pb.StepID, Attempt: 1, Reason: wire.ReasonBaseUnavailable})
715 s := r.engineeringStep(task)
716 if s.State != wire.StepFailed || s.Reason != wire.ReasonBaseUnavailable || !s.Terminated || s.Placement != "" || r.needsYou(task) != wire.NeedsRetry {
717 t.Fatalf("base unavailable: %+v needs %q", s, r.needsYou(task))
718 }
719 if acc, err := r.client.RetryTask(r.ctx, task); err != nil || acc.Attempt != 2 {
720 t.Fatalf("retry %+v %v", acc, err)
721 }
722 pb2 := r.prepared(task)
723 if pb2.Attempt != 2 || pb2.StepID != pb.StepID {
724 t.Fatalf("second prepare_base %+v", pb2)
725 }
726 // A late report for the older attempt.
727 r.based(pb, sha(2))
728 waiting("older attempt", 2)
729 if !strings.Contains(r.inst.Logs(), "base_refused: attempt not current") {
730 t.Fatal("older attempt's report not logged")
731 }
732 // The Mac is removed while the attempt waits for its base: the attempt
733 // is withdrawn (the next waits for a Mac), and its report is refused.
734 r.remove(w.fr.Welcome.RunnerID, false)
735 if s := r.engineeringStep(task); s.Attempt != 3 || s.Placement != wire.PlacementMac {
736 t.Fatalf("withdrawn: %+v", s)
737 }
738 r.based(pb2, sha(3))
739 if s := r.engineeringStep(task); s.Attempt != 3 || s.BaseSHA != "" || s.Placement != wire.PlacementMac {
740 t.Fatalf("withdrawn attempt's base bound: %+v", s)
741 }
742 if strings.Count(r.inst.Logs(), "base_refused: attempt not current") < 2 {
743 t.Fatal("withdrawn attempt's report not logged")
744 }
745 // A Mac that fits enrols: the waiting attempt is prepared for it.
746 w2 := r.newMacEngineer("Mac B", wire.EngineeringReady)
747 if pb3 := r.prepared(task); pb3.Attempt != 3 {
748 t.Fatalf("third prepare_base %+v", pb3)
749 }
750 // After Cancel.
751 other := r.macTask("iOS cancelled")
752 pc := r.prepared(other)
753 if _, err := r.client.CancelTask(r.ctx, other); err != nil {
754 t.Fatal(err)
755 }
756 r.based(pc, sha(4))
757 if k := r.task(other); k.Stage != wire.StageCancelled || k.Steps[0].BaseSHA != "" {
758 t.Fatalf("cancelled task's base bound: %+v", k)
759 }
760 if !strings.Contains(r.inst.Logs(), "base_refused: task ended") {
761 t.Fatal("cancelled task's report not logged")
762 }
763 w2.none(wire.FrameDispatch, 50*time.Millisecond)
764 // A second report for the same attempt changes nothing.
765 third := r.macTask("iOS twice")
766 pt := r.prepared(third)
767 r.based(pt, sha(5))
768 w2.expect(wire.FrameDispatch)
769 r.based(pt, sha(6))
770 if s := r.engineeringStep(third); s.BaseSHA != sha(5) || s.Attempt != 1 {
771 t.Fatalf("second report rebound: %+v", s)
772 }
773 w2.none(wire.FrameDispatch, 50*time.Millisecond)
774 if n := r.mailbox(r.primary.fr.Welcome.RunnerID, wire.FrameSendPack); n != 1 {
775 t.Fatalf("%d transfers", n)
776 }
777}
778
779// 10. Xcode access for Engineering follows the proof: sent only to a Mac
780// the instance holds sandbox-proven (seatbelt, untainted) whose probe F5
781// is denied. Without F5, with the sandbox not proven, or tainted, none.
782func TestContractMacEngineeringXcodeAccess(t *testing.T) {
783 r := newMacRig(t)
784 w := r.newMacEngineerAt("Tito Studio", wire.EngineeringReady, wire.ProtocolMacEngineering, true)
785 access := func(title string) string {
786 t.Helper()
787 task := r.macTask(title)
788 r.based(r.prepared(task), sha(1))
789 _, body := w.expect(wire.FrameDispatch)
790 r.fromPrimary(wire.FrameSendPack)
791 return body.(*wire.DispatchCommand).XcodeAccess
792 }
793 if got := access("iOS proven"); got != wire.XcodeAccessSandboxed {
794 t.Fatalf("proven with F5 denied: %q", got)
795 }
796 r.macState(w, wire.EngineeringReady, false)
797 if got := access("iOS no F5"); got != "" {
798 t.Fatalf("without F5: %q", got)
799 }
800 h := macEngineerHello("Tito Studio", wire.EngineeringReady, wire.ProtocolMacEngineering, true)
801 h.Sandbox = wire.SandboxNone
802 w.heartbeat(h)
803 if got := access("iOS unproven"); got != "" {
804 t.Fatalf("sandbox not proven: %q", got)
805 }
806 r.macState(w, wire.EngineeringReady, true)
807 if _, err := r.inst.DB.Writer().Exec("UPDATE runners SET tainted_at = ? WHERE id = ?", time.Now().UTC(), w.fr.Welcome.RunnerID); err != nil {
808 t.Fatal(err)
809 }
810 if got := access("iOS tainted"); got != "" {
811 t.Fatalf("tainted: %q", got)
812 }
813}
814
815// 11. A worker's Engineering reports: pushed is refused; committed opens
816// the outbound transfer for exactly that candidate; done waits for the
817// primary's published, in either order.
818func TestContractWorkerEngineeringReports(t *testing.T) {
819 r := newMacRig(t)
820 w := r.newMacEngineer("Mac A", wire.EngineeringReady)
821 base, cand := sha(1), sha(0xc1)
822 task, d := r.macDispatch(w, "iOS reports", base)
823 if !w.lease(d.StepID, 1) {
824 t.Fatal("start refused")
825 }
826 w.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, Findings: []wire.Finding{}})
827 // A worker claiming it pushed is refused: the step does not end.
828 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{}})
829 if s := r.engineeringStep(task); s.State != wire.StepRunning || s.Pushed || s.CandidateSHA != "" {
830 t.Fatalf("a worker's pushed counted: %+v", s)
831 }
832 w.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, CandidateSHA: cand, Phase: wire.OutcomeCommitted, Findings: []wire.Finding{}})
833 _, body := w.expect(wire.FrameSendPack)
834 h := body.(*wire.SendPackCommand).Transfer
835 if h.Direction != wire.TransferOutbound || h.CandidateSHA != cand || h.BaseSHA != base || h.Kind != "" || h.Attempt != 1 {
836 t.Fatalf("outbound %+v", h)
837 }
838 // Another committed, for another commit, opens nothing more.
839 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{}})
840 w.none(wire.FrameSendPack, 50*time.Millisecond)
841 if s := r.engineeringStep(task); s.CandidateSHA != cand {
842 t.Fatalf("candidate moved: %+v", s)
843 }
844 // Done first: nothing is judged until the primary has published.
845 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{}})
846 w.send(wire.FrameBlob, chunk(h, []byte("PACK commit")))
847 r.fromPrimary(wire.FrameBlob)
848 pub := r.fromPrimary(wire.FramePublish).(*wire.PublishCommand)
849 if k := r.task(task); k.Steps[0].Pushed || k.CandidateSHA != "" || len(k.Steps) != 1 {
850 t.Fatalf("judged before publication: %+v", k)
851 }
852 r.primary.send(wire.FramePublished, wire.PublishedReport{Publication: pub.Publication, TaskID: task, StepID: d.StepID, Attempt: 1, CandidateSHA: cand, Pushed: true})
853 if k := r.task(task); !k.Steps[0].Pushed || k.CandidateSHA != cand {
854 t.Fatalf("after publication %+v", k)
855 }
856 r.macChecked(task, w)
857}
858
859// The primary may publish before the worker's final report: that report
860// keeps the primary's publication, and checks follow.
861func TestContractPublishedBeforeWorkerDone(t *testing.T) {
862 r := newMacRig(t)
863 w := r.newMacEngineer("Mac A", wire.EngineeringReady)
864 cand := sha(0xc)
865 task, d := r.macDispatch(w, "Published early", sha(1))
866 pub := r.workerCommitted(w, d, cand, false)
867 r.primary.send(wire.FramePublished, wire.PublishedReport{Publication: pub.Publication, TaskID: task, StepID: d.StepID, Attempt: 1, CandidateSHA: cand, Pushed: true})
868 w.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d.StepID, Attempt: 1, State: wire.StepDone, CandidateSHA: cand, Termination: true, Findings: []wire.Finding{}})
869 k := r.task(task)
870 if !k.Steps[0].Pushed || k.Steps[0].Publication != wire.PublicationPublished || k.CandidateSHA != cand {
871 t.Fatalf("the worker's report cleared the publication: %+v", k.Steps[0])
872 }
873 if _, c := r.macChecked(task, w); c.CandidateSHA != cand {
874 t.Fatalf("checks %+v", c)
875 }
876}
877
878// 12. Review of a Mac-made candidate is placed on the primary after
879// publication, never on a Mac.
880func TestContractReviewStaysOnPrimary(t *testing.T) {
881 r := newMacRig(t)
882 w := r.newMacEngineer("Mac A", wire.EngineeringReady)
883 cand := sha(0xc1)
884 task, _ := r.macCandidate(w, "iOS review", sha(1), cand)
885 cw, c := r.macChecked(task, w)
886 cw.send(wire.FrameStep, passed(task, c.StepID, c.Attempt, cand))
887 rv := r.fromPrimary(wire.FrameDispatch).(*wire.DispatchCommand)
888 if rv.Specialist != wire.SpecialistReview || rv.RunnerID != r.primary.fr.Welcome.RunnerID || rv.CandidateSHA != cand || len(rv.Needs) != 0 {
889 t.Fatalf("review %+v", rv)
890 }
891 w.none(wire.FrameDispatch, 50*time.Millisecond)
892 for _, s := range r.task(task).Steps {
893 if s.Specialist == wire.SpecialistReview && s.RunnerID != r.primary.fr.Welcome.RunnerID {
894 t.Fatalf("review off the primary %+v", s)
895 }
896 }
897}
898
899// 12. Ready to merge never merges a Mac-made candidate by policy (a
900// worker cannot run certified base gates): work that would merge on its
901// own from the primary asks; the person's Merge acts.
902func TestContractMacMadeNeverAutoMerges(t *testing.T) {
903 r := newMacRig(t)
904 r.shipsNo(r.project())
905 w := r.newMacEngineer("Mac A", wire.EngineeringReady)
906 cand := sha(0xc1)
907 task, _ := r.macCandidate(w, "iOS swipe", sha(1), cand)
908 cw, c := r.macChecked(task, w)
909 // Not run, for an environment reason: small, ordinary, approved work
910 // that would merge on its own were it made on the primary.
911 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{}})
912 rv := r.fromPrimary(wire.FrameDispatch).(*wire.DispatchCommand)
913 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."})
914 card := r.mergeCardFor(task)
915 k := r.task(task)
916 if k.Stage != wire.StageReadyToMerge || k.MergeDecision == nil || k.MergeDecision.Class != "ask" {
917 t.Fatalf("a Mac-made candidate was not asked about: %+v", k.MergeDecision)
918 }
919 made := false
920 for _, c := range k.MergeDecision.Reasons {
921 made = made || c.Name == "made_on_primary" && !c.OK
922 }
923 if !made {
924 t.Fatalf("decision %+v", k.MergeDecision)
925 }
926 if n := r.mailbox(r.primary.fr.Welcome.RunnerID, wire.FrameDispatch); n != 1 {
927 // Review, then nothing: no merge was dispatched.
928 t.Fatalf("%d dispatches to the primary", n)
929 }
930 if _, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceMerge, card.Revision); err != nil {
931 t.Fatal(err)
932 }
933 if m := r.fromPrimary(wire.FrameDispatch).(*wire.DispatchCommand); m.Specialist != wire.SpecialistMerge || m.CandidateSHA != cand {
934 t.Fatalf("the person's merge %+v", m)
935 }
936}
937
938// A primary replaced after it acked prepare_base: the preparation it can
939// no longer answer is invalidated (the attempt moves on) and asked of the
940// replacement, which must speak 37 (until then waiting_mac_update naming
941// it). The old primary's report, and a report for the invalidated
942// request, are refused and logged.
943func TestContractPrepareBaseAfterPrimaryReplaced(t *testing.T) {
944 r := newMacRig(t)
945 w := r.newMacEngineer("Tito Studio", wire.EngineeringReady)
946 // Work the old primary may have started (a Linux change), so its
947 // removal waits for that proof and it stays connected, removing.
948 plain := primaryHello(0)
949 plain.Protocol = wire.ProtocolMacEngineering
950 r.primary.heartbeat(plain)
951 started := r.macTask("Linux change")
952 d0 := r.fromPrimary(wire.FrameDispatch).(*wire.DispatchCommand)
953 if d0.TaskID != started || !r.primary.lease(d0.StepID, d0.Attempt) {
954 t.Fatalf("plain engineering %+v", d0)
955 }
956 mac := primaryHello(0)
957 mac.Protocol = wire.ProtocolMacEngineering
958 mac.Catalog[0].NeedsMacOS = true
959 r.primary.heartbeat(mac)
960 task := r.macTask("iOS replaced primary")
961 pb := r.prepared(task)
962 old := r.primary.fr.Welcome.RunnerID
963 r.ackedBy(old, wire.FramePrepareBase)
964 r.remove(old, false)
965 if r.revokedAt(old) {
966 t.Fatal("revoked before its proof")
967 }
968 token := r.inst.EnrolRunner(t).Token
969 h := primaryHello(0)
970 // A Linux replacement whose catalog does not name the repository: the
971 // task's Mac need outlives that.
972 h.Protocol, h.Label, h.Catalog = wire.ProtocolChangeDiffs, "docs-t2", []wire.RepoInfo{}
973 p35, err := DialRunnerHello(r.ctx, r.inst.URL, token, h)
974 if err != nil || p35.Welcome.Role != wire.RolePrimary {
975 t.Fatalf("replacement %+v %v", p35, err)
976 }
977 s := r.engineeringStep(task)
978 if s.Attempt != 2 || s.State != wire.StepQueued || s.Placement != wire.PlacementMacUpdate || s.RunnerLabel != "docs-t2" || r.needsYou(task) != wire.NeedsMacUpdate {
979 t.Fatalf("with a replacement below 37: %+v needs %q", s, r.needsYou(task))
980 }
981 if n := r.unacked(p35.Welcome.RunnerID, wire.FramePrepareBase); n != 0 {
982 t.Fatalf("%d prepare_base for a primary below 37", n)
983 }
984 // The old primary's late answer, on its own connection.
985 r.primary.send(wire.FrameBase, wire.BaseReport{TaskID: task, StepID: pb.StepID, Attempt: 1, BaseSHA: sha(1)})
986 if s := r.engineeringStep(task); s.BaseSHA != "" || s.Attempt != 2 {
987 t.Fatalf("the old primary's base bound: %+v", s)
988 }
989 if !strings.Contains(r.inst.Logs(), "base_refused: not the primary") {
990 t.Fatal("the old primary's report not logged")
991 }
992 // The replacement updated: asked afresh, for the new attempt.
993 p35.Close()
994 h.Protocol = wire.ProtocolMacEngineering
995 p37, err := DialRunnerHello(r.ctx, r.inst.URL, token, h)
996 if err != nil {
997 t.Fatal(err)
998 }
999 t.Cleanup(p37.Close)
1000 np := &peer{t: t, r: r.toolRig, fr: p37}
1001 _, body := np.expect(wire.FramePrepareBase)
1002 pb2 := body.(*wire.PrepareBaseCommand)
1003 if pb2.StepID != pb.StepID || pb2.Attempt != 2 || !pb2.Valid() {
1004 t.Fatalf("fresh prepare_base %+v", pb2)
1005 }
1006 // A report for the invalidated request.
1007 np.send(wire.FrameBase, wire.BaseReport{TaskID: task, StepID: pb.StepID, Attempt: 1, BaseSHA: sha(1)})
1008 if s := r.engineeringStep(task); s.BaseSHA != "" || s.Placement != wire.PlacementBase {
1009 t.Fatalf("the invalidated request bound: %+v", s)
1010 }
1011 if !strings.Contains(r.inst.Logs(), "base_refused: attempt not current") {
1012 t.Fatal("the invalidated request's report not logged")
1013 }
1014 np.send(wire.FrameBase, wire.BaseReport{TaskID: task, StepID: pb2.StepID, Attempt: 2, BaseSHA: sha(2)})
1015 _, body = w.expect(wire.FrameDispatch)
1016 if d := body.(*wire.DispatchCommand); d.Attempt != 2 || d.BaseSHA != sha(2) {
1017 t.Fatalf("dispatch %+v", d)
1018 }
1019 if n := r.mailboxHas(p37.Welcome.RunnerID, `"specialist":"engineering"`); n != 0 {
1020 t.Fatalf("%d engineering dispatches to the Linux replacement", n)
1021 }
1022}
1023
1024// ackedBy waits until runner's commands of kind are all acked.
1025func (r *runnersRig) ackedBy(runner, kind string) {
1026 r.t.Helper()
1027 deadline := time.Now().Add(5 * time.Second)
1028 for r.unacked(runner, kind) != 0 {
1029 if time.Now().After(deadline) {
1030 r.t.Fatalf("%s not acked by %s", kind, runner)
1031 }
1032 time.Sleep(20 * time.Millisecond)
1033 }
1034}
1035
1036func (r *runnersRig) unacked(runner, kind string) int {
1037 r.t.Helper()
1038 var n int
1039 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 {
1040 r.t.Fatal(err)
1041 }
1042 return n
1043}
1044
1045// The same primary back below protocol 37 after it acked prepare_base
1046// cannot answer it: invalidated, and the attempt waits for its update.
1047func TestContractPrepareBasePrimaryDowngraded(t *testing.T) {
1048 r := newMacRig(t)
1049 r.newMacEngineer("Tito Studio", wire.EngineeringReady)
1050 task := r.macTask("iOS downgraded primary")
1051 r.prepared(task)
1052 r.ackedBy(r.primary.fr.Welcome.RunnerID, wire.FramePrepareBase)
1053 r.primary.fr.Close()
1054 h := primaryHello(0)
1055 h.Protocol = wire.ProtocolChangeDiffs
1056 h.Catalog[0].NeedsMacOS = true
1057 p, err := DialRunnerHello(r.ctx, r.inst.URL, r.rig.runner, h)
1058 if err != nil {
1059 t.Fatal(err)
1060 }
1061 t.Cleanup(p.Close)
1062 if s := r.engineeringStep(task); s.Attempt != 2 || s.Placement != wire.PlacementMacUpdate || s.RunnerLabel != "docs-t1" || r.needsYou(task) != wire.NeedsMacUpdate {
1063 t.Fatalf("after the downgrade: %+v", s)
1064 }
1065}
1066
1067// Pinned to a Mac that is removed before anything it made was published:
1068// the task still needs a Mac when the catalog no longer says so.
1069func TestContractMacEngineeringPinnedBeforeCommit(t *testing.T) {
1070 r := newMacRig(t)
1071 a := r.newMacEngineer("Mac A", wire.EngineeringReady)
1072 task, d := r.macDispatch(a, "iOS early removal", sha(1))
1073 if !a.lease(d.StepID, d.Attempt) {
1074 t.Fatal("start refused")
1075 }
1076 r.remove(a.fr.Welcome.RunnerID, true)
1077 if _, err := r.client.RecoverTask(r.ctx, task); err != nil {
1078 t.Fatal(err)
1079 }
1080 h := primaryHello(0)
1081 h.Protocol, h.Catalog = wire.ProtocolMacEngineering, []wire.RepoInfo{}
1082 r.primary.heartbeat(h)
1083 if acc, err := r.client.RetryTask(r.ctx, task); err != nil || acc.Attempt != 2 {
1084 t.Fatalf("retry %+v %v", acc, err)
1085 }
1086 if s := r.engineeringStep(task); s.State != wire.StepQueued || s.Placement != wire.PlacementMac || s.RunnerID != "" {
1087 t.Fatalf("after recovery: %+v", s)
1088 }
1089 r.primary.none(wire.FrameDispatch, 100*time.Millisecond)
1090}
1091
1092// macPrimaryHello is the rig's primary become a Mac: every tag Mac
1093// Engineering needs.
1094func macPrimaryHello() wire.Hello {
1095 h := primaryHello(0)
1096 h.Protocol, h.Platform = wire.ProtocolMacEngineering, &wire.Platform{OS: "darwin", Arch: "arm64"}
1097 h.Capabilities.Tags = []string{wire.TagMacOS, wire.TagXcode, wire.TagIOSSimulator, wire.TagClaude}
1098 h.Catalog[0].NeedsMacOS = true
1099 return h
1100}
1101
1102// macNeedOutlivesPins: the task's Engineering, quarantined on Mac A
1103// (step at attempt), re-pins on Recover and Retry to a primary that is a
1104// Mac; that primary is removed too, and the Linux primary that replaces
1105// it has catalog (one without the repository, or naming it as not
1106// needing a Mac). Retry still waits for a Mac:
1107// the task's Mac need is its own record, not its current pin or its
1108// publications.
1109func (r *runnersRig) macNeedOutlivesPins(task, step string, attempt int64, a *peer, catalog []wire.RepoInfo) {
1110 r.t.Helper()
1111 r.remove(a.fr.Welcome.RunnerID, true)
1112 if _, err := r.client.RecoverTask(r.ctx, task); err != nil {
1113 r.t.Fatal(err)
1114 }
1115 r.primary.heartbeat(macPrimaryHello())
1116 if acc, err := r.client.RetryTask(r.ctx, task); err != nil || acc.Attempt != attempt+1 {
1117 r.t.Fatalf("retry %+v %v", acc, err)
1118 }
1119 d := r.fromPrimary(wire.FrameDispatch).(*wire.DispatchCommand)
1120 if d.StepID != step || d.Attempt != attempt+1 || d.Specialist != wire.SpecialistEngineering {
1121 r.t.Fatalf("on the Mac primary %+v", d)
1122 }
1123 if k := r.task(task); k.EngineeringRunner != r.primary.fr.Welcome.RunnerID {
1124 r.t.Fatalf("not re-pinned to the Mac primary: %q", k.EngineeringRunner)
1125 }
1126 if !r.primary.lease(d.StepID, d.Attempt) {
1127 r.t.Fatal("start refused")
1128 }
1129 r.remove(r.primary.fr.Welcome.RunnerID, true)
1130 token := r.inst.EnrolRunner(r.t).Token
1131 h := primaryHello(0)
1132 h.Protocol, h.Label, h.Catalog = wire.ProtocolMacEngineering, "docs-t2", catalog
1133 np, err := DialRunnerHello(r.ctx, r.inst.URL, token, h)
1134 if err != nil || np.Welcome.Role != wire.RolePrimary {
1135 r.t.Fatalf("replacement %+v %v", np, err)
1136 }
1137 r.t.Cleanup(np.Close)
1138 if _, err := r.client.RecoverTask(r.ctx, task); err != nil {
1139 r.t.Fatal(err)
1140 }
1141 if acc, err := r.client.RetryTask(r.ctx, task); err != nil || acc.Attempt != attempt+2 {
1142 r.t.Fatalf("second retry %+v %v", acc, err)
1143 }
1144 if s := r.newestEngineering(task); s.State != wire.StepQueued || s.Placement != wire.PlacementMac || s.RunnerID != "" {
1145 r.t.Fatalf("after the Linux replacement: %+v", s)
1146 }
1147 time.Sleep(100 * time.Millisecond)
1148 if n := r.mailboxHas(np.Welcome.RunnerID, `"specialist":"engineering"`); n != 0 {
1149 r.t.Fatalf("%d engineering dispatches to the Linux primary", n)
1150 }
1151}
1152
1153// Before anything was published: Mac A removed while its first attempt
1154// may run, then the Mac primary that took it over.
1155func TestContractMacNeedOutlivesPinsBeforePublication(t *testing.T) {
1156 r := newMacRig(t)
1157 a := r.newMacEngineer("Mac A", wire.EngineeringReady)
1158 task, d := r.macDispatch(a, "iOS twice removed", sha(1))
1159 if !a.lease(d.StepID, d.Attempt) {
1160 t.Fatal("start refused")
1161 }
1162 r.macNeedOutlivesPins(task, d.StepID, d.Attempt, a, []wire.RepoInfo{})
1163}
1164
1165// After a published round: Mac A removed during the fix round, then the
1166// Mac primary that took it over.
1167func TestContractMacNeedOutlivesPinsAfterPublication(t *testing.T) {
1168 r := newMacRig(t)
1169 a := r.newMacEngineer("Mac A", wire.EngineeringReady)
1170 c1 := sha(0xc1)
1171 task, _ := r.macCandidate(a, "iOS fixed, twice removed", sha(1), c1)
1172 cw, c := r.macChecked(task, a)
1173 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{}})
1174 _, body := a.expect(wire.FrameDispatch)
1175 fix := body.(*wire.DispatchCommand)
1176 r.engineeringTransfer(a, fix)
1177 if !a.lease(fix.StepID, fix.Attempt) {
1178 t.Fatal("fix round refused")
1179 }
1180 // The replacement's catalog names the repository, as not needing a
1181 // Mac: a catalog only adds needs.
1182 r.macNeedOutlivesPins(task, fix.StepID, fix.Attempt, a, primaryHello(0).Catalog)
1183}
1184
1185// A task whose Engineering never needed a Mac records no Mac need, and
1186// stays on the Linux primary when the catalog later omits its repository.
1187func TestContractNeverMacTaskUnaffected(t *testing.T) {
1188 r := newMacRig(t)
1189 r.newMacEngineer("Mac A", wire.EngineeringReady)
1190 h := primaryHello(0)
1191 h.Protocol = wire.ProtocolMacEngineering
1192 r.primary.heartbeat(h)
1193 task := r.macTask("Linux fix")
1194 d := r.fromPrimary(wire.FrameDispatch).(*wire.DispatchCommand)
1195 if d.Specialist != wire.SpecialistEngineering || d.RunnerID != r.primary.fr.Welcome.RunnerID {
1196 t.Fatalf("engineering %+v", d)
1197 }
1198 var needs string
1199 if err := r.inst.DB.Writer().QueryRow("SELECT coalesce(mac_needs, '') FROM chat_tasks WHERE id = ?", task).Scan(&needs); err != nil || needs != "" {
1200 t.Fatalf("mac_needs %q %v", needs, err)
1201 }
1202 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{}})
1203 h.Catalog = []wire.RepoInfo{}
1204 r.primary.heartbeat(h)
1205 if acc, err := r.client.RetryTask(r.ctx, task); err != nil || acc.Attempt != 2 {
1206 t.Fatalf("retry %+v %v", acc, err)
1207 }
1208 if d := r.fromPrimary(wire.FrameDispatch).(*wire.DispatchCommand); d.Specialist != wire.SpecialistEngineering || d.Attempt != 2 || d.RunnerID != r.primary.fr.Welcome.RunnerID {
1209 t.Fatalf("retry %+v", d)
1210 }
1211}
1212
1213// forget_task reaches every runner that holds the task's steps: the
1214// primary, as before, and the Mac worker that kept the task's
1215// Engineering session and candidate (Mac runners slice F, task 12).
1216func TestContractForgetReachesWorkers(t *testing.T) {
1217 r := newMacRig(t)
1218 w := r.newMacEngineer("Tito Studio", wire.EngineeringReady)
1219 task, _ := r.macCandidate(w, "iOS forget", sha(1), sha(0xf1))
1220 _, c := r.macChecked(task, w)
1221 if res := r.call("c-forget", wire.ToolCancelTask, map[string]string{"task": task}); res.IsError {
1222 t.Fatalf("cancel: %+v", res)
1223 }
1224 w.expect(wire.FrameCancelStep)
1225 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{}})
1226 _, body := w.expect(wire.FrameForgetTask)
1227 if f := body.(*wire.ForgetTaskCommand); f.TaskID != task || f.KeepUntil != nil {
1228 t.Fatalf("the worker's forget %+v", f)
1229 }
1230 if f := r.fromPrimary(wire.FrameForgetTask).(*wire.ForgetTaskCommand); f.TaskID != task || f.KeepUntil != nil {
1231 t.Fatalf("the primary's forget %+v", f)
1232 }
1233 if n := r.mailbox(w.fr.Welcome.RunnerID, wire.FrameForgetTask); n != 1 {
1234 t.Fatalf("%d forgets to the worker", n)
1235 }
1236}
1237