| 1 | package cmd |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "io" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "strings" |
| 11 | "sync/atomic" |
| 12 | "testing" |
| 13 | "time" |
| 14 | |
| 15 | "the-valley/flow/internal/checksfix" |
| 16 | "the-valley/flow/internal/event" |
| 17 | "the-valley/flow/internal/git" |
| 18 | "the-valley/flow/internal/integration" |
| 19 | "the-valley/flow/internal/restack" |
| 20 | "the-valley/flow/internal/run" |
| 21 | ) |
| 22 | |
| 23 | // TestQueueStateIsWhoseMove: each state is the coordinator's, the |
| 24 | // operator's, flow's or nobody's, and failed checks or a restack conflict |
| 25 | // are flow's only while its dispatcher works on them: a dispatch is due, |
| 26 | // or the run it dispatched is alive or left a new head. |
| 27 | func TestQueueStateIsWhoseMove(t *testing.T) { |
| 28 | checks := func(state string) *checksfix.View { return &checksfix.View{State: state} } |
| 29 | conflict := func(state string) *restack.View { return &restack.View{State: state} } |
| 30 | s := &run.State{ID: "r1"} |
| 31 | for _, tc := range []struct { |
| 32 | name string |
| 33 | row runRow |
| 34 | wantState string |
| 35 | want party |
| 36 | }{ |
| 37 | {"running", runRow{status: "running"}, "running", partyFlow}, |
| 38 | {"working", runRow{status: "working"}, "working", partyFlow}, |
| 39 | {"needs attention", runRow{status: "needs-attention"}, "needs-attention", partyCoordinator}, |
| 40 | {"draft awaiting review", runRow{status: "awaiting-review"}, "awaiting-review", partyCoordinator}, |
| 41 | {"stale", runRow{status: "stale"}, "stale", partyCoordinator}, |
| 42 | {"rejected", runRow{status: "rejected"}, "rejected", partyCoordinator}, |
| 43 | {"failed", runRow{status: "failed"}, "failed", partyCoordinator}, |
| 44 | {"draft", runRow{status: "draft"}, "draft", partyCoordinator}, |
| 45 | {"ready", runRow{status: "awaiting-approval", ci: "pending"}, "awaiting-approval", partyOperator}, |
| 46 | {"pushed branch", runRow{status: "awaiting-integration"}, "awaiting-integration", partyOperator}, |
| 47 | {"uncertain", runRow{status: "uncertain"}, "uncertain", partyOperator}, |
| 48 | {"approved", runRow{status: "approved"}, "approved", partyFlow}, |
| 49 | {"open PR", runRow{status: "pr-created", merge: "pending"}, "pr-created", partyFlow}, |
| 50 | {"PR ready to merge", runRow{status: "pr-created", merge: "ready"}, "ready-to-merge", partyOperator}, |
| 51 | {"PR ready and approved on any of its runs", runRow{status: "pr-created", merge: "ready", approved: true}, "pr-created", partyFlow}, |
| 52 | {"draft PR ready to merge", runRow{status: "pr-created", merge: "ready", draftPR: true}, "pr-created", partyFlow}, |
| 53 | {"tracked GitHub work ready to merge", runRow{status: "tracking", merge: "ready", run: &run.State{ID: "t1", Type: "track", PRURL: strPtr("https://github.com/acme/widget/pull/9")}}, "ready-to-merge", partyOperator}, |
| 54 | {"integrated", runRow{status: "integrated"}, "integrated", partyNone}, |
| 55 | {"older version", runRow{status: "older-version"}, "older-version", partyNone}, |
| 56 | {"checks failed, not flow's", runRow{status: "awaiting-approval", ci: "failing"}, "checks-failed", partyCoordinator}, |
| 57 | {"checks failed, fix due", runRow{status: "awaiting-approval", ci: "failing", checks: checks(checksfix.StateDue)}, "checks-failed", partyFlow}, |
| 58 | {"checks failed, fix run alive", runRow{status: "awaiting-approval", ci: "failing", checks: checks(checksfix.StateDispatched)}, "checks-failed", partyFlow}, |
| 59 | {"checks failed, fix run finished without a new head", runRow{status: "awaiting-approval", ci: "failing", checks: checks(checksfix.StateDispatched), checksDone: true}, "checks-failed", partyCoordinator}, |
| 60 | {"checks failed, fixes spent", runRow{status: "awaiting-approval", ci: "failing", checks: checks(checksfix.StateStopped)}, "checks-failed", partyCoordinator}, |
| 61 | {"checks failed, launch failed", runRow{status: "awaiting-approval", ci: "failing", checks: checks(checksfix.StateRefused)}, "checks-failed", partyCoordinator}, |
| 62 | {"stale for failed checks, fixes spent", runRow{status: "checks-failed", checks: checks(checksfix.StateStopped)}, "checks-failed", partyCoordinator}, |
| 63 | {"conflict, cooling down", runRow{status: "awaiting-approval", restack: conflict(restack.StateCooldown)}, "conflicting", partyFlow}, |
| 64 | {"conflict, resolution run alive", runRow{status: "awaiting-approval", restack: conflict(restack.StateDispatched)}, "conflicting", partyFlow}, |
| 65 | {"conflict, resolution run finished without a new head", runRow{status: "awaiting-approval", restack: conflict(restack.StateDispatched), restackDone: true}, "conflicting", partyCoordinator}, |
| 66 | {"conflict left alone", runRow{status: "awaiting-approval", restack: conflict(restack.StateHeld)}, "conflicting", partyCoordinator}, |
| 67 | {"stale for a conflict, not flow's", runRow{status: "conflicting"}, "conflicting", partyCoordinator}, |
| 68 | {"draft while flow's restack run launches", runRow{status: "draft", restack: conflict(restack.StateLaunching)}, "conflicting", partyFlow}, |
| 69 | {"draft, flow's restack runs spent", runRow{status: "draft", restack: conflict(restack.StateStopped)}, "conflicting", partyCoordinator}, |
| 70 | } { |
| 71 | t.Run(tc.name, func(t *testing.T) { |
| 72 | if tc.row.run == nil { |
| 73 | tc.row.run = s |
| 74 | } |
| 75 | state, p := queueState(tc.row) |
| 76 | if state != tc.wantState || p != tc.want { |
| 77 | t.Errorf("queueState = %s, %d; want %s, %d", state, p, tc.wantState, tc.want) |
| 78 | } |
| 79 | }) |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | // TestDispatchFinished: a dispatched run has finished once its record reads |
| 84 | // it not running, unless it left a new head, and once cleanup removed its |
| 85 | // record; a run with no record that cleanup didn't remove is still |
| 86 | // launching. |
| 87 | func TestDispatchFinished(t *testing.T) { |
| 88 | store := run.NewHomeDirStoreFromPath(t.TempDir()) |
| 89 | if err := store.EnsureDirs(); err != nil { |
| 90 | t.Fatal(err) |
| 91 | } |
| 92 | same, other := "aaaa", "bbbb" |
| 93 | for _, s := range []*run.State{{ID: "idle"}, {ID: "pushed-same", PushedSHA: &same}, {ID: "pushed-new", PushedSHA: &other}, {ID: "alive"}, {ID: "removed"}} { |
| 94 | if err := store.Save(s); err != nil { |
| 95 | t.Fatal(err) |
| 96 | } |
| 97 | } |
| 98 | idle := CleanupDeps{IsRunActive: func(*run.State) bool { return false }} |
| 99 | if err := cleanupOneTo(io.Discard, context.Background(), "", store, git.NewExecClient(), "removed", false, idle, isolatedTmux(t)); err != nil { |
| 100 | t.Fatal(err) |
| 101 | } |
| 102 | states, err := store.List() |
| 103 | if err != nil { |
| 104 | t.Fatal(err) |
| 105 | } |
| 106 | cleared, err := clearedOf(store, states) |
| 107 | if err != nil { |
| 108 | t.Fatal(err) |
| 109 | } |
| 110 | statuses := make([]string, len(states)) |
| 111 | for i, s := range states { |
| 112 | statuses[i] = "exited" |
| 113 | if s.ID == "alive" { |
| 114 | statuses[i] = "running" |
| 115 | } |
| 116 | } |
| 117 | for id, want := range map[string]bool{"idle": true, "pushed-same": true, "pushed-new": false, "alive": false, "removed": true, "launching": false, "": false} { |
| 118 | if got := dispatchFinished(id, same, states, statuses, cleared.IDs); got != want { |
| 119 | t.Errorf("dispatchFinished(%q) = %t, want %t", id, got, want) |
| 120 | } |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | // clockEvent is an event at t. |
| 125 | func clockEvent(t time.Time, runID, typ string, data map[string]interface{}) event.Event { |
| 126 | return event.Event{Timestamp: t.UTC().Format(time.RFC3339), RunID: runID, Type: typ, Data: data} |
| 127 | } |
| 128 | |
| 129 | // TestStateClockDatesStates: a state is dated by the latest event that |
| 130 | // enters it, about the run, its change or its PR as the state's scope |
| 131 | // says, and not about another head; with no such event, and for a |
| 132 | // finished state, the age is unknown. A ready change waits from when its |
| 133 | // head was marked ready, not from when its checks passed. |
| 134 | func TestStateClockDatesStates(t *testing.T) { |
| 135 | base := time.Date(2026, 11, 20, 9, 0, 0, 0, time.UTC) |
| 136 | at := func(m int) time.Time { return base.Add(time.Duration(m) * time.Minute) } |
| 137 | c := newStateClock() |
| 138 | for _, e := range []event.Event{ |
| 139 | clockEvent(at(10), "run-a", event.AgentChangeDraft, map[string]interface{}{"change_id": "cid"}), |
| 140 | clockEvent(at(30), "run-b", event.AgentChangeDraft, map[string]interface{}{"change_id": "cid"}), |
| 141 | clockEvent(at(35), "run-b", event.AgentChangeReady, map[string]interface{}{"change_id": "cid", "head": "h1"}), |
| 142 | clockEvent(at(36), "nxvp", event.ChangeChecksFailed, map[string]interface{}{"change_id": "cid", "head": "h1"}), |
| 143 | clockEvent(at(38), "nxvp", event.ChangeChecksPassed, map[string]interface{}{"change_id": "cid"}), |
| 144 | clockEvent(at(40), "nxvp", event.ChangeStale, map[string]interface{}{"change_id": "cid", "repo": "widget", "head": "h1"}), |
| 145 | clockEvent(at(50), "run-b", event.AgentNeedsAttention, map[string]interface{}{"change_id": "cid"}), |
| 146 | clockEvent(at(60), "42", event.PRAwaitingApproval, map[string]interface{}{"pr_number": "42", "key": "acme/widget#42"}), |
| 147 | clockEvent(at(70), "42", event.PRAwaitingApproval, map[string]interface{}{"pr_number": "42", "key": "acme/gadget#42"}), |
| 148 | } { |
| 149 | c.observe(e) |
| 150 | } |
| 151 | created := at(0).Format(time.RFC3339) |
| 152 | dur := int64(5 * time.Minute / time.Millisecond) |
| 153 | a := &run.State{ID: "run-a", ChangeID: "cid", CreatedAt: created, DurationMS: &dur} |
| 154 | pr, url := "42", "https://github.com/acme/widget/pull/42" |
| 155 | p := &run.State{ID: "run-p", ChangeID: "pid", CreatedAt: created, PR: &pr, PRURL: &url} |
| 156 | for _, tc := range []struct { |
| 157 | name string |
| 158 | s *run.State |
| 159 | state string |
| 160 | head string |
| 161 | want time.Time |
| 162 | }{ |
| 163 | {"a change's state, by any run of it", a, "awaiting-review", "h1", at(30)}, |
| 164 | {"ready since marked ready, not since checks passed", a, "awaiting-approval", "h1", at(35)}, |
| 165 | {"failed checks at the head they failed", a, "checks-failed", "h1", at(40)}, |
| 166 | {"not by another head's failure", a, "checks-failed", "h2", time.Time{}}, |
| 167 | {"not by another head's readying", a, "awaiting-approval", "h2", time.Time{}}, |
| 168 | {"a change's state, by the change's event", a, "stale", "h1", at(40)}, |
| 169 | {"a run's own state, by its own events only", a, "needs-attention", "h1", time.Time{}}, |
| 170 | {"a PR's state, by its repo's PR only", p, "ready-to-merge", "", at(60)}, |
| 171 | {"no entering event", a, "awaiting-integration", "h1", time.Time{}}, |
| 172 | {"a finished state", a, "integrated", "h1", time.Time{}}, |
| 173 | } { |
| 174 | if got := c.since(tc.s, tc.state, tc.head); !got.Equal(tc.want) { |
| 175 | t.Errorf("%s: since = %v, want %v", tc.name, got, tc.want) |
| 176 | } |
| 177 | } |
| 178 | if got := (*stateClock)(nil).since(a, "awaiting-review", "h1"); !got.IsZero() { |
| 179 | t.Errorf("no clock dates %v", got) |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | // TestBuildQueue: the coordinator's items and the operator's, each oldest |
| 184 | // first, a change once under its newest run and a run's own attention as |
| 185 | // its own, with the command that moves each of the coordinator's on and |
| 186 | // none for the operator's, whose checks it shows. A change all of whose |
| 187 | // runs read older-version stands where the valley says. An unknown age |
| 188 | // reads - and null; one ahead of the clock, 0. |
| 189 | func TestBuildQueue(t *testing.T) { |
| 190 | base := time.Date(2026, 11, 20, 9, 0, 0, 0, time.UTC) |
| 191 | at := func(m int) time.Time { return base.Add(time.Duration(m) * time.Minute) } |
| 192 | repo := "widget" |
| 193 | mk := func(id, change string, m int) *run.State { |
| 194 | sha := strings.Repeat(id[len(id)-1:], 40) |
| 195 | return &run.State{ID: id, ChangeID: change, CreatedAt: at(m).Format(time.RFC3339), TargetRepo: &repo, |
| 196 | Valley: &run.Valley{Repo: "widget", Handle: "h" + change}, PushedSHA: &sha} |
| 197 | } |
| 198 | oldDraft, newDraft := mk("run-1", "c1", 0), mk("run-2", "c1", 10) |
| 199 | salvaged := mk("run-3", "c1", 5) |
| 200 | ready := mk("run-4", "c2", 20) |
| 201 | restacked := mk("run-5", "c3", 1) |
| 202 | running := mk("run-6", "c4", 2) |
| 203 | pushed := mk("run-7", "c5", 3) |
| 204 | rows := []runRow{ |
| 205 | {run: oldDraft, status: "older-version"}, |
| 206 | {run: newDraft, status: "awaiting-review", since: at(40), label: "hc1", change: &integration.Change{Repo: "widget", Handle: "hc1", Head: *newDraft.PushedSHA}}, |
| 207 | {run: salvaged, status: "needs-attention", since: at(30), label: "hc1"}, |
| 208 | {run: ready, status: "awaiting-approval", since: at(25), label: "hc2", ci: "pending"}, |
| 209 | {run: restacked, status: "older-version", label: "hc3"}, |
| 210 | {run: running, status: "running", since: at(2)}, |
| 211 | {run: pushed, status: "awaiting-integration", since: at(120), label: "hc5", ci: "-"}, |
| 212 | } |
| 213 | report := integration.Report{Changes: map[integration.ChangeKey]integration.Result{ |
| 214 | {Repo: "widget", ChangeID: "c3"}: {Verdict: integration.Stale, Change: &integration.Change{Repo: "widget", Handle: "hc3", Head: "f00d"}}, |
| 215 | }} |
| 216 | q := buildQueue(rows, report, newStateClock()) |
| 217 | |
| 218 | var got []string |
| 219 | for _, it := range q.coordinator { |
| 220 | got = append(got, it.Run+" "+it.State+" "+it.Next) |
| 221 | } |
| 222 | want := []string{ |
| 223 | `run-3 needs-attention valley flow launch --repo widget --resume-from run-3 "<brief>"`, |
| 224 | "run-2 awaiting-review valley flow ready run-2 --head " + *newDraft.PushedSHA, |
| 225 | `run-5 stale valley flow launch --repo widget --change run-5 "<brief>"`, |
| 226 | } |
| 227 | if strings.Join(got, "\n") != strings.Join(want, "\n") { |
| 228 | t.Errorf("coordinator's items:\n%s\nwant (oldest first, the undated last):\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) |
| 229 | } |
| 230 | if len(q.operator) != 2 || q.operator[0].Run != "run-4" || q.operator[0].Checks != "pending" || q.operator[0].Next != "" || q.operator[1].Run != "run-7" { |
| 231 | t.Errorf("operator's items = %+v, want run-4 awaiting approval, checks pending, no command; then run-7", q.operator) |
| 232 | } |
| 233 | |
| 234 | var text bytes.Buffer |
| 235 | q.write(&text, at(100)) |
| 236 | for _, line := range []string{ |
| 237 | "Waiting on the coordinator", |
| 238 | "◇ widget hc1 · awaiting-review · for 1h · head 2222222", |
| 239 | " run: valley flow ready run-2 --head " + *newDraft.PushedSHA, |
| 240 | "◇ widget hc3 · stale · for - · head f00d", |
| 241 | "Waiting on the operator", |
| 242 | "◇ widget hc2 · awaiting-approval · for 1h · head 4444444 · checks pending", |
| 243 | "◇ widget hc5 · awaiting-integration · for 0s · head 7777777", |
| 244 | } { |
| 245 | if !strings.Contains(text.String(), line+"\n") { |
| 246 | t.Errorf("text queue lacks %q:\n%s", line, text.String()) |
| 247 | } |
| 248 | } |
| 249 | var js map[string][]map[string]interface{} |
| 250 | var buf bytes.Buffer |
| 251 | if err := q.writeJSON(&buf, at(100)); err != nil { |
| 252 | t.Fatal(err) |
| 253 | } |
| 254 | if err := json.Unmarshal(buf.Bytes(), &js); err != nil { |
| 255 | t.Fatalf("queue --json: %v\n%s", err, buf.String()) |
| 256 | } |
| 257 | if it := js["coordinator"][1]; it["state"] != "awaiting-review" || it["age_seconds"] != float64(3600) || it["since"] != at(40).Format(time.RFC3339) { |
| 258 | t.Errorf("JSON item = %v", it) |
| 259 | } |
| 260 | if it := js["coordinator"][2]; it["since"] != nil || it["age_seconds"] != nil { |
| 261 | t.Errorf("an undated JSON item = %v, want since and age_seconds null", it) |
| 262 | } |
| 263 | if it := js["operator"][1]; it["age_seconds"] != float64(0) { |
| 264 | t.Errorf("a JSON item ahead of the clock = %v, want age_seconds 0", it) |
| 265 | } |
| 266 | |
| 267 | buf.Reset() |
| 268 | if err := (queue{}).writeJSON(&buf, at(0)); err != nil || strings.TrimSpace(buf.String()) != `{"coordinator":[],"operator":[]}` { |
| 269 | t.Errorf("empty queue --json = %q, %v", buf.String(), err) |
| 270 | } |
| 271 | buf.Reset() |
| 272 | queue{}.write(&buf, at(0)) |
| 273 | if buf.Len() != 0 { |
| 274 | t.Errorf("empty queue printed %q", buf.String()) |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | // TestBuildQueueListsAChangeNoRunSpeaksFor: a change with a run that reads |
| 279 | // older-version stands where the valley lists it unless another run speaks |
| 280 | // for it. A run that exited without pushing speaks for no version; a run at |
| 281 | // work on the change does. |
| 282 | func TestBuildQueueListsAChangeNoRunSpeaksFor(t *testing.T) { |
| 283 | repo := "widget" |
| 284 | mk := func(id, change string, pushed bool) *run.State { |
| 285 | s := &run.State{ID: id, ChangeID: change, CreatedAt: "2026-11-20T09:00:00Z", TargetRepo: &repo, Valley: &run.Valley{Repo: "widget"}} |
| 286 | if pushed { |
| 287 | sha := strings.Repeat("a", 40) |
| 288 | s.PushedSHA = &sha |
| 289 | } |
| 290 | return s |
| 291 | } |
| 292 | rows := []runRow{ |
| 293 | {run: mk("run-1", "c1", false), status: "exited"}, |
| 294 | {run: mk("run-2", "c1", true), status: "older-version"}, |
| 295 | {run: mk("run-3", "c2", true), status: "older-version"}, |
| 296 | {run: mk("run-4", "c2", false), status: "running"}, |
| 297 | } |
| 298 | ready := func(head string) integration.Result { |
| 299 | return integration.Result{Verdict: integration.Ready, Change: &integration.Change{Repo: "widget", Head: head}} |
| 300 | } |
| 301 | report := integration.Report{Changes: map[integration.ChangeKey]integration.Result{ |
| 302 | {Repo: "widget", ChangeID: "c1"}: ready("f00d"), |
| 303 | {Repo: "widget", ChangeID: "c2"}: ready("beef"), |
| 304 | }} |
| 305 | q := buildQueue(rows, report, newStateClock()) |
| 306 | if len(q.coordinator) != 0 || len(q.operator) != 1 { |
| 307 | t.Fatalf("queue = %+v, want c1's active version alone, awaiting approval", q) |
| 308 | } |
| 309 | if it := q.operator[0]; it.key != "change:widget/c1" || it.State != "awaiting-approval" || it.Head != "f00d" { |
| 310 | t.Errorf("operator's item = %+v, want c1 awaiting approval at f00d", it) |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | var waitingDraft = queueItem{party: partyCoordinator, key: "change:widget/cid-b", Run: "run-b", Change: "nxvp", ChangeID: "cid-b", Project: "widget", |
| 315 | Head: "1a2b3c4d", State: "awaiting-review", Since: time.Now().Add(-time.Hour), Next: "valley flow ready run-b --head 1a2b3c4d"} |
| 316 | |
| 317 | var waitingApproval = queueItem{party: partyOperator, key: "change:widget/cid-c", Run: "run-c", Change: "k3fd", ChangeID: "cid-c", Project: "widget", |
| 318 | Head: "9f8e7d6c", State: "awaiting-approval", Checks: "pending", Since: time.Now().Add(-time.Minute), Note: "checks pending"} |
| 319 | |
| 320 | // TestQueueDigest: the digest stays as it was while only ages, notes and |
| 321 | // order change, and changes with every transition: an item arriving or |
| 322 | // leaving, its state, its head, its group, and the operator's checks. |
| 323 | func TestQueueDigest(t *testing.T) { |
| 324 | q := queue{coordinator: []queueItem{waitingDraft}, operator: []queueItem{waitingApproval}} |
| 325 | d := q.digest() |
| 326 | if d == (queue{}).digest() { |
| 327 | t.Fatal("a queue with items has an empty queue's digest") |
| 328 | } |
| 329 | |
| 330 | aged := queue{coordinator: []queueItem{waitingDraft}, operator: []queueItem{waitingApproval}} |
| 331 | aged.coordinator[0].Since = aged.coordinator[0].Since.Add(-3 * time.Hour) |
| 332 | aged.operator[0].Since = time.Time{} |
| 333 | aged.coordinator[0].Note = "something else" |
| 334 | if aged.digest() != d { |
| 335 | t.Error("ages and notes changed the digest") |
| 336 | } |
| 337 | second := waitingDraft |
| 338 | second.key, second.Run = "change:widget/cid-d", "run-d" |
| 339 | if (queue{coordinator: []queueItem{waitingDraft, second}}).digest() != (queue{coordinator: []queueItem{second, waitingDraft}}).digest() { |
| 340 | t.Error("order changed the digest") |
| 341 | } |
| 342 | |
| 343 | with := func(f func(*queue)) string { |
| 344 | c := queue{coordinator: []queueItem{waitingDraft}, operator: []queueItem{waitingApproval}} |
| 345 | f(&c) |
| 346 | return c.digest() |
| 347 | } |
| 348 | for name, changed := range map[string]string{ |
| 349 | "an item arrives": with(func(c *queue) { c.coordinator = append(c.coordinator, second) }), |
| 350 | "an item leaves": with(func(c *queue) { c.operator = nil }), |
| 351 | "a state changes": with(func(c *queue) { c.coordinator[0].State = "draft" }), |
| 352 | "a head changes": with(func(c *queue) { c.coordinator[0].Head = "5e6f7a8b" }), |
| 353 | "the checks pass": with(func(c *queue) { c.operator[0].Checks = "passing" }), |
| 354 | "an item changes groups": with(func(c *queue) { c.operator = append(c.operator, c.coordinator[0]); c.coordinator = nil }), |
| 355 | } { |
| 356 | if changed == d { |
| 357 | t.Errorf("%s: the digest stayed %s", name, d) |
| 358 | } |
| 359 | } |
| 360 | } |
| 361 | |
| 362 | // watchQueueHarness runs watchQueue in a temp session, with a queue source |
| 363 | // the test drives: each read of the queue is announced on looks and |
| 364 | // answered by answer. |
| 365 | type watchQueueHarness struct { |
| 366 | t *testing.T |
| 367 | src queueSource |
| 368 | looks chan int |
| 369 | answer func(n int) (queue, bool) |
| 370 | out bytes.Buffer |
| 371 | done chan error |
| 372 | cancel context.CancelFunc |
| 373 | } |
| 374 | |
| 375 | func newWatchQueueHarness(t *testing.T, answer func(n int) (queue, bool)) *watchQueueHarness { |
| 376 | dir := t.TempDir() |
| 377 | h := &watchQueueHarness{t: t, looks: make(chan int, 16), answer: answer, done: make(chan error, 1), |
| 378 | src: queueSource{events: filepath.Join(dir, "events.jsonl"), runs: filepath.Join(dir, "runs")}} |
| 379 | var n int32 |
| 380 | h.src.compute = func(context.Context) (queue, bool, error) { |
| 381 | k := int(atomic.AddInt32(&n, 1)) |
| 382 | q, provisional := h.answer(k) |
| 383 | h.looks <- k |
| 384 | return q, provisional, nil |
| 385 | } |
| 386 | return h |
| 387 | } |
| 388 | |
| 389 | func (h *watchQueueHarness) start(seen string) { |
| 390 | ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| 391 | h.cancel = cancel |
| 392 | h.t.Cleanup(cancel) |
| 393 | next := func(d string) string { return nextQueueWatchCommand("", d) } |
| 394 | go func() { h.done <- watchQueue(ctx, h.src, seen, next, &h.out) }() |
| 395 | } |
| 396 | |
| 397 | // look waits for the watch's next read of the queue and returns its number. |
| 398 | func (h *watchQueueHarness) look() int { |
| 399 | h.t.Helper() |
| 400 | select { |
| 401 | case n := <-h.looks: |
| 402 | return n |
| 403 | case err := <-h.done: |
| 404 | h.t.Fatalf("the watch ended (%v) before it read the queue:\n%s", err, h.out.String()) |
| 405 | } |
| 406 | return 0 |
| 407 | } |
| 408 | |
| 409 | // write appends to the session's event log, or writes a run record. |
| 410 | func (h *watchQueueHarness) write(path string) { |
| 411 | h.t.Helper() |
| 412 | f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) |
| 413 | if err != nil { |
| 414 | h.t.Fatal(err) |
| 415 | } |
| 416 | defer f.Close() |
| 417 | if _, err := f.WriteString("{}\n"); err != nil { |
| 418 | h.t.Fatal(err) |
| 419 | } |
| 420 | } |
| 421 | |
| 422 | func (h *watchQueueHarness) wait() string { |
| 423 | h.t.Helper() |
| 424 | if err := <-h.done; err != nil { |
| 425 | h.t.Fatalf("watch --queue: %v\n%s", err, h.out.String()) |
| 426 | } |
| 427 | return h.out.String() |
| 428 | } |
| 429 | |
| 430 | // TestWatchQueueReturnsAtOnceWhenAnythingWaits: without --seen the watch |
| 431 | // compares with an empty queue, so it returns from its first read when |
| 432 | // anything waits, printing the queue and the next: line that names its |
| 433 | // digest. |
| 434 | func TestWatchQueueReturnsAtOnceWhenAnythingWaits(t *testing.T) { |
| 435 | q := queue{coordinator: []queueItem{waitingDraft}} |
| 436 | h := newWatchQueueHarness(t, func(int) (queue, bool) { return q, false }) |
| 437 | h.start("") |
| 438 | out := h.wait() |
| 439 | for _, want := range []string{"Waiting on the coordinator\n", "◇ widget nxvp · awaiting-review · for 1h", " run: valley flow ready run-b --head 1a2b3c4d\n"} { |
| 440 | if !strings.Contains(out, want) { |
| 441 | t.Errorf("output lacks %q:\n%s", want, out) |
| 442 | } |
| 443 | } |
| 444 | if want := "next: valley flow watch --queue --seen " + q.digest() + "\n"; !strings.HasSuffix(out, want) { |
| 445 | t.Errorf("output doesn't end with %q:\n%s", want, out) |
| 446 | } |
| 447 | } |
| 448 | |
| 449 | // TestWatchQueueWaitsForADifferentQueue: a watch from the last one's |
| 450 | // digest reads the queue again on each write to the event log or the run |
| 451 | // records, and doesn't return while the queue is as it saw it, the draft |
| 452 | // still waiting. It returns once a second item comes to wait beside the |
| 453 | // first, printing both. It reads nothing but the queue: no run, pane or |
| 454 | // event decides when it returns. |
| 455 | func TestWatchQueueWaitsForADifferentQueue(t *testing.T) { |
| 456 | first := queue{coordinator: []queueItem{waitingDraft}} |
| 457 | both := queue{coordinator: []queueItem{waitingDraft}, operator: []queueItem{waitingApproval}} |
| 458 | h := newWatchQueueHarness(t, func(n int) (queue, bool) { |
| 459 | if n < 3 { |
| 460 | return first, false |
| 461 | } |
| 462 | return both, false |
| 463 | }) |
| 464 | h.start(first.digest()) |
| 465 | h.look() |
| 466 | h.write(h.src.events) |
| 467 | if n := h.look(); n != 2 { |
| 468 | t.Fatalf("read %d on the event log's write", n) |
| 469 | } |
| 470 | h.write(filepath.Join(h.src.runs, "run-c.json")) |
| 471 | out := h.wait() |
| 472 | if !strings.Contains(out, "◇ widget nxvp · awaiting-review") || !strings.Contains(out, "Waiting on the operator\n◇ widget k3fd · awaiting-approval") { |
| 473 | t.Errorf("want both items:\n%s", out) |
| 474 | } |
| 475 | if want := "next: valley flow watch --queue --seen " + both.digest() + "\n"; !strings.HasSuffix(out, want) { |
| 476 | t.Errorf("output doesn't end with %q:\n%s", want, out) |
| 477 | } |
| 478 | } |
| 479 | |
| 480 | // TestWatchQueueWaitsOutAHalfWrittenRecord: a queue read while a run |
| 481 | // record reads half written is provisional: the watch doesn't return on |
| 482 | // it, even when it differs, and the write that completes the record ends |
| 483 | // the wait with the draft the record holds. |
| 484 | func TestWatchQueueWaitsOutAHalfWrittenRecord(t *testing.T) { |
| 485 | ready := queue{operator: []queueItem{waitingApproval}} |
| 486 | h := newWatchQueueHarness(t, func(n int) (queue, bool) { |
| 487 | if n == 1 { |
| 488 | return ready, true // the draft's record caught mid-write |
| 489 | } |
| 490 | return queue{coordinator: []queueItem{waitingDraft}, operator: []queueItem{waitingApproval}}, false |
| 491 | }) |
| 492 | h.start("") |
| 493 | h.look() |
| 494 | h.write(filepath.Join(h.src.runs, "run-b.json")) |
| 495 | if out := h.wait(); !strings.Contains(out, "◇ widget nxvp · awaiting-review") { |
| 496 | t.Errorf("want the draft once its record is whole:\n%s", out) |
| 497 | } |
| 498 | } |
| 499 | |
| 500 | // TestWatchQueueInterrupted: cancelled while it waits, the watch prints |
| 501 | // just the next: line, which waits from the digest it was given. |
| 502 | func TestWatchQueueInterrupted(t *testing.T) { |
| 503 | q := queue{coordinator: []queueItem{waitingDraft}} |
| 504 | h := newWatchQueueHarness(t, func(int) (queue, bool) { return q, false }) |
| 505 | h.start(q.digest()) |
| 506 | h.look() |
| 507 | h.cancel() |
| 508 | if out, want := h.wait(), "next: valley flow watch --queue --seen "+q.digest()+"\n"; out != want { |
| 509 | t.Errorf("interrupted watch printed %q, want %q", out, want) |
| 510 | } |
| 511 | } |
| 512 | |
| 513 | // TestComputeQueueIsProvisionalOnAHalfWrittenRecord: a run record that |
| 514 | // doesn't parse makes the queue provisional; with every record whole, it |
| 515 | // isn't. |
| 516 | func TestComputeQueueIsProvisionalOnAHalfWrittenRecord(t *testing.T) { |
| 517 | store := run.NewHomeDirStoreFromPath(t.TempDir()) |
| 518 | if err := store.EnsureDirs(); err != nil { |
| 519 | t.Fatal(err) |
| 520 | } |
| 521 | if _, provisional, err := computeQueue(context.Background(), store); err != nil || provisional { |
| 522 | t.Fatalf("an empty session: provisional %t, %v", provisional, err) |
| 523 | } |
| 524 | if err := os.WriteFile(filepath.Join(store.StateDir(), "run-b.json"), []byte(`{"id": "run-b", "pro`), 0o644); err != nil { |
| 525 | t.Fatal(err) |
| 526 | } |
| 527 | if q, provisional, err := computeQueue(context.Background(), store); err != nil || !provisional || len(q.coordinator)+len(q.operator) != 0 { |
| 528 | t.Errorf("a half-written record: provisional %t, %v, %+v", provisional, err, q) |
| 529 | } |
| 530 | } |
| 531 | |
| 532 | // TestWatchOnceHandlesLinesAsItReads: a one-shot watch from the start of a |
| 533 | // backlog writes the first matching event before it reads the rest. The |
| 534 | // output truncates the file at that first write, so a watch that read the |
| 535 | // whole backlog before handling its lines would print the later match |
| 536 | // too. |
| 537 | func TestWatchOnceHandlesLinesAsItReads(t *testing.T) { |
| 538 | path := filepath.Join(t.TempDir(), "events.jsonl") |
| 539 | line := func(typ, runID string) string { |
| 540 | data, err := json.Marshal(event.New(runID, typ, nil)) |
| 541 | if err != nil { |
| 542 | t.Fatal(err) |
| 543 | } |
| 544 | return string(data) + "\n" |
| 545 | } |
| 546 | backlog := line(event.PRMerged, "1") + strings.Repeat(line(event.PhaseStarted, "routine"), 4096) + line(event.PRMerged, "2") |
| 547 | if err := os.WriteFile(path, []byte(backlog), 0o644); err != nil { |
| 548 | t.Fatal(err) |
| 549 | } |
| 550 | out := &truncatingWriter{path: path} |
| 551 | flt := buildFilter([]string{event.PRMerged}, nil, nil) |
| 552 | next := func(int64) string { return "next" } |
| 553 | if err := watchOnce(context.Background(), path, flt, 0, true, next, out); err != nil { |
| 554 | t.Fatal(err) |
| 555 | } |
| 556 | if got := out.String(); !strings.Contains(got, `"run_id":"1"`) || strings.Contains(got, `"run_id":"2"`) { |
| 557 | t.Errorf("want the first merge alone, written before the backlog was read:\n%s", got) |
| 558 | } |
| 559 | } |
| 560 | |
| 561 | // truncatingWriter empties the file at path at its first write. |
| 562 | type truncatingWriter struct { |
| 563 | bytes.Buffer |
| 564 | path string |
| 565 | } |
| 566 | |
| 567 | func (w *truncatingWriter) Write(p []byte) (int, error) { |
| 568 | if w.Len() == 0 { |
| 569 | if err := os.Truncate(w.path, 0); err != nil { |
| 570 | return 0, err |
| 571 | } |
| 572 | } |
| 573 | return w.Buffer.Write(p) |
| 574 | } |