package thin import ( "context" "errors" "os" "os/exec" "path/filepath" "strings" "sync/atomic" "testing" "time" "amadan.net/oficina/equipo/internal/runner/forge" "amadan.net/oficina/equipo/internal/runner/forge/forgetest" "amadan.net/oficina/equipo/internal/runner/workspace" "amadan.net/oficina/equipo/internal/testci" "amadan.net/oficina/equipo/internal/wire" ) // hubForge is a bare repository on disk behind a hub-like merge: the // test decides each answer (or lets it merge). type hubForge struct { Forge dir string requests int // answer, if set, replaces the hub's answer for request n (merge may // be called to land the merge first). answer func(n int, merge func() (forge.MergeResult, error)) (forge.MergeResult, error) } func (f *hubForge) Remote(context.Context, string, Use) (workspace.Remote, error) { return workspace.Remote{URL: f.dir}, nil } func (f *hubForge) Merge(ctx context.Context, repo, branch string, req forge.MergeRequest) (forge.MergeResult, error) { f.requests++ merge := func() (forge.MergeResult, error) { return forgetest.Merge(ctx, "/usr/bin/git", f.dir, branch, req) } if f.answer != nil { return f.answer(f.requests, merge) } return merge() } func gitOut(t *testing.T, dir string, args ...string) string { t.Helper() testci.Tools(t, "git") cmd := exec.Command("git", args...) cmd.Dir = dir 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") out, err := cmd.CombinedOutput() if err != nil { t.Fatalf("git %v: %v %s", args, err, out) } return strings.TrimSpace(string(out)) } // hubRig is a remote with main at base and the task branch at cand (one // change on base), and an Engineer whose forge merges there. func hubRig(t *testing.T) (*Engineer, *hubForge, stepRow, string) { t.Helper() root := t.TempDir() work := filepath.Join(root, "seed") gitOut(t, root, "init", "-q", "-b", "main", work) os.WriteFile(filepath.Join(work, "README.md"), []byte("teh panes\n"), 0644) os.WriteFile(filepath.Join(work, "NEWS"), []byte("news\n"), 0644) gitOut(t, work, "add", "-A") gitOut(t, work, "commit", "-q", "-m", "base") gitOut(t, work, "checkout", "-q", "-b", "equipo/tk1-fix-typo") os.WriteFile(filepath.Join(work, "README.md"), []byte("the panes\n"), 0644) gitOut(t, work, "commit", "-q", "-am", "fix") cand := gitOut(t, work, "rev-parse", "HEAD") gitOut(t, work, "checkout", "-q", "main") remote := filepath.Join(root, "remote.git") gitOut(t, root, "clone", "-q", "--bare", work, remote) os.MkdirAll(filepath.Join(root, "state"), 0700) os.MkdirAll(filepath.Join(root, "work"), 0700) s, err := OpenState(context.Background(), filepath.Join(root, "state")) if err != nil { t.Fatal(err) } t.Cleanup(func() { s.Close() }) f := &hubForge{dir: remote} e := &Engineer{Clones: &Clones{Root: filepath.Join(root, "work"), Git: "/usr/bin/git", Forge: f}, Forge: f, Owners: []string{"p@x"}, Host: "test"} 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 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}} return e, f, r, cand } // TestMergeStep: the runner merges the judged SHA through forge and the // hub: a merge commit on main with the candidate as its second parent, the // task branch gone, the merge watch ended (this report says it landed). func TestMergeStep(t *testing.T) { e, f, r, cand := hubRig(t) ctx := context.Background() 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 { t.Fatal(err) } rep := e.Exec(ctx, r, func(wire.StepReport) {}) tip := gitOut(t, f.dir, "rev-parse", "main") if rep.State != wire.StepDone || rep.MergeSHA != tip || rep.Into != "main" || rep.Strategy != wire.MergeCommit || rep.CandidateSHA != cand || !rep.Termination || f.requests != 1 { t.Fatalf("report %+v (%d requests)", rep, f.requests) } if parents := gitOut(t, f.dir, "rev-list", "--parents", "-n", "1", tip); !strings.HasSuffix(parents, " "+cand) { t.Fatalf("merge parents %s", parents) } if out, _ := exec.Command("git", "--git-dir="+f.dir, "rev-parse", "--verify", "--quiet", "refs/heads/"+r.Branch).Output(); len(out) > 0 { t.Fatal("the task branch was kept") } if ws, _ := e.O.State.watches(ctx); len(ws) != 0 { t.Fatalf("watch kept %+v", ws) } // Run again (a restart before the report was acked): reconciled from // the record, no second request. if again := e.Exec(ctx, r, func(wire.StepReport) {}); again.State != wire.StepDone || again.MergeSHA != tip || f.requests != 1 { t.Fatalf("again %+v (%d requests)", again, f.requests) } } // TestMergeStepReconcilesALostAnswer: the hub merged but its answer was // lost: the default branch shows the merge, found as the commit that // brought the candidate in; one request only. func TestMergeStepReconcilesALostAnswer(t *testing.T) { e, f, r, cand := hubRig(t) f.answer = func(n int, merge func() (forge.MergeResult, error)) (forge.MergeResult, error) { merge() return forge.MergeResult{}, forge.ErrMergeUncertain } rep := e.Exec(context.Background(), r, func(wire.StepReport) {}) tip := gitOut(t, f.dir, "rev-parse", "main") if rep.State != wire.StepDone || rep.MergeSHA != tip || rep.Into != "main" || f.requests != 1 { t.Fatalf("report %+v (%d requests)", rep, f.requests) } // Someone commits on main after the merge: the commit that brought the // candidate in is still the one reported. work := filepath.Join(filepath.Dir(f.dir), "after") gitOut(t, filepath.Dir(f.dir), "clone", "-q", f.dir, work) os.WriteFile(filepath.Join(work, "NEWS"), []byte("more news\n"), 0644) gitOut(t, work, "commit", "-q", "-am", "later") gitOut(t, work, "push", "-q", "origin", "main") st, err := e.inspectMerge(context.Background(), r.Repo, r.Branch, cand) if err != nil || !st.Landed || st.MergeSHA != tip || st.Tip == tip { t.Fatalf("inspect after a later commit %+v %v", st, err) } } // TestMergeStepRefusals: a branch not at the judged SHA is never merged // (no request at all); the hub's conflict, its CI and a forbidden answer // become their reasons; CI still running is waited for. func TestMergeStepRefusals(t *testing.T) { old := []any{mergeCIPoll, mergeCIWait, mergeBackoff} mergeCIPoll, mergeCIWait, mergeBackoff = 10*time.Millisecond, 50*time.Millisecond, time.Millisecond t.Cleanup(func() { mergeCIPoll, mergeCIWait, mergeBackoff = old[0].(time.Duration), old[1].(time.Duration), old[2].(time.Duration) }) e, f, r, _ := hubRig(t) moved := r moved.CandidateSHA = strings.Repeat("a", 40) if rep := e.Exec(context.Background(), moved, func(wire.StepReport) {}); rep.State != wire.StepFailed || rep.Reason != "branch_moved" || f.requests != 0 { t.Fatalf("moved %+v (%d requests)", rep, f.requests) } for _, c := range []struct { res forge.MergeResult reason string }{ {forge.MergeResult{Status: 409, Reason: "conflicts"}, "merge_conflict"}, {forge.MergeResult{Status: 409, Reason: "ci_not_green", CIState: "failure"}, "amadan_ci_failed"}, {forge.MergeResult{Status: 403}, "merge_forbidden"}, {forge.MergeResult{Status: 409, Reason: "archived"}, "merge_failed"}, } { f.requests = 0 f.answer = func(int, func() (forge.MergeResult, error)) (forge.MergeResult, error) { return c.res, nil } if rep := e.Exec(context.Background(), r, func(wire.StepReport) {}); rep.State != wire.StepFailed || rep.Reason != c.reason || !rep.Termination { t.Fatalf("%+v: %+v", c.res, rep) } } // The hub's CI still running: deferred (the queue moves on), and past // the wait it ends amadan_ci_pending. f.answer = func(int, func() (forge.MergeResult, error)) (forge.MergeResult, error) { return forge.MergeResult{Status: 409, Reason: "ci_not_green", CIState: "running"}, nil } if err := e.O.State.AcceptDispatch(context.Background(), "d1", r.DispatchCommand); err != nil { t.Fatal(err) } if rep := e.Exec(context.Background(), r, func(wire.StepReport) {}); rep.State != stepDeferred { t.Fatalf("CI running %+v", rep) } e.O.State.deferStep(context.Background(), r, time.Millisecond) e.O.State.db.Exec("UPDATE steps SET deferred_since=? WHERE step_id=?", stamp(time.Now().Add(-time.Hour)), r.StepID) if rep := e.Exec(context.Background(), r, func(wire.StepReport) {}); rep.State != wire.StepFailed || rep.Reason != "amadan_ci_pending" { t.Fatalf("after the wait %+v", rep) } f.answer = nil // Policy: not this runner's person, or not a task branch. other := r other.Person = "q@x" if rep := e.Exec(context.Background(), other, func(wire.StepReport) {}); rep.Reason != "policy_rejected" { t.Fatalf("other person %+v", rep) } } // TestRecoverStepsRerunsAMerge: a runner that died mid-merge does not // report the merge failed: the attempt stays held and runs again, and // forge settles it from its record and the default branch. func TestRecoverStepsRerunsAMerge(t *testing.T) { ctx := context.Background() s, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } defer s.Close() d := dispatchFor("tk1", "s1", 1) d.Specialist, d.CandidateSHA = wire.SpecialistMerge, strings.Repeat("a", 40) if err := s.AcceptDispatch(ctx, "c1", d); err != nil { t.Fatal(err) } eng := dispatchFor("tk2", "s2", 1) if err := s.AcceptDispatch(ctx, "c2", eng); err != nil { t.Fatal(err) } if err := s.RecoverSteps(ctx, nil); err != nil { t.Fatal(err) } reps := outbox(t, s) if len(reps) != 1 || reps[0].StepID != "s2" || reps[0].Reason != "runner_restarted" { t.Fatalf("recovery reports %+v", reps) } r, ok, err := s.nextStep(ctx) if err != nil || !ok || r.StepID != "s1" || r.Specialist != wire.SpecialistMerge { t.Fatalf("the merge is not held to run again: %+v %v %v", r, ok, err) } if errors.Is(err, os.ErrNotExist) { t.Fatal(err) } } // Astra 4c round 1, finding 3: a merge waiting for the hub's CI is held // between polls and releases the serial queue: another step runs while it // waits; each resumption runs the merge afresh (lease, judged SHA), so a // branch that moved meanwhile is never merged. func TestMergeCIWaitReleasesTheQueue(t *testing.T) { old := []any{mergeCIPoll, mergeCIWait} mergeCIPoll, mergeCIWait = 50*time.Millisecond, time.Minute t.Cleanup(func() { mergeCIPoll, mergeCIWait = old[0].(time.Duration), old[1].(time.Duration) }) for _, moves := range []bool{false, true} { e, f, r, cand := hubRig(t) s := e.O.State var stepped atomic.Int32 hubSawStep := false f.answer = func(n int, merge func() (forge.MergeResult, error)) (forge.MergeResult, error) { if n < 3 { return forge.MergeResult{Status: 409, Reason: "ci_not_green", CIState: "running"}, nil } hubSawStep = stepped.Load() == 1 return merge() } engine := &StepEngine{State: s, Notify: func() {}, Exec: func(ctx context.Context, row stepRow, p func(wire.StepReport)) wire.StepReport { if row.Specialist == wire.SpecialistMerge { if moves && f.requests == 2 { // The branch moves while the merge waits. 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")) } return e.Exec(ctx, row, p) } stepped.Add(1) return wire.StepReport{TaskID: row.TaskID, StepID: row.StepID, Attempt: row.Attempt, State: wire.StepFailed, Reason: "no_changes", Termination: true} }} ctx, cancel := context.WithCancel(context.Background()) if err := engine.Start(ctx); err != nil { t.Fatal(err) } if err := s.AcceptDispatch(ctx, "c1", r.DispatchCommand); err != nil { t.Fatal(err) } other := dispatchFor("tk2", "s2", 1) if err := s.AcceptDispatch(ctx, "c2", other); err != nil { t.Fatal(err) } engine.Wake() var final wire.StepReport waitFor(t, func() bool { for _, rep := range outbox(t, s) { if rep.StepID == r.StepID && wire.StepTerminal(rep.State) { final = rep return true } } return false }) cancel() engine.Wait() if stepped.Load() != 1 { t.Fatalf("moves=%v: the other step did not run while the merge waited", moves) } if moves { if final.State != wire.StepFailed || final.Reason != "branch_moved" || f.requests != 2 { t.Fatalf("moved while waiting: %+v (%d requests)", final, f.requests) } continue } if final.State != wire.StepDone || final.CandidateSHA != cand || f.requests != 3 || !hubSawStep { t.Fatalf("after waiting %+v (%d requests, step before merge %v)", final, f.requests, hubSawStep) } } } // Astra 4c round 1, finding 1: a merge asked to stop still reports what // the hub did: the answer was lost and the step cancelled, yet the // default branch shows the merge, so it reports done. func TestMergeStepSettlesDespiteCancel(t *testing.T) { e, f, r, _ := hubRig(t) ctx, cancel := context.WithCancel(context.Background()) f.answer = func(_ int, merge func() (forge.MergeResult, error)) (forge.MergeResult, error) { merge() cancel() return forge.MergeResult{}, forge.ErrMergeUncertain } rep := e.Exec(ctx, r, func(wire.StepReport) {}) if rep.State != wire.StepDone || rep.MergeSHA == "" || f.requests != 1 { t.Fatalf("cancelled mid-merge: %+v (%d requests)", rep, f.requests) } } // TestMergeConfirmPurpose: right before each hub request the runner asks // the instance to confirm the merge itself (ConfirmMerge, the // merge_request purpose); a refusal ends the step merge_not_authorized // with nothing sent and the forge record still prepared, and a refused // start lease ends it the same way. func TestMergeConfirmPurpose(t *testing.T) { e, f, r, _ := hubRig(t) var asked []string e.ConfirmMerge = func(_ context.Context, step string, attempt int64) error { asked = append(asked, step+"/"+itoa(attempt)) return ErrMergeNotAuthorized } rep := e.Exec(context.Background(), r, func(wire.StepReport) {}) if rep.State != wire.StepFailed || rep.Reason != "merge_not_authorized" || !rep.Termination || f.requests != 0 { t.Fatalf("refused %+v (%d requests)", rep, f.requests) } if len(asked) != 1 || asked[0] != "s1/1" { t.Fatalf("confirmations %v", asked) } records, _ := filepath.Glob(filepath.Join(e.root(), "merge", "merge-*.json")) if len(records) != 1 { t.Fatalf("merge records %v", records) } if raw, _ := os.ReadFile(records[0]); !strings.Contains(string(raw), `"prepared"`) { t.Fatalf("a refused merge's record: %s", raw) } // Granted: the merge goes, after exactly one confirmation per request. asked = nil e.ConfirmMerge = func(_ context.Context, step string, attempt int64) error { asked = append(asked, step) return nil } if rep := e.Exec(context.Background(), r, func(wire.StepReport) {}); rep.State != wire.StepDone || f.requests != 1 || len(asked) != 1 { t.Fatalf("granted %+v (%d requests, %v)", rep, f.requests, asked) } // A refused start lease: the same reason, nothing sent. e2, f2, r2, _ := hubRig(t) e2.AuthorizeStep = func(context.Context, string, int64) error { return ErrMergeNotAuthorized } if rep := e2.Exec(context.Background(), r2, func(wire.StepReport) {}); rep.State != wire.StepFailed || rep.Reason != "merge_not_authorized" || f2.requests != 0 { t.Fatalf("start refused %+v", rep) } } // TestMergeSource: the report says where the merge SHA came from. The // hub's own answer carries the merge commit's parents (second parent the // candidate); a reconciled or cached landing carries none. func TestMergeSource(t *testing.T) { e, f, r, cand := hubRig(t) rep := e.Exec(context.Background(), r, func(wire.StepReport) {}) if rep.State != wire.StepDone || rep.MergeSource != wire.MergeSourceHub || len(rep.MergeParents) != 2 || rep.MergeParents[1] != cand || f.requests != 1 { t.Fatalf("hub %+v", rep) } if again := e.Exec(context.Background(), r, func(wire.StepReport) {}); again.MergeSource != wire.MergeSourceCached || again.MergeParents != nil { t.Fatalf("cached %+v", again) } e2, f2, r2, _ := hubRig(t) f2.answer = func(n int, merge func() (forge.MergeResult, error)) (forge.MergeResult, error) { merge() return forge.MergeResult{}, forge.ErrMergeUncertain } if rep := e2.Exec(context.Background(), r2, func(wire.StepReport) {}); rep.State != wire.StepDone || rep.MergeSource != wire.MergeSourceReconciled || rep.MergeParents != nil { t.Fatalf("reconciled %+v", rep) } } // TestLeaseRefusalReasons: the instance's merge_not_authorized refusal is // its own error, so the merge step ends with that reason; any other // refusal is a withdrawal. func TestLeaseRefusalReasons(t *testing.T) { if leaseRefusal("") != nil || !errors.Is(leaseRefusal(wire.RefusedMergeNotAuthorized), ErrMergeNotAuthorized) || !errors.Is(leaseRefusal("withdrawn"), ErrWithdrawn) { t.Fatal("lease refusals") } }