oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package thin
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "os"
8 "path/filepath"
9 "testing"
10 "time"
11
12 "amadan.net/oficina/equipo/internal/wire"
13)
14
15func dispatchFor(task, step string, attempt int64) wire.DispatchCommand {
16 return wire.DispatchCommand{Person: "owner@example.com", TaskID: task, StepID: step, Attempt: attempt, Specialist: wire.SpecialistEngineering, Repo: "amadan.net/oficina/sample", Branch: "equipo/" + task + "-x", Findings: []wire.Finding{}}
17}
18
19func outbox(t *testing.T, s *State) []wire.StepReport {
20 t.Helper()
21 frames, _, err := s.Unacked(context.Background(), 0)
22 if err != nil {
23 t.Fatal(err)
24 }
25 var out []wire.StepReport
26 for _, f := range frames {
27 if f.Type == wire.FrameStep {
28 var r wire.StepReport
29 json.Unmarshal(f.Data, &r)
30 out = append(out, r)
31 }
32 }
33 return out
34}
35
36// TestStepStateCancelFirst: a cancel that arrives before its dispatch
37// holds the attempt cancelled; the late dispatch is never executed and
38// the instance still gets a termination report.
39func TestStepStateCancelFirst(t *testing.T) {
40 ctx := context.Background()
41 s, err := OpenState(ctx, t.TempDir())
42 if err != nil {
43 t.Fatal(err)
44 }
45 defer s.Close()
46 if err := s.RequestStepCancel(ctx, "c1", wire.CancelStepCommand{Person: "owner@example.com", TaskID: "tk1", StepID: "s1", Attempt: 1}); err != nil {
47 t.Fatal(err)
48 }
49 if err := s.AcceptDispatch(ctx, "c2", dispatchFor("tk1", "s1", 1)); err != nil {
50 t.Fatal(err)
51 }
52 ran := false
53 e := &StepEngine{State: s, Notify: func() {}, Exec: func(context.Context, stepRow, func(wire.StepReport)) wire.StepReport {
54 ran = true
55 return wire.StepReport{State: wire.StepDone}
56 }}
57 r, ok, err := s.nextStep(ctx)
58 if err != nil || !ok || !r.Cancel {
59 t.Fatalf("next %+v %v %v", r, ok, err)
60 }
61 e.runOne(ctx, r)
62 reps := outbox(t, s)
63 if ran || len(reps) != 1 || reps[0].State != wire.StepCancelled || !reps[0].Termination {
64 t.Fatalf("ran %v reports %+v", ran, reps)
65 }
66 // A cancel for a running attempt is durable: a restart sees it.
67 if err := s.AcceptDispatch(ctx, "c3", dispatchFor("tk2", "s2", 1)); err != nil {
68 t.Fatal(err)
69 }
70 if err := s.RequestStepCancel(ctx, "c4", wire.CancelStepCommand{TaskID: "tk2", StepID: "s2", Attempt: 1}); err != nil {
71 t.Fatal(err)
72 }
73 if r, _, _ := s.nextStep(ctx); r.StepID != "s2" || !r.Cancel || !s.stepCancelled(ctx, r) {
74 t.Fatalf("cancel not recorded: %+v", r)
75 }
76}
77
78// TestStepStateRecover: after a crash, an attempt that had not committed
79// ends failed with termination; a committed one keeps only its push; a
80// cancelled one ends cancelled. One attempt of a task runs at a time.
81func TestStepStateRecover(t *testing.T) {
82 ctx := context.Background()
83 dir := t.TempDir()
84 s, err := OpenState(ctx, dir)
85 if err != nil {
86 t.Fatal(err)
87 }
88 for i, d := range []wire.DispatchCommand{dispatchFor("tka", "sa", 1), dispatchFor("tkb", "sb", 1), dispatchFor("tkc", "sc", 1)} {
89 if err := s.AcceptDispatch(ctx, "f"+itoa(int64(i)), d); err != nil {
90 t.Fatal(err)
91 }
92 }
93 // A second running attempt of the same task is not held.
94 if err := s.AcceptDispatch(ctx, "f9", dispatchFor("tka", "sa", 2)); err != nil {
95 t.Fatal(err)
96 }
97 b, _, _ := s.nextStep(ctx)
98 if err := s.setStepPhase(ctx, stepRow{DispatchCommand: dispatchFor("tkb", "sb", 1)}, phaseCommitted, "1111111111111111111111111111111111111111", "2222222222222222222222222222222222222222"); err != nil {
99 t.Fatal(err)
100 }
101 if err := s.RequestStepCancel(ctx, "f10", wire.CancelStepCommand{TaskID: "tkc", StepID: "sc", Attempt: 1}); err != nil {
102 t.Fatal(err)
103 }
104 _ = b
105 s.Close()
106 s, err = OpenState(ctx, dir)
107 if err != nil {
108 t.Fatal(err)
109 }
110 defer s.Close()
111 if err := s.RecoverSteps(ctx, nil); err != nil {
112 t.Fatal(err)
113 }
114 got := map[string]wire.StepReport{}
115 for _, r := range outbox(t, s) {
116 got[r.StepID] = r
117 }
118 if r := got["sa"]; r.State != wire.StepFailed || r.Reason != "runner_restarted" || !r.Termination || r.Attempt != 1 {
119 t.Fatalf("sa %+v", r)
120 }
121 if r := got["sc"]; r.State != wire.StepCancelled || !r.Termination {
122 t.Fatalf("sc %+v", r)
123 }
124 if _, ok := got["sb"]; ok {
125 t.Fatal("a committed attempt was settled instead of pushed")
126 }
127 r, ok, _ := s.nextStep(ctx)
128 if !ok || r.StepID != "sb" || r.Phase != phaseCommitted || r.Candidate == "" {
129 t.Fatalf("committed attempt %+v", r)
130 }
131 sync, _ := s.Sync(ctx)
132 if len(sync.Steps) != 3 {
133 t.Fatalf("sync %+v", sync.Steps)
134 }
135 // The ack of a final report finishes the attempt.
136 frames, _, _ := s.Unacked(ctx, 0)
137 for _, f := range frames {
138 if err := s.Acked(ctx, f.ID); err != nil {
139 t.Fatal(err)
140 }
141 }
142 if sync, _ = s.Sync(ctx); len(sync.Steps) != 1 || sync.Steps[0].StepID != "sb" {
143 t.Fatalf("after acks %+v", sync.Steps)
144 }
145}
146
147// TestEngineerRefusesOtherPersons: a dispatch for someone this runner
148// does not execute for, or for another branch or specialist, runs nothing.
149func TestEngineerRefusesOtherPersons(t *testing.T) {
150 e := &Engineer{Owners: []string{"owner@example.com"}}
151 for name, d := range map[string]wire.DispatchCommand{
152 "another person": func() wire.DispatchCommand {
153 d := dispatchFor("tk1", "s1", 1)
154 d.Person = "mallory@example.com"
155 return d
156 }(),
157 "not a task branch": func() wire.DispatchCommand { d := dispatchFor("tk1", "s1", 1); d.Branch = "main"; return d }(),
158 "bad repository": func() wire.DispatchCommand { d := dispatchFor("tk1", "s1", 1); d.Repo = "github.com/x/y"; return d }(),
159 "another specialist": func() wire.DispatchCommand { d := dispatchFor("tk1", "s1", 1); d.Specialist = "review"; return d }(),
160 } {
161 ctx, cancel := context.WithTimeout(context.Background(), time.Second)
162 rep := e.Exec(ctx, stepRow{DispatchCommand: d}, func(wire.StepReport) { t.Fatalf("%s: progressed", name) })
163 cancel()
164 if rep.State != wire.StepFailed || rep.Reason != "policy_rejected" || !rep.Termination {
165 t.Fatalf("%s: %+v", name, rep)
166 }
167 }
168}
169
170// TestStopStepNeedsVerifiedExit: a step's termination counts only when
171// the containment verified the namespace's exit; a Wait error (exit not
172// verified, proof not durable) or no exit at all is no termination, so
173// nothing is committed, published or retried on it.
174func TestStopStepNeedsVerifiedExit(t *testing.T) {
175 for name, tc := range map[string]struct {
176 wait error
177 exit bool
178 want bool
179 }{
180 "verified": {nil, true, true},
181 "verify failed": {errors.New("exit proof not durable"), true, false},
182 "exit never seen": {nil, false, false},
183 } {
184 exited := make(chan error, 1)
185 killed := false
186 kill := func() {
187 killed = true
188 if tc.exit {
189 exited <- tc.wait
190 }
191 }
192 if got := stopStep(func() {}, exited, kill, false, 10*time.Millisecond, 50*time.Millisecond); got != tc.want || !killed {
193 t.Fatalf("%s: terminated %v (killed %v), want %v", name, got, killed, tc.want)
194 }
195 }
196}
197
198// TestStepFilesKeptUntilAcked: a step's private repository outlives its
199// push until the final report is acked; then it is swept.
200func TestStepFilesKeptUntilAcked(t *testing.T) {
201 ctx := context.Background()
202 state := t.TempDir()
203 s, err := OpenState(ctx, state)
204 if err != nil {
205 t.Fatal(err)
206 }
207 defer s.Close()
208 e := &Engineer{}
209 e.O.Runner.StateDir = state
210 d := dispatchFor("tk6", "s6", 1)
211 if err := s.AcceptDispatch(ctx, "f1", d); err != nil {
212 t.Fatal(err)
213 }
214 r, _, _ := s.nextStep(ctx)
215 dir := filepath.Join(e.root(), stepKey(r))
216 if err := os.MkdirAll(filepath.Join(dir, "git"), 0700); err != nil {
217 t.Fatal(err)
218 }
219 if err := s.ReportStep(ctx, r, wire.StepReport{TaskID: "tk6", StepID: "s6", Attempt: 1, State: wire.StepDone, Pushed: true, Termination: true}); err != nil {
220 t.Fatal(err)
221 }
222 e.Sweep(ctx, s)
223 if _, err := os.Stat(dir); err != nil {
224 t.Fatalf("swept before the report was acked: %v", err)
225 }
226 frames, _, _ := s.Unacked(ctx, 0)
227 for _, f := range frames {
228 if err := s.Acked(ctx, f.ID); err != nil {
229 t.Fatal(err)
230 }
231 }
232 e.Sweep(ctx, s)
233 if _, err := os.Stat(dir); !errors.Is(err, os.ErrNotExist) {
234 t.Fatalf("kept after the ack: %v", err)
235 }
236}
237
238// TestStepPendingTermination: an attempt that ended without a verified
239// exit stays pending, through its ack and a restart, until a probe
240// verifies the namespace's exit; then a follow-up report carries the
241// termination, so the instance can allow Retry.
242func TestStepPendingTermination(t *testing.T) {
243 ctx := context.Background()
244 dir := t.TempDir()
245 s, err := OpenState(ctx, dir)
246 if err != nil {
247 t.Fatal(err)
248 }
249 if err := s.AcceptDispatch(ctx, "f1", dispatchFor("tk7", "s7", 1)); err != nil {
250 t.Fatal(err)
251 }
252 r, _, _ := s.nextStep(ctx)
253 if err := s.setStepNamespace(ctx, r, "ns-7"); err != nil {
254 t.Fatal(err)
255 }
256 if err := s.ReportStep(ctx, r, wire.StepReport{TaskID: "tk7", StepID: "s7", Attempt: 1, State: wire.StepFailed, Reason: "provider_failed"}); err != nil {
257 t.Fatal(err)
258 }
259 ack := func() {
260 frames, _, _ := s.Unacked(ctx, 0)
261 for _, f := range frames {
262 s.Acked(ctx, f.ID)
263 }
264 }
265 ack()
266 s.Close()
267 if s, err = OpenState(ctx, dir); err != nil {
268 t.Fatal(err)
269 }
270 defer s.Close()
271 verified := false
272 verify := func(_ context.Context, id string) bool { return id == "ns-7" && verified }
273 e := &StepEngine{State: s, Notify: func() {}, Verify: verify}
274 e.Probe(ctx)
275 if reps := outbox(t, s); len(reps) != 0 {
276 t.Fatalf("reported without proof: %+v", reps)
277 }
278 verified = true
279 e.Probe(ctx)
280 reps := outbox(t, s)
281 if len(reps) != 1 || reps[0].State != wire.StepFailed || reps[0].Reason != "provider_failed" || !reps[0].Termination {
282 t.Fatalf("follow-up %+v", reps)
283 }
284 e.Probe(ctx)
285 if len(outbox(t, s)) != 1 {
286 t.Fatal("follow-up sent twice")
287 }
288 ack()
289 if steps, _ := s.finishedSteps(ctx); len(steps) != 1 {
290 t.Fatalf("not finished after the follow-up's ack: %+v", steps)
291 }
292}
293
294// TestStepRecoverWithoutProof: after a crash, a running attempt whose
295// namespace exit cannot be verified is reported failed without
296// termination and stays pending for later probes.
297func TestStepRecoverWithoutProof(t *testing.T) {
298 ctx := context.Background()
299 s, err := OpenState(ctx, t.TempDir())
300 if err != nil {
301 t.Fatal(err)
302 }
303 defer s.Close()
304 s.AcceptDispatch(ctx, "f1", dispatchFor("tk8", "s8", 1))
305 r, _, _ := s.nextStep(ctx)
306 s.setStepNamespace(ctx, r, "ns-8")
307 if err := s.RecoverSteps(ctx, func(context.Context, string) bool { return false }); err != nil {
308 t.Fatal(err)
309 }
310 reps := outbox(t, s)
311 if len(reps) != 1 || reps[0].Termination || reps[0].Reason != "runner_restarted" {
312 t.Fatalf("recovered %+v", reps)
313 }
314 if p, _ := s.pendingSteps(ctx); len(p) != 1 || p[0].ns != "ns-8" {
315 t.Fatalf("pending %+v", p)
316 }
317}
318
319// TestSyncHoldsPendingTermination: an attempt whose failure report (no
320// termination proof) is not yet acked, and one still waiting for its
321// proof after the ack, are both in sync: present, termination
322// unverified. Only an attempt the runner has finished is absent.
323func TestSyncHoldsPendingTermination(t *testing.T) {
324 ctx := context.Background()
325 s, err := OpenState(ctx, t.TempDir())
326 if err != nil {
327 t.Fatal(err)
328 }
329 defer s.Close()
330 s.AcceptDispatch(ctx, "f1", dispatchFor("tk9", "s9", 1))
331 r, _, _ := s.nextStep(ctx)
332 if err := s.ReportStep(ctx, r, wire.StepReport{TaskID: "tk9", StepID: "s9", Attempt: 1, State: wire.StepFailed, Reason: "provider_failed"}); err != nil {
333 t.Fatal(err)
334 }
335 held := func() []wire.StepRun {
336 sync, err := s.Sync(ctx)
337 if err != nil {
338 t.Fatal(err)
339 }
340 return sync.Steps
341 }
342 if h := held(); len(h) != 1 || h[0].StepID != "s9" || h[0].State != runPending {
343 t.Fatalf("unacked pending report: %+v", h)
344 }
345 frames, _, _ := s.Unacked(ctx, 0)
346 for _, f := range frames {
347 s.Acked(ctx, f.ID)
348 }
349 if h := held(); len(h) != 1 || h[0].State != runPending {
350 t.Fatalf("acked, proof still pending: %+v", h)
351 }
352}
353
354// An attempt that recorded nothing before the crash is not ended by
355// default: verify is asked about it by name (UnrecordedStep), and while
356// unproven it stays pending under that record.
357func TestStepRecoverUnrecorded(t *testing.T) {
358 ctx := context.Background()
359 s, err := OpenState(ctx, t.TempDir())
360 if err != nil {
361 t.Fatal(err)
362 }
363 defer s.Close()
364 s.AcceptDispatch(ctx, "f1", dispatchFor("tk9", "s9", 1))
365 r, _, _ := s.nextStep(ctx)
366 var asked []string
367 if err := s.RecoverSteps(ctx, func(_ context.Context, id string) bool { asked = append(asked, id); return false }); err != nil {
368 t.Fatal(err)
369 }
370 if len(asked) != 1 || asked[0] != UnrecordedStep(r.key()) {
371 t.Fatalf("asked %v", asked)
372 }
373 if reps := outbox(t, s); len(reps) != 1 || reps[0].Termination {
374 t.Fatalf("an unrecorded attempt counted as ended: %+v", reps)
375 }
376 if p, _ := s.pendingSteps(ctx); len(p) != 1 || p[0].ns != UnrecordedStep(r.key()) {
377 t.Fatalf("pending %+v", p)
378 }
379}
380