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 "errors"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "strings"
10 "sync/atomic"
11 "testing"
12 "time"
13
14 "amadan.net/oficina/equipo/internal/runner/forge"
15 "amadan.net/oficina/equipo/internal/runner/forge/forgetest"
16 "amadan.net/oficina/equipo/internal/runner/workspace"
17 "amadan.net/oficina/equipo/internal/testci"
18 "amadan.net/oficina/equipo/internal/wire"
19)
20
21// hubForge is a bare repository on disk behind a hub-like merge: the
22// test decides each answer (or lets it merge).
23type hubForge struct {
24 Forge
25 dir string
26 requests int
27 // answer, if set, replaces the hub's answer for request n (merge may
28 // be called to land the merge first).
29 answer func(n int, merge func() (forge.MergeResult, error)) (forge.MergeResult, error)
30}
31
32func (f *hubForge) Remote(context.Context, string, Use) (workspace.Remote, error) {
33 return workspace.Remote{URL: f.dir}, nil
34}
35
36func (f *hubForge) Merge(ctx context.Context, repo, branch string, req forge.MergeRequest) (forge.MergeResult, error) {
37 f.requests++
38 merge := func() (forge.MergeResult, error) { return forgetest.Merge(ctx, "/usr/bin/git", f.dir, branch, req) }
39 if f.answer != nil {
40 return f.answer(f.requests, merge)
41 }
42 return merge()
43}
44
45func gitOut(t *testing.T, dir string, args ...string) string {
46 t.Helper()
47 testci.Tools(t, "git")
48 cmd := exec.Command("git", args...)
49 cmd.Dir = dir
50 cmd.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL=/dev/null", "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@example.com", "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@example.com")
51 out, err := cmd.CombinedOutput()
52 if err != nil {
53 t.Fatalf("git %v: %v %s", args, err, out)
54 }
55 return strings.TrimSpace(string(out))
56}
57
58// hubRig is a remote with main at base and the task branch at cand (one
59// change on base), and an Engineer whose forge merges there.
60func hubRig(t *testing.T) (*Engineer, *hubForge, stepRow, string) {
61 t.Helper()
62 root := t.TempDir()
63 work := filepath.Join(root, "seed")
64 gitOut(t, root, "init", "-q", "-b", "main", work)
65 os.WriteFile(filepath.Join(work, "README.md"), []byte("teh panes\n"), 0644)
66 os.WriteFile(filepath.Join(work, "NEWS"), []byte("news\n"), 0644)
67 gitOut(t, work, "add", "-A")
68 gitOut(t, work, "commit", "-q", "-m", "base")
69 gitOut(t, work, "checkout", "-q", "-b", "equipo/tk1-fix-typo")
70 os.WriteFile(filepath.Join(work, "README.md"), []byte("the panes\n"), 0644)
71 gitOut(t, work, "commit", "-q", "-am", "fix")
72 cand := gitOut(t, work, "rev-parse", "HEAD")
73 gitOut(t, work, "checkout", "-q", "main")
74 remote := filepath.Join(root, "remote.git")
75 gitOut(t, root, "clone", "-q", "--bare", work, remote)
76 os.MkdirAll(filepath.Join(root, "state"), 0700)
77 os.MkdirAll(filepath.Join(root, "work"), 0700)
78 s, err := OpenState(context.Background(), filepath.Join(root, "state"))
79 if err != nil {
80 t.Fatal(err)
81 }
82 t.Cleanup(func() { s.Close() })
83 f := &hubForge{dir: remote}
84 e := &Engineer{Clones: &Clones{Root: filepath.Join(root, "work"), Git: "/usr/bin/git", Forge: f}, Forge: f, Owners: []string{"p@x"}, Host: "test"}
85 e.O.Runner.GitPath, e.O.Runner.WorkspaceRoot, e.O.Runner.StateDir, e.O.State = "/usr/bin/git", filepath.Join(root, "work"), filepath.Join(root, "state"), s
86 r := stepRow{DispatchCommand: wire.DispatchCommand{Person: "p@x", TaskID: "tk1", StepID: "s1", Attempt: 1, Specialist: wire.SpecialistMerge, Repo: "amadan.net/oficina/sample", Branch: "equipo/tk1-fix-typo", Title: "Fix the typo", CandidateSHA: cand}}
87 return e, f, r, cand
88}
89
90// TestMergeStep: the runner merges the judged SHA through forge and the
91// hub: a merge commit on main with the candidate as its second parent, the
92// task branch gone, the merge watch ended (this report says it landed).
93func TestMergeStep(t *testing.T) {
94 e, f, r, cand := hubRig(t)
95 ctx := context.Background()
96 if err := e.O.State.AcceptWatch(ctx, "w1", wire.WatchMergeCommand{Person: "p@x", TaskID: "tk1", Repo: r.Repo, Branch: r.Branch, CandidateSHA: cand}); err != nil {
97 t.Fatal(err)
98 }
99 rep := e.Exec(ctx, r, func(wire.StepReport) {})
100 tip := gitOut(t, f.dir, "rev-parse", "main")
101 if rep.State != wire.StepDone || rep.MergeSHA != tip || rep.Into != "main" || rep.Strategy != wire.MergeCommit || rep.CandidateSHA != cand || !rep.Termination || f.requests != 1 {
102 t.Fatalf("report %+v (%d requests)", rep, f.requests)
103 }
104 if parents := gitOut(t, f.dir, "rev-list", "--parents", "-n", "1", tip); !strings.HasSuffix(parents, " "+cand) {
105 t.Fatalf("merge parents %s", parents)
106 }
107 if out, _ := exec.Command("git", "--git-dir="+f.dir, "rev-parse", "--verify", "--quiet", "refs/heads/"+r.Branch).Output(); len(out) > 0 {
108 t.Fatal("the task branch was kept")
109 }
110 if ws, _ := e.O.State.watches(ctx); len(ws) != 0 {
111 t.Fatalf("watch kept %+v", ws)
112 }
113 // Run again (a restart before the report was acked): reconciled from
114 // the record, no second request.
115 if again := e.Exec(ctx, r, func(wire.StepReport) {}); again.State != wire.StepDone || again.MergeSHA != tip || f.requests != 1 {
116 t.Fatalf("again %+v (%d requests)", again, f.requests)
117 }
118}
119
120// TestMergeStepReconcilesALostAnswer: the hub merged but its answer was
121// lost: the default branch shows the merge, found as the commit that
122// brought the candidate in; one request only.
123func TestMergeStepReconcilesALostAnswer(t *testing.T) {
124 e, f, r, cand := hubRig(t)
125 f.answer = func(n int, merge func() (forge.MergeResult, error)) (forge.MergeResult, error) {
126 merge()
127 return forge.MergeResult{}, forge.ErrMergeUncertain
128 }
129 rep := e.Exec(context.Background(), r, func(wire.StepReport) {})
130 tip := gitOut(t, f.dir, "rev-parse", "main")
131 if rep.State != wire.StepDone || rep.MergeSHA != tip || rep.Into != "main" || f.requests != 1 {
132 t.Fatalf("report %+v (%d requests)", rep, f.requests)
133 }
134 // Someone commits on main after the merge: the commit that brought the
135 // candidate in is still the one reported.
136 work := filepath.Join(filepath.Dir(f.dir), "after")
137 gitOut(t, filepath.Dir(f.dir), "clone", "-q", f.dir, work)
138 os.WriteFile(filepath.Join(work, "NEWS"), []byte("more news\n"), 0644)
139 gitOut(t, work, "commit", "-q", "-am", "later")
140 gitOut(t, work, "push", "-q", "origin", "main")
141 st, err := e.inspectMerge(context.Background(), r.Repo, r.Branch, cand)
142 if err != nil || !st.Landed || st.MergeSHA != tip || st.Tip == tip {
143 t.Fatalf("inspect after a later commit %+v %v", st, err)
144 }
145}
146
147// TestMergeStepRefusals: a branch not at the judged SHA is never merged
148// (no request at all); the hub's conflict, its CI and a forbidden answer
149// become their reasons; CI still running is waited for.
150func TestMergeStepRefusals(t *testing.T) {
151 old := []any{mergeCIPoll, mergeCIWait, mergeBackoff}
152 mergeCIPoll, mergeCIWait, mergeBackoff = 10*time.Millisecond, 50*time.Millisecond, time.Millisecond
153 t.Cleanup(func() {
154 mergeCIPoll, mergeCIWait, mergeBackoff = old[0].(time.Duration), old[1].(time.Duration), old[2].(time.Duration)
155 })
156 e, f, r, _ := hubRig(t)
157 moved := r
158 moved.CandidateSHA = strings.Repeat("a", 40)
159 if rep := e.Exec(context.Background(), moved, func(wire.StepReport) {}); rep.State != wire.StepFailed || rep.Reason != "branch_moved" || f.requests != 0 {
160 t.Fatalf("moved %+v (%d requests)", rep, f.requests)
161 }
162 for _, c := range []struct {
163 res forge.MergeResult
164 reason string
165 }{
166 {forge.MergeResult{Status: 409, Reason: "conflicts"}, "merge_conflict"},
167 {forge.MergeResult{Status: 409, Reason: "ci_not_green", CIState: "failure"}, "amadan_ci_failed"},
168 {forge.MergeResult{Status: 403}, "merge_forbidden"},
169 {forge.MergeResult{Status: 409, Reason: "archived"}, "merge_failed"},
170 } {
171 f.requests = 0
172 f.answer = func(int, func() (forge.MergeResult, error)) (forge.MergeResult, error) { return c.res, nil }
173 if rep := e.Exec(context.Background(), r, func(wire.StepReport) {}); rep.State != wire.StepFailed || rep.Reason != c.reason || !rep.Termination {
174 t.Fatalf("%+v: %+v", c.res, rep)
175 }
176 }
177 // The hub's CI still running: deferred (the queue moves on), and past
178 // the wait it ends amadan_ci_pending.
179 f.answer = func(int, func() (forge.MergeResult, error)) (forge.MergeResult, error) {
180 return forge.MergeResult{Status: 409, Reason: "ci_not_green", CIState: "running"}, nil
181 }
182 if err := e.O.State.AcceptDispatch(context.Background(), "d1", r.DispatchCommand); err != nil {
183 t.Fatal(err)
184 }
185 if rep := e.Exec(context.Background(), r, func(wire.StepReport) {}); rep.State != stepDeferred {
186 t.Fatalf("CI running %+v", rep)
187 }
188 e.O.State.deferStep(context.Background(), r, time.Millisecond)
189 e.O.State.db.Exec("UPDATE steps SET deferred_since=? WHERE step_id=?", stamp(time.Now().Add(-time.Hour)), r.StepID)
190 if rep := e.Exec(context.Background(), r, func(wire.StepReport) {}); rep.State != wire.StepFailed || rep.Reason != "amadan_ci_pending" {
191 t.Fatalf("after the wait %+v", rep)
192 }
193 f.answer = nil
194 // Policy: not this runner's person, or not a task branch.
195 other := r
196 other.Person = "q@x"
197 if rep := e.Exec(context.Background(), other, func(wire.StepReport) {}); rep.Reason != "policy_rejected" {
198 t.Fatalf("other person %+v", rep)
199 }
200}
201
202// TestRecoverStepsRerunsAMerge: a runner that died mid-merge does not
203// report the merge failed: the attempt stays held and runs again, and
204// forge settles it from its record and the default branch.
205func TestRecoverStepsRerunsAMerge(t *testing.T) {
206 ctx := context.Background()
207 s, err := OpenState(ctx, t.TempDir())
208 if err != nil {
209 t.Fatal(err)
210 }
211 defer s.Close()
212 d := dispatchFor("tk1", "s1", 1)
213 d.Specialist, d.CandidateSHA = wire.SpecialistMerge, strings.Repeat("a", 40)
214 if err := s.AcceptDispatch(ctx, "c1", d); err != nil {
215 t.Fatal(err)
216 }
217 eng := dispatchFor("tk2", "s2", 1)
218 if err := s.AcceptDispatch(ctx, "c2", eng); err != nil {
219 t.Fatal(err)
220 }
221 if err := s.RecoverSteps(ctx, nil); err != nil {
222 t.Fatal(err)
223 }
224 reps := outbox(t, s)
225 if len(reps) != 1 || reps[0].StepID != "s2" || reps[0].Reason != "runner_restarted" {
226 t.Fatalf("recovery reports %+v", reps)
227 }
228 r, ok, err := s.nextStep(ctx)
229 if err != nil || !ok || r.StepID != "s1" || r.Specialist != wire.SpecialistMerge {
230 t.Fatalf("the merge is not held to run again: %+v %v %v", r, ok, err)
231 }
232 if errors.Is(err, os.ErrNotExist) {
233 t.Fatal(err)
234 }
235}
236
237// Astra 4c round 1, finding 3: a merge waiting for the hub's CI is held
238// between polls and releases the serial queue: another step runs while it
239// waits; each resumption runs the merge afresh (lease, judged SHA), so a
240// branch that moved meanwhile is never merged.
241func TestMergeCIWaitReleasesTheQueue(t *testing.T) {
242 old := []any{mergeCIPoll, mergeCIWait}
243 mergeCIPoll, mergeCIWait = 50*time.Millisecond, time.Minute
244 t.Cleanup(func() { mergeCIPoll, mergeCIWait = old[0].(time.Duration), old[1].(time.Duration) })
245 for _, moves := range []bool{false, true} {
246 e, f, r, cand := hubRig(t)
247 s := e.O.State
248 var stepped atomic.Int32
249 hubSawStep := false
250 f.answer = func(n int, merge func() (forge.MergeResult, error)) (forge.MergeResult, error) {
251 if n < 3 {
252 return forge.MergeResult{Status: 409, Reason: "ci_not_green", CIState: "running"}, nil
253 }
254 hubSawStep = stepped.Load() == 1
255 return merge()
256 }
257 engine := &StepEngine{State: s, Notify: func() {}, Exec: func(ctx context.Context, row stepRow, p func(wire.StepReport)) wire.StepReport {
258 if row.Specialist == wire.SpecialistMerge {
259 if moves && f.requests == 2 {
260 // The branch moves while the merge waits.
261 gitOut(t, filepath.Dir(f.dir), "--git-dir="+f.dir, "update-ref", "refs/heads/"+r.Branch, gitOut(t, filepath.Dir(f.dir), "--git-dir="+f.dir, "rev-parse", "main"))
262 }
263 return e.Exec(ctx, row, p)
264 }
265 stepped.Add(1)
266 return wire.StepReport{TaskID: row.TaskID, StepID: row.StepID, Attempt: row.Attempt, State: wire.StepFailed, Reason: "no_changes", Termination: true}
267 }}
268 ctx, cancel := context.WithCancel(context.Background())
269 if err := engine.Start(ctx); err != nil {
270 t.Fatal(err)
271 }
272 if err := s.AcceptDispatch(ctx, "c1", r.DispatchCommand); err != nil {
273 t.Fatal(err)
274 }
275 other := dispatchFor("tk2", "s2", 1)
276 if err := s.AcceptDispatch(ctx, "c2", other); err != nil {
277 t.Fatal(err)
278 }
279 engine.Wake()
280 var final wire.StepReport
281 waitFor(t, func() bool {
282 for _, rep := range outbox(t, s) {
283 if rep.StepID == r.StepID && wire.StepTerminal(rep.State) {
284 final = rep
285 return true
286 }
287 }
288 return false
289 })
290 cancel()
291 engine.Wait()
292 if stepped.Load() != 1 {
293 t.Fatalf("moves=%v: the other step did not run while the merge waited", moves)
294 }
295 if moves {
296 if final.State != wire.StepFailed || final.Reason != "branch_moved" || f.requests != 2 {
297 t.Fatalf("moved while waiting: %+v (%d requests)", final, f.requests)
298 }
299 continue
300 }
301 if final.State != wire.StepDone || final.CandidateSHA != cand || f.requests != 3 || !hubSawStep {
302 t.Fatalf("after waiting %+v (%d requests, step before merge %v)", final, f.requests, hubSawStep)
303 }
304 }
305}
306
307// Astra 4c round 1, finding 1: a merge asked to stop still reports what
308// the hub did: the answer was lost and the step cancelled, yet the
309// default branch shows the merge, so it reports done.
310func TestMergeStepSettlesDespiteCancel(t *testing.T) {
311 e, f, r, _ := hubRig(t)
312 ctx, cancel := context.WithCancel(context.Background())
313 f.answer = func(_ int, merge func() (forge.MergeResult, error)) (forge.MergeResult, error) {
314 merge()
315 cancel()
316 return forge.MergeResult{}, forge.ErrMergeUncertain
317 }
318 rep := e.Exec(ctx, r, func(wire.StepReport) {})
319 if rep.State != wire.StepDone || rep.MergeSHA == "" || f.requests != 1 {
320 t.Fatalf("cancelled mid-merge: %+v (%d requests)", rep, f.requests)
321 }
322}
323
324// TestMergeConfirmPurpose: right before each hub request the runner asks
325// the instance to confirm the merge itself (ConfirmMerge, the
326// merge_request purpose); a refusal ends the step merge_not_authorized
327// with nothing sent and the forge record still prepared, and a refused
328// start lease ends it the same way.
329func TestMergeConfirmPurpose(t *testing.T) {
330 e, f, r, _ := hubRig(t)
331 var asked []string
332 e.ConfirmMerge = func(_ context.Context, step string, attempt int64) error {
333 asked = append(asked, step+"/"+itoa(attempt))
334 return ErrMergeNotAuthorized
335 }
336 rep := e.Exec(context.Background(), r, func(wire.StepReport) {})
337 if rep.State != wire.StepFailed || rep.Reason != "merge_not_authorized" || !rep.Termination || f.requests != 0 {
338 t.Fatalf("refused %+v (%d requests)", rep, f.requests)
339 }
340 if len(asked) != 1 || asked[0] != "s1/1" {
341 t.Fatalf("confirmations %v", asked)
342 }
343 records, _ := filepath.Glob(filepath.Join(e.root(), "merge", "merge-*.json"))
344 if len(records) != 1 {
345 t.Fatalf("merge records %v", records)
346 }
347 if raw, _ := os.ReadFile(records[0]); !strings.Contains(string(raw), `"prepared"`) {
348 t.Fatalf("a refused merge's record: %s", raw)
349 }
350 // Granted: the merge goes, after exactly one confirmation per request.
351 asked = nil
352 e.ConfirmMerge = func(_ context.Context, step string, attempt int64) error {
353 asked = append(asked, step)
354 return nil
355 }
356 if rep := e.Exec(context.Background(), r, func(wire.StepReport) {}); rep.State != wire.StepDone || f.requests != 1 || len(asked) != 1 {
357 t.Fatalf("granted %+v (%d requests, %v)", rep, f.requests, asked)
358 }
359 // A refused start lease: the same reason, nothing sent.
360 e2, f2, r2, _ := hubRig(t)
361 e2.AuthorizeStep = func(context.Context, string, int64) error { return ErrMergeNotAuthorized }
362 if rep := e2.Exec(context.Background(), r2, func(wire.StepReport) {}); rep.State != wire.StepFailed || rep.Reason != "merge_not_authorized" || f2.requests != 0 {
363 t.Fatalf("start refused %+v", rep)
364 }
365}
366
367// TestMergeSource: the report says where the merge SHA came from. The
368// hub's own answer carries the merge commit's parents (second parent the
369// candidate); a reconciled or cached landing carries none.
370func TestMergeSource(t *testing.T) {
371 e, f, r, cand := hubRig(t)
372 rep := e.Exec(context.Background(), r, func(wire.StepReport) {})
373 if rep.State != wire.StepDone || rep.MergeSource != wire.MergeSourceHub || len(rep.MergeParents) != 2 || rep.MergeParents[1] != cand || f.requests != 1 {
374 t.Fatalf("hub %+v", rep)
375 }
376 if again := e.Exec(context.Background(), r, func(wire.StepReport) {}); again.MergeSource != wire.MergeSourceCached || again.MergeParents != nil {
377 t.Fatalf("cached %+v", again)
378 }
379 e2, f2, r2, _ := hubRig(t)
380 f2.answer = func(n int, merge func() (forge.MergeResult, error)) (forge.MergeResult, error) {
381 merge()
382 return forge.MergeResult{}, forge.ErrMergeUncertain
383 }
384 if rep := e2.Exec(context.Background(), r2, func(wire.StepReport) {}); rep.State != wire.StepDone || rep.MergeSource != wire.MergeSourceReconciled || rep.MergeParents != nil {
385 t.Fatalf("reconciled %+v", rep)
386 }
387}
388
389// TestLeaseRefusalReasons: the instance's merge_not_authorized refusal is
390// its own error, so the merge step ends with that reason; any other
391// refusal is a withdrawal.
392func TestLeaseRefusalReasons(t *testing.T) {
393 if leaseRefusal("") != nil || !errors.Is(leaseRefusal(wire.RefusedMergeNotAuthorized), ErrMergeNotAuthorized) || !errors.Is(leaseRefusal("withdrawn"), ErrWithdrawn) {
394 t.Fatal("lease refusals")
395 }
396}
397