gunk-dev/the-valley

publish_test.go

sourceea038b6f45c6main's published tip history
18.9 KiB
1package main
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "os"
9 "os/exec"
10 "path/filepath"
11 "strings"
12 "sync"
13 "testing"
14 "time"
15
16 "the-valley/change"
17 "the-valley/rebase"
18)
19
20// hooked is a fixture whose origin runs the fixture host's rendered hook,
21// which grants restack to the principal restacker and request to
22// requester. Without the hook, the test is skipped.
23func hooked(t *testing.T) *fixture {
24 t.Helper()
25 hook := os.Getenv(hookEnv)
26 if hook == "" {
27 t.Skip(hookEnv + " names no rendered hook; restack-unit supplies one")
28 }
29 withoutIdentity(t)
30 return newFixture(t, hook)
31}
32
33// pass runs one write pass, as `valley-restacker once`, under a cue that
34// composes every policy to the cap given, pushing as the restacker's
35// principal. It returns what the pass printed with --json.
36func (r *restacker) pass(cap int) *Plan {
37 r.t.Helper()
38 schema, floor := fakePolicyCap(r.t, cap)
39 r.t.Setenv("VALLEY_PRINCIPAL", r.c.principal)
40 var out, errOut bytes.Buffer
41 if err := once(context.Background(), append(writeArgs(r.c, schema, floor), "--json"), &out, &errOut); err != nil {
42 r.t.Fatalf("once: %v\n%s", err, errOut.String())
43 }
44 var p Plan
45 if err := json.Unmarshal(out.Bytes(), &p); err != nil {
46 r.t.Fatalf("the pass does not read: %v\n%s", err, out.String())
47 }
48 return &p
49}
50
51// writeArgs is the arguments of a write pass with c's configuration.
52func writeArgs(c config, schema, floor string) []string {
53 return []string{"--repo", c.repo, "--state", c.state, "--principal", c.principal,
54 "--commit-name", c.commitName, "--commit-email", c.commitEmail, "--schema", schema, "--instance", floor}
55}
56
57// pushAs pushes to origin as a principal, through the hook.
58func (f *fixture) pushAs(principal string, args ...string) error {
59 g := f.as(principal)
60 cmd := exec.Command("git", append([]string{"push", "--quiet", "origin"}, args...)...)
61 cmd.Dir, cmd.Env = g.Dir, g.Env
62 if out, err := cmd.CombinedOutput(); err != nil {
63 return fmt.Errorf("%v: %s", err, out)
64 }
65 return nil
66}
67
68// judge writes an outcome record on origin's side, as the integrator does:
69// no push may write one.
70func (f *fixture) judge(name, head, decision string) {
71 f.t.Helper()
72 line := fmt.Sprintf("%s %s %s %s\n", head, f.at("refs/heads/main"), change.EvidenceFingerprint(nil), decision)
73 path := filepath.Join(f.t.TempDir(), "outcome")
74 if err := os.WriteFile(path, []byte(line), 0o644); err != nil {
75 f.t.Fatal(err)
76 }
77 blob := f.onOrigin("hash-object", "-w", path)
78 f.onOrigin("update-ref", rebase.OutcomePrefix+name, blob)
79}
80
81// recordOf is the change's record on origin.
82func (f *fixture) recordOf(id string) *change.Record {
83 f.t.Helper()
84 data := f.onOrigin("cat-file", "blob", change.Ref(rebase.Target, id)+":record.json")
85 r, err := change.Parse([]byte(data + "\n"))
86 if err != nil {
87 f.t.Fatal(err)
88 }
89 return r
90}
91
92// reportAt is the report a report commit on origin holds.
93func (f *fixture) reportAt(commit string) *change.RestackReport {
94 f.t.Helper()
95 data := f.onOrigin("cat-file", "blob", commit+":report.json")
96 r, err := change.ParseRestackReport([]byte(data + "\n"))
97 if err != nil {
98 f.t.Fatal(err)
99 }
100 return r
101}
102
103// reportOf is the change's latest report on origin, or nil for none.
104func (f *fixture) reportOf(id string) *change.RestackReport {
105 f.t.Helper()
106 commit := f.at(rebase.RestackPrefix + id)
107 if commit == "" {
108 return nil
109 }
110 return f.reportAt(commit)
111}
112
113// restackedTo holds that the change's record gained exactly one version,
114// v2, uploaded by the restacker at head, keeping the owner, the title and
115// the branch, and that its latest report says complete with that version.
116func (f *fixture) restackedTo(id, owner, title, branch, head string) {
117 f.t.Helper()
118 r := f.recordOf(id)
119 v := r.ActiveVersion()
120 if r.State != change.Ready || r.Seq != 2 || len(r.Versions) != 2 || v.N != 2 || rebase.HeadOf(v) != head ||
121 v.Uploader != "restacker" || v.Title != title || v.Branch != branch || r.Owner != owner {
122 f.t.Errorf("%s's record is not restacked to %s once: %+v", id[:4], short(head), r)
123 }
124 rep := f.reportOf(id)
125 if rep == nil || rep.Result != change.RestackComplete {
126 f.t.Fatalf("%s's report is %+v", id[:4], rep)
127 }
128 for _, l := range rep.Layers {
129 if l.ChangeID == id && (l.Published == nil || l.Published.Version == nil || *l.Published.Version != 2 ||
130 l.Published.Head != change.HeadPrefix+head) {
131 f.t.Errorf("%s's report does not say v2 was published at %s: %+v", id[:4], short(head), l.Published)
132 }
133 }
134}
135
136// settledState holds that the pass left no journal and kept no object for
137// one.
138func (r *restacker) settledState() {
139 r.t.Helper()
140 if _, err := os.Stat(filepath.Join(r.c.state, journalFile)); err == nil {
141 r.t.Error("the pass left a journal")
142 }
143 if kept := gitOutT(r.t, r.g, "for-each-ref", retainPrefix, "refs/valley-rebase/"); kept != "" {
144 r.t.Errorf("the pass kept objects:\n%s", kept)
145 }
146}
147
148// count is how many of the pass's actions are of the write given.
149func count(p *Plan, write string) int {
150 n := 0
151 for _, a := range p.Actions {
152 if a.Write == write {
153 n++
154 }
155 }
156 return n
157}
158
159// After a landing, one write pass rebases every ready change onto main
160// through the rendered hook, as the restacker's principal: a stack of two
161// owners' changes is one family, and each layer descends from the new
162// layer below it, with only its own file changed. Each change gains one
163// version, uploaded by the restacker, under its owner and title, and a
164// report that says complete. A change that conflicts with the landing
165// moves nothing and gets a report that says conflict, naming the path,
166// and a draft is left alone. The pass lets go of its journal. A second
167// pass pushes nothing: the restacked stack is current, and the conflict
168// is not tried again while nothing it observed has moved.
169func TestAPassRestacksReadyChangesAfterALanding(t *testing.T) {
170 f := hooked(t)
171 f.readyAs(idA, "alice", "a", "main", "A's title")
172 f.readyAs(idB, "bob", "b", "a", "B's title")
173 f.git("checkout", "--quiet", "-B", "c", "main")
174 conflicted := f.commit("c's line", "shared.txt")
175 f.git("push", "--quiet", "origin", "c")
176 f.writeRecord(idC, &change.Record{
177 Schema: change.Schema, ChangeID: idC, Target: rebase.Target, Owner: "carol", State: change.Ready, Seq: 1, Active: 1,
178 Versions: []change.Version{{N: 1, Head: change.HeadPrefix + conflicted, Title: "C's title", Branch: "c", Uploader: "carol"}},
179 }, "", conflicted)
180 draft := f.readyAs(idE, "alice", "e", "main", "E's title")
181 f.setState(idE, change.Draft)
182 f.git("checkout", "--quiet", "main")
183 f.commit("main's line", "shared.txt")
184 f.git("push", "--quiet", "origin", "main")
185 tip := f.at("refs/heads/main")
186 cRecord := f.at(change.Ref(rebase.Target, idC))
187
188 r := newRestacker(t, f)
189 p := r.pass(64)
190 a, b := f.at("refs/heads/a"), f.at("refs/heads/b")
191 if parent := f.onOrigin("rev-parse", a+"^"); parent != tip {
192 t.Errorf("a is on %s, not main's tip %s", short(parent), short(tip))
193 }
194 if parent := f.onOrigin("rev-parse", b+"^"); parent != a {
195 t.Errorf("b is on %s, not a's new head %s", short(parent), short(a))
196 }
197 for _, d := range [][3]string{{tip, a, "a.txt"}, {a, b, "b.txt"}} {
198 if changed := f.onOrigin("diff", "--name-only", d[0], d[1]); changed != d[2] {
199 t.Errorf("%s changes %q, not %s alone", short(d[1]), changed, d[2])
200 }
201 }
202 f.restackedTo(idA, "alice", "A's title", "a", a)
203 f.restackedTo(idB, "bob", "B's title", "b", b)
204
205 if f.at("refs/heads/c") != conflicted || f.at(change.Ref(rebase.Target, idC)) != cRecord {
206 t.Error("the conflicting change moved")
207 }
208 if rep := f.reportOf(idC); rep == nil || rep.Result != change.RestackConflict || rep.Failing == nil || *rep.Failing != idC ||
209 len(rep.Conflicts) != 1 || rep.Conflicts[0] != "shared.txt" {
210 t.Errorf("c's report is %+v", rep)
211 }
212 if f.at("refs/heads/e") != draft || f.recordOf(idE).Seq != 2 || f.reportOf(idE) != nil {
213 t.Error("the draft was touched")
214 }
215 if count(p, "branches") != 1 || count(p, "version") != 2 || count(p, "report") != 3 {
216 t.Errorf("the pass pushed %+v", p.Actions)
217 }
218 r.settledState()
219
220 before := f.refs()
221 p = r.pass(64)
222 if len(p.Actions) != 0 || f.refs() != before {
223 t.Errorf("a second pass pushed %+v", p.Actions)
224 }
225 for _, fp := range p.Families {
226 if fp.Layers[0].ID == idC && fp.Writes != nil && len(fp.Writes.Reports) == 1 && !fp.Writes.Reports[0].Unchanged {
227 t.Errorf("the second pass rebased the conflict again: %+v", fp.Writes)
228 }
229 }
230 r.settledState()
231}
232
233// A related request that might still land holds its family: the pass
234// moves no branch and adds no version, and its report says blocked,
235// naming the request. Once the integrator's outcome for the request is a
236// current stale, the next pass restacks the change and leaves the
237// request as it was.
238func TestARequestHoldsItsFamilyUntilACurrentStaleReleasesIt(t *testing.T) {
239 f := hooked(t)
240 head := f.readyAs(idA, "alice", "a", "main", "A's title")
241 request := rebase.RequestPrefix + change.RequestName(idA)
242 if err := f.pushAs("requester", head+":"+request); err != nil {
243 t.Fatal(err)
244 }
245 f.moveMain()
246 record := f.at(change.Ref(rebase.Target, idA))
247
248 r := newRestacker(t, f)
249 r.pass(64)
250 if f.at("refs/heads/a") != head || f.at(change.Ref(rebase.Target, idA)) != record {
251 t.Fatal("the pass moved a change a request holds")
252 }
253 rep := f.reportOf(idA)
254 if rep == nil || rep.Result != change.RestackBlocked || len(rep.Requests) != 1 || rep.Requests[0].Ref != request ||
255 rep.Refusal == nil || !strings.Contains(*rep.Refusal, "might still land") {
256 t.Fatalf("a's report is %+v", rep)
257 }
258
259 f.judge(change.RequestName(idA), head, "stale")
260 r.pass(64)
261 f.restackedTo(idA, "alice", "A's title", "a", f.at("refs/heads/a"))
262 if f.at(request) != head {
263 t.Error("the restacker moved the request")
264 }
265 r.settledState()
266}
267
268// A pass that ended after any step of its journal is finished by the
269// next: each write already on origin is not pushed again, each change has
270// exactly one new version, every report says complete, and the journal
271// is let go.
272func TestAPassFinishesAJournalLeftAtAnyStep(t *testing.T) {
273 steps := []string{"kept", "branches pushed", "lower version added", "both versions added", "one report pushed"}
274 for n, step := range steps {
275 t.Run(step, func(t *testing.T) {
276 f := hooked(t)
277 f.readyAs(idA, "alice", "a", "main", "A's title")
278 f.readyAs(idB, "bob", "b", "a", "B's title")
279 f.moveMain()
280 t.Setenv("VALLEY_PRINCIPAL", "restacker")
281 r := newRestacker(t, f)
282 fam := of(t, r.journal(), idA)
283 ctx := context.Background()
284 made := []func() bool{
285 func() bool { push, _ := fam.Branches.Push(ctx, r.g); return push == rebase.Pushed },
286 func() bool { return fam.Versions[0].Push(ctx, r.g).Err == nil },
287 func() bool { return fam.Versions[1].Push(ctx, r.g).Err == nil },
288 func() bool { return fam.Reports[0].Pending.Push(ctx, r.g).Push == rebase.Pushed },
289 }
290 for i := 0; i < n; i++ {
291 if !made[i]() {
292 t.Fatalf("step %d of the journal was not pushed", i+1)
293 }
294 }
295
296 p := r.pass(64)
297 f.restackedTo(idA, "alice", "A's title", "a", fam.Branches.Updates[0].New)
298 f.restackedTo(idB, "bob", "B's title", "b", fam.Branches.Updates[1].New)
299 if want := min(n, 1); count(p, "branches") != 1-want {
300 t.Errorf("the pass pushed the branches %d times, after %s", count(p, "branches"), step)
301 }
302 if want := 2 - min(max(n-1, 0), 2); count(p, "version") != want {
303 t.Errorf("the pass added %d versions, after %s, where %d were left", count(p, "version"), step, want)
304 }
305 if p.Recovery == nil || p.Pending != nil {
306 t.Errorf("the journal was not found, or is still open: %+v", p.Pending)
307 }
308 r.settledState()
309 })
310 }
311}
312
313// An owner who pushes to a branch the restacker has moved stops that
314// change's version for good: the pass adds the version below it, adds
315// none to the moved change, and reports partial for both, with each
316// version origin holds. The moved change's record stays as its owner left
317// it, and the plan that follows in the same pass holds it, since its
318// branch is not at its version's head.
319func TestAnOwnerWhoMovesARestackedBranchStopsItsVersion(t *testing.T) {
320 f := hooked(t)
321 f.readyAs(idA, "alice", "a", "main", "A's title")
322 f.readyAs(idB, "bob", "b", "a", "B's title")
323 f.moveMain()
324 t.Setenv("VALLEY_PRINCIPAL", "restacker")
325 r := newRestacker(t, f)
326 fam := of(t, r.journal(), idA)
327 if push, _ := fam.Branches.Push(context.Background(), r.g); push != rebase.Pushed {
328 t.Fatal("the branches were not pushed")
329 }
330 f.ownerPushes("b")
331 bRecord := f.at(change.Ref(rebase.Target, idB))
332
333 p := r.pass(64)
334 for _, fp := range p.Families {
335 if fp.Layers[0].ID == idB && fp.Action != hold {
336 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)
337 }
338 }
339 if got := f.recordOf(idA); got.Seq != 2 || rebase.HeadOf(got.ActiveVersion()) != fam.Branches.Updates[0].New {
340 t.Errorf("a's version was not added: %+v", got)
341 }
342 if f.at(change.Ref(rebase.Target, idB)) != bRecord {
343 t.Error("a version was added to the change its owner moved")
344 }
345 // The latest report or one before it, since a later plan in the same
346 // pass may report on b again, says partial.
347 partial := false
348 for commit := f.at(rebase.RestackPrefix + idB); commit != ""; commit = f.parentOf(commit) {
349 rep := f.reportAt(commit)
350 if rep.Result != change.RestackPartial {
351 continue
352 }
353 partial = true
354 for _, l := range rep.Layers {
355 switch {
356 case l.ChangeID == idA && (l.Published == nil || l.Published.Version == nil || *l.Published.Version != 2):
357 t.Errorf("the partial report does not say a's v2 was added: %+v", l.Published)
358 case l.ChangeID == idB && (l.Published == nil || l.Published.Version != nil):
359 t.Errorf("the partial report says b's version was added: %+v", l.Published)
360 }
361 }
362 if rep.Refusal == nil || !strings.Contains(*rep.Refusal, "its author moved it") {
363 t.Errorf("the partial report does not say why: %v", rep.Refusal)
364 }
365 }
366 if !partial {
367 t.Error("no report of b says partial")
368 }
369 r.settledState()
370}
371
372// parentOf is a commit's first parent on origin, or "" for none.
373func (f *fixture) parentOf(commit string) string {
374 cmd := exec.Command("git", "rev-parse", "--verify", "--quiet", commit+"^")
375 cmd.Dir, cmd.Env = f.origin, f.env
376 out, _ := cmd.Output()
377 return strings.TrimSpace(string(out))
378}
379
380// A request filed between a family's branch push and its versions pauses
381// the versions: the pass reports partial, adds none, and keeps the
382// journal open, so it starts no new operation. Once the request's outcome
383// is a current stale, the next pass adds the version, reports complete,
384// and lets go of the journal.
385func TestARequestBetweenPhasesPausesTheVersions(t *testing.T) {
386 f := hooked(t)
387 old := f.readyAs(idA, "alice", "a", "main", "A's title")
388 f.moveMain()
389 t.Setenv("VALLEY_PRINCIPAL", "restacker")
390 r := newRestacker(t, f)
391 fam := of(t, r.journal(), idA)
392 if push, _ := fam.Branches.Push(context.Background(), r.g); push != rebase.Pushed {
393 t.Fatal("the branches were not pushed")
394 }
395 if err := f.pushAs("requester", old+":"+rebase.RequestPrefix+"zz-old"); err != nil {
396 t.Fatal(err)
397 }
398 record := f.at(change.Ref(rebase.Target, idA))
399
400 p := r.pass(64)
401 if f.at(change.Ref(rebase.Target, idA)) != record || p.Pending == nil {
402 t.Fatalf("the paused version was added, or the journal let go: %+v", p.Pending)
403 }
404 if _, err := os.Stat(filepath.Join(r.c.state, journalFile)); err != nil {
405 t.Errorf("the open journal is gone: %v", err)
406 }
407 rep := f.reportOf(idA)
408 if rep == nil || rep.Result != change.RestackPartial || rep.Refusal == nil || !strings.Contains(*rep.Refusal, "zz-old might still land") {
409 t.Fatalf("a's report is %+v", rep)
410 }
411 if p = r.pass(64); len(p.Actions) != 0 || p.Pending == nil {
412 t.Errorf("a pass with the request still open pushed %+v", p.Actions)
413 }
414
415 f.judge("zz-old", old, "stale")
416 p = r.pass(64)
417 if p.Pending != nil {
418 t.Errorf("the journal is still open: %+v", p.Pending)
419 }
420 f.restackedTo(idA, "alice", "A's title", "a", fam.Branches.Updates[0].New)
421 r.settledState()
422}
423
424// The project's cap on automatic versions holds: with a cap of 1, the
425// first landing's restack adds the change's one automatic version, and
426// after a second landing the pass holds the change and reports blocked,
427// saying the cap is why.
428func TestAPassHonoursTheCap(t *testing.T) {
429 f := hooked(t)
430 f.readyAs(idA, "alice", "a", "main", "A's title")
431 f.moveMain()
432 r := newRestacker(t, f)
433 r.pass(1)
434 f.restackedTo(idA, "alice", "A's title", "a", f.at("refs/heads/a"))
435 head, record := f.at("refs/heads/a"), f.at(change.Ref(rebase.Target, idA))
436
437 f.git("checkout", "--quiet", "main")
438 f.commit("main moves again", "again.txt")
439 f.git("push", "--quiet", "origin", "main")
440 r.pass(1)
441 if f.at("refs/heads/a") != head || f.at(change.Ref(rebase.Target, idA)) != record {
442 t.Fatal("the pass restacked a change over the cap")
443 }
444 if rep := f.reportOf(idA); rep == nil || rep.Result != change.RestackBlocked || rep.Refusal == nil ||
445 !strings.Contains(*rep.Refusal, "over the cap of 1") {
446 t.Errorf("a's report is %+v", rep)
447 }
448 r.settledState()
449}
450
451// run reconciles at once and then on its interval, without being told
452// anything has moved: after a landing it restacks a ready change, and a
453// change readied later, off an older main, is restacked with no landing
454// between. Stopped, it returns.
455func TestRunConverges(t *testing.T) {
456 f := hooked(t)
457 base := f.at("refs/heads/main")
458 f.readyAs(idA, "alice", "a", "main", "A's title")
459 f.moveMain()
460 r := newRestacker(t, f)
461 schema, floor := fakePolicyCap(t, 64)
462 t.Setenv("VALLEY_PRINCIPAL", r.c.principal)
463 ctx, cancel := context.WithCancel(context.Background())
464 done := make(chan error, 1)
465 var out, errOut syncBuffer
466 go func() {
467 done <- loop(ctx, append(writeArgs(r.c, schema, floor), "--interval", "200ms"), &out, &errOut)
468 }()
469 // A pass prints what it pushed once it ends.
470 restacked := func(id string) {
471 t.Helper()
472 for deadline := time.Now().Add(60 * time.Second); time.Now().Before(deadline); time.Sleep(100 * time.Millisecond) {
473 if strings.Contains(out.String(), "report "+id+": pushed") {
474 return
475 }
476 }
477 cancel()
478 t.Fatalf("run did not restack %s:\n%s\n%s", id[:4], out.String(), errOut.String())
479 }
480 restacked(idA)
481 f.readyAs(idB, "bob", "b", base, "B's title")
482 restacked(idB)
483 cancel()
484 select {
485 case err := <-done:
486 if err != nil {
487 t.Errorf("run ended with %v", err)
488 }
489 case <-time.After(30 * time.Second):
490 t.Fatal("run did not end once stopped")
491 }
492 f.restackedTo(idA, "alice", "A's title", "a", f.at("refs/heads/a"))
493 f.restackedTo(idB, "bob", "B's title", "b", f.at("refs/heads/b"))
494}
495
496// A pass's wait after failures doubles from the interval, up to the
497// bound.
498func TestBackoffIsBounded(t *testing.T) {
499 for failures, want := range []time.Duration{15 * time.Second, 30 * time.Second, time.Minute, 2 * time.Minute, 4 * time.Minute, maxBackoff, maxBackoff} {
500 if got := backoff(15*time.Second, failures); got != want {
501 t.Errorf("after %d failures, run waits %v, not %v", failures, got, want)
502 }
503 }
504}
505
506// syncBuffer is a buffer one goroutine writes while another reads it.
507type syncBuffer struct {
508 mu sync.Mutex
509 buf bytes.Buffer
510}
511
512func (b *syncBuffer) Write(p []byte) (int, error) {
513 b.mu.Lock()
514 defer b.mu.Unlock()
515 return b.buf.Write(p)
516}
517
518func (b *syncBuffer) String() string {
519 b.mu.Lock()
520 defer b.mu.Unlock()
521 return b.buf.String()
522}