| 1 | //go:build e2e |
| 2 | |
| 3 | package e2e |
| 4 | |
| 5 | import ( |
| 6 | "encoding/json" |
| 7 | "fmt" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "slices" |
| 11 | "strings" |
| 12 | "syscall" |
| 13 | "testing" |
| 14 | "time" |
| 15 | |
| 16 | "the-valley/flow/internal/event" |
| 17 | "the-valley/flow/internal/restack" |
| 18 | "the-valley/flow/internal/valley" |
| 19 | ) |
| 20 | |
| 21 | // restackListing is a valley-changes/v1 listing of widget with one change, |
| 22 | // id (handle nxvp), owned by owner and in state at v1, head on branch. Its |
| 23 | // latest restack report, commit report, says rebasing it onto tip |
| 24 | // conflicted in its own commits, and is current while the change is ready. |
| 25 | func restackListing(id, branch, head, state, owner, record, report, tip string) map[string]any { |
| 26 | sha := func(oid string) string { return "git-sha1:" + oid } |
| 27 | ch := map[string]any{ |
| 28 | "change_id": id, "handle": "nxvp", "target": "main", "owner": owner, "state": state, |
| 29 | "record": record, "seq": 1, "active": 1, "includes": []string{}, |
| 30 | "versions": []any{map[string]any{"n": 1, "head": head, "title": "Add a greeting", "branch": branch, |
| 31 | "uploader": "operator", "landing": "not-landed", "landed_commit": nil, "request": nil, "outcome": nil}}, |
| 32 | "restack": map[string]any{"ref": restack.ReportRef("main", id), "commit": report, "current": state == valley.StateReady, |
| 33 | "report": map[string]any{ |
| 34 | "schema": valley.RestackSchema, "change_id": id, "target": "main", "target_tip": sha(tip), |
| 35 | "operation": "e2e", "result": valley.RestackConflict, |
| 36 | "layers": []any{map[string]any{"change_id": id, "record": sha(record), "version": 1, "head": sha(head), |
| 37 | "branch": branch, "branch_tip": sha(head), "published": nil}}, |
| 38 | "failing_layer": id, "conflict_paths": []string{"greeting.txt"}, "blocking_requests": []any{}, "refusal": nil, |
| 39 | }}, |
| 40 | } |
| 41 | return map[string]any{"schema": "valley-changes/v1", "host": "valley-host", "repos": []any{map[string]any{ |
| 42 | "repo": "widget", "url": "git@valley-host:widget.git", "error": nil, "changes": []any{ch}, "branches": []any{}, |
| 43 | }}} |
| 44 | } |
| 45 | |
| 46 | // writeE2EJSON writes v as JSON to name in the e2e directory, where the |
| 47 | // stubs read their answers. |
| 48 | func (h *Harness) writeE2EJSON(name string, v any) { |
| 49 | h.t.Helper() |
| 50 | data, err := json.Marshal(v) |
| 51 | if err != nil { |
| 52 | h.t.Fatal(err) |
| 53 | } |
| 54 | if err := os.WriteFile(filepath.Join(h.E2EDir, name), data, 0o644); err != nil { |
| 55 | h.t.Fatal(err) |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | // originCommit makes a commit on origin with an empty tree and returns it, |
| 60 | // for a ref the valley keeps there. |
| 61 | func (h *Harness) originCommit(msg string) string { |
| 62 | h.t.Helper() |
| 63 | return h.GitOutput(h.OriginDir, "commit-tree", h.gitStdin(h.OriginDir, "", "mktree"), "-m", msg) |
| 64 | } |
| 65 | |
| 66 | // strictChange is a change operator owns that a finished run pushed as v1 |
| 67 | // on branch, with main moved on to tip since, and the change's record and |
| 68 | // a restack report on origin. The stub valley offers unready. |
| 69 | type strictChange struct{ id, branch, v1, record, report, tip string } |
| 70 | |
| 71 | func (h *Harness) strictChange() strictChange { |
| 72 | h.t.Helper() |
| 73 | h.installValleyStub() |
| 74 | h.joinValley() |
| 75 | if err := os.WriteFile(filepath.Join(h.E2EDir, "valley.has-unready"), nil, 0o644); err != nil { |
| 76 | h.t.Fatal(err) |
| 77 | } |
| 78 | h.git(h.RepoDir, "config", "valley.principal", "operator") |
| 79 | |
| 80 | first, _ := h.launchRun("add a greeting") |
| 81 | h.WaitForClaudeStart(30 * time.Second) |
| 82 | v1 := h.pushWork(first, "greeting.txt", "Add a greeting") |
| 83 | first = h.finishRun(first.ID) |
| 84 | c := strictChange{id: first.ChangeID, branch: first.Branch, v1: v1} |
| 85 | c.tip = h.commitToMain("greeting.txt", "Greet from main\n") |
| 86 | c.record, c.report = h.originCommit("record"), h.originCommit("report") |
| 87 | h.git(h.OriginDir, "update-ref", restack.RecordRef("main", c.id), c.record) |
| 88 | h.git(h.OriginDir, "update-ref", restack.ReportRef("main", c.id), c.report) |
| 89 | return c |
| 90 | } |
| 91 | |
| 92 | // listing is the change's listing in state, owned by operator at v1. |
| 93 | func (c strictChange) listing(state string) map[string]any { |
| 94 | return restackListing(c.id, c.branch, c.v1, state, "operator", c.record, c.report, c.tip) |
| 95 | } |
| 96 | |
| 97 | // launchArgs launch a run on the change as a restack pass does: under |
| 98 | // runID, expecting operator's draft at v1 on its branch. |
| 99 | func (c strictChange) launchArgs(runID string) []string { |
| 100 | return []string{"launch", "--change", c.id, "--run-id", runID, "--expect-owner", "operator", |
| 101 | "--expect-branch", c.branch, "--expect-head", c.v1, "--expect-draft", "--", "resolve the conflict"} |
| 102 | } |
| 103 | |
| 104 | // livePanesNaming returns the live panes on the harness's tmux server |
| 105 | // whose command names s. |
| 106 | func (h *Harness) livePanesNaming(s string) []string { |
| 107 | h.t.Helper() |
| 108 | var live []string |
| 109 | for _, line := range strings.Split(h.tmux("list-panes", "-a", "-F", "#{pane_dead} #{pane_id} #{pane_start_command}"), "\n") { |
| 110 | if strings.HasPrefix(line, "0 ") && strings.Contains(line, s) { |
| 111 | live = append(live, line) |
| 112 | } |
| 113 | } |
| 114 | return live |
| 115 | } |
| 116 | |
| 117 | // TestRestackConflictLaunchesStrictly runs against the stub valley, so it |
| 118 | // runs where no valley is installed. A run pushes v1 of a change operator |
| 119 | // owns. Launch with the dispatcher's expectations refuses, with status 3, |
| 120 | // before it creates a worktree or returns the change to draft, a change |
| 121 | // that was readied, taken over or advanced since the dispatcher checked it. |
| 122 | // A restack pass then dispatches exactly one run, under the run ID its |
| 123 | // ledger recorded before launching, and the dashboard shows it without |
| 124 | // asking the valley more than its check does. And when the change is readied again |
| 125 | // between the pass's unready and the launch, no worker starts and the |
| 126 | // attempt is given back. |
| 127 | func TestRestackConflictLaunchesStrictly(t *testing.T) { |
| 128 | t.Parallel() |
| 129 | h := NewHarness(t) |
| 130 | c := h.strictChange() |
| 131 | id, branch, v1, record, report, tip := c.id, c.branch, c.v1, c.record, c.report, c.tip |
| 132 | |
| 133 | for i, tc := range []struct { |
| 134 | name, state, owner, head, want string |
| 135 | }{ |
| 136 | {"readied since", valley.StateReady, "operator", v1, "change nxvp is ready, not a draft"}, |
| 137 | {"another owner's", valley.StateDraft, "someone-else", v1, `change nxvp's owner is "someone-else", not "operator"`}, |
| 138 | {"advanced since", valley.StateDraft, "operator", strings.Repeat("9", 40), "change nxvp's head is 9999999"}, |
| 139 | } { |
| 140 | h.writeValleyChanges(restackListing(id, branch, tc.head, tc.state, tc.owner, record, report, tip)) |
| 141 | runID := fmt.Sprintf("20261027-1200-%08x", i+1) |
| 142 | unreadies, runs := len(h.valleyCalls("unready")), len(h.RunIDs()) |
| 143 | res := h.RunKlaus("launch", "--change", id, "--run-id", runID, "--expect-owner", "operator", |
| 144 | "--expect-branch", branch, "--expect-head", v1, "--expect-draft", "--", "resolve the conflict") |
| 145 | if res.ExitCode != 3 || !strings.Contains(res.Stderr, tc.want) { |
| 146 | t.Errorf("%s: launch exited %d, want 3 saying %q:\n%s", tc.name, res.ExitCode, tc.want, res.Stderr) |
| 147 | } |
| 148 | if n := len(h.RunIDs()); n != runs { |
| 149 | t.Errorf("%s: launch recorded a run", tc.name) |
| 150 | } |
| 151 | if wt := h.GitOutput(h.RepoDir, "worktree", "list"); strings.Contains(wt, runID) { |
| 152 | t.Errorf("%s: launch left a worktree:\n%s", tc.name, wt) |
| 153 | } |
| 154 | if n := len(h.valleyCalls("unready")); n != unreadies { |
| 155 | t.Errorf("%s: launch returned the change to draft before refusing", tc.name) |
| 156 | } |
| 157 | } |
| 158 | if res := h.RunKlaus("launch", "--change", id, "--expect-owner", "nobody", "--", "x"); res.ExitCode != 1 { |
| 159 | t.Errorf("without --run-id a refusal exits 1, exited %d", res.ExitCode) |
| 160 | } |
| 161 | |
| 162 | // One pass, one run, under the ID the ledger recorded first. |
| 163 | ready := restackListing(id, branch, v1, valley.StateReady, "operator", record, report, tip) |
| 164 | draft := restackListing(id, branch, v1, valley.StateDraft, "operator", record, report, tip) |
| 165 | h.writeValleyChanges(ready) |
| 166 | h.writeE2EJSON("valley.changes.unready.json", draft) |
| 167 | h.resetWorker() |
| 168 | out, resolver := h.restackPass() |
| 169 | if resolver == nil { |
| 170 | t.Fatalf("the pass launched nothing:\n%s", out) |
| 171 | } |
| 172 | e := h.restackEntry("widget", id) |
| 173 | if e.Last().RunID != resolver.ID || e.Last().Pending || e.Attempts != 1 { |
| 174 | t.Errorf("the ledger should hold the launched run %s, settled, as attempt 1: %+v", resolver.ID, e.Last()) |
| 175 | } |
| 176 | if resolver.ChangeID != id || resolver.Branch != branch || resolver.DispatchReason != event.DispatchRestackConflict { |
| 177 | t.Errorf("the run is on change %s, branch %s, for %q", resolver.ChangeID, resolver.Branch, resolver.DispatchReason) |
| 178 | } |
| 179 | h.WaitForClaudeStart(30 * time.Second) |
| 180 | if brief := h.ClaudeStdin(); !strings.Contains(brief, v1) || !strings.Contains(brief, tip) || strings.Contains(brief, "greeting.txt") { |
| 181 | t.Errorf("the brief should name the head and main's tip, and not the report's paths:\n%s", brief) |
| 182 | } |
| 183 | if out, again := h.restackPass(); again != nil { |
| 184 | t.Fatalf("a second pass launched %s:\n%s", again.ID, out) |
| 185 | } |
| 186 | |
| 187 | // The real dashboard shows the dispatch on the change's row, and its |
| 188 | // restack pass reads the integration check's listing: the check asks |
| 189 | // the valley once, and the pass asks nothing more. |
| 190 | before := len(h.valleyCalls("changes")) |
| 191 | _, screen := h.startDashboard(220) |
| 192 | screen("restack conflict", "resolution run "+resolver.ID+" dispatched (attempt 1 of 3)") |
| 193 | if calls := h.valleyCalls("changes")[before:]; len(calls) != 1 || !strings.HasSuffix(calls[0], ": changes --all --json --checks") { |
| 194 | t.Errorf("valley changes calls from the dashboard = %q, want one listing for every repo", calls) |
| 195 | } |
| 196 | h.tmux("kill-session", "-t", "dash") |
| 197 | h.finishRun(resolver.ID) |
| 198 | |
| 199 | // main moves on and the restacker reports again; the change is |
| 200 | // readied again after the pass's unready and before launch reads it. |
| 201 | tip = h.commitToMain("farewell.txt", "Farewell from main\n") |
| 202 | report = h.originCommit("report 2") |
| 203 | h.git(h.OriginDir, "update-ref", restack.ReportRef("main", id), report) |
| 204 | h.writeValleyChanges(restackListing(id, branch, v1, valley.StateReady, "operator", record, report, tip)) |
| 205 | h.writeE2EJSON("valley.changes.unready.1.json", restackListing(id, branch, v1, valley.StateDraft, "operator", record, report, tip)) |
| 206 | h.writeE2EJSON("valley.changes.unready.json", restackListing(id, branch, v1, valley.StateReady, "operator", record, report, tip)) |
| 207 | h.ageLedger() |
| 208 | h.resetWorker() |
| 209 | out, raced := h.restackPass() |
| 210 | if raced != nil || !strings.Contains(out, "not dispatched: launch failed, and the change is left a draft") || |
| 211 | !strings.Contains(out, "is ready, not a draft") { |
| 212 | t.Fatalf("a change readied before launch read it got run %v:\n%s", raced, out) |
| 213 | } |
| 214 | if e := h.restackEntry("widget", id); e.Attempts != 1 || e.Last().RunID != "" || e.Last().Pending { |
| 215 | t.Errorf("a launch that started no worker should give its attempt back: attempts %d, %+v", e.Attempts, e.Last()) |
| 216 | } |
| 217 | if _, err := os.Stat(filepath.Join(h.E2EDir, "claude.started")); err == nil { |
| 218 | t.Error("a worker started") |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | // TestStrictLaunchReadsOriginUnderTheLock: origin's branch moves on, with |
| 223 | // no new version in the valley, while a strict launch waits for the |
| 224 | // continuation lock. Launch reads origin under the lock, not as its fetch |
| 225 | // before it found it, and refuses with status 3 before it creates a |
| 226 | // worktree. |
| 227 | func TestStrictLaunchReadsOriginUnderTheLock(t *testing.T) { |
| 228 | t.Parallel() |
| 229 | h := NewHarness(t) |
| 230 | c := h.strictChange() |
| 231 | h.writeValleyChanges(c.listing(valley.StateDraft)) |
| 232 | |
| 233 | lock, err := os.OpenFile(filepath.Join(h.RepoDir, ".git", "klaus-continue.lock"), os.O_CREATE|os.O_RDWR, 0o644) |
| 234 | if err != nil { |
| 235 | t.Fatal(err) |
| 236 | } |
| 237 | defer lock.Close() |
| 238 | if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX); err != nil { |
| 239 | t.Fatal(err) |
| 240 | } |
| 241 | const runID = "20261027-1200-0000000a" |
| 242 | p := h.startKlaus(nil, c.launchArgs(runID)...) |
| 243 | p.waitFor(func() bool { |
| 244 | _, stderr := p.output() |
| 245 | return strings.Contains(stderr, "waiting for another launch") |
| 246 | }, "to wait for the continuation lock") |
| 247 | |
| 248 | tree := h.GitOutput(h.OriginDir, "rev-parse", c.v1+"^{tree}") |
| 249 | moved := h.GitOutput(h.OriginDir, "commit-tree", tree, "-p", c.v1, "-m", "pushed elsewhere") |
| 250 | h.git(h.OriginDir, "update-ref", "refs/heads/"+c.branch, moved) |
| 251 | lock.Close() // drops the flock |
| 252 | |
| 253 | res := p.wait() |
| 254 | want := fmt.Sprintf("origin's %s is at %s, not change nxvp's expected head %s", c.branch, moved[:7], c.v1[:7]) |
| 255 | if res.ExitCode != 3 || !strings.Contains(res.Stderr, want) { |
| 256 | t.Fatalf("launch exited %d, want 3 saying %q:\n%s", res.ExitCode, want, res.Stderr) |
| 257 | } |
| 258 | if wt := h.GitOutput(h.RepoDir, "worktree", "list"); strings.Contains(wt, runID) { |
| 259 | t.Errorf("launch left a worktree:\n%s", wt) |
| 260 | } |
| 261 | if n := len(h.valleyCalls("unready")); n != 0 { |
| 262 | t.Errorf("launch returned the change to draft before refusing") |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | // TestStrictLaunchRefusesAChangeReadiedDuringSetup: a strict launch passes |
| 267 | // its checks and returns the change to draft, and the change is readied |
| 268 | // while launch sets the worker up, after the point it used to check last. |
| 269 | // Launch asks again as the worker starts, and starts none. |
| 270 | func TestStrictLaunchRefusesAChangeReadiedDuringSetup(t *testing.T) { |
| 271 | t.Parallel() |
| 272 | h := NewHarness(t) |
| 273 | c := h.strictChange() |
| 274 | h.writeValleyChanges(c.listing(valley.StateDraft)) |
| 275 | h.writeE2EJSON("valley.changes.unready.json", c.listing(valley.StateDraft)) |
| 276 | h.resetWorker() |
| 277 | |
| 278 | // The last setup step before the worker starts snapshots the clone's |
| 279 | // shared git files, its config among them. |
| 280 | b := h.gitBarrier() |
| 281 | const runID = "20261027-1200-0000000b" |
| 282 | p := h.startKlaus(b.pause("config --file * --list -z", 1, false), c.launchArgs(runID)...) |
| 283 | b.waitPaused(p) |
| 284 | if n := len(h.valleyCalls("unready")); n != 1 { |
| 285 | t.Fatalf("held before launch returned the change to draft (%d unready calls)", n) |
| 286 | } |
| 287 | h.writeE2EJSON("valley.changes.unready.json", c.listing(valley.StateReady)) |
| 288 | b.release() |
| 289 | |
| 290 | res := p.wait() |
| 291 | if res.ExitCode != 3 || !strings.Contains(res.Stderr, "change nxvp is ready, not a draft") { |
| 292 | t.Fatalf("launch exited %d, want 3 refusing the readied change:\n%s", res.ExitCode, res.Stderr) |
| 293 | } |
| 294 | if _, err := os.Stat(filepath.Join(h.E2EDir, "claude.started")); err == nil { |
| 295 | t.Error("a worker started") |
| 296 | } |
| 297 | if slices.Contains(h.RunIDs(), runID) { |
| 298 | t.Error("launch recorded the run") |
| 299 | } |
| 300 | if wt := h.GitOutput(h.RepoDir, "worktree", "list"); strings.Contains(wt, runID) { |
| 301 | t.Errorf("launch left a worktree:\n%s", wt) |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | // TestRestackLaunchWhoseStateSaveFails: a restack pass launches a run whose |
| 306 | // worker starts and whose state launch can't save. Launch stops the worker |
| 307 | // and exits 1, as a worker started; the pass keeps the attempt and, once |
| 308 | // it proves no worker of the run is left, settles the launch. While a live |
| 309 | // pane still names the run, the change stays busy whatever its inputs; once |
| 310 | // none does, the next inputs dispatch. |
| 311 | func TestRestackLaunchWhoseStateSaveFails(t *testing.T) { |
| 312 | t.Parallel() |
| 313 | h := NewHarness(t) |
| 314 | c := h.strictChange() |
| 315 | h.writeValleyChanges(c.listing(valley.StateReady)) |
| 316 | h.writeE2EJSON("valley.changes.unready.json", c.listing(valley.StateDraft)) |
| 317 | h.resetWorker() |
| 318 | |
| 319 | if err := os.Chmod(h.RunsDir(), 0o555); err != nil { |
| 320 | t.Fatal(err) |
| 321 | } |
| 322 | t.Cleanup(func() { os.Chmod(h.RunsDir(), 0o755) }) |
| 323 | out, launched := h.restackPass() |
| 324 | if err := os.Chmod(h.RunsDir(), 0o755); err != nil { |
| 325 | t.Fatal(err) |
| 326 | } |
| 327 | e := h.restackEntry("widget", c.id) |
| 328 | runID := e.Last().RunID |
| 329 | if launched != nil || runID == "" || e.Attempts != 1 || e.Last().Pending || |
| 330 | !strings.Contains(e.Last().Refused, "no worker of run "+runID+" runs") || !strings.Contains(e.Last().Refused, "saving state") { |
| 331 | t.Fatalf("the pass should keep the attempt and settle a launch whose worker launch stopped: %+v\n%s", e.Last(), out) |
| 332 | } |
| 333 | if live := h.livePanesNaming(runID); len(live) != 0 { |
| 334 | t.Errorf("a worker no run records is left running: %v", live) |
| 335 | } |
| 336 | if wt := h.GitOutput(h.RepoDir, "worktree", "list"); strings.Contains(wt, runID) { |
| 337 | t.Errorf("launch left a worktree:\n%s", wt) |
| 338 | } |
| 339 | |
| 340 | // Had its worker been left running, as a pass that lost sight of the |
| 341 | // launch finds it, the change is busy: main moves on, and nothing |
| 342 | // launches while a live pane names the run. |
| 343 | h.editLedger(func(entries map[string]*restack.Entry) { |
| 344 | a := entries[restack.Key{Repo: "widget", ChangeID: c.id}.String()].Last() |
| 345 | a.Pending, a.Refused = true, "" |
| 346 | }) |
| 347 | h.tmux("new-session", "-d", "-s", "holdout", "sleep 300 # "+runID) |
| 348 | if live := h.livePanesNaming(runID); len(live) != 1 { |
| 349 | t.Fatalf("the stand-in worker's pane isn't found by its command: %v", live) |
| 350 | } |
| 351 | c.tip = h.commitToMain("farewell.txt", "Farewell from main\n") |
| 352 | c.report = h.originCommit("report 2") |
| 353 | h.git(h.OriginDir, "update-ref", restack.ReportRef("main", c.id), c.report) |
| 354 | h.writeValleyChanges(c.listing(valley.StateReady)) |
| 355 | h.writeE2EJSON("valley.changes.unready.json", c.listing(valley.StateDraft)) |
| 356 | os.Remove(filepath.Join(h.E2EDir, "valley.after-unready")) // the stub lists the ready change until the next unready |
| 357 | h.ageLedger() |
| 358 | unreadies := len(h.valleyCalls("unready")) |
| 359 | out, launched = h.restackPass() |
| 360 | if launched != nil || !strings.Contains(out, "launching resolution run "+runID) || len(h.valleyCalls("unready")) != unreadies { |
| 361 | t.Fatalf("a change whose worker may run got another run %v:\n%s", launched, out) |
| 362 | } |
| 363 | |
| 364 | h.tmux("kill-session", "-t", "holdout") |
| 365 | h.resetWorker() |
| 366 | out, launched = h.restackPass() |
| 367 | if launched == nil { |
| 368 | t.Fatalf("once no worker of the lost launch runs, the new inputs should dispatch:\n%s", out) |
| 369 | } |
| 370 | if e := h.restackEntry("widget", c.id); e.Attempts != 2 || e.Last().RunID != launched.ID { |
| 371 | t.Errorf("attempts %d, last %+v; want the lost launch's attempt kept and the new run as attempt 2", e.Attempts, e.Last()) |
| 372 | } |
| 373 | if n := len(h.eventsOfType(event.ChangeRestackStalled)); n != 2 { |
| 374 | t.Errorf("%d stalled events, want one for each launch that came to nothing", n) |
| 375 | } |
| 376 | } |