gunk-dev/the-valley

change_transitions_test.go

source68d12192bbd3main's published tip history
14.7 KiB
1package cmd
2
3import (
4 "encoding/json"
5 "fmt"
6 "maps"
7 "os"
8 "path/filepath"
9 "slices"
10 "strings"
11 "testing"
12 "time"
13
14 "the-valley/flow/internal/config"
15 "the-valley/flow/internal/event"
16 gh "the-valley/flow/internal/github"
17 "the-valley/flow/internal/integration"
18 "the-valley/flow/internal/pipeline"
19 "the-valley/flow/internal/run"
20 "the-valley/flow/internal/valley"
21)
22
23// changeSession is a session directory whose dashboards run the real
24// integration check, a ValleyChecker over real git, against a fake valley
25// serving the listing the test last wrote for repo site.
26type changeSession struct {
27 *gitFixture
28 store *run.HomeDirStore
29 listing string
30 seen int // events next has returned
31}
32
33func newChangeSession(t *testing.T) *changeSession {
34 t.Helper()
35 f := newGitFixture(t)
36 bin := t.TempDir()
37 listing := filepath.Join(bin, "changes.json")
38 script := "#!/bin/sh\nif [ \"$1\" = changes ] && [ -f '" + listing + "' ]; then exec cat '" + listing + "'; fi\n" +
39 "echo 'valley: cannot reach valley-host' >&2\nexit 1\n"
40 if err := os.WriteFile(filepath.Join(bin, "valley"), []byte(script), 0o755); err != nil {
41 t.Fatal(err)
42 }
43 t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
44 store := run.NewHomeDirStoreFromPath(t.TempDir())
45 if err := store.EnsureDirs(); err != nil {
46 t.Fatal(err)
47 }
48 return &changeSession{gitFixture: f, store: store, listing: listing}
49}
50
51// pushed records a run of the session that pushed files on a branch of its
52// own as a version of change handle, as finalize does: version 0 is a run
53// finalize has recorded the push of but not yet the version it became.
54func (c *changeSession) pushed(id, handle string, version int, files ...string) *run.State {
55 c.t.Helper()
56 s := c.push(id, "work on "+handle, time.Now().Add(-time.Hour), files...)
57 s.ChangeID = handleChangeID(handle)
58 if version > 0 {
59 s.Valley = &run.Valley{Repo: "site", Handle: handle, Version: version, Title: "Tune " + handle}
60 }
61 if err := c.store.Save(s); err != nil {
62 c.t.Fatal(err)
63 }
64 return s
65}
66
67// handleChangeID is a change ID that handle is the start of.
68func handleChangeID(handle string) string { return handle + strings.Repeat("k", 32-len(handle)) }
69
70// list sets what the valley lists in repo site.
71func (c *changeSession) list(changes ...map[string]any) {
72 c.t.Helper()
73 data, err := json.Marshal(map[string]any{"schema": valley.SchemaV1, "host": "valley-host",
74 "repos": []any{map[string]any{"repo": "site", "url": "git@valley-host:site.git", "error": nil, "changes": changes}}})
75 if err != nil {
76 c.t.Fatal(err)
77 }
78 if err := os.WriteFile(c.listing, data, 0o644); err != nil {
79 c.t.Fatal(err)
80 }
81}
82
83// dashboard starts a dashboard on the session, as klaus dashboard does, and
84// returns what runs one of its integration checks on the session's runs.
85func (c *changeSession) dashboard() (check func() integrationMsg) {
86 m := newDashboardModel(c.store, config.Config{}, gh.NewGHCLIClient(""))
87 m.restackOn = false // no restack reports here; a pass would read every session
88 return func() integrationMsg {
89 c.t.Helper()
90 states, err := c.store.List()
91 if err != nil {
92 c.t.Fatal(err)
93 }
94 m.states = states
95 _, cmd := m.Update(integrationTickMsg{})
96 msg, ok := cmd().(integrationMsg)
97 if !ok {
98 c.t.Fatalf("the integration check returned %T", msg)
99 }
100 return msg
101 }
102}
103
104// next returns the change transition events emitted since it last ran.
105func (c *changeSession) next() []event.Event {
106 c.t.Helper()
107 evts, err := event.NewLog(c.store.BaseDir()).Read()
108 if err != nil {
109 c.t.Fatal(err)
110 }
111 var out []event.Event
112 for _, e := range evts[c.seen:] {
113 if strings.HasPrefix(e.Type, "change:") {
114 out = append(out, e)
115 }
116 }
117 c.seen = len(evts)
118 return out
119}
120
121// expect checks the events since the last expect, each as "<run ID>
122// <type> v<version>", and returns them.
123func (c *changeSession) expect(step string, want ...string) []event.Event {
124 c.t.Helper()
125 evts := c.next()
126 var got []string
127 for _, e := range evts {
128 got = append(got, fmt.Sprintf("%s %s v%v", e.RunID, e.Type, e.Data["version"]))
129 }
130 if !slices.Equal(got, want) {
131 c.t.Errorf("%s: events %q, want %q", step, got, want)
132 }
133 return evts
134}
135
136// listed is a valley-changes/v1 version that uploader marked ready.
137func listed(n int, head, uploader string) map[string]any {
138 return map[string]any{"n": n, "head": head, "title": fmt.Sprintf("Tune the cache (v%d)", n), "branch": "agent/x",
139 "uploader": uploader, "landing": "not-landed", "landed_commit": nil, "request": nil, "outcome": nil}
140}
141
142// with returns a copy of version v with its fields set from kv pairs.
143func with(v map[string]any, kv ...any) map[string]any {
144 out := maps.Clone(v)
145 for i := 0; i+1 < len(kv); i += 2 {
146 out[kv[i].(string)] = kv[i+1]
147 }
148 return out
149}
150
151// approved is version v with an integration request filed.
152func approved(v map[string]any) map[string]any {
153 return with(v, "request", map[string]any{"ref": "refs/valley/requests/x", "commit": strings.Repeat("e", 40)})
154}
155
156// decided is approved version v with the integrator's decision on it.
157func decided(v map[string]any, decision string) map[string]any {
158 return with(approved(v), "outcome", map[string]any{"decision": decision, "head": v["head"], "tip": strings.Repeat("f", 40)})
159}
160
161// landedAs is approved version v landed as commit.
162func landedAs(v map[string]any, commit string) map[string]any {
163 return with(approved(v), "landing", "landed", "landed_commit", commit)
164}
165
166// listedChange is a change record whose active version is its last.
167func listedChange(handle, state string, versions ...map[string]any) map[string]any {
168 return map[string]any{"change_id": handleChangeID(handle), "handle": handle, "target": "main", "owner": "operator",
169 "state": state, "active": versions[len(versions)-1]["n"], "versions": versions, "includes": []string{}}
170}
171
172// TestChangeApprovedThenLanded: the operator approving a change, and the
173// change landing, each reach the event stream once, with the change's
174// handle as the run ID, however many checks and dashboard restarts see it.
175func TestChangeApprovedThenLanded(t *testing.T) {
176 c := newChangeSession(t)
177 s := c.pushed("20261030-0900-0001", "nxvp", 1, "cache.txt")
178 v1 := listed(1, *s.PushedSHA, "operator")
179 c.list(listedChange("nxvp", "ready", v1))
180
181 check := c.dashboard()
182 check()
183 c.expect("ready")
184
185 c.list(listedChange("nxvp", "ready", approved(v1)))
186 check()
187 check()
188 c.expect("approved", "nxvp change:approved v1")
189 check = c.dashboard()
190 check()
191 c.expect("approved, the dashboard restarted")
192
193 c.fastForward(*s.PushedSHA) // the integrator lands it
194 c.list(listedChange("nxvp", "ready", landedAs(v1, *s.PushedSHA)))
195 check()
196 evts := c.expect("landed", "nxvp change:integrated v1")
197 check()
198 c.expect("landed, checked again")
199 check = c.dashboard()
200 check()
201 c.expect("landed, the dashboard restarted")
202
203 if len(evts) == 1 {
204 want := map[string]any{"repo": "site", "handle": "nxvp", "change_id": s.ChangeID, "version": 1.0,
205 "head": *s.PushedSHA, "title": "Tune the cache (v1)", "landed_commit": *s.PushedSHA,
206 "repo_key": "valley:site", "key": "valley:site@" + s.ChangeID}
207 if !maps.Equal(evts[0].Data, want) {
208 t.Errorf("change:integrated carries %v, want %v", evts[0].Data, want)
209 }
210 }
211}
212
213// TestChangeRestackedTwiceThenLanded: each version the valley's restacker
214// records is a change:new-version, and the change landing at the last of
215// them is the change's change:integrated, once, and the run's own version
216// reads integrated.
217func TestChangeRestackedTwiceThenLanded(t *testing.T) {
218 c := newChangeSession(t)
219 s := c.pushed("20261030-0900-0001", "rstk", 1, "restack.txt")
220 v1 := listed(1, *s.PushedSHA, "operator")
221 c.list(listedChange("rstk", "ready", v1))
222 check := c.dashboard()
223 check()
224 c.expect("ready")
225
226 c.advanceMain("u1.txt")
227 v2 := listed(2, c.rebaseOntoMain(*s.PushedBranch), "restacker")
228 c.list(listedChange("rstk", "ready", v1, v2))
229 check()
230 if evts := c.expect("restacked", "rstk change:new-version v2"); len(evts) == 1 &&
231 (evts[0].Data["uploader"] != "restacker" || evts[0].Data["head"] != v2["head"]) {
232 t.Errorf("change:new-version should name the version's head and uploader: %v", evts[0].Data)
233 }
234
235 c.advanceMain("u2.txt")
236 v3 := listed(3, c.rebaseOntoMain(*s.PushedBranch), "restacker")
237 c.list(listedChange("rstk", "ready", v1, v2, v3))
238 check()
239 check()
240 c.expect("restacked again", "rstk change:new-version v3")
241
242 c.list(listedChange("rstk", "ready", v1, v2, approved(v3)))
243 check()
244 c.expect("approved", "rstk change:approved v3")
245
246 c.fastForward(v3["head"].(string))
247 c.list(listedChange("rstk", "ready", v1, v2, landedAs(v3, v3["head"].(string))))
248 msg := check()
249 c.expect("landed", "rstk change:integrated v3")
250 if r := msg.results[s.ID]; r.Verdict != integration.Integrated {
251 t.Errorf("the run's own version reads %v, want integrated", r.Verdict)
252 }
253 check()
254 c.dashboard()()
255 c.expect("landed, checked again and restarted")
256}
257
258// TestChangeNextRoundAfterALanding: a follow-up run's version, made on a
259// main that already holds the change's landing, is the change's next round,
260// which the valley reads unlanded (landed_version null). The follow-up and
261// the change's row read it as it stands, so cleanup --done and the knot step
262// leave it alone, the integrator's decision on it is news again, and so is
263// its landing.
264func TestChangeNextRoundAfterALanding(t *testing.T) {
265 c := newChangeSession(t)
266 s1 := c.pushed("20261030-0900-0001", "nrnd", 1, "round1.txt")
267 v1 := listed(1, *s1.PushedSHA, "operator")
268 c.list(listedChange("nrnd", "ready", v1))
269 check := c.dashboard()
270 check()
271 c.expect("ready")
272
273 c.fastForward(*s1.PushedSHA)
274 v1 = landedAs(v1, *s1.PushedSHA)
275 c.list(with(listedChange("nrnd", "ready", v1), "landed_version", 1, "landed_commit", *s1.PushedSHA))
276 check()
277 c.expect("landed", "nrnd change:approved v1", "nrnd change:integrated v1")
278
279 s2 := c.pushed("20261030-1000-0002", "nrnd", 2, "round2.txt")
280 s2.Knot = &run.Knot{ID: "oc-1", Project: "site", Type: "outcome", Linked: "valley:site/" + s2.ChangeID}
281 if err := c.store.Save(s2); err != nil {
282 t.Fatal(err)
283 }
284 v2 := listed(2, *s2.PushedSHA, "operator")
285 c.list(with(listedChange("nrnd", "ready", v1, v2), "landed_version", nil, "landed_commit", nil))
286 msg := check()
287 c.expect("next round")
288 if r := msg.results[s2.ID]; r.Verdict != integration.Ready {
289 t.Errorf("the next round's run reads %v, want ready", r.Verdict)
290 }
291 row := msg.changes[integration.ChangeKey{Repo: "site", ChangeID: s2.ChangeID}]
292 if row.Verdict != integration.Ready || finishedVerdict(row.Verdict) != "" {
293 t.Errorf("the change's row reads %v, want ready and unfinished", row.Verdict)
294 }
295 states, err := c.store.List()
296 if err != nil {
297 t.Fatal(err)
298 }
299 if lks := knotsToSettle(states, msg.results, msg.changes); len(lks) != 0 {
300 t.Errorf("knots to settle on the next round: %+v", lks)
301 }
302
303 c.list(with(listedChange("nrnd", "ready", v1, decided(v2, "stale")), "landed_version", nil, "landed_commit", nil))
304 check()
305 c.expect("next round stale", "nrnd change:approved v2", "nrnd change:stale v2")
306
307 c.fastForward(*s2.PushedSHA)
308 c.list(with(listedChange("nrnd", "ready", v1, landedAs(v2, *s2.PushedSHA)), "landed_version", 2, "landed_commit", *s2.PushedSHA))
309 check()
310 check()
311 c.expect("next round landed", "nrnd change:integrated v2")
312}
313
314// TestChangeStaleThenApprovedAgain: an approved version going stale is a
315// change:stale; the restacker's next version, and its approval, report
316// again; and a version a run of the session pushed is no news, even before
317// finalize records the version it became.
318func TestChangeStaleThenApprovedAgain(t *testing.T) {
319 c := newChangeSession(t)
320 s := c.pushed("20261030-0900-0001", "stal", 1, "stale.txt")
321 v1 := listed(1, *s.PushedSHA, "operator")
322 c.list(listedChange("stal", "ready", v1))
323 check := c.dashboard()
324 check()
325 c.list(listedChange("stal", "ready", approved(v1)))
326 check()
327 c.expect("approved", "stal change:approved v1")
328
329 c.list(listedChange("stal", "ready", decided(v1, "stale")))
330 check()
331 check()
332 c.expect("stale", "stal change:stale v1")
333
334 c.advanceMain("u1.txt")
335 v2 := listed(2, c.rebaseOntoMain(*s.PushedBranch), "restacker")
336 c.list(listedChange("stal", "ready", decided(v1, "stale"), v2))
337 check()
338 c.expect("restacked", "stal change:new-version v2")
339
340 c.list(listedChange("stal", "ready", decided(v1, "stale"), approved(v2)))
341 check()
342 c.expect("approved again", "stal change:approved v2")
343
344 c.list(listedChange("stal", "ready", decided(v1, "stale"), decided(v2, "rejected")))
345 check()
346 c.expect("rejected", "stal change:rejected v2")
347
348 followUp := c.pushed("20261030-0900-0002", "stal", 0, "fix.txt")
349 v3 := listed(3, *followUp.PushedSHA, "operator")
350 c.list(listedChange("stal", "ready", decided(v1, "stale"), decided(v2, "rejected"), v3))
351 check()
352 c.expect("the session's follow-up pushed a version")
353}
354
355// TestChangeWithdrawn: a tracked change being withdrawn is a
356// change:withdrawn, once.
357func TestChangeWithdrawn(t *testing.T) {
358 c := newChangeSession(t)
359 head := c.push("20261030-0900-0001", "unused", time.Now(), "w.txt").PushedSHA
360 clone := c.clone
361 tracked := &run.State{ID: "20261030-0900-0002", Type: "track", ChangeID: handleChangeID("wdrn"), CloneDir: &clone,
362 HeadSHA: *head, CreatedAt: time.Now().Format(time.RFC3339),
363 Valley: &run.Valley{Repo: "site", Handle: "wdrn", Version: 1, Title: "Drop the shim"}}
364 if err := c.store.Save(tracked); err != nil {
365 t.Fatal(err)
366 }
367 v1 := listed(1, *head, "someone")
368 c.list(listedChange("wdrn", "ready", v1))
369 check := c.dashboard()
370 check()
371 c.expect("ready")
372
373 c.list(listedChange("wdrn", "withdrawn", v1))
374 check()
375 check()
376 c.expect("withdrawn", "wdrn change:withdrawn v1")
377}
378
379// TestChangeFirstStartReportsNoHistory: a session's first look at its
380// changes, with no ledger, records where each stands and reports none of
381// it, landed, approved, decided, withdrawn or restacked; nor do later
382// checks and restarts while nothing moves.
383func TestChangeFirstStartReportsNoHistory(t *testing.T) {
384 c := newChangeSession(t)
385 runOf := func(n int, handle string) map[string]any {
386 s := c.pushed(fmt.Sprintf("20261030-0900-000%d", n), handle, 1, handle+".txt")
387 return listed(1, *s.PushedSHA, "operator")
388 }
389 landed := runOf(1, "lndd")
390 c.fastForward(landed["head"].(string))
391 approvedV := runOf(2, "appr")
392 staleV := runOf(3, "stal")
393 withdrawn := runOf(4, "wdrn")
394 restacked := runOf(5, "rstk")
395 c.list(
396 listedChange("lndd", "ready", landedAs(landed, landed["head"].(string))),
397 listedChange("appr", "ready", approved(approvedV)),
398 listedChange("stal", "ready", decided(staleV, "stale")),
399 listedChange("wdrn", "withdrawn", withdrawn),
400 listedChange("rstk", "ready", restacked, listed(2, strings.Repeat("a", 40), "restacker")),
401 )
402
403 check := c.dashboard()
404 check()
405 c.expect("first start")
406 if _, err := os.Stat(filepath.Join(c.store.BaseDir(), pipeline.ChangeLedgerFile)); err != nil {
407 t.Errorf("the first start should record where the changes stand: %v", err)
408 }
409 check()
410 c.dashboard()()
411 c.expect("checked again and restarted")
412}