gunk-dev/the-valley

git_checker_test.go

source68d12192bbd3main's published tip history
12.7 KiB
1package integration
2
3import (
4 "context"
5 "fmt"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "strings"
10 "testing"
11 "time"
12
13 "the-valley/flow/internal/run"
14)
15
16// fixture is a bare origin with two clones: the run's clone (the agent's
17// CloneDir, which the checker reads) and the operator's clone, which lands
18// and deletes branches the way the operator or an integrator would.
19type fixture struct {
20 t *testing.T
21 origin string
22 clone string
23 ops string
24}
25
26func newFixture(t *testing.T) *fixture {
27 t.Helper()
28 isolateGit(t)
29 dir := t.TempDir()
30 f := &fixture{
31 t: t,
32 origin: filepath.Join(dir, "origin.git"),
33 clone: filepath.Join(dir, "clone"),
34 ops: filepath.Join(dir, "ops"),
35 }
36 git(t, dir, "init", "-q", "--bare", "-b", "main", f.origin)
37 git(t, dir, "clone", "-q", f.origin, f.ops)
38 writeFile(t, f.ops, "README", "hello\n")
39 git(t, f.ops, "add", "README")
40 git(t, f.ops, "commit", "-q", "-m", "init")
41 git(t, f.ops, "push", "-q", "origin", "HEAD:main")
42 git(t, dir, "clone", "-q", f.origin, f.clone)
43 return f
44}
45
46// isolateGit keeps the user's git config out of the test and gives commits
47// an identity.
48func isolateGit(t *testing.T) {
49 t.Helper()
50 t.Setenv("GIT_CONFIG_GLOBAL", filepath.Join(t.TempDir(), "gitconfig"))
51 t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
52 for _, k := range []string{"GIT_AUTHOR_NAME", "GIT_COMMITTER_NAME"} {
53 t.Setenv(k, "test")
54 }
55 for _, k := range []string{"GIT_AUTHOR_EMAIL", "GIT_COMMITTER_EMAIL"} {
56 t.Setenv(k, "test@example.com")
57 }
58}
59
60func git(t *testing.T, dir string, args ...string) string {
61 t.Helper()
62 cmd := exec.Command("git", args...)
63 cmd.Dir = dir
64 out, err := cmd.CombinedOutput()
65 if err != nil {
66 t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
67 }
68 return strings.TrimSpace(string(out))
69}
70
71func writeFile(t *testing.T, dir, name, content string) {
72 t.Helper()
73 if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o644); err != nil {
74 t.Fatal(err)
75 }
76}
77
78// agentPush does what a direct-push agent does: commits each file on a new
79// branch cut from origin's main, pushes the branch, and (like _finalize)
80// deletes the local branch. It returns the run as finalize records it.
81func (f *fixture) agentPush(id, branch string, files ...string) *run.State {
82 f.t.Helper()
83 git(f.t, f.clone, "fetch", "-q", "origin")
84 git(f.t, f.clone, "checkout", "-q", "-b", branch, "origin/main")
85 for _, name := range files {
86 writeFile(f.t, f.clone, name, name+" from "+branch+"\n")
87 git(f.t, f.clone, "add", name)
88 git(f.t, f.clone, "commit", "-q", "-m", "add "+name)
89 }
90 git(f.t, f.clone, "push", "-q", "origin", branch)
91 sha := git(f.t, f.clone, "rev-parse", "HEAD")
92 git(f.t, f.clone, "checkout", "-q", "--detach")
93 git(f.t, f.clone, "branch", "-q", "-D", branch)
94 clone := f.clone
95 return &run.State{
96 ID: id,
97 PushedBranch: &branch,
98 PushedSHA: &sha,
99 CloneDir: &clone,
100 CreatedAt: time.Now().Add(-time.Hour).UTC().Format(time.RFC3339),
101 }
102}
103
104// ops runs git in the operator's clone after fetching origin.
105func (f *fixture) opsFetch() {
106 f.t.Helper()
107 git(f.t, f.ops, "fetch", "-q", "--prune", "origin")
108}
109
110// advanceMain lands an unrelated commit on main.
111func (f *fixture) advanceMain(name string) {
112 f.t.Helper()
113 f.opsFetch()
114 git(f.t, f.ops, "checkout", "-q", "-B", "main", "origin/main")
115 writeFile(f.t, f.ops, name, "unrelated\n")
116 git(f.t, f.ops, "add", name)
117 git(f.t, f.ops, "commit", "-q", "-m", "unrelated "+name)
118 git(f.t, f.ops, "push", "-q", "origin", "main")
119}
120
121// advanceMainAt lands an unrelated commit on main, committed at when.
122func (f *fixture) advanceMainAt(name string, when time.Time) {
123 f.t.Helper()
124 f.t.Setenv("GIT_COMMITTER_DATE", fmt.Sprintf("@%d +0000", when.Unix()))
125 defer os.Unsetenv("GIT_COMMITTER_DATE")
126 f.advanceMain(name)
127}
128
129// fastForward moves main to sha.
130func (f *fixture) fastForward(sha string) {
131 f.t.Helper()
132 f.opsFetch()
133 git(f.t, f.ops, "push", "-q", "origin", sha+":refs/heads/main")
134}
135
136// integrate lands branch the way the valley's integrator does when it can't
137// fast-forward: one new commit whose only parent is main's tip and whose tree
138// is the merge-tree of main and the branch.
139func (f *fixture) integrate(branch string) {
140 f.t.Helper()
141 f.opsFetch()
142 main := git(f.t, f.ops, "rev-parse", "origin/main")
143 tip := git(f.t, f.ops, "rev-parse", "origin/"+branch)
144 tree := git(f.t, f.ops, "merge-tree", "--write-tree", main, tip)
145 commit := git(f.t, f.ops, "commit-tree", tree, "-p", main, "-m", "land "+branch)
146 git(f.t, f.ops, "push", "-q", "origin", commit+":refs/heads/main")
147}
148
149// rebaseAndForcePush rebases branch onto main and force-pushes it, like the
150// operator's [b]ase in valley review. It returns the new tip.
151func (f *fixture) rebaseAndForcePush(branch string) string {
152 f.t.Helper()
153 f.opsFetch()
154 git(f.t, f.ops, "checkout", "-q", "-B", branch, "origin/"+branch)
155 git(f.t, f.ops, "rebase", "-q", "origin/main")
156 git(f.t, f.ops, "push", "-q", "--force", "origin", branch)
157 tip := git(f.t, f.ops, "rev-parse", "HEAD")
158 git(f.t, f.ops, "checkout", "-q", "--detach")
159 return tip
160}
161
162func (f *fixture) deleteBranch(branch string) {
163 f.t.Helper()
164 git(f.t, f.ops, "push", "-q", "origin", "--delete", branch)
165}
166
167func checkOne(t *testing.T, c Checker, s *run.State) Verdict {
168 t.Helper()
169 got := c.Check(context.Background(), []*run.State{s}).Runs
170 r, ok := got[s.ID]
171 if !ok {
172 t.Fatalf("no verdict for %s: %v", s.ID, got)
173 }
174 return r.Verdict
175}
176
177func TestGitCheckerFastForwardLanding(t *testing.T) {
178 f := newFixture(t)
179 s := f.agentPush("r1", "agent/ff", "a.txt", "b.txt")
180 f.fastForward(*s.PushedSHA)
181
182 if v := checkOne(t, NewGitChecker(nil), s); v != Integrated {
183 t.Errorf("verdict = %v, want integrated", v)
184 }
185}
186
187func TestGitCheckerRebasedThenFastForwarded(t *testing.T) {
188 // The operator rebases the branch onto main and force-pushes it, then it
189 // fast-forwards: only the current tip is an ancestor of main.
190 f := newFixture(t)
191 s := f.agentPush("r1", "agent/rebased", "a.txt")
192 c := NewGitChecker(nil)
193 if v := checkOne(t, c, s); v != Awaiting {
194 t.Fatalf("before landing: verdict = %v, want awaiting", v)
195 }
196
197 f.advanceMain("other.txt")
198 tip := f.rebaseAndForcePush("agent/rebased")
199 if v := checkOne(t, c, s); v != Awaiting {
200 t.Fatalf("after rebase: verdict = %v, want awaiting", v)
201 }
202
203 f.fastForward(tip)
204 if anc := exec.Command("git", "-C", f.ops, "merge-base", "--is-ancestor", *s.PushedSHA, tip).Run(); anc == nil {
205 t.Fatal("test setup: the pushed SHA should not be an ancestor of the rebased tip")
206 }
207 if v := checkOne(t, c, s); v != Integrated {
208 t.Errorf("after fast-forward: verdict = %v, want integrated", v)
209 }
210}
211
212func TestGitCheckerIntegratorLanding(t *testing.T) {
213 // A multi-commit branch lands as one new commit on top of a main that
214 // moved, on unrelated files, after the branch was cut.
215 f := newFixture(t)
216 s := f.agentPush("r1", "agent/multi", "a.txt", "b.txt", "c.txt")
217 f.advanceMain("unrelated-1.txt")
218 f.advanceMain("unrelated-2.txt")
219 f.integrate("agent/multi")
220
221 c := NewGitChecker(nil)
222 if v := checkOne(t, c, s); v != IntegratedContent {
223 t.Errorf("verdict = %v, want integrated by content", v)
224 }
225
226 // Landed, then the branch is deleted: still integrated, never gone.
227 f.deleteBranch("agent/multi")
228 if v := checkOne(t, c, s); v != IntegratedContent {
229 t.Errorf("after delete: verdict = %v, want integrated by content", v)
230 }
231}
232
233func TestGitCheckerDeletedAfterFastForward(t *testing.T) {
234 f := newFixture(t)
235 s := f.agentPush("r1", "agent/ff-del", "a.txt")
236 f.fastForward(*s.PushedSHA)
237 f.deleteBranch("agent/ff-del")
238
239 if v := checkOne(t, NewGitChecker(nil), s); v != Integrated {
240 t.Errorf("verdict = %v, want integrated", v)
241 }
242}
243
244func TestGitCheckerDeletedWithoutLanding(t *testing.T) {
245 f := newFixture(t)
246 s := f.agentPush("r1", "agent/rejected", "a.txt")
247 f.advanceMain("other.txt")
248 f.deleteBranch("agent/rejected")
249
250 if v := checkOne(t, NewGitChecker(nil), s); v != Gone {
251 t.Errorf("verdict = %v, want gone", v)
252 }
253}
254
255func TestGitCheckerDeletedAndPrunedIsUnknown(t *testing.T) {
256 // The branch was deleted without landing and the clone no longer has the
257 // pushed commit, so nothing rules out that it landed: unknown, not gone.
258 f := newFixture(t)
259 s := f.agentPush("r1", "agent/pruned", "a.txt")
260 f.advanceMain("other.txt")
261 f.deleteBranch("agent/pruned")
262 git(t, f.clone, "fetch", "-q", "--prune", "origin")
263 git(t, f.clone, "checkout", "-q", "--detach", "origin/main")
264 git(t, f.clone, "reflog", "expire", "--expire=now", "--all")
265 git(t, f.clone, "gc", "-q", "--prune=now")
266 if exec.Command("git", "-C", f.clone, "cat-file", "-e", *s.PushedSHA).Run() == nil {
267 t.Fatal("test setup: the pushed commit should be pruned from the clone")
268 }
269
270 c := NewGitChecker(nil)
271 if v := checkOne(t, c, s); v != Unknown {
272 t.Fatalf("verdict = %v, want unknown", v)
273 }
274
275 // The commit comes back while origin's tips stay put: the unknown wasn't
276 // cached, so the next check has the evidence and says gone.
277 git(t, f.ops, "push", "-q", f.clone, *s.PushedSHA+":refs/heads/restored")
278 if v := checkOne(t, c, s); v != Gone {
279 t.Errorf("after the commit is back: verdict = %v, want gone", v)
280 }
281}
282
283func TestGitCheckerTruncatedScanIsNotGone(t *testing.T) {
284 // Two deleted branches that never landed. The walk of main runs back to
285 // the older run's creation but stops at the cap first: it covers the
286 // newer run, which is gone, but not the older one, whose landing it might
287 // have missed.
288 now := time.Now()
289 f := newFixture(t)
290 old := f.agentPush("old", "agent/old", "a.txt")
291 newer := f.agentPush("newer", "agent/newer", "b.txt")
292 old.CreatedAt = now.Add(-time.Hour).UTC().Format(time.RFC3339)
293 newer.CreatedAt = now.Add(-10 * time.Minute).UTC().Format(time.RFC3339)
294 f.advanceMainAt("o1.txt", now.Add(-30*time.Minute))
295 f.advanceMainAt("o2.txt", now.Add(-20*time.Minute))
296 f.advanceMain("o3.txt")
297 f.deleteBranch("agent/old")
298 f.deleteBranch("agent/newer")
299 runs := []*run.State{old, newer}
300
301 c := NewGitChecker(nil)
302 c.scanLimit = 2 // o3 and o2
303 got := c.Check(context.Background(), runs).Runs
304 if got["old"].Verdict != Unknown {
305 t.Errorf("old: verdict = %v, want unknown", got["old"].Verdict)
306 }
307 if got["newer"].Verdict != Gone {
308 t.Errorf("newer: verdict = %v, want gone", got["newer"].Verdict)
309 }
310
311 got = NewGitChecker(nil).Check(context.Background(), runs).Runs
312 for _, s := range runs {
313 if got[s.ID].Verdict != Gone {
314 t.Errorf("%s without a cap: verdict = %v, want gone", s.ID, got[s.ID].Verdict)
315 }
316 }
317}
318
319func TestGitCheckerOneSnapshotForManyRuns(t *testing.T) {
320 // Runs in the same clone share one check: one waiting, one landed by
321 // fast-forward, one landed by the integrator, one deleted.
322 f := newFixture(t)
323 waiting := f.agentPush("waiting", "agent/waiting", "w.txt")
324 ff := f.agentPush("ff", "agent/ff", "f.txt")
325 content := f.agentPush("content", "agent/content", "c1.txt", "c2.txt")
326 gone := f.agentPush("gone", "agent/gone", "g.txt")
327 f.fastForward(*ff.PushedSHA)
328 f.advanceMain("other.txt")
329 f.integrate("agent/content")
330 f.deleteBranch("agent/gone")
331
332 got := NewGitChecker(nil).Check(context.Background(), []*run.State{waiting, ff, content, gone}).Runs
333 want := map[string]Verdict{"waiting": Awaiting, "ff": Integrated, "content": IntegratedContent, "gone": Gone}
334 for id, w := range want {
335 if got[id].Verdict != w {
336 t.Errorf("%s: verdict = %v, want %v", id, got[id].Verdict, w)
337 }
338 }
339}
340
341func TestGitCheckerUnreachableOriginIsUnknown(t *testing.T) {
342 // A bad origin URL can't be listed: unknown, never gone, even though the
343 // branch is nowhere to be seen.
344 f := newFixture(t)
345 s := f.agentPush("r1", "agent/x", "a.txt")
346 git(t, f.clone, "remote", "set-url", "origin", filepath.Join(t.TempDir(), "no-such-origin.git"))
347
348 c := NewGitChecker(nil)
349 if v := checkOne(t, c, s); v != Unknown {
350 t.Fatalf("verdict = %v, want unknown", v)
351 }
352
353 // Once origin is fixed, the next check gives a real verdict.
354 git(t, f.clone, "remote", "set-url", "origin", f.origin)
355 if v := checkOne(t, c, s); v != Awaiting {
356 t.Errorf("after fixing origin: verdict = %v, want awaiting", v)
357 }
358}
359
360func TestGitCheckerWithoutCloneIsUnknown(t *testing.T) {
361 isolateGit(t)
362 branch, sha := "agent/x", "0123456789abcdef0123456789abcdef01234567"
363 noClone := &run.State{ID: "no-clone", PushedBranch: &branch, PushedSHA: &sha}
364 missing := filepath.Join(t.TempDir(), "gone")
365 missingClone := &run.State{ID: "missing-clone", PushedBranch: &branch, PushedSHA: &sha, CloneDir: &missing}
366 notPushed := &run.State{ID: "not-pushed"}
367
368 got := NewGitChecker(nil).Check(context.Background(), []*run.State{noClone, missingClone, notPushed}).Runs
369 if r, ok := got["no-clone"]; !ok || r.Verdict != Unknown {
370 t.Errorf("no clone: verdict = %v (present %v), want unknown", r.Verdict, ok)
371 }
372 if r, ok := got["missing-clone"]; !ok || r.Verdict != Unknown {
373 t.Errorf("missing clone: verdict = %v (present %v), want unknown", r.Verdict, ok)
374 }
375 if _, ok := got["not-pushed"]; ok {
376 t.Error("a run that pushed nothing should get no verdict")
377 }
378}