gunk-dev/the-valley

publish_test.go

source672eff5ffaecmain's published tip history
33.7 KiB
1package main
2
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "encoding/json"
8 "fmt"
9 "io"
10 "os"
11 "os/exec"
12 "path/filepath"
13 "strconv"
14 "strings"
15 "sync"
16 "testing"
17 "time"
18
19 "the-valley/change"
20 "the-valley/rebase"
21)
22
23// hooked is a fixture whose origin runs the fixture host's rendered hook,
24// which grants restack to the principal restacker and request to
25// requester. Without the hook, the test is skipped.
26func hooked(t *testing.T) *fixture {
27 t.Helper()
28 hook := os.Getenv(hookEnv)
29 if hook == "" {
30 t.Skip(hookEnv + " names no rendered hook; restack-unit supplies one")
31 }
32 withoutIdentity(t)
33 return newFixture(t, hook)
34}
35
36// pass runs one write pass, as `valley-restacker once`, under a cue that
37// composes every policy to the cap given, pushing as the restacker's
38// principal. It returns what the pass printed with --json.
39func (r *restacker) pass(cap int) *Plan {
40 r.t.Helper()
41 schema, floor := fakePolicyCap(r.t, cap)
42 r.t.Setenv("VALLEY_PRINCIPAL", r.c.principal)
43 var out, errOut bytes.Buffer
44 if err := once(context.Background(), append(writeArgs(r.c, schema, floor), "--json"), &out, &errOut); err != nil {
45 r.t.Fatalf("once: %v\n%s", err, errOut.String())
46 }
47 var p Plan
48 if err := json.Unmarshal(out.Bytes(), &p); err != nil {
49 r.t.Fatalf("the pass does not read: %v\n%s", err, out.String())
50 }
51 return &p
52}
53
54// writeArgs is the arguments of a write pass with c's configuration.
55func writeArgs(c config, schema, floor string) []string {
56 return []string{"--repo", c.repo, "--state", c.state, "--principal", c.principal,
57 "--commit-name", c.commitName, "--commit-email", c.commitEmail, "--schema", schema, "--instance", floor}
58}
59
60// pushAs pushes to origin as a principal, through the hook.
61func (f *fixture) pushAs(principal string, args ...string) error {
62 g := f.as(principal)
63 cmd := exec.Command("git", append([]string{"push", "--quiet", "origin"}, args...)...)
64 cmd.Dir, cmd.Env = g.Dir, g.Env
65 if out, err := cmd.CombinedOutput(); err != nil {
66 return fmt.Errorf("%v: %s", err, out)
67 }
68 return nil
69}
70
71// judge writes an outcome record on origin's side, as the integrator does:
72// no push may write one.
73func (f *fixture) judge(name, head, decision string) {
74 f.t.Helper()
75 line := fmt.Sprintf("%s %s %s %s\n", head, f.at("refs/heads/main"), change.EvidenceFingerprint(nil), decision)
76 path := filepath.Join(f.t.TempDir(), "outcome")
77 if err := os.WriteFile(path, []byte(line), 0o644); err != nil {
78 f.t.Fatal(err)
79 }
80 blob := f.onOrigin("hash-object", "-w", path)
81 f.onOrigin("update-ref", rebase.OutcomePrefix+name, blob)
82}
83
84// recordOf is the change's record on origin.
85func (f *fixture) recordOf(id string) *change.Record {
86 f.t.Helper()
87 data := f.onOrigin("cat-file", "blob", change.Ref(rebase.Target, id)+":record.json")
88 r, err := change.Parse([]byte(data + "\n"))
89 if err != nil {
90 f.t.Fatal(err)
91 }
92 return r
93}
94
95// reportAt is the report a report commit on origin holds.
96func (f *fixture) reportAt(commit string) *change.RestackReport {
97 f.t.Helper()
98 data := f.onOrigin("cat-file", "blob", commit+":report.json")
99 r, err := change.ParseRestackReport([]byte(data + "\n"))
100 if err != nil {
101 f.t.Fatal(err)
102 }
103 return r
104}
105
106// reportOf is the change's latest report on origin, or nil for none.
107func (f *fixture) reportOf(id string) *change.RestackReport {
108 f.t.Helper()
109 commit := f.at(rebase.RestackPrefix + id)
110 if commit == "" {
111 return nil
112 }
113 return f.reportAt(commit)
114}
115
116// restackedTo holds that the change's record gained exactly one version,
117// v2, uploaded by the restacker at head, keeping the owner, the title and
118// the branch, and that its latest report says complete with that version.
119func (f *fixture) restackedTo(id, owner, title, branch, head string) {
120 f.t.Helper()
121 r := f.recordOf(id)
122 v := r.ActiveVersion()
123 if r.State != change.Ready || r.Seq != 2 || len(r.Versions) != 2 || v.N != 2 || rebase.HeadOf(v) != head ||
124 v.Uploader != "restacker" || v.Title != title || v.Branch != branch || r.Owner != owner {
125 f.t.Errorf("%s's record is not restacked to %s once: %+v", id[:4], short(head), r)
126 }
127 rep := f.reportOf(id)
128 if rep == nil || rep.Result != change.RestackComplete {
129 f.t.Fatalf("%s's report is %+v", id[:4], rep)
130 }
131 for _, l := range rep.Layers {
132 if l.ChangeID == id && (l.Published == nil || l.Published.Version == nil || *l.Published.Version != 2 ||
133 l.Published.Head != change.HeadPrefix+head) {
134 f.t.Errorf("%s's report does not say v2 was published at %s: %+v", id[:4], short(head), l.Published)
135 }
136 }
137}
138
139// settledState holds that the pass left no journal and kept no object for
140// one.
141func (r *restacker) settledState() {
142 r.t.Helper()
143 if _, err := os.Stat(filepath.Join(r.c.state, journalFile)); err == nil {
144 r.t.Error("the pass left a journal")
145 }
146 if kept := gitOutT(r.t, r.g, "for-each-ref", retainPrefix, "refs/valley-rebase/"); kept != "" {
147 r.t.Errorf("the pass kept objects:\n%s", kept)
148 }
149}
150
151// count is how many of the pass's actions are of the write given.
152func count(p *Plan, write string) int {
153 n := 0
154 for _, a := range p.Actions {
155 if a.Write == write {
156 n++
157 }
158 }
159 return n
160}
161
162// After a landing, one write pass rebases every ready change onto main
163// through the rendered hook, as the restacker's principal: a stack of two
164// owners' changes is one family, and each layer descends from the new
165// layer below it, with only its own file changed. Each change gains one
166// version, uploaded by the restacker, under its owner and title, and a
167// report that says complete. A change that conflicts with the landing
168// moves nothing and gets a report that says conflict, naming the path,
169// and a draft is left alone. The pass lets go of its journal. A second
170// pass pushes nothing: the restacked stack is current, and the conflict
171// is not tried again while nothing it observed has moved.
172func TestAPassRestacksReadyChangesAfterALanding(t *testing.T) {
173 f := hooked(t)
174 f.readyAs(idA, "alice", "a", "main", "A's title")
175 f.readyAs(idB, "bob", "b", "a", "B's title")
176 f.git("checkout", "--quiet", "-B", "c", "main")
177 conflicted := f.commit("c's line", "shared.txt")
178 f.git("push", "--quiet", "origin", "c")
179 f.writeRecord(idC, &change.Record{
180 Schema: change.Schema, ChangeID: idC, Target: rebase.Target, Owner: "carol", State: change.Ready, Seq: 1, Active: 1,
181 Versions: []change.Version{{N: 1, Head: change.HeadPrefix + conflicted, Title: "C's title", Branch: "c", Uploader: "carol"}},
182 }, "", conflicted)
183 draft := f.readyAs(idE, "alice", "e", "main", "E's title")
184 f.setState(idE, change.Draft)
185 f.git("checkout", "--quiet", "main")
186 f.commit("main's line", "shared.txt")
187 f.git("push", "--quiet", "origin", "main")
188 tip := f.at("refs/heads/main")
189 cRecord := f.at(change.Ref(rebase.Target, idC))
190
191 r := newRestacker(t, f)
192 p := r.pass(64)
193 a, b := f.at("refs/heads/a"), f.at("refs/heads/b")
194 if parent := f.onOrigin("rev-parse", a+"^"); parent != tip {
195 t.Errorf("a is on %s, not main's tip %s", short(parent), short(tip))
196 }
197 if parent := f.onOrigin("rev-parse", b+"^"); parent != a {
198 t.Errorf("b is on %s, not a's new head %s", short(parent), short(a))
199 }
200 for _, d := range [][3]string{{tip, a, "a.txt"}, {a, b, "b.txt"}} {
201 if changed := f.onOrigin("diff", "--name-only", d[0], d[1]); changed != d[2] {
202 t.Errorf("%s changes %q, not %s alone", short(d[1]), changed, d[2])
203 }
204 }
205 f.restackedTo(idA, "alice", "A's title", "a", a)
206 f.restackedTo(idB, "bob", "B's title", "b", b)
207
208 if f.at("refs/heads/c") != conflicted || f.at(change.Ref(rebase.Target, idC)) != cRecord {
209 t.Error("the conflicting change moved")
210 }
211 if rep := f.reportOf(idC); rep == nil || rep.Result != change.RestackConflict || rep.Failing == nil || *rep.Failing != idC ||
212 len(rep.Conflicts) != 1 || rep.Conflicts[0] != "shared.txt" {
213 t.Errorf("c's report is %+v", rep)
214 }
215 if f.at("refs/heads/e") != draft || f.recordOf(idE).Seq != 2 || f.reportOf(idE) != nil {
216 t.Error("the draft was touched")
217 }
218 if count(p, "branches") != 1 || count(p, "version") != 2 || count(p, "report") != 3 {
219 t.Errorf("the pass pushed %+v", p.Actions)
220 }
221 r.settledState()
222
223 before := f.refs()
224 p = r.pass(64)
225 if len(p.Actions) != 0 || f.refs() != before {
226 t.Errorf("a second pass pushed %+v", p.Actions)
227 }
228 for _, fp := range p.Families {
229 if fp.Layers[0].ID == idC && fp.Writes != nil && len(fp.Writes.Reports) == 1 && !fp.Writes.Reports[0].Unchanged {
230 t.Errorf("the second pass rebased the conflict again: %+v", fp.Writes)
231 }
232 }
233 r.settledState()
234}
235
236// A related request that might still land holds its family: the pass
237// moves no branch and adds no version, and its report says blocked,
238// naming the request. Once the integrator's outcome for the request is a
239// current stale, the next pass restacks the change and leaves the
240// request as it was.
241func TestARequestHoldsItsFamilyUntilACurrentStaleReleasesIt(t *testing.T) {
242 f := hooked(t)
243 head := f.readyAs(idA, "alice", "a", "main", "A's title")
244 request := rebase.RequestPrefix + change.RequestName(idA)
245 if err := f.pushAs("requester", head+":"+request); err != nil {
246 t.Fatal(err)
247 }
248 f.moveMain()
249 record := f.at(change.Ref(rebase.Target, idA))
250
251 r := newRestacker(t, f)
252 r.pass(64)
253 if f.at("refs/heads/a") != head || f.at(change.Ref(rebase.Target, idA)) != record {
254 t.Fatal("the pass moved a change a request holds")
255 }
256 rep := f.reportOf(idA)
257 if rep == nil || rep.Result != change.RestackBlocked || len(rep.Requests) != 1 || rep.Requests[0].Ref != request ||
258 rep.Refusal == nil || !strings.Contains(*rep.Refusal, "might still land") {
259 t.Fatalf("a's report is %+v", rep)
260 }
261
262 f.judge(change.RequestName(idA), head, "stale")
263 r.pass(64)
264 f.restackedTo(idA, "alice", "A's title", "a", f.at("refs/heads/a"))
265 if f.at(request) != head {
266 t.Error("the restacker moved the request")
267 }
268 r.settledState()
269}
270
271// A pass that ended after any step of its journal is finished by the
272// next: each write already on origin is not pushed again, each change has
273// exactly one new version, every report says complete, and the journal
274// is let go.
275func TestAPassFinishesAJournalLeftAtAnyStep(t *testing.T) {
276 steps := []string{"kept", "branches pushed", "lower version added", "both versions added", "one report pushed"}
277 for n, step := range steps {
278 t.Run(step, func(t *testing.T) {
279 f := hooked(t)
280 f.readyAs(idA, "alice", "a", "main", "A's title")
281 f.readyAs(idB, "bob", "b", "a", "B's title")
282 f.moveMain()
283 t.Setenv("VALLEY_PRINCIPAL", "restacker")
284 r := newRestacker(t, f)
285 fam := of(t, r.journal(), idA)
286 ctx := context.Background()
287 made := []func() bool{
288 func() bool { push, _ := fam.Branches.Push(ctx, r.g); return push == rebase.Pushed },
289 func() bool { return fam.Versions[0].Push(ctx, r.g).Err == nil },
290 func() bool { return fam.Versions[1].Push(ctx, r.g).Err == nil },
291 func() bool { return fam.Reports[0].Pending.Push(ctx, r.g).Push == rebase.Pushed },
292 }
293 for i := 0; i < n; i++ {
294 if !made[i]() {
295 t.Fatalf("step %d of the journal was not pushed", i+1)
296 }
297 }
298
299 p := r.pass(64)
300 f.restackedTo(idA, "alice", "A's title", "a", fam.Branches.Updates[0].New)
301 f.restackedTo(idB, "bob", "B's title", "b", fam.Branches.Updates[1].New)
302 if want := min(n, 1); count(p, "branches") != 1-want {
303 t.Errorf("the pass pushed the branches %d times, after %s", count(p, "branches"), step)
304 }
305 if want := 2 - min(max(n-1, 0), 2); count(p, "version") != want {
306 t.Errorf("the pass added %d versions, after %s, where %d were left", count(p, "version"), step, want)
307 }
308 if p.Recovery == nil || p.Pending != nil {
309 t.Errorf("the journal was not found, or is still open: %+v", p.Pending)
310 }
311 r.settledState()
312 })
313 }
314}
315
316// An owner who pushes to a branch the restacker has moved stops that
317// change's version for good: the pass adds the version below it, adds
318// none to the moved change, and reports partial for both, with each
319// version origin holds. The moved change's record stays as its owner left
320// it, and the plan that follows in the same pass holds it, since its
321// branch is not at its version's head.
322func TestAnOwnerWhoMovesARestackedBranchStopsItsVersion(t *testing.T) {
323 f := hooked(t)
324 f.readyAs(idA, "alice", "a", "main", "A's title")
325 f.readyAs(idB, "bob", "b", "a", "B's title")
326 f.moveMain()
327 t.Setenv("VALLEY_PRINCIPAL", "restacker")
328 r := newRestacker(t, f)
329 fam := of(t, r.journal(), idA)
330 if push, _ := fam.Branches.Push(context.Background(), r.g); push != rebase.Pushed {
331 t.Fatal("the branches were not pushed")
332 }
333 f.ownerPushes("b")
334 bRecord := f.at(change.Ref(rebase.Target, idB))
335
336 p := r.pass(64)
337 for _, fp := range p.Families {
338 if fp.Layers[0].ID == idB && fp.Action != hold {
339 t.Errorf("once the journal is let go, the plan does not hold b, whose branch is not at its version's head: %+v", fp)
340 }
341 }
342 if got := f.recordOf(idA); got.Seq != 2 || rebase.HeadOf(got.ActiveVersion()) != fam.Branches.Updates[0].New {
343 t.Errorf("a's version was not added: %+v", got)
344 }
345 if f.at(change.Ref(rebase.Target, idB)) != bRecord {
346 t.Error("a version was added to the change its owner moved")
347 }
348 // The latest report or one before it, since a later plan in the same
349 // pass may report on b again, says partial.
350 partial := false
351 for commit := f.at(rebase.RestackPrefix + idB); commit != ""; commit = f.parentOf(commit) {
352 rep := f.reportAt(commit)
353 if rep.Result != change.RestackPartial {
354 continue
355 }
356 partial = true
357 for _, l := range rep.Layers {
358 switch {
359 case l.ChangeID == idA && (l.Published == nil || l.Published.Version == nil || *l.Published.Version != 2):
360 t.Errorf("the partial report does not say a's v2 was added: %+v", l.Published)
361 case l.ChangeID == idB && (l.Published == nil || l.Published.Version != nil):
362 t.Errorf("the partial report says b's version was added: %+v", l.Published)
363 }
364 }
365 if rep.Refusal == nil || !strings.Contains(*rep.Refusal, "its author moved it") {
366 t.Errorf("the partial report does not say why: %v", rep.Refusal)
367 }
368 }
369 if !partial {
370 t.Error("no report of b says partial")
371 }
372 r.settledState()
373}
374
375// parentOf is a commit's first parent on origin, or "" for none.
376func (f *fixture) parentOf(commit string) string {
377 cmd := exec.Command("git", "rev-parse", "--verify", "--quiet", commit+"^")
378 cmd.Dir, cmd.Env = f.origin, f.env
379 out, _ := cmd.Output()
380 return strings.TrimSpace(string(out))
381}
382
383// A request filed between a family's branch push and its versions pauses
384// the versions: the pass reports partial, adds none, and keeps the
385// journal open, and the family waits in the plan. Once the request's
386// outcome is a current stale, the next pass adds the version, reports
387// complete, and lets go of the journal.
388func TestARequestBetweenPhasesPausesTheVersions(t *testing.T) {
389 f := hooked(t)
390 old := f.readyAs(idA, "alice", "a", "main", "A's title")
391 f.moveMain()
392 t.Setenv("VALLEY_PRINCIPAL", "restacker")
393 r := newRestacker(t, f)
394 fam := of(t, r.journal(), idA)
395 if push, _ := fam.Branches.Push(context.Background(), r.g); push != rebase.Pushed {
396 t.Fatal("the branches were not pushed")
397 }
398 if err := f.pushAs("requester", old+":"+rebase.RequestPrefix+"zz-old"); err != nil {
399 t.Fatal(err)
400 }
401 record := f.at(change.Ref(rebase.Target, idA))
402
403 p := r.pass(64)
404 if f.at(change.Ref(rebase.Target, idA)) != record || p.Pending == nil {
405 t.Fatalf("the paused version was added, or the journal let go: %+v", p.Pending)
406 }
407 if _, err := os.Stat(filepath.Join(r.c.state, journalFile)); err != nil {
408 t.Errorf("the open journal is gone: %v", err)
409 }
410 rep := f.reportOf(idA)
411 if rep == nil || rep.Result != change.RestackPartial || rep.Refusal == nil || !strings.Contains(*rep.Refusal, "zz-old might still land") {
412 t.Fatalf("a's report is %+v", rep)
413 }
414 if p = r.pass(64); len(p.Actions) != 0 || p.Pending == nil {
415 t.Errorf("a pass with the request still open pushed %+v", p.Actions)
416 }
417 if len(p.Families) != 1 || p.Families[0].Action != wait || p.Families[0].Writes != nil {
418 t.Errorf("the paused family does not wait: %+v", p.Families)
419 }
420
421 f.judge("zz-old", old, "stale")
422 p = r.pass(64)
423 if p.Pending != nil {
424 t.Errorf("the journal is still open: %+v", p.Pending)
425 }
426 f.restackedTo(idA, "alice", "A's title", "a", fam.Branches.Updates[0].New)
427 r.settledState()
428}
429
430// A family a request has paused stays in the journal without holding up
431// work it shares nothing with. With a's versions paused, a change readied
432// beside it, off the main a was on, is restacked in the next pass, while
433// a's family waits and stays in the journal alone. Once the request is
434// released, the pass after adds a's version and lets go of the journal.
435func TestAPausedFamilyDoesNotHoldAnotherChange(t *testing.T) {
436 f := hooked(t)
437 base := f.at("refs/heads/main")
438 old := f.readyAs(idA, "alice", "a", "main", "A's title")
439 f.moveMain()
440 t.Setenv("VALLEY_PRINCIPAL", "restacker")
441 r := newRestacker(t, f)
442 fam := of(t, r.journal(), idA)
443 if push, _ := fam.Branches.Push(context.Background(), r.g); push != rebase.Pushed {
444 t.Fatal("the branches were not pushed")
445 }
446 if err := f.pushAs("requester", old+":"+rebase.RequestPrefix+"zz-old"); err != nil {
447 t.Fatal(err)
448 }
449 record := f.at(change.Ref(rebase.Target, idA))
450 if p := r.pass(64); p.Pending == nil {
451 t.Fatal("the pass let go of the paused family")
452 }
453
454 f.readyAs(idE, "bob", "e", base, "E's title")
455 p := r.pass(64)
456 f.restackedTo(idE, "bob", "E's title", "e", f.at("refs/heads/e"))
457 if f.at(change.Ref(rebase.Target, idA)) != record || p.Pending == nil {
458 t.Fatalf("the paused version was added, or the journal let go: %+v", p.Pending)
459 }
460 actions := map[string]string{}
461 for _, fp := range p.Families {
462 actions[fp.Layers[0].ID] = fp.Action
463 }
464 if actions[idA] != wait || actions[idE] != restack {
465 t.Errorf("the pass planned a as %q and e as %q", actions[idA], actions[idE])
466 }
467 j, err := loadJournal(r.c.state, r.c.binding())
468 if err != nil || j == nil || len(j.Families) != 1 || j.Families[0].Observed.Layers[0].ID != idA {
469 t.Fatalf("the journal does not hold a's family alone: %+v, %v", j, err)
470 }
471
472 f.judge("zz-old", old, "stale")
473 if p = r.pass(64); p.Pending != nil {
474 t.Errorf("the journal is still open: %+v", p.Pending)
475 }
476 f.restackedTo(idA, "alice", "A's title", "a", fam.Branches.Updates[0].New)
477 r.settledState()
478}
479
480// Two ready changes that name one branch, at heads neither of which
481// descends from the other, are two families, and the journal takes no two
482// families that share a branch. The pass has both wait, saying why, and
483// builds nothing for either, while a change beside them is restacked.
484func TestFamiliesThatShareABranchWait(t *testing.T) {
485 f := hooked(t)
486 f.readyAs(idA, "alice", "shared", "main", "A's title")
487 f.git("checkout", "--quiet", "-B", "elsewhere", "main")
488 other := f.commit("bob's own layer", "bob.txt")
489 f.writeRecord(idB, &change.Record{
490 Schema: change.Schema, ChangeID: idB, Target: rebase.Target, Owner: "bob", State: change.Ready, Seq: 1, Active: 1,
491 Versions: []change.Version{{N: 1, Head: change.HeadPrefix + other, Title: "B's title", Branch: "shared", Uploader: "bob"}},
492 }, "", other)
493 f.readyAs(idE, "carol", "e", "main", "E's title")
494 f.moveMain()
495 shared, a, b := f.at("refs/heads/shared"), f.at(change.Ref(rebase.Target, idA)), f.at(change.Ref(rebase.Target, idB))
496
497 r := newRestacker(t, f)
498 p := r.pass(64)
499 f.restackedTo(idE, "carol", "E's title", "e", f.at("refs/heads/e"))
500 waiting := 0
501 for _, fp := range p.Families {
502 if id := fp.Layers[0].ID; id == idA || id == idB {
503 if fp.Action != wait || fp.Writes != nil || len(fp.Reasons) != 1 || !strings.Contains(fp.Reasons[0], "shares the branch shared with") {
504 t.Errorf("%s is planned as %+v", id[:4], fp)
505 }
506 waiting++
507 }
508 }
509 if waiting != 2 {
510 t.Errorf("the pass planned %d of the two families on shared", waiting)
511 }
512 if f.at("refs/heads/shared") != shared || f.at(change.Ref(rebase.Target, idA)) != a || f.at(change.Ref(rebase.Target, idB)) != b ||
513 f.reportOf(idA) != nil || f.reportOf(idB) != nil {
514 t.Error("the pass wrote for a family that shares a branch")
515 }
516 r.settledState()
517}
518
519// A report of what did happen is kept in the journal before it is pushed,
520// and stays there until a read of origin shows it. Here an owner moves a
521// restacked branch, so the version above stops and the family's reports
522// say partial. When origin refuses the push of one of them, the pass
523// leaves the journal open with that report in it, and the next pass
524// pushes it. When origin takes the push and its answer is lost, the next
525// read finds it there, and it is not pushed again.
526func TestAReportOfWhatHappenedOutlivesAFailedPush(t *testing.T) {
527 for _, failure := range []string{"refused", "answer lost"} {
528 t.Run(failure, func(t *testing.T) {
529 f := hooked(t)
530 f.readyAs(idA, "alice", "a", "main", "A's title")
531 f.readyAs(idB, "bob", "b", "a", "B's title")
532 f.moveMain()
533 t.Setenv("VALLEY_PRINCIPAL", "restacker")
534 r := newRestacker(t, f)
535 fam := of(t, r.journal(), idA)
536 if push, _ := fam.Branches.Push(context.Background(), r.g); push != rebase.Pushed {
537 t.Fatal("the branches were not pushed")
538 }
539 f.ownerPushes("b")
540 ref := rebase.RestackPrefix + idB
541 lift := func() {}
542 if failure == "refused" {
543 lift = f.refuseOnOrigin(ref)
544 } else {
545 r.loseAnswers(ref)
546 }
547
548 p := r.pass(64)
549 var pushes []string
550 for _, a := range p.Actions {
551 if a.Write == "replacement" && a.ID == idB {
552 pushes = append(pushes, a.Result)
553 }
554 }
555 if failure == "answer lost" {
556 if strings.Join(pushes, " ") != "unknown" {
557 t.Errorf("b's report of what happened was pushed as %v, where once, its answer lost, is expected", pushes)
558 }
559 if !partialOf(f, idB, "its author moved it") {
560 t.Error("no report of b on origin says partial")
561 }
562 r.settledState()
563 return
564 }
565 if len(pushes) == 0 || strings.Trim(strings.Join(pushes, " "), "refused ") != "" {
566 t.Errorf("b's report of what happened was pushed as %v", pushes)
567 }
568 if f.reportOf(idB) != nil {
569 t.Fatal("origin holds a report of b it refused")
570 }
571 j, err := loadJournal(r.c.state, r.c.binding())
572 if err != nil || j == nil || p.Pending == nil {
573 t.Fatalf("the pass let go of the journal that holds b's report: %v", err)
574 }
575 kept := false
576 for _, rep := range of(t, j, idA).Replacements {
577 kept = kept || rep.Pending.ID == idB && rep.Pending.Report.Result == change.RestackPartial
578 }
579 if !kept {
580 t.Fatalf("the journal does not hold b's report of what happened: %+v", of(t, j, idA).Replacements)
581 }
582
583 lift()
584 r.pass(64)
585 if !partialOf(f, idB, "its author moved it") {
586 t.Error("no report of b on origin says partial once origin takes it")
587 }
588 r.settledState()
589 })
590 }
591}
592
593// What origin took of a family's writes stays in the journal, so an
594// author who rewrites or deletes every branch the family moved does not
595// unmake the report of it. Here an owner moves a restacked branch, so the
596// family's reports say partial, and origin refuses the push of one of
597// them. Every branch the family moved is then rewritten, or deleted, and
598// once origin takes the push, the next pass pushes that report, saying
599// what became of the branch.
600func TestAReportOfWhatHappenedOutlivesTheBranchesItReports(t *testing.T) {
601 for author, why := range map[string]string{"rewrites": "its author moved it", "deletes": "origin no longer has b"} {
602 t.Run(author, func(t *testing.T) {
603 f := hooked(t)
604 f.readyAs(idA, "alice", "a", "main", "A's title")
605 f.readyAs(idB, "bob", "b", "a", "B's title")
606 f.moveMain()
607 t.Setenv("VALLEY_PRINCIPAL", "restacker")
608 r := newRestacker(t, f)
609 fam := of(t, r.journal(), idA)
610 if push, _ := fam.Branches.Push(context.Background(), r.g); push != rebase.Pushed {
611 t.Fatal("the branches were not pushed")
612 }
613 f.ownerPushes("b")
614 lift := f.refuseOnOrigin(rebase.RestackPrefix + idB)
615 if p := r.pass(64); p.Pending == nil || f.reportOf(idB) != nil {
616 t.Fatalf("the pass let go of the journal, or origin holds a report of b it refused: %+v", p.Pending)
617 }
618
619 for _, branch := range []string{"a", "b"} {
620 if author == "deletes" {
621 f.git("push", "--quiet", "origin", "--delete", branch)
622 continue
623 }
624 f.git("checkout", "--quiet", "-B", branch, "main")
625 f.commit("the author's rewrite of "+branch, branch+"-rewrite.txt")
626 f.git("push", "--quiet", "--force", "origin", branch)
627 }
628 lift()
629 r.pass(64)
630 if !partialOf(f, idB, why) {
631 t.Errorf("no report of b on origin says partial, since %s, once origin takes it", why)
632 }
633 r.settledState()
634 })
635 }
636}
637
638// A report origin keeps refusing holds back only its own family. Here an
639// owner moves a restacked branch, so the family's reports say partial,
640// and origin refuses every push of one of them. A change beside that
641// family is restacked in the same pass and let go of, while the refused
642// report keeps its own family in the journal. After the next landing,
643// the change beside it is restacked again, and the refused family waits.
644func TestARefusedReportHoldsBackOnlyItsOwnFamily(t *testing.T) {
645 f := hooked(t)
646 f.readyAs(idA, "alice", "a", "main", "A's title")
647 f.readyAs(idB, "bob", "b", "a", "B's title")
648 f.readyAs(idE, "carol", "e", "main", "E's title")
649 f.moveMain()
650 t.Setenv("VALLEY_PRINCIPAL", "restacker")
651 r := newRestacker(t, f)
652 fam := of(t, r.journal(), idA)
653 if push, _ := fam.Branches.Push(context.Background(), r.g); push != rebase.Pushed {
654 t.Fatal("the branches were not pushed")
655 }
656 f.ownerPushes("b")
657 f.refuseOnOrigin(rebase.RestackPrefix + idB)
658 journaled := func() {
659 t.Helper()
660 j, err := loadJournal(r.c.state, r.c.binding())
661 if err != nil || j == nil || len(j.Families) != 1 || j.Families[0].Observed.Layers[0].ID != idA {
662 t.Fatalf("the journal does not hold a's family alone: %+v, %v", j, err)
663 }
664 }
665
666 r.pass(64)
667 f.restackedTo(idE, "carol", "E's title", "e", f.at("refs/heads/e"))
668 journaled()
669
670 f.git("checkout", "--quiet", "main")
671 f.commit("main moves again", "again.txt")
672 f.git("push", "--quiet", "origin", "main")
673 p := r.pass(64)
674 actions := map[string]string{}
675 for _, fp := range p.Families {
676 actions[fp.Layers[0].ID] = fp.Action
677 }
678 if actions[idA] != wait || actions[idE] != restack {
679 t.Errorf("after the landing, the pass planned a as %q and e as %q", actions[idA], actions[idE])
680 }
681 e := f.at("refs/heads/e")
682 if rec := f.recordOf(idE); len(rec.Versions) != 3 || rebase.HeadOf(rec.ActiveVersion()) != e || rec.ActiveVersion().Uploader != "restacker" {
683 t.Errorf("e was not restacked again: %+v", rec)
684 }
685 if parent := f.onOrigin("rev-parse", e+"^"); parent != f.at("refs/heads/main") {
686 t.Errorf("e is on %s, not main's tip", short(parent))
687 }
688 journaled()
689}
690
691// partialOf reports whether the change's latest report on origin, or one
692// before it, says partial: a's version added, the change's own not, for
693// the reason given. A later plan in the same pass may report on the
694// change again.
695func partialOf(f *fixture, id, why string) bool {
696 f.t.Helper()
697 for commit := f.at(rebase.RestackPrefix + id); commit != ""; commit = f.parentOf(commit) {
698 rep := f.reportAt(commit)
699 if rep.Result != change.RestackPartial || rep.Refusal == nil || !strings.Contains(*rep.Refusal, why) {
700 continue
701 }
702 for _, l := range rep.Layers {
703 if l.Published == nil || (l.ChangeID == idA) != (l.Published.Version != nil) {
704 f.t.Errorf("the partial report of %s does not say what was published: %+v", id[:4], l)
705 }
706 }
707 return true
708 }
709 return false
710}
711
712// refuseOnOrigin has origin refuse every push that moves the ref, ahead
713// of its own hook, until the function it returns is called.
714func (f *fixture) refuseOnOrigin(ref string) (lift func()) {
715 f.t.Helper()
716 hook := filepath.Join(f.origin, "hooks", "pre-receive")
717 own := hook + ".own"
718 if err := os.Rename(hook, own); err != nil {
719 f.t.Fatal(err)
720 }
721 script := fmt.Sprintf("#!/bin/sh\nlines=$(cat)\n"+
722 "if printf '%%s\\n' \"$lines\" | grep -q ' %s$'; then echo 'origin refuses %s for the test' >&2; exit 1; fi\n"+
723 "printf '%%s\\n' \"$lines\" | exec '%s'\n", ref, ref, own)
724 if err := os.WriteFile(hook, []byte(script), 0o755); err != nil {
725 f.t.Fatal(err)
726 }
727 return func() {
728 if err := os.Rename(own, hook); err != nil {
729 f.t.Fatal(err)
730 }
731 }
732}
733
734// dropEnv names the ref whose pushes lossyReceivePack loses the answer to.
735const dropEnv = "RESTACK_TEST_DROP"
736
737// loseAnswers has origin's answer lost to every push of the restacker's
738// that moves the ref: origin takes the push, and the pass hears nothing.
739func (r *restacker) loseAnswers(ref string) {
740 r.t.Helper()
741 self, err := os.Executable()
742 if err != nil {
743 r.t.Fatal(err)
744 }
745 path := filepath.Join(r.t.TempDir(), "lossy-receive-pack")
746 script := fmt.Sprintf("#!/bin/sh\n%s=drop-acks %s='%s' exec '%s' \"$@\"\n", roleEnv, dropEnv, ref, self)
747 if err := os.WriteFile(path, []byte(script), 0o755); err != nil {
748 r.t.Fatal(err)
749 }
750 gitOutT(r.t, r.g, "config", "remote.origin.receivepack", path)
751}
752
753// lossyReceivePack is git receive-pack less its answer to a push that
754// moves the ref named. It runs the real receive-pack, which takes the
755// push, and passes its report on without the status of any ref when one
756// of them is that ref, as when origin's answer is lost. The side-band
757// capabilities are taken out of its advertisement, so the report comes as
758// plain pkt-lines. The rebase engine's tests drop every answer the same
759// way.
760func lossyReceivePack(ref string, args []string) int {
761 cmd := exec.Command("git", append([]string{"receive-pack"}, args...)...)
762 cmd.Stdin, cmd.Stderr = os.Stdin, os.Stderr
763 out, err := cmd.StdoutPipe()
764 if err != nil || cmd.Start() != nil {
765 return 1
766 }
767 r := bufio.NewReader(out)
768 advertised := false
769 var status [][]byte
770 for {
771 p, err := readPkt(r)
772 if err != nil {
773 break
774 }
775 switch {
776 case !advertised && p == nil:
777 advertised = true
778 case !advertised:
779 if refs, caps, ok := bytes.Cut(p, []byte{0}); ok {
780 var kept []string
781 for _, c := range strings.Fields(string(caps)) {
782 if !strings.HasPrefix(c, "side-band") {
783 kept = append(kept, c)
784 }
785 }
786 p = []byte(string(refs) + "\x00" + strings.Join(kept, " ") + "\n")
787 }
788 case bytes.HasPrefix(p, []byte("ok ")) || bytes.HasPrefix(p, []byte("ng ")) || bytes.HasPrefix(p, []byte("option ")):
789 status = append(status, p)
790 continue
791 case p == nil:
792 lost := false
793 for _, line := range status {
794 if fields := strings.Fields(string(line)); len(fields) > 1 && fields[1] == ref {
795 lost = true
796 }
797 }
798 for _, line := range status {
799 if !lost {
800 writePkt(line)
801 }
802 }
803 status = nil
804 }
805 writePkt(p)
806 }
807 if cmd.Wait() != nil {
808 return 1
809 }
810 return 0
811}
812
813// readPkt reads one pkt-line, nil for a flush.
814func readPkt(r *bufio.Reader) ([]byte, error) {
815 var size [4]byte
816 if _, err := io.ReadFull(r, size[:]); err != nil {
817 return nil, err
818 }
819 n, err := strconv.ParseUint(string(size[:]), 16, 16)
820 if err != nil || n < 4 {
821 return nil, err
822 }
823 p := make([]byte, n-4)
824 _, err = io.ReadFull(r, p)
825 return p, err
826}
827
828// writePkt writes one pkt-line to stdout, nil as a flush.
829func writePkt(p []byte) {
830 if p == nil {
831 io.WriteString(os.Stdout, "0000")
832 return
833 }
834 fmt.Fprintf(os.Stdout, "%04x%s", len(p)+4, p)
835}
836
837// The project's cap on automatic versions holds: with a cap of 1, the
838// first landing's restack adds the change's one automatic version, and
839// after a second landing the pass holds the change and reports blocked,
840// saying the cap is why.
841func TestAPassHonoursTheCap(t *testing.T) {
842 f := hooked(t)
843 f.readyAs(idA, "alice", "a", "main", "A's title")
844 f.moveMain()
845 r := newRestacker(t, f)
846 r.pass(1)
847 f.restackedTo(idA, "alice", "A's title", "a", f.at("refs/heads/a"))
848 head, record := f.at("refs/heads/a"), f.at(change.Ref(rebase.Target, idA))
849
850 f.git("checkout", "--quiet", "main")
851 f.commit("main moves again", "again.txt")
852 f.git("push", "--quiet", "origin", "main")
853 r.pass(1)
854 if f.at("refs/heads/a") != head || f.at(change.Ref(rebase.Target, idA)) != record {
855 t.Fatal("the pass restacked a change over the cap")
856 }
857 if rep := f.reportOf(idA); rep == nil || rep.Result != change.RestackBlocked || rep.Refusal == nil ||
858 !strings.Contains(*rep.Refusal, "over the cap of 1") {
859 t.Errorf("a's report is %+v", rep)
860 }
861 r.settledState()
862}
863
864// run reconciles at once and then on its interval, without being told
865// anything has moved: after a landing it restacks a ready change, and a
866// change readied later, off an older main, is restacked with no landing
867// between. Stopped, it returns.
868func TestRunConverges(t *testing.T) {
869 f := hooked(t)
870 base := f.at("refs/heads/main")
871 f.readyAs(idA, "alice", "a", "main", "A's title")
872 f.moveMain()
873 r := newRestacker(t, f)
874 schema, floor := fakePolicyCap(t, 64)
875 t.Setenv("VALLEY_PRINCIPAL", r.c.principal)
876 ctx, cancel := context.WithCancel(context.Background())
877 done := make(chan error, 1)
878 var out, errOut syncBuffer
879 go func() {
880 done <- loop(ctx, append(writeArgs(r.c, schema, floor), "--interval", "200ms"), &out, &errOut)
881 }()
882 // A pass prints what it pushed once it ends.
883 restacked := func(id string) {
884 t.Helper()
885 for deadline := time.Now().Add(60 * time.Second); time.Now().Before(deadline); time.Sleep(100 * time.Millisecond) {
886 if strings.Contains(out.String(), "report "+id+": pushed") {
887 return
888 }
889 }
890 cancel()
891 t.Fatalf("run did not restack %s:\n%s\n%s", id[:4], out.String(), errOut.String())
892 }
893 restacked(idA)
894 f.readyAs(idB, "bob", "b", base, "B's title")
895 restacked(idB)
896 cancel()
897 select {
898 case err := <-done:
899 if err != nil {
900 t.Errorf("run ended with %v", err)
901 }
902 case <-time.After(30 * time.Second):
903 t.Fatal("run did not end once stopped")
904 }
905 f.restackedTo(idA, "alice", "A's title", "a", f.at("refs/heads/a"))
906 f.restackedTo(idB, "bob", "B's title", "b", f.at("refs/heads/b"))
907}
908
909// A pass's wait after failures doubles from the interval, up to the
910// bound.
911func TestBackoffIsBounded(t *testing.T) {
912 for failures, want := range []time.Duration{15 * time.Second, 30 * time.Second, time.Minute, 2 * time.Minute, 4 * time.Minute, maxBackoff, maxBackoff} {
913 if got := backoff(15*time.Second, failures); got != want {
914 t.Errorf("after %d failures, run waits %v, not %v", failures, got, want)
915 }
916 }
917}
918
919// syncBuffer is a buffer one goroutine writes while another reads it.
920type syncBuffer struct {
921 mu sync.Mutex
922 buf bytes.Buffer
923}
924
925func (b *syncBuffer) Write(p []byte) (int, error) {
926 b.mu.Lock()
927 defer b.mu.Unlock()
928 return b.buf.Write(p)
929}
930
931func (b *syncBuffer) String() string {
932 b.mu.Lock()
933 defer b.mu.Unlock()
934 return b.buf.String()
935}