gunk-dev/the-valley

publish_test.go

source75d050a4e31bmain's published tip history
29.9 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// A report of what did happen is kept in the journal before it is pushed,
481// and stays there until a read of origin shows it. Here an owner moves a
482// restacked branch, so the version above stops and the family's reports
483// say partial. When origin refuses the push of one of them, the pass
484// leaves the journal open with that report in it, and the next pass
485// pushes it. When origin takes the push and its answer is lost, the next
486// read finds it there, and it is not pushed again.
487func TestAReportOfWhatHappenedOutlivesAFailedPush(t *testing.T) {
488 for _, failure := range []string{"refused", "answer lost"} {
489 t.Run(failure, func(t *testing.T) {
490 f := hooked(t)
491 f.readyAs(idA, "alice", "a", "main", "A's title")
492 f.readyAs(idB, "bob", "b", "a", "B's title")
493 f.moveMain()
494 t.Setenv("VALLEY_PRINCIPAL", "restacker")
495 r := newRestacker(t, f)
496 fam := of(t, r.journal(), idA)
497 if push, _ := fam.Branches.Push(context.Background(), r.g); push != rebase.Pushed {
498 t.Fatal("the branches were not pushed")
499 }
500 f.ownerPushes("b")
501 ref := rebase.RestackPrefix + idB
502 lift := func() {}
503 if failure == "refused" {
504 lift = f.refuseOnOrigin(ref)
505 } else {
506 r.loseAnswers(ref)
507 }
508
509 p := r.pass(64)
510 var pushes []string
511 for _, a := range p.Actions {
512 if a.Write == "replacement" && a.ID == idB {
513 pushes = append(pushes, a.Result)
514 }
515 }
516 if failure == "answer lost" {
517 if strings.Join(pushes, " ") != "unknown" {
518 t.Errorf("b's report of what happened was pushed as %v, where once, its answer lost, is expected", pushes)
519 }
520 if !partialOf(f, idB, "its author moved it") {
521 t.Error("no report of b on origin says partial")
522 }
523 r.settledState()
524 return
525 }
526 if len(pushes) == 0 || strings.Trim(strings.Join(pushes, " "), "refused ") != "" {
527 t.Errorf("b's report of what happened was pushed as %v", pushes)
528 }
529 if f.reportOf(idB) != nil {
530 t.Fatal("origin holds a report of b it refused")
531 }
532 j, err := loadJournal(r.c.state, r.c.binding())
533 if err != nil || j == nil || p.Pending == nil {
534 t.Fatalf("the pass let go of the journal that holds b's report: %v", err)
535 }
536 kept := false
537 for _, rep := range of(t, j, idA).Replacements {
538 kept = kept || rep.Pending.ID == idB && rep.Pending.Report.Result == change.RestackPartial
539 }
540 if !kept {
541 t.Fatalf("the journal does not hold b's report of what happened: %+v", of(t, j, idA).Replacements)
542 }
543
544 lift()
545 r.pass(64)
546 if !partialOf(f, idB, "its author moved it") {
547 t.Error("no report of b on origin says partial once origin takes it")
548 }
549 r.settledState()
550 })
551 }
552}
553
554// What origin took of a family's writes stays in the journal, so an
555// author who rewrites or deletes every branch the family moved does not
556// unmake the report of it. Here an owner moves a restacked branch, so the
557// family's reports say partial, and origin refuses the push of one of
558// them. Every branch the family moved is then rewritten, or deleted, and
559// once origin takes the push, the next pass pushes that report, saying
560// what became of the branch.
561func TestAReportOfWhatHappenedOutlivesTheBranchesItReports(t *testing.T) {
562 for author, why := range map[string]string{"rewrites": "its author moved it", "deletes": "origin no longer has b"} {
563 t.Run(author, func(t *testing.T) {
564 f := hooked(t)
565 f.readyAs(idA, "alice", "a", "main", "A's title")
566 f.readyAs(idB, "bob", "b", "a", "B's title")
567 f.moveMain()
568 t.Setenv("VALLEY_PRINCIPAL", "restacker")
569 r := newRestacker(t, f)
570 fam := of(t, r.journal(), idA)
571 if push, _ := fam.Branches.Push(context.Background(), r.g); push != rebase.Pushed {
572 t.Fatal("the branches were not pushed")
573 }
574 f.ownerPushes("b")
575 lift := f.refuseOnOrigin(rebase.RestackPrefix + idB)
576 if p := r.pass(64); p.Pending == nil || f.reportOf(idB) != nil {
577 t.Fatalf("the pass let go of the journal, or origin holds a report of b it refused: %+v", p.Pending)
578 }
579
580 for _, branch := range []string{"a", "b"} {
581 if author == "deletes" {
582 f.git("push", "--quiet", "origin", "--delete", branch)
583 continue
584 }
585 f.git("checkout", "--quiet", "-B", branch, "main")
586 f.commit("the author's rewrite of "+branch, branch+"-rewrite.txt")
587 f.git("push", "--quiet", "--force", "origin", branch)
588 }
589 lift()
590 r.pass(64)
591 if !partialOf(f, idB, why) {
592 t.Errorf("no report of b on origin says partial, since %s, once origin takes it", why)
593 }
594 r.settledState()
595 })
596 }
597}
598
599// partialOf reports whether the change's latest report on origin, or one
600// before it, says partial: a's version added, the change's own not, for
601// the reason given. A later plan in the same pass may report on the
602// change again.
603func partialOf(f *fixture, id, why string) bool {
604 f.t.Helper()
605 for commit := f.at(rebase.RestackPrefix + id); commit != ""; commit = f.parentOf(commit) {
606 rep := f.reportAt(commit)
607 if rep.Result != change.RestackPartial || rep.Refusal == nil || !strings.Contains(*rep.Refusal, why) {
608 continue
609 }
610 for _, l := range rep.Layers {
611 if l.Published == nil || (l.ChangeID == idA) != (l.Published.Version != nil) {
612 f.t.Errorf("the partial report of %s does not say what was published: %+v", id[:4], l)
613 }
614 }
615 return true
616 }
617 return false
618}
619
620// refuseOnOrigin has origin refuse every push that moves the ref, ahead
621// of its own hook, until the function it returns is called.
622func (f *fixture) refuseOnOrigin(ref string) (lift func()) {
623 f.t.Helper()
624 hook := filepath.Join(f.origin, "hooks", "pre-receive")
625 own := hook + ".own"
626 if err := os.Rename(hook, own); err != nil {
627 f.t.Fatal(err)
628 }
629 script := fmt.Sprintf("#!/bin/sh\nlines=$(cat)\n"+
630 "if printf '%%s\\n' \"$lines\" | grep -q ' %s$'; then echo 'origin refuses %s for the test' >&2; exit 1; fi\n"+
631 "printf '%%s\\n' \"$lines\" | exec '%s'\n", ref, ref, own)
632 if err := os.WriteFile(hook, []byte(script), 0o755); err != nil {
633 f.t.Fatal(err)
634 }
635 return func() {
636 if err := os.Rename(own, hook); err != nil {
637 f.t.Fatal(err)
638 }
639 }
640}
641
642// dropEnv names the ref whose pushes lossyReceivePack loses the answer to.
643const dropEnv = "RESTACK_TEST_DROP"
644
645// loseAnswers has origin's answer lost to every push of the restacker's
646// that moves the ref: origin takes the push, and the pass hears nothing.
647func (r *restacker) loseAnswers(ref string) {
648 r.t.Helper()
649 self, err := os.Executable()
650 if err != nil {
651 r.t.Fatal(err)
652 }
653 path := filepath.Join(r.t.TempDir(), "lossy-receive-pack")
654 script := fmt.Sprintf("#!/bin/sh\n%s=drop-acks %s='%s' exec '%s' \"$@\"\n", roleEnv, dropEnv, ref, self)
655 if err := os.WriteFile(path, []byte(script), 0o755); err != nil {
656 r.t.Fatal(err)
657 }
658 gitOutT(r.t, r.g, "config", "remote.origin.receivepack", path)
659}
660
661// lossyReceivePack is git receive-pack less its answer to a push that
662// moves the ref named. It runs the real receive-pack, which takes the
663// push, and passes its report on without the status of any ref when one
664// of them is that ref, as when origin's answer is lost. The side-band
665// capabilities are taken out of its advertisement, so the report comes as
666// plain pkt-lines. The rebase engine's tests drop every answer the same
667// way.
668func lossyReceivePack(ref string, args []string) int {
669 cmd := exec.Command("git", append([]string{"receive-pack"}, args...)...)
670 cmd.Stdin, cmd.Stderr = os.Stdin, os.Stderr
671 out, err := cmd.StdoutPipe()
672 if err != nil || cmd.Start() != nil {
673 return 1
674 }
675 r := bufio.NewReader(out)
676 advertised := false
677 var status [][]byte
678 for {
679 p, err := readPkt(r)
680 if err != nil {
681 break
682 }
683 switch {
684 case !advertised && p == nil:
685 advertised = true
686 case !advertised:
687 if refs, caps, ok := bytes.Cut(p, []byte{0}); ok {
688 var kept []string
689 for _, c := range strings.Fields(string(caps)) {
690 if !strings.HasPrefix(c, "side-band") {
691 kept = append(kept, c)
692 }
693 }
694 p = []byte(string(refs) + "\x00" + strings.Join(kept, " ") + "\n")
695 }
696 case bytes.HasPrefix(p, []byte("ok ")) || bytes.HasPrefix(p, []byte("ng ")) || bytes.HasPrefix(p, []byte("option ")):
697 status = append(status, p)
698 continue
699 case p == nil:
700 lost := false
701 for _, line := range status {
702 if fields := strings.Fields(string(line)); len(fields) > 1 && fields[1] == ref {
703 lost = true
704 }
705 }
706 for _, line := range status {
707 if !lost {
708 writePkt(line)
709 }
710 }
711 status = nil
712 }
713 writePkt(p)
714 }
715 if cmd.Wait() != nil {
716 return 1
717 }
718 return 0
719}
720
721// readPkt reads one pkt-line, nil for a flush.
722func readPkt(r *bufio.Reader) ([]byte, error) {
723 var size [4]byte
724 if _, err := io.ReadFull(r, size[:]); err != nil {
725 return nil, err
726 }
727 n, err := strconv.ParseUint(string(size[:]), 16, 16)
728 if err != nil || n < 4 {
729 return nil, err
730 }
731 p := make([]byte, n-4)
732 _, err = io.ReadFull(r, p)
733 return p, err
734}
735
736// writePkt writes one pkt-line to stdout, nil as a flush.
737func writePkt(p []byte) {
738 if p == nil {
739 io.WriteString(os.Stdout, "0000")
740 return
741 }
742 fmt.Fprintf(os.Stdout, "%04x%s", len(p)+4, p)
743}
744
745// The project's cap on automatic versions holds: with a cap of 1, the
746// first landing's restack adds the change's one automatic version, and
747// after a second landing the pass holds the change and reports blocked,
748// saying the cap is why.
749func TestAPassHonoursTheCap(t *testing.T) {
750 f := hooked(t)
751 f.readyAs(idA, "alice", "a", "main", "A's title")
752 f.moveMain()
753 r := newRestacker(t, f)
754 r.pass(1)
755 f.restackedTo(idA, "alice", "A's title", "a", f.at("refs/heads/a"))
756 head, record := f.at("refs/heads/a"), f.at(change.Ref(rebase.Target, idA))
757
758 f.git("checkout", "--quiet", "main")
759 f.commit("main moves again", "again.txt")
760 f.git("push", "--quiet", "origin", "main")
761 r.pass(1)
762 if f.at("refs/heads/a") != head || f.at(change.Ref(rebase.Target, idA)) != record {
763 t.Fatal("the pass restacked a change over the cap")
764 }
765 if rep := f.reportOf(idA); rep == nil || rep.Result != change.RestackBlocked || rep.Refusal == nil ||
766 !strings.Contains(*rep.Refusal, "over the cap of 1") {
767 t.Errorf("a's report is %+v", rep)
768 }
769 r.settledState()
770}
771
772// run reconciles at once and then on its interval, without being told
773// anything has moved: after a landing it restacks a ready change, and a
774// change readied later, off an older main, is restacked with no landing
775// between. Stopped, it returns.
776func TestRunConverges(t *testing.T) {
777 f := hooked(t)
778 base := f.at("refs/heads/main")
779 f.readyAs(idA, "alice", "a", "main", "A's title")
780 f.moveMain()
781 r := newRestacker(t, f)
782 schema, floor := fakePolicyCap(t, 64)
783 t.Setenv("VALLEY_PRINCIPAL", r.c.principal)
784 ctx, cancel := context.WithCancel(context.Background())
785 done := make(chan error, 1)
786 var out, errOut syncBuffer
787 go func() {
788 done <- loop(ctx, append(writeArgs(r.c, schema, floor), "--interval", "200ms"), &out, &errOut)
789 }()
790 // A pass prints what it pushed once it ends.
791 restacked := func(id string) {
792 t.Helper()
793 for deadline := time.Now().Add(60 * time.Second); time.Now().Before(deadline); time.Sleep(100 * time.Millisecond) {
794 if strings.Contains(out.String(), "report "+id+": pushed") {
795 return
796 }
797 }
798 cancel()
799 t.Fatalf("run did not restack %s:\n%s\n%s", id[:4], out.String(), errOut.String())
800 }
801 restacked(idA)
802 f.readyAs(idB, "bob", "b", base, "B's title")
803 restacked(idB)
804 cancel()
805 select {
806 case err := <-done:
807 if err != nil {
808 t.Errorf("run ended with %v", err)
809 }
810 case <-time.After(30 * time.Second):
811 t.Fatal("run did not end once stopped")
812 }
813 f.restackedTo(idA, "alice", "A's title", "a", f.at("refs/heads/a"))
814 f.restackedTo(idB, "bob", "B's title", "b", f.at("refs/heads/b"))
815}
816
817// A pass's wait after failures doubles from the interval, up to the
818// bound.
819func TestBackoffIsBounded(t *testing.T) {
820 for failures, want := range []time.Duration{15 * time.Second, 30 * time.Second, time.Minute, 2 * time.Minute, 4 * time.Minute, maxBackoff, maxBackoff} {
821 if got := backoff(15*time.Second, failures); got != want {
822 t.Errorf("after %d failures, run waits %v, not %v", failures, got, want)
823 }
824 }
825}
826
827// syncBuffer is a buffer one goroutine writes while another reads it.
828type syncBuffer struct {
829 mu sync.Mutex
830 buf bytes.Buffer
831}
832
833func (b *syncBuffer) Write(p []byte) (int, error) {
834 b.mu.Lock()
835 defer b.mu.Unlock()
836 return b.buf.Write(p)
837}
838
839func (b *syncBuffer) String() string {
840 b.mu.Lock()
841 defer b.mu.Unlock()
842 return b.buf.String()
843}