gunk-dev/the-valley

restack_conflicts_test.go

source6a6791929c36main's published tip history
16.0 KiB
1//go:build e2e
2
3package e2e
4
5import (
6 "bytes"
7 "encoding/json"
8 "fmt"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "strings"
13 "testing"
14 "time"
15
16 "the-valley/flow/internal/event"
17 "the-valley/flow/internal/restack"
18 "the-valley/flow/internal/run"
19 "the-valley/flow/internal/valley"
20)
21
22// gitStdin runs real git in dir with stdin, as GitOutput does.
23func (h *Harness) gitStdin(dir, stdin string, args ...string) string {
24 h.t.Helper()
25 cmd := exec.Command("git", args...)
26 cmd.Dir = dir
27 cmd.Env = append(os.Environ(), "HOME="+h.Home, "GIT_CONFIG_GLOBAL="+filepath.Join(h.Home, ".gitconfig"), "GIT_CONFIG_NOSYSTEM=1")
28 cmd.Stdin = strings.NewReader(stdin)
29 out, err := cmd.CombinedOutput()
30 if err != nil {
31 h.t.Fatalf("git %v: %v: %s", args, err, out)
32 }
33 return strings.TrimSpace(string(out))
34}
35
36// valleyIn runs the valley on PATH in dir, failing the test unless it
37// succeeds.
38func (h *Harness) valleyIn(dir string, args ...string) string {
39 h.t.Helper()
40 cmd := exec.Command("valley", args...)
41 cmd.Dir, cmd.Env = dir, h.env()
42 out, err := cmd.CombinedOutput()
43 if err != nil {
44 h.t.Fatalf("valley %v: %v: %s", args, err, out)
45 }
46 return string(out)
47}
48
49// commitToMain commits content to file on main and pushes it, returning
50// main's new tip.
51func (h *Harness) commitToMain(file, content string) string {
52 h.t.Helper()
53 if err := os.WriteFile(filepath.Join(h.RepoDir, file), []byte(content), 0o644); err != nil {
54 h.t.Fatal(err)
55 }
56 h.git(h.RepoDir, "add", file)
57 h.git(h.RepoDir, "commit", "-qm", "main: "+file)
58 h.git(h.RepoDir, "push", "-q", "origin", "main")
59 return h.GitOutput(h.RepoDir, "rev-parse", "HEAD")
60}
61
62// plantReport writes a conflict report on change id to origin, as the
63// host's restacker pushes one: a commit holding report.json alone, on the
64// change's previous report, at refs/the-valley/restack/main/<id>. It
65// observes what origin holds now (the record, the branch's tip, version
66// and head as the valley lists them) and main at tip, and names path as
67// the conflict. It returns the report commit.
68func (h *Harness) plantReport(id, tip, path string) string {
69 h.t.Helper()
70 var ch valley.Change
71 for _, c := range h.valleyChanges().Changes {
72 if c.ChangeID == id {
73 ch = c
74 }
75 }
76 var head, branch string
77 for _, v := range ch.Versions {
78 if v.N == ch.Active {
79 head, branch = v.Head, v.Branch
80 }
81 }
82 if head == "" {
83 h.t.Fatalf("the valley lists no active version of %s", id)
84 }
85 sha := func(oid string) string { return "git-sha1:" + oid }
86 report := map[string]any{
87 "schema": valley.RestackSchema, "change_id": id, "target": "main", "target_tip": sha(tip),
88 "operation": fmt.Sprintf("e2e-%d", time.Now().UnixNano()), "result": valley.RestackConflict,
89 "layers": []any{map[string]any{
90 "change_id": id, "record": sha(ch.Record), "version": ch.Active, "head": sha(head), "branch": branch,
91 "branch_tip": sha(h.GitOutput(h.OriginDir, "rev-parse", "refs/heads/"+branch)), "published": nil,
92 }},
93 "failing_layer": id, "conflict_paths": []string{path}, "blocking_requests": []any{}, "refusal": nil,
94 }
95 data, err := json.MarshalIndent(report, "", " ")
96 if err != nil {
97 h.t.Fatal(err)
98 }
99 ref := restack.ReportRef("main", id)
100 blob := h.gitStdin(h.OriginDir, string(data)+"\n", "hash-object", "-w", "--stdin")
101 tree := h.gitStdin(h.OriginDir, "100644 blob "+blob+"\treport.json\n", "mktree")
102 args := []string{"commit-tree", tree, "-m", "valley restack: conflict"}
103 if old, err := h.gitTry(h.OriginDir, "rev-parse", "--verify", "-q", ref); err == nil {
104 args = append(args, "-p", strings.TrimSpace(old))
105 }
106 commit := h.GitOutput(h.OriginDir, args...)
107 h.git(h.OriginDir, "update-ref", ref, commit)
108 return commit
109}
110
111// changeOf returns the valley's view of change id.
112func (h *Harness) changeOf(id string) valley.Change {
113 h.t.Helper()
114 for _, c := range h.valleyChanges().Changes {
115 if c.ChangeID == id {
116 return c
117 }
118 }
119 h.t.Fatalf("the valley lists no change %s", id)
120 return valley.Change{}
121}
122
123// restackLedger is the session's restack ledger file.
124func (h *Harness) restackLedger() string {
125 return filepath.Join(h.Home, ".klaus", "sessions", h.SessionID, restack.LedgerFile)
126}
127
128// ageLedger moves every dispatch in the restack ledger back past the
129// cooldown, as if the time had passed.
130func (h *Harness) ageLedger() {
131 h.t.Helper()
132 h.editLedger(func(entries map[string]*restack.Entry) {
133 for _, e := range entries {
134 for _, a := range e.Actions {
135 a.At = a.At.Add(-2 * restack.Cooldown)
136 }
137 }
138 })
139}
140
141// editLedger rewrites the restack ledger through edit.
142func (h *Harness) editLedger(edit func(map[string]*restack.Entry)) {
143 h.t.Helper()
144 data, err := os.ReadFile(h.restackLedger())
145 if err != nil {
146 h.t.Fatal(err)
147 }
148 var entries map[string]*restack.Entry
149 if err := json.Unmarshal(data, &entries); err != nil {
150 h.t.Fatal(err)
151 }
152 edit(entries)
153 if data, err = json.Marshal(entries); err != nil {
154 h.t.Fatal(err)
155 }
156 if err := os.WriteFile(h.restackLedger(), data, 0o644); err != nil {
157 h.t.Fatal(err)
158 }
159}
160
161// restackPass runs klaus restack-conflicts, failing the test unless it
162// succeeds and launches at most one run, and returns its output and the run
163// it launched, if any.
164func (h *Harness) restackPass() (string, *run.State) {
165 h.t.Helper()
166 known := make(map[string]bool)
167 for _, id := range h.RunIDs() {
168 known[id] = true
169 }
170 res := h.RunKlaus("restack-conflicts")
171 if res.ExitCode != 0 {
172 h.t.Fatalf("restack-conflicts exited %d\nstdout:\n%s\nstderr:\n%s", res.ExitCode, res.Stdout, res.Stderr)
173 }
174 var launched []*run.State
175 for _, id := range h.RunIDs() {
176 if !known[id] {
177 st, err := h.ReadState(id)
178 if err != nil {
179 h.t.Fatal(err)
180 }
181 launched = append(launched, st)
182 }
183 }
184 switch len(launched) {
185 case 0:
186 return res.Stdout, nil
187 case 1:
188 return res.Stdout, launched[0]
189 }
190 h.t.Fatalf("one pass launched %d runs, want at most one:\n%s", len(launched), res.Stdout)
191 return "", nil
192}
193
194// restackEntry returns the restack ledger's entry for change id in repo.
195func (h *Harness) restackEntry(repo, id string) *restack.Entry {
196 h.t.Helper()
197 data, err := os.ReadFile(h.restackLedger())
198 if err != nil {
199 h.t.Fatal(err)
200 }
201 var entries map[string]*restack.Entry
202 if err := json.Unmarshal(data, &entries); err != nil {
203 h.t.Fatal(err)
204 }
205 e := entries[restack.Key{Repo: repo, ChangeID: id}.String()]
206 if e == nil {
207 h.t.Fatalf("the restack ledger has no entry for %s/%s: %s", repo, id, data)
208 }
209 return e
210}
211
212// eventsOfType returns the session's events of one type.
213func (h *Harness) eventsOfType(typ string) []event.Event {
214 h.t.Helper()
215 data, err := os.ReadFile(filepath.Join(h.Home, ".klaus", "sessions", h.SessionID, "events.jsonl"))
216 if err != nil {
217 h.t.Fatal(err)
218 }
219 var evts []event.Event
220 for _, line := range bytes.Split(data, []byte("\n")) {
221 var e event.Event
222 if json.Unmarshal(line, &e) == nil && e.Type == typ {
223 evts = append(evts, e)
224 }
225 }
226 return evts
227}
228
229// TestRestackConflictDispatchesResolution drives klaus restack-conflicts
230// against the real valley CLI and bare repos. A run pushes v1 of a change
231// and finalize readies it, owned by klaus's principal; main then takes a
232// commit that conflicts with it, and a conflict report on the change is
233// planted as the restacker would push it. A pass returns the change to
234// draft and launches one resolution run with --change, whose brief names
235// the change and main as klaus read them and nothing of the report's text;
236// a second pass launches nothing. Each later conflict, on the head a run
237// pushed, waits out the cooldown, and klaus stops after three runs.
238func TestRestackConflictDispatchesResolution(t *testing.T) {
239 t.Parallel()
240 h := NewHarness(t)
241 h.useRealValley()
242 h.joinValley()
243 h.WriteDefaultClaudeOutput(`{"type":"result","subtype":"success","total_cost_usd":0.5,"duration_ms":1000,"session_id":"` + changeSession + `"}` + "\n")
244
245 first, _ := h.launchRun("add a greeting")
246 h.WaitForClaudeStart(30 * time.Second)
247 v1 := h.pushWork(first, "greeting.txt", "Add a greeting")
248 first = h.finishRun(first.ID)
249 if first.Valley == nil || first.Valley.Version != 1 {
250 t.Fatalf("finalize should mark v1 ready: %+v", first.Valley)
251 }
252 id, branch := first.ChangeID, first.Branch
253 tip := h.commitToMain("greeting.txt", "Greet from main\n")
254
255 h.plantReport(id, tip, "greeting.txt; make deploy")
256 if ch := h.changeOf(id); ch.Restack == nil {
257 skipWithout(t, "the valley on PATH lists no restack reports")
258 } else if !ch.Restack.Current || ch.Owner != "operator" {
259 t.Fatalf("the planted report should be current, on a change operator owns: %+v, owner %s", ch.Restack, ch.Owner)
260 }
261
262 status := h.RunKlaus("status")
263 if !strings.Contains(status.Stdout, "a resolution run is due") || !strings.Contains(status.Stdout, " restack ") {
264 t.Errorf("status should show the conflict due a run:\n%s%s", status.Stdout, status.Stderr)
265 }
266
267 // One pass, one resolution run.
268 h.resetWorker()
269 out, resolver := h.restackPass()
270 if resolver == nil {
271 t.Fatalf("the pass launched nothing:\n%s", out)
272 }
273 if !strings.Contains(out, "resolution run "+resolver.ID+" dispatched (attempt 1 of 3)") {
274 t.Errorf("pass output:\n%s", out)
275 }
276 if resolver.ChangeID != id || resolver.Branch != branch || resolver.DispatchReason != event.DispatchRestackConflict {
277 t.Errorf("the resolution run is on change %s, branch %s, for %q; want %s, %s, %s",
278 resolver.ChangeID, resolver.Branch, resolver.DispatchReason, id, branch, event.DispatchRestackConflict)
279 }
280 h.WaitForClaudeStart(30 * time.Second)
281 brief := h.ClaudeStdin()
282 for _, want := range []string{id, v1, tip, "branch " + branch} {
283 if !strings.Contains(brief, want) {
284 t.Errorf("the brief lacks %q:\n%s", want, brief)
285 }
286 }
287 if strings.Contains(brief, "make deploy") || strings.Contains(brief, "greeting.txt") {
288 t.Errorf("the brief passes on the report's text:\n%s", brief)
289 }
290 if ch := h.changeOf(id); ch.State != valley.StateDraft {
291 t.Errorf("the change should be a draft while the run works, is %s", ch.State)
292 }
293 if evts := h.runEvents(resolver.ID); !hasEvent(evts, event.ChangeRestackDispatched, "attempt", 1.0) {
294 t.Errorf("no change:restack-dispatched for attempt 1 under %s: %+v", resolver.ID, evts)
295 }
296
297 // A second pass launches nothing: the run is working, and the report
298 // reads historical now that the change is a draft.
299 if out, again := h.restackPass(); again != nil || !strings.Contains(out, "dispatched (attempt 1 of 3)") {
300 t.Fatalf("a second pass launched %v:\n%s", again, out)
301 }
302
303 // Each run pushes a head that still conflicts; finalize readies it,
304 // and the restacker reports it.
305 for attempt := 2; attempt <= 4; attempt++ {
306 h.pushWork(resolver, fmt.Sprintf("note%d.txt", attempt), fmt.Sprintf("Note %d", attempt))
307 h.finishRun(resolver.ID)
308 if ch := h.changeOf(id); ch.State != valley.StateReady || ch.Active != attempt {
309 t.Fatalf("finalize should ready v%d: %s v%d", attempt, ch.State, ch.Active)
310 }
311 h.plantReport(id, tip, "greeting.txt")
312
313 if attempt == 2 {
314 // Within the cooldown after the last dispatch, nothing.
315 if out, early := h.restackPass(); early != nil || !strings.Contains(out, "waiting out the cooldown after run "+resolver.ID) {
316 t.Fatalf("a pass within the cooldown launched %v:\n%s", early, out)
317 }
318 }
319 h.ageLedger()
320 h.resetWorker()
321 out, next := h.restackPass()
322 if attempt == 4 {
323 if next != nil || !strings.Contains(out, "stopped after 3 resolution runs") {
324 t.Fatalf("after three runs a pass launched %v:\n%s", next, out)
325 }
326 break
327 }
328 if next == nil || !strings.Contains(out, fmt.Sprintf("dispatched (attempt %d of 3)", attempt)) {
329 t.Fatalf("attempt %d: the pass launched %v:\n%s", attempt, next, out)
330 }
331 h.WaitForClaudeStart(30 * time.Second)
332 resolver = next
333 }
334 if ch := h.changeOf(id); ch.State != valley.StateReady {
335 t.Errorf("a change klaus stopped on should be left ready, is %s", ch.State)
336 }
337 if stalled := h.eventsOfType(event.ChangeRestackStalled); len(stalled) != 1 || stalled[0].RunID != id {
338 t.Errorf("want one change:restack-stalled under %s, got %+v", id, stalled)
339 }
340 if n := len(h.eventsOfType(event.ChangeRestackDispatched)); n != 3 {
341 t.Errorf("%d change:restack-dispatched events, want 3", n)
342 }
343 if status := h.RunKlaus("status"); !strings.Contains(status.Stdout, "stopped after 3 resolution runs") {
344 t.Errorf("status should show klaus stopped:\n%s", status.Stdout)
345 }
346}
347
348// TestRestackConflictLeavesAlone plants reports klaus must not act on,
349// against the real valley CLI: a current conflict on a change another
350// principal owns, and a report on klaus's own change that main has moved
351// past. A pass launches nothing and returns neither change to draft. Then,
352// with a valley whose unready fails, a current conflict on klaus's change
353// launches nothing either: klaus says why, and leaves the change ready.
354func TestRestackConflictLeavesAlone(t *testing.T) {
355 t.Parallel()
356 h := NewHarness(t)
357 h.useRealValley()
358 h.joinValley()
359
360 first, _ := h.launchRun("add a greeting")
361 h.WaitForClaudeStart(30 * time.Second)
362 h.pushWork(first, "greeting.txt", "Add a greeting")
363 first = h.finishRun(first.ID)
364 id := first.ChangeID
365
366 // Someone else's change, from their own clone.
367 const theirs = "kkkkllllmmmmnnnnooooppppqqqqrrrr"
368 other := filepath.Join(t.TempDir(), "other")
369 h.git("", "clone", "-q", h.OriginDir, other)
370 h.git(other, "config", "valley.principal", "someone-else")
371 h.git(other, "checkout", "-qb", "farewell")
372 if err := os.WriteFile(filepath.Join(other, "greeting.txt"), []byte("Farewell\n"), 0o644); err != nil {
373 t.Fatal(err)
374 }
375 h.git(other, "add", "greeting.txt")
376 h.git(other, "commit", "-qm", "Say farewell")
377 h.git(other, "push", "-q", "origin", "farewell")
378 h.valleyIn(other, "ready", "--change", theirs, "farewell")
379
380 before := h.GitOutput(h.RepoDir, "rev-parse", "HEAD")
381 tip := h.commitToMain("greeting.txt", "Greet from main\n")
382 h.plantReport(theirs, tip, "greeting.txt")
383 h.plantReport(id, before, "greeting.txt")
384 if ch := h.changeOf(theirs); ch.Restack == nil {
385 skipWithout(t, "the valley on PATH lists no restack reports")
386 } else if !ch.Restack.Current || ch.Owner != "someone-else" {
387 t.Fatalf("their report should be current, on their change: %+v, owner %s", ch.Restack, ch.Owner)
388 }
389 if ch := h.changeOf(id); ch.Restack.Current {
390 t.Fatal("a report on main before it moved should read historical")
391 }
392
393 if out, launched := h.restackPass(); launched != nil || !strings.Contains(out, "No restack conflicts on changes flow owns.") {
394 t.Fatalf("the pass launched %v:\n%s", launched, out)
395 }
396 for _, c := range []string{id, theirs} {
397 if ch := h.changeOf(c); ch.State != valley.StateReady {
398 t.Errorf("%s should be left ready, is %s", c, ch.State)
399 }
400 }
401
402 // A valley whose unready fails: klaus launches nothing.
403 real, err := exec.LookPath("valley")
404 if err != nil {
405 t.Fatal(err)
406 }
407 h.WriteStub("valley", fmt.Sprintf("#!/bin/sh\nif [ \"$1\" = unready ]; then echo 'unready refused by the e2e valley' >&2; exit 1; fi\nexec %q \"$@\"\n", real))
408 h.plantReport(id, tip, "greeting.txt")
409 if ch := h.changeOf(id); !ch.Restack.Current {
410 t.Fatalf("the report on main's tip should be current: %+v", ch.Restack)
411 }
412 out, launched := h.restackPass()
413 if launched != nil || !strings.Contains(out, "not dispatched: could not return the change to draft") ||
414 !strings.Contains(out, "unready refused by the e2e valley") {
415 t.Fatalf("with unready failing the pass launched %v:\n%s", launched, out)
416 }
417 if ch := h.changeOf(id); ch.State != valley.StateReady {
418 t.Errorf("the change should be left ready, is %s", ch.State)
419 }
420 if out, launched := h.restackPass(); launched != nil || !strings.Contains(out, "not dispatched") {
421 t.Errorf("a later pass launched %v:\n%s", launched, out)
422 }
423 if stalled := h.eventsOfType(event.ChangeRestackStalled); len(stalled) != 1 ||
424 !strings.Contains(fmt.Sprint(stalled[0].Data["reason"]), "could not return the change to draft") {
425 t.Errorf("want one change:restack-stalled saying unready failed, got %+v", stalled)
426 }
427 if status := h.RunKlaus("status"); !strings.Contains(status.Stdout, "not dispatched: could not return the change to draft") {
428 t.Errorf("status should say why klaus didn't dispatch:\n%s", status.Stdout)
429 }
430}
431
432// hasEvent reports whether evts holds one of type typ whose data has key
433// at want.
434func hasEvent(evts []event.Event, typ, key string, want any) bool {
435 for _, e := range evts {
436 if e.Type == typ && e.Data[key] == want {
437 return true
438 }
439 }
440 return false
441}