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 "context"
5 "io"
6 "net/http"
7 "net/url"
8 "strings"
9 "testing"
10 "time"
11
12 "amadan.net/oficina/equipo/internal/wire"
13)
14
15// Ask the implementer, pinned exactly (Mac runners slice F, plan task
16// 13): a question about an Engineering step is frozen, when it is asked,
17// to the attempt, account, kept session, runner, base and candidate it is
18// about. Dispatch, cancel, the runner's replies and a reconnect's sync
19// all use those frozen values, never the step as it stands later.
20
21// askableOn runs w's Engineering attempt d to a commit of cand made on
22// account, done with its session kept (session), and the primary
23// publishes it.
24func (r *runnersRig) askableOn(w *peer, d *wire.DispatchCommand, cand, account, session string) {
25 r.t.Helper()
26 if !w.lease(d.StepID, d.Attempt) {
27 r.t.Fatal("start refused")
28 }
29 w.send(wire.FrameStep, wire.StepReport{TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, State: wire.StepRunning, BaseSHA: d.BaseSHA, Family: "claude", Account: account, Findings: []wire.Finding{}})
30 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{}})
31 _, body := w.expect(wire.FrameSendPack)
32 h := body.(*wire.SendPackCommand).Transfer
33 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, Family: "claude", Account: account, Askable: true, SessionID: session, Findings: []wire.Finding{}})
34 w.send(wire.FrameBlob, chunk(h, []byte("PACK commit")))
35 r.fromPrimary(wire.FrameBlob)
36 pub := r.fromPrimary(wire.FramePublish).(*wire.PublishCommand)
37 r.primary.send(wire.FramePublished, wire.PublishedReport{Publication: pub.Publication, TaskID: d.TaskID, StepID: d.StepID, Attempt: d.Attempt, CandidateSHA: cand, Pushed: true})
38 if s := r.engineeringStep(d.TaskID); s.State != wire.StepDone || !s.Askable || s.Attempt != d.Attempt || s.CandidateSHA != cand {
39 r.t.Fatalf("not askable: %+v", s)
40 }
41}
42
43// frozen is what a question row holds of the attempt it is about.
44type frozen struct {
45 attempt int64
46 account, session, runner, base, candidate string
47}
48
49func (r *runnersRig) frozenOf(q string) frozen {
50 r.t.Helper()
51 var f frozen
52 if err := r.inst.DB.Writer().QueryRow("SELECT coalesce(eng_attempt, 0), coalesce(eng_account, ''), coalesce(eng_session, ''), coalesce(runner_id, ''), coalesce(base_sha, ''), coalesce(candidate_sha, '') FROM chat_questions WHERE id = ?", q).Scan(&f.attempt, &f.account, &f.session, &f.runner, &f.base, &f.candidate); err != nil {
53 r.t.Fatal(err)
54 }
55 return f
56}
57
58// moveStep stands for any later path that moves a done Engineering step
59// on after a question was asked (no path does today: a done step's Retry
60// is a republish of the same attempt, and a fix round is a new step): a
61// new attempt on runner, with a new base, candidate, account and session.
62func (r *runnersRig) moveStep(step string, attempt int64, runner, base, cand string) {
63 r.t.Helper()
64 if _, err := r.inst.DB.Writer().Exec("UPDATE chat_steps SET attempt = ?, runner_id = ?, base_sha = ?, candidate_sha = ?, account = 'moved-account', session_id = 'moved-session' WHERE id = ?", attempt, runner, base, cand, step); err != nil {
65 r.t.Fatal(err)
66 }
67}
68
69// askIs checks an ask command against what its question froze.
70func askIs(t *testing.T, a *wire.AskCommand, q, step string, attempt int64, account, session, base, cand string) {
71 t.Helper()
72 if a.QuestionID != q || a.StepID != step || a.Specialist != wire.SpecialistEngineering || a.EngAttempt != attempt || a.EngAccount != account || a.EngSession != session || a.BaseSHA != base || a.CandidateSHA != cand {
73 t.Fatalf("ask %+v, want %s on attempt %d (%s, %s) of %s..%s", a, q, attempt, account, session, base, cand)
74 }
75}
76
77// A question created after a newer attempt made the same candidate is
78// bound to the attempt it was asked about (the newer one: its account and
79// session), never found by its commit; the step moving on later does not
80// change the runner, base or candidate a waiting question goes to, and a
81// reply from the runner the step moved to is refused.
82func TestContractAskBindsTheSession(t *testing.T) {
83 r := newMacRig(t)
84 a := r.newMacEngineer("Tito Studio", wire.EngineeringReady)
85 base, cand := sha(1), sha(0xc1)
86 task, d1 := r.macDispatch(a, "iOS asked", base)
87 // Attempt 1 commits cand on one account, then fails.
88 if !a.lease(d1.StepID, 1) {
89 t.Fatal("start refused")
90 }
91 a.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d1.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: base, Family: "claude", Account: "mac-c1", Findings: []wire.Finding{}})
92 a.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d1.StepID, Attempt: 1, State: wire.StepRunning, CandidateSHA: cand, Phase: wire.OutcomeCommitted, Findings: []wire.Finding{}})
93 a.expect(wire.FrameSendPack)
94 a.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d1.StepID, Attempt: 1, State: wire.StepFailed, Reason: "provider_failed", Termination: true, TerminationKind: wire.TerminationProcessGroup, Account: "mac-c1", SessionID: "sess-1", Findings: []wire.Finding{}})
95 if acc, err := r.client.RetryTask(r.ctx, task); err != nil || acc.Attempt != 2 {
96 t.Fatalf("retry %+v %v", acc, err)
97 }
98 _, body := a.expect(wire.FrameDispatch)
99 d2 := body.(*wire.DispatchCommand)
100 if d2.StepID != d1.StepID || d2.Attempt != 2 {
101 t.Fatalf("retry %+v", d2)
102 }
103 r.engineeringTransfer(a, d2)
104 // Attempt 2 makes the same commit, on another account, its session kept.
105 r.askableOn(a, d2, cand, "mac-c2", "sess-2")
106
107 q1, err := r.client.Ask(r.ctx, task, "What did you change?", "", "b1")
108 if err != nil || q1.StepID != d1.StepID {
109 t.Fatalf("ask %+v %v", q1, err)
110 }
111 want := frozen{2, "mac-c2", "sess-2", a.fr.Welcome.RunnerID, base, cand}
112 if got := r.frozenOf(q1.ID); got != want {
113 t.Fatalf("frozen %+v, want %+v", got, want)
114 }
115 _, body = a.expect(wire.FrameAsk)
116 askIs(t, body.(*wire.AskCommand), q1.ID, d1.StepID, 2, "mac-c2", "sess-2", base, cand)
117 r.primary.none(wire.FrameAsk, 0)
118 // A second question waits for the first.
119 q2, err := r.client.Ask(r.ctx, task, "And the tests?", "", "b2")
120 if err != nil {
121 t.Fatal(err)
122 }
123 if got := r.frozenOf(q2.ID); got != want {
124 t.Fatalf("second frozen %+v, want %+v", got, want)
125 }
126
127 // The step moves on, to another Mac.
128 b := r.newMacEngineer("Mac B", wire.EngineeringReady)
129 r.moveStep(d1.StepID, 3, b.fr.Welcome.RunnerID, sha(9), sha(0xc9))
130 // Mac B's reply is refused; Mac A's is the answer.
131 b.send(wire.FrameAnswer, wire.AnswerReport{TaskID: task, QuestionID: q1.ID, Attempt: 1, State: wire.QuestionAnswered, Text: "Not mine."})
132 if q, _ := r.client.Question(r.ctx, q1.ID); q.State != wire.QuestionQueued || q.Answer != "" {
133 t.Fatalf("the other Mac answered: %+v", q)
134 }
135 a.send(wire.FrameAnswer, wire.AnswerReport{TaskID: task, QuestionID: q1.ID, Attempt: 1, State: wire.QuestionAnswered, Text: "The swipe."})
136 if q, _ := r.client.Question(r.ctx, q1.ID); q.State != wire.QuestionAnswered || q.Answer != "The swipe." {
137 t.Fatalf("answer %+v", q)
138 }
139 // The waiting question goes where it was asked, as it was asked.
140 _, body = a.expect(wire.FrameAsk)
141 askIs(t, body.(*wire.AskCommand), q2.ID, d1.StepID, 2, "mac-c2", "sess-2", base, cand)
142 b.none(wire.FrameAsk, 50*time.Millisecond)
143 r.primary.none(wire.FrameAsk, 0)
144 if got := r.frozenOf(q2.ID); got != want {
145 t.Fatalf("the move changed the question: %+v", got)
146 }
147}
148
149// Cancel, a reply and a reconnect's sync after the step moved to a new
150// attempt on another runner all address the runner and attempt the
151// question was frozen to.
152func TestContractQuestionLifecycleFrozen(t *testing.T) {
153 r := newMacRig(t)
154 a := r.newMacEngineer("Tito Studio", wire.EngineeringReady)
155 base, cand := sha(1), sha(0xc1)
156 task, d := r.macDispatch(a, "iOS lifecycle", base)
157 r.askableOn(a, d, cand, "mac-c1", "sess-1")
158 q1, err := r.client.Ask(r.ctx, task, "What did you change?", "", "l1")
159 if err != nil {
160 t.Fatal(err)
161 }
162 _, body := a.expect(wire.FrameAsk)
163 askIs(t, body.(*wire.AskCommand), q1.ID, d.StepID, 1, "mac-c1", "sess-1", base, cand)
164 q2, err := r.client.Ask(r.ctx, task, "Why that way?", "", "l2")
165 if err != nil {
166 t.Fatal(err)
167 }
168 b := r.newMacEngineer("Mac B", wire.EngineeringReady)
169 r.moveStep(d.StepID, 2, b.fr.Welcome.RunnerID, sha(9), sha(0xc9))
170
171 // Cancel goes to Mac A, for the question's attempt.
172 if _, err := r.client.CancelQuestion(r.ctx, q1.ID); err != nil {
173 t.Fatal(err)
174 }
175 _, body = a.expect(wire.FrameCancelAsk)
176 if c := body.(*wire.CancelAskCommand); c.QuestionID != q1.ID || c.Attempt != 1 {
177 t.Fatalf("cancel_ask %+v", c)
178 }
179 b.none(wire.FrameCancelAsk, 50*time.Millisecond)
180 r.primary.none(wire.FrameCancelAsk, 0)
181 // Mac B cannot end it; Mac A does.
182 b.send(wire.FrameAnswer, wire.AnswerReport{TaskID: task, QuestionID: q1.ID, Attempt: 1, State: wire.QuestionCancelled, Reason: "cancelled"})
183 if q, _ := r.client.Question(r.ctx, q1.ID); q.State != wire.QuestionQueued {
184 t.Fatalf("the other Mac ended it: %+v", q)
185 }
186 a.send(wire.FrameAnswer, wire.AnswerReport{TaskID: task, QuestionID: q1.ID, Attempt: 1, State: wire.QuestionCancelled, Reason: "cancelled"})
187 if q, _ := r.client.Question(r.ctx, q1.ID); q.State != wire.QuestionCancelled {
188 t.Fatalf("cancelled %+v", q)
189 }
190 // The next question goes to Mac A, frozen.
191 _, body = a.expect(wire.FrameAsk)
192 askIs(t, body.(*wire.AskCommand), q2.ID, d.StepID, 1, "mac-c1", "sess-1", base, cand)
193 b.none(wire.FrameAsk, 0)
194 // Mac B's sync, which does not hold it, does not end it; Mac A's does.
195 b.send(wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{}, Steps: []wire.StepRun{}, Asks: []wire.AskRun{}})
196 if q, _ := r.client.Question(r.ctx, q2.ID); q.State != wire.QuestionQueued {
197 t.Fatalf("the other Mac's sync ended it: %+v", q)
198 }
199 a.send(wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{}, Steps: []wire.StepRun{}, Asks: []wire.AskRun{}})
200 r.wait("interrupted", func(c *Conversation) bool {
201 q := c.Questions[q2.ID]
202 return q.State == wire.QuestionFailed && q.Reason == "interrupted"
203 })
204}
205
206// macOffline disconnects the Mac w and waits until the instance shows it
207// offline, with the primary still online.
208func (r *runnersRig) macOffline(w *peer) {
209 r.t.Helper()
210 w.fr.Close()
211 deadline := time.Now().Add(5 * time.Second)
212 for {
213 rs, err := r.client.Runners(context.Background())
214 online := map[string]bool{}
215 for _, x := range rs.Items {
216 online[x.ID] = x.Online
217 }
218 if err == nil && !online[w.fr.Welcome.RunnerID] && online[r.primary.fr.Welcome.RunnerID] {
219 return
220 }
221 if time.Now().After(deadline) {
222 r.t.Fatalf("Mac still online: %+v %v", rs, err)
223 }
224 time.Sleep(50 * time.Millisecond)
225 }
226}
227
228// Asking about a Mac-made step while that Mac is offline is answered at
229// once (runner_offline), even with the primary online, and nothing
230// queues; once the Mac is back, the question is asked of it.
231func TestContractAskMacOffline(t *testing.T) {
232 r := newMacRig(t)
233 a := r.newMacEngineer("Tito Studio", wire.EngineeringReady)
234 base, cand := sha(1), sha(0xc1)
235 task, d := r.macDispatch(a, "iOS offline", base)
236 r.askableOn(a, d, cand, "mac-c1", "sess-1")
237 r.macOffline(a)
238 if _, err := r.client.Ask(r.ctx, task, "What did you change?", "", "o1"); Status(err) != http.StatusConflict || !strings.Contains(err.Error(), "runner_offline") {
239 t.Fatalf("ask of an offline Mac: %v", err)
240 }
241 // The task page's composer is told which Mac, and when to ask again,
242 // with and without script.
243 line := "Tito Studio is offline. Ask again when it is back."
244 for _, accept := range []string{"text/html", "application/json"} {
245 req, _ := http.NewRequest("POST", r.inst.URL+"/tasks/"+task+"/ask", strings.NewReader(url.Values{"body": {"What did you change?"}, "request_id": {"pg-" + accept}, "specialist": {""}}.Encode()))
246 req.AddCookie(r.inst.Cookie())
247 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
248 req.Header.Set("Origin", r.inst.URL)
249 req.Header.Set("Sec-Fetch-Site", "same-origin")
250 req.Header.Set("Accept", accept)
251 res, err := http.DefaultClient.Do(req)
252 if err != nil {
253 t.Fatal(err)
254 }
255 raw, _ := io.ReadAll(res.Body)
256 res.Body.Close()
257 if res.StatusCode != http.StatusConflict || !strings.Contains(string(raw), line) {
258 t.Fatalf("page ask (%s) of an offline Mac: %d %.400s", accept, res.StatusCode, raw)
259 }
260 }
261 if k := r.task(task); len(k.Questions) != 0 {
262 t.Fatalf("a question queued for an offline Mac: %+v", k.Questions)
263 }
264 r.primary.none(wire.FrameAsk, 0)
265 if n := r.mailbox(a.fr.Welcome.RunnerID, wire.FrameAsk); n != 0 {
266 t.Fatalf("%d asks wait for the offline Mac", n)
267 }
268 c := r.creds[a.fr]
269 wh := macEngineerHello(c[1], wire.EngineeringReady, wire.ProtocolMacEngineering, false)
270 wh.Generation = a.fr.Welcome.Generation
271 fr, err := DialRunnerHello(r.ctx, r.inst.URL, c[0], wh)
272 if err != nil {
273 t.Fatal(err)
274 }
275 t.Cleanup(fr.Close)
276 back := &peer{t: t, r: r.toolRig, fr: fr}
277 q, err := r.client.Ask(r.ctx, task, "What did you change?", "", "o2")
278 if err != nil {
279 t.Fatal(err)
280 }
281 _, body := back.expect(wire.FrameAsk)
282 askIs(t, body.(*wire.AskCommand), q.ID, d.StepID, 1, "mac-c1", "sess-1", base, cand)
283}
284