gunk-dev/the-valley

valley_checker_test.go

source60ad80d5a5a5main's published tip history
17.7 KiB
1package integration
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "log/slog"
9 "os"
10 "path/filepath"
11 "strings"
12 "testing"
13 "time"
14
15 "the-valley/flow/internal/run"
16 "the-valley/flow/internal/valley"
17)
18
19// changesFixture is a valley-changes/v1 listing with a change in every state
20// klaus reads, and one in a state it doesn't, in two repos that share a
21// change ID.
22const changesFixture = `{
23 "schema": "valley-changes/v1",
24 "host": "valley-host",
25 "repos": [
26 { "repo": "site", "url": "git@valley-host:site.git", "error": null,
27 "changes": [
28 { "change_id": "nxvp-id", "handle": "nxvp", "target": "main", "state": "ready", "active": 2,
29 "versions": [
30 { "n": 1, "head": "nxvp-1", "title": "First try", "landing": "not-landed" },
31 { "n": 2, "head": "nxvp-2", "title": "Second try", "landing": "not-landed" }
32 ] },
33 { "change_id": "appr-id", "handle": "appr", "state": "ready", "active": 1,
34 "versions": [ { "n": 1, "head": "appr-1", "landing": "not-landed",
35 "request": { "ref": "refs/valley/requests/appr", "commit": "r" }, "outcome": null } ] },
36 { "change_id": "land-id", "handle": "land", "state": "ready", "active": 2,
37 "versions": [
38 { "n": 1, "head": "land-1", "landing": "landed" },
39 { "n": 2, "head": "land-2", "landing": "landed-recorded" }
40 ] },
41 { "change_id": "with-id", "handle": "with", "state": "withdrawn", "active": 1,
42 "versions": [ { "n": 1, "head": "with-1", "landing": "not-landed" } ] },
43 { "change_id": "unce-id", "handle": "unce", "state": "ready", "active": 1,
44 "versions": [ { "n": 1, "head": "unce-1", "landing": "uncertain",
45 "request": { "ref": "x", "commit": "r" } } ] },
46 { "change_id": "stal-id", "handle": "stal", "state": "ready", "active": 3,
47 "versions": [
48 { "n": 1, "head": "stal-1", "landing": "not-landed", "outcome": { "decision": "stale" } },
49 { "n": 2, "head": "stal-2", "landing": "not-landed", "outcome": { "decision": "rejected" } },
50 { "n": 3, "head": "stal-3", "landing": "not-landed", "outcome": { "decision": "failed" } }
51 ] },
52 { "change_id": "redo-id", "handle": "redo", "state": "ready", "active": 2,
53 "versions": [
54 { "n": 1, "head": "redo-h", "landing": "not-landed" },
55 { "n": 2, "head": "redo-h", "landing": "not-landed" }
56 ] },
57 { "change_id": "drft-id", "handle": "drft", "state": "draft", "active": 1,
58 "versions": [ { "n": 1, "head": "drft-1", "landing": "not-landed",
59 "request": { "ref": "x", "commit": "r" }, "outcome": { "decision": "rejected" } } ] },
60 { "change_id": "dunc-id", "handle": "dunc", "state": "draft", "active": 1,
61 "versions": [ { "n": 1, "head": "dunc-1", "landing": "uncertain",
62 "request": { "ref": "x", "commit": "r" } } ] },
63 { "change_id": "dlnd-id", "handle": "dlnd", "state": "draft", "active": 1,
64 "versions": [ { "n": 1, "head": "dlnd-1", "landing": "landed-recorded" } ] },
65 { "change_id": "rstk-id", "handle": "rstk", "state": "ready", "active": 3,
66 "versions": [
67 { "n": 1, "head": "rstk-1", "uploader": "operator", "landing": "not-landed" },
68 { "n": 2, "head": "rstk-2", "uploader": "restacker", "landing": "not-landed" },
69 { "n": 3, "head": "rstk-3", "uploader": "restacker", "landing": "landed" }
70 ] },
71 { "change_id": "late-id", "handle": "late", "state": "ready", "active": 4,
72 "versions": [
73 { "n": 1, "head": "late-1", "uploader": "operator", "landing": "not-landed" },
74 { "n": 2, "head": "late-2", "uploader": "operator", "landing": "not-landed" },
75 { "n": 3, "head": "late-3", "uploader": "restacker", "landing": "landed-recorded",
76 "request": { "ref": "x", "commit": "late-3" } },
77 { "n": 4, "head": "late-4", "uploader": "restacker", "landing": "not-landed" }
78 ] },
79 { "change_id": "frzn-id", "handle": "frzn", "state": "frozen", "active": 1,
80 "versions": [ { "n": 1, "head": "frzn-1", "landing": "landed" } ] }
81 ] },
82 { "repo": "fork", "url": "git@valley-host:fork.git", "error": null,
83 "changes": [
84 { "change_id": "nxvp-id", "handle": "nxvpf", "state": "withdrawn", "active": 1,
85 "versions": [ { "n": 1, "head": "nxvp-2", "landing": "not-landed" } ] }
86 ] },
87 { "repo": "dark", "url": "git@valley-host:dark.git", "error": "unreadable", "changes": [] }
88 ]
89}`
90
91func TestPlaceMatchesRunsToVersions(t *testing.T) {
92 changes, err := valley.Decode([]byte(changesFixture))
93 if err != nil {
94 t.Fatal(err)
95 }
96 pushed := func(repo, changeID, head string) *run.State {
97 branch := "agent/x"
98 s := &run.State{ID: changeID + "@" + head, ChangeID: changeID, PushedBranch: &branch, PushedSHA: &head}
99 if repo != "" {
100 s.Valley = &run.Valley{Repo: repo}
101 }
102 return s
103 }
104 target := func(targetRepo string, s *run.State) *run.State {
105 s.TargetRepo = &targetRepo
106 return s
107 }
108
109 // replaced are the versions, besides the superseded ones, that aren't
110 // their change's active one.
111 replaced := map[string]bool{"landed, then superseded": true, "restacked, then landed": true,
112 "restacked once, then landed": true, "landed, restacked since": true}
113 for _, tc := range []struct {
114 name string
115 run *run.State
116 want Verdict
117 handle string
118 version int
119 }{
120 {"active version, ready", pushed("site", "nxvp-id", "nxvp-2"), Ready, "nxvp", 2},
121 {"earlier version", pushed("site", "nxvp-id", "nxvp-1"), Superseded, "nxvp", 1},
122 {"same change in another repo", pushed("fork", "nxvp-id", "nxvp-2"), Withdrawn, "nxvpf", 1},
123 {"repo from the target repo's name", target("maintainer/site.git", pushed("", "nxvp-id", "nxvp-2")), Ready, "nxvp", 2},
124 {"repo from the target repo's URL", target("git@valley-host:fork.git", pushed("", "nxvp-id", "nxvp-2")), Withdrawn, "nxvpf", 1},
125 {"request filed", pushed("site", "appr-id", "appr-1"), Approved, "appr", 1},
126 {"landed", pushed("site", "land-id", "land-2"), Integrated, "land", 2},
127 {"landed, then superseded", pushed("site", "land-id", "land-1"), Integrated, "land", 1},
128 {"restacked, then landed", pushed("site", "rstk-id", "rstk-1"), Integrated, "rstk", 1},
129 {"restacked once, then landed", pushed("site", "rstk-id", "rstk-2"), Integrated, "rstk", 2},
130 {"landed, restacked since", pushed("site", "late-id", "late-2"), Integrated, "late", 2},
131 {"active restack after a landing", pushed("site", "late-id", "late-4"), Integrated, "late", 4},
132 {"withdrawn", pushed("site", "with-id", "with-1"), Withdrawn, "with", 1},
133 {"uncertain", pushed("site", "unce-id", "unce-1"), Uncertain, "unce", 1},
134 {"stale, superseded", pushed("site", "stal-id", "stal-1"), Superseded, "stal", 1},
135 {"failed", pushed("site", "stal-id", "stal-3"), Failed, "stal", 3},
136 {"head readied twice", pushed("site", "redo-id", "redo-h"), Ready, "redo", 2},
137 {"draft, after a rejection", pushed("site", "drft-id", "drft-1"), Draft, "drft", 1},
138 {"draft, landing uncertain", pushed("site", "dunc-id", "dunc-1"), Draft, "dunc", 1},
139 {"draft, landed", pushed("site", "dlnd-id", "dlnd-1"), Integrated, "dlnd", 1},
140 } {
141 t.Run(tc.name, func(t *testing.T) {
142 got, ok := place(changes, tc.run)
143 if !ok {
144 t.Fatal("run not placed")
145 }
146 if got.Verdict != tc.want || got.Change.Handle != tc.handle || got.Change.Version != tc.version ||
147 got.Change.Head != *tc.run.PushedSHA || got.Change.ChangeID != tc.run.ChangeID ||
148 got.Change.Active != (tc.want != Superseded && !replaced[tc.name]) {
149 t.Errorf("placed as %v %+v, want %v %s v%d", got.Verdict, *got.Change, tc.want, tc.handle, tc.version)
150 }
151 if tc.handle == "late" && (got.Change.LandedAs != 3 || got.Change.LandedCommit != "late-3") {
152 t.Errorf("late should read landed as v3 at late-3: %+v", *got.Change)
153 }
154 })
155 }
156
157 // The outcome decides: each of stale, rejected and failed, on the
158 // active version.
159 for decision, want := range map[string]Verdict{"stale": Stale, "rejected": Rejected, "failed": Failed, "deferred": Uncertain} {
160 ch := changes.Repos[0].Changes[5]
161 v := ch.Versions[2]
162 v.Outcome = &valley.Outcome{Decision: decision}
163 if got := verdictOf(ch, v); got != want {
164 t.Errorf("outcome %q: verdict %v, want %v", decision, got, want)
165 }
166 }
167
168 for _, tc := range []struct {
169 name string
170 run *run.State
171 }{
172 {"head that isn't a version", pushed("site", "nxvp-id", "elsewhere")},
173 {"change the valley lacks", pushed("site", "none-id", "nxvp-2")},
174 {"repo the valley lacks", pushed("other", "nxvp-id", "nxvp-2")},
175 {"repo the valley couldn't read", pushed("dark", "nxvp-id", "nxvp-2")},
176 {"run without a change ID", pushed("site", "", "nxvp-2")},
177 // nxvp-id's head nxvp-2 is in both site and fork: a run that
178 // doesn't know its repo can't tell which is its.
179 {"run without a repo", pushed("", "nxvp-id", "nxvp-2")},
180 {"target repo the valley lacks", target("maintainer/other", pushed("", "nxvp-id", "nxvp-2"))},
181 // A later valley's state: git judges the run, landed or not.
182 {"change in a state klaus doesn't know", pushed("site", "frzn-id", "frzn-1")},
183 } {
184 if got, ok := place(changes, tc.run); ok {
185 t.Errorf("%s: placed as %v %+v, want unplaced", tc.name, got.Verdict, *got.Change)
186 }
187 }
188}
189
190// TestPlaceFollowsTheValleysLandedVerdict: where the listing carries the
191// valley's landed_version, it alone says whether a change landed, for every
192// run of it and for the change's row; a listing without it falls back to
193// any version having landed.
194func TestPlaceFollowsTheValleysLandedVerdict(t *testing.T) {
195 listing := func(verdict string) *valley.Changes {
196 t.Helper()
197 changes, err := valley.Decode([]byte(`{"schema": "valley-changes/v1", "repos": [{"repo": "site", "changes": [
198 { "change_id": "actv-id", "handle": "actv", "state": "ready", "active": 2` + verdict + `,
199 "versions": [ { "n": 1, "head": "actv-1", "landing": "not-landed" },
200 { "n": 2, "head": "actv-2", "landing": "landed", "landed_commit": "actv-2" } ] },
201 { "change_id": "belo-id", "handle": "belo", "state": "ready", "active": 2` + verdict + `,
202 "versions": [ { "n": 1, "head": "belo-1", "landing": "landed", "landed_commit": "belo-1",
203 "request": { "ref": "x", "commit": "belo-1" } },
204 { "n": 2, "head": "belo-2", "uploader": "restacker", "landing": "not-landed" } ] },
205 { "change_id": "next-id", "handle": "next", "state": "ready", "active": 2` + verdict + `,
206 "versions": [ { "n": 1, "head": "next-1", "landing": "landed", "landed_commit": "next-1" },
207 { "n": 2, "head": "next-2", "landing": "not-landed" } ] }
208 ]}]}`))
209 if err != nil {
210 t.Fatal(err)
211 }
212 return changes
213 }
214 withVerdict := map[string]*valley.Changes{
215 "actv": listing(`, "landed_version": 2, "landed_commit": "actv-c"`),
216 "belo": listing(`, "landed_version": 1, "landed_commit": "belo-c"`),
217 "next": listing(`, "landed_version": null, "landed_commit": null`),
218 }
219 older := listing("")
220 for _, tc := range []struct {
221 name string
222 changes *valley.Changes
223 handle string
224 want [2]Verdict // the runs at v1 and v2, the active one
225 landedAs int
226 commit string
227 }{
228 {"landed at the active version", withVerdict["actv"], "actv", [2]Verdict{Integrated, Integrated}, 2, "actv-c"},
229 {"landed below a restacked active version", withVerdict["belo"], "belo", [2]Verdict{Integrated, Integrated}, 1, "belo-c"},
230 {"next round on top of a landing", withVerdict["next"], "next", [2]Verdict{Superseded, Ready}, 0, ""},
231 {"no verdict listed: any version landed", older, "next", [2]Verdict{Integrated, Integrated}, 1, "next-1"},
232 } {
233 t.Run(tc.name, func(t *testing.T) {
234 for i, want := range tc.want {
235 head, branch := fmt.Sprintf("%s-%d", tc.handle, i+1), "agent/x"
236 s := &run.State{ID: head, ChangeID: tc.handle + "-id", Valley: &run.Valley{Repo: "site"},
237 PushedBranch: &branch, PushedSHA: &head}
238 got, ok := place(tc.changes, s)
239 if !ok {
240 t.Fatalf("run at %s not placed", head)
241 }
242 if got.Verdict != want || got.Change.LandedAs != tc.landedAs || got.Change.LandedCommit != tc.commit {
243 t.Errorf("run at %s: %v, landed as v%d at %q; want %v, v%d at %q",
244 head, got.Verdict, got.Change.LandedAs, got.Change.LandedCommit, want, tc.landedAs, tc.commit)
245 }
246 }
247 row := activeVersions(tc.changes)[ChangeKey{Repo: "site", ChangeID: tc.handle + "-id"}]
248 if row.Verdict != tc.want[1] {
249 t.Errorf("change row reads %v, want %v", row.Verdict, tc.want[1])
250 }
251 })
252 }
253}
254
255// TestValleyCheckerFallsBackToGit runs a ValleyChecker against a fake valley
256// and real git. A run is judged by git when the valley can't vouch for it: its
257// repo's listing carries an error (whatever stale records sit beside it),
258// klaus doesn't know its repo, or valley fails. And git never settles a
259// change finalize marked ready: a deleted branch leaves it Unknown, not Gone.
260func TestValleyCheckerFallsBackToGit(t *testing.T) {
261 f := newFixture(t)
262 bin := t.TempDir()
263 listing := filepath.Join(bin, "changes.json")
264 script := "#!/bin/sh\nif [ \"$1\" = changes ] && [ -f '" + listing + "' ]; then exec cat '" + listing + "'; fi\n" +
265 "echo 'valley: cannot reach valley-host' >&2\nexit 1\n"
266 writeFile(t, bin, "valley", script)
267 if err := os.Chmod(filepath.Join(bin, "valley"), 0o755); err != nil {
268 t.Fatal(err)
269 }
270 t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
271
272 readied := func(id string) *run.State {
273 s := f.agentPush(id, "agent/"+id, id+".txt")
274 s.ChangeID = id + "-id"
275 s.Valley = &run.Valley{Repo: "site", Handle: id, Version: 1}
276 return s
277 }
278 // Listed as landed, but in a repo the valley couldn't read.
279 dark := readied("dark")
280 // Listed as landed in two repos, and the run knows neither its own nor
281 // its target repo.
282 orphan := f.agentPush("orph", "agent/orph", "orph.txt")
283 orphan.ChangeID = "orph-id"
284 // Not listed, and its branch is deleted without landing.
285 gone := readied("gone")
286 // A plain direct-push run whose branch is deleted: git settles it.
287 plain := f.agentPush("plain", "agent/plain", "plain.txt")
288 f.advanceMain("other.txt")
289 f.deleteBranch("agent/gone")
290 f.deleteBranch("agent/plain")
291
292 landed := func(s *run.State) map[string]any {
293 return map[string]any{"change_id": s.ChangeID, "handle": s.ID, "state": "ready", "active": 1,
294 "versions": []any{map[string]any{"n": 1, "head": *s.PushedSHA, "landing": "landed"}}}
295 }
296 data, err := json.Marshal(map[string]any{
297 "schema": valley.SchemaV1, "host": "valley-host",
298 "repos": []any{
299 map[string]any{"repo": "site", "error": "fetch failed", "changes": []any{landed(dark)}},
300 map[string]any{"repo": "fork", "error": nil, "changes": []any{landed(orphan)}},
301 map[string]any{"repo": "spoon", "error": nil, "changes": []any{landed(orphan)}},
302 },
303 })
304 if err != nil {
305 t.Fatal(err)
306 }
307 writeFile(t, bin, "changes.json", string(data))
308
309 c := NewValleyChecker(nil)
310 runs := []*run.State{dark, orphan, gone, plain}
311 check := func(want map[*run.State]Verdict) {
312 t.Helper()
313 got := c.Check(context.Background(), runs).Runs
314 for s, v := range want {
315 if r := got[s.ID]; r.Verdict != v || r.Change != nil {
316 t.Errorf("%s: %v %+v, want %v from git", s.ID, r.Verdict, r.Change, v)
317 }
318 }
319 }
320 check(map[*run.State]Verdict{dark: Awaiting, orphan: Awaiting, gone: Unknown, plain: Gone})
321
322 // The valley is unreachable.
323 if err := os.Remove(listing); err != nil {
324 t.Fatal(err)
325 }
326 check(map[*run.State]Verdict{dark: Awaiting, orphan: Awaiting, gone: Unknown, plain: Gone})
327}
328
329// TestValleyCheckerSaysWhyAndLogsOncePerStreak runs the checker against a
330// fake valley that hangs past a short timeout, then exits non-zero, then
331// answers: each failed report names the reason, the log has one warning for
332// the streak and one for the recovery.
333func TestValleyCheckerSaysWhyAndLogsOncePerStreak(t *testing.T) {
334 f := newFixture(t)
335 bin := t.TempDir()
336 mode := filepath.Join(bin, "mode")
337 writeFile(t, bin, "mode", "hang")
338 script := `#!/bin/sh
339case "$(cat '` + mode + `')" in
340hang) exec sleep 30 ;;
341fail) echo 'valley: cannot reach valley-host' >&2; exit 1 ;;
342*) echo '{"schema":"valley-changes/v1","host":"h","repos":[]}' ;;
343esac
344`
345 writeFile(t, bin, "valley", script)
346 if err := os.Chmod(filepath.Join(bin, "valley"), 0o755); err != nil {
347 t.Fatal(err)
348 }
349 t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
350 old := valley.ListTimeout
351 valley.ListTimeout = 300 * time.Millisecond
352 t.Cleanup(func() { valley.ListTimeout = old })
353
354 s := f.agentPush("a", "agent/a", "a.txt")
355 s.ChangeID = "a-id"
356 s.Valley = &run.Valley{Repo: "site", Handle: "a", Version: 1}
357
358 var logs bytes.Buffer
359 c := NewValleyChecker(slog.New(slog.NewTextHandler(&logs, nil)))
360 check := func() Report { return c.Check(context.Background(), []*run.State{s}) }
361
362 if r := check(); !strings.Contains(r.ValleyErr, "timed out after 300ms") || !r.Asked {
363 t.Errorf("hung valley: ValleyErr = %q, Asked = %v", r.ValleyErr, r.Asked)
364 }
365 writeFile(t, bin, "mode", "fail")
366 if r := check(); !strings.Contains(r.ValleyErr, "cannot reach valley-host") {
367 t.Errorf("failing valley: ValleyErr = %q", r.ValleyErr)
368 }
369 if n := strings.Count(logs.String(), "level=WARN msg=\"valley check failed"); n != 1 {
370 t.Errorf("failure streak logged %d warnings, want 1:\n%s", n, logs.String())
371 }
372 if !strings.Contains(logs.String(), "took=") || !strings.Contains(logs.String(), "dir=") {
373 t.Errorf("warning should carry the directory and duration:\n%s", logs.String())
374 }
375 writeFile(t, bin, "mode", "ok")
376 if r := check(); r.ValleyErr != "" || r.Listing == nil {
377 t.Errorf("recovered valley: ValleyErr = %q, Listing = %v", r.ValleyErr, r.Listing)
378 }
379 if n := strings.Count(logs.String(), "valley check recovered"); n != 1 {
380 t.Errorf("recovery logged %d times, want 1:\n%s", n, logs.String())
381 }
382 check()
383 if n := strings.Count(logs.String(), "level=WARN"); n != 2 {
384 t.Errorf("a healthy check should log nothing; %d warnings:\n%s", n, logs.String())
385 }
386}