gunk-dev/the-valley

journal_test.go

source30fe2c053de0main's published tip history
31.2 KiB
1package main
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "os"
9 "path/filepath"
10 "reflect"
11 "sort"
12 "strings"
13 "testing"
14 "time"
15
16 "the-valley/change"
17 "the-valley/rebase"
18)
19
20var (
21 idB = strings.Repeat("m", 32)
22 idC = strings.Repeat("n", 32)
23 idE = strings.Repeat("p", 32)
24)
25
26// readyAs pushes a branch off from with one commit, and readies it as the
27// change id, owned by owner, under a title unlike the commit's subject. It
28// returns the head.
29func (f *fixture) readyAs(id, owner, branch, from, title string) string {
30 f.t.Helper()
31 f.git("checkout", "--quiet", "-B", branch, from)
32 head := f.commit("layer "+branch, branch+".txt")
33 f.git("push", "--quiet", "--force", "origin", branch)
34 r := &change.Record{
35 Schema: change.Schema, ChangeID: id, Target: rebase.Target, Owner: owner, State: change.Ready, Seq: 1, Active: 1,
36 Versions: []change.Version{{N: 1, Head: change.HeadPrefix + head, Title: title, Branch: branch, Uploader: owner}},
37 }
38 f.writeRecord(id, r, "", head)
39 return head
40}
41
42func (f *fixture) writeRecord(id string, r *change.Record, old string, parents ...string) {
43 f.t.Helper()
44 ctx := context.Background()
45 g := f.as(r.Owner)
46 commit, err := rebase.WriteRecord(ctx, g, r, "test record", parents...)
47 if err != nil {
48 f.t.Fatal(err)
49 }
50 if w := rebase.PushRecord(ctx, g, id, old, commit); w.Push != rebase.Pushed {
51 f.t.Fatalf("the record of %s was not pushed: %+v", id, w)
52 }
53}
54
55// setState writes the change's record again in another state.
56func (f *fixture) setState(id, state string) {
57 f.t.Helper()
58 ref := change.Ref(rebase.Target, id)
59 old := f.at(ref)
60 data := f.run(f.origin, "cat-file", "blob", ref+":record.json")
61 r, err := change.Parse([]byte(data + "\n"))
62 if err != nil {
63 f.t.Fatal(err)
64 }
65 r.State, r.Seq = state, r.Seq+1
66 f.git("fetch", "--quiet", "origin", ref)
67 f.writeRecord(id, r, old, old)
68}
69
70// plainBranch pushes a branch off from that no record is on.
71func (f *fixture) plainBranch(branch, from string) {
72 f.t.Helper()
73 f.git("checkout", "--quiet", "-B", branch, from)
74 f.commit("plain "+branch, branch+".txt")
75 f.git("push", "--quiet", "origin", branch)
76}
77
78// ownerPushes adds a commit of the owner's own on origin's branch.
79func (f *fixture) ownerPushes(branch string) {
80 f.t.Helper()
81 f.git("fetch", "--quiet", "origin")
82 f.git("checkout", "--quiet", "-B", branch, "origin/"+branch)
83 f.commit("the owner's own work on "+branch, branch+"-own.txt")
84 f.git("push", "--quiet", "origin", branch)
85}
86
87// refs is every ref on origin, to tell that nothing moved.
88func (f *fixture) refs() string {
89 f.t.Helper()
90 return f.run(f.origin, "for-each-ref", "--format=%(objectname) %(refname)")
91}
92
93// onOrigin runs git in origin itself, as a server-side change is made.
94func (f *fixture) onOrigin(args ...string) string {
95 f.t.Helper()
96 return f.run(f.origin, args...)
97}
98
99// restacker is the restacker's side of a fixture: a configuration and the
100// scratch repository a pass reads origin into.
101type restacker struct {
102 t *testing.T
103 f *fixture
104 c config
105 g rebase.Git
106}
107
108func newRestacker(t *testing.T, f *fixture) *restacker {
109 t.Helper()
110 c := config{repo: f.origin, target: rebase.Target, state: t.TempDir(), principal: "restacker",
111 commitName: "The Restacker", commitEmail: "restacker@example.invalid"}
112 g, err := scratchRepo(context.Background(), c)
113 if err != nil {
114 t.Fatal(err)
115 }
116 return &restacker{t: t, f: f, c: c, g: g}
117}
118
119// plan reads origin and plans it under a cap of 64, deciding the journal
120// in the state directory if there is one.
121func (r *restacker) plan() (*Plan, *rebase.Snapshot) {
122 r.t.Helper()
123 ctx := context.Background()
124 s, err := rebase.ReadSnapshot(ctx, r.g, r.c.verify)
125 if err != nil {
126 r.t.Fatal(err)
127 }
128 p, err := plan(ctx, r.g, r.c, s, 64)
129 if err != nil {
130 r.t.Fatal(err)
131 }
132 return p, s
133}
134
135// journal plans origin, builds the pass's writes and keeps them, as a pass
136// does before its first push.
137func (r *restacker) journal() *Journal {
138 r.t.Helper()
139 ctx := context.Background()
140 p, s := r.plan()
141 out, err := build(ctx, r.g, s, p, r.c.binding(), newOperation(time.Now()))
142 if err != nil {
143 r.t.Fatal(err)
144 }
145 defer out.releasePrepared(ctx, r.g)
146 if err := keep(ctx, r.g, r.c.state, out.journal); err != nil {
147 r.t.Fatal(err)
148 }
149 return out.journal
150}
151
152// recovery is what recovery decides of the journal now.
153func (r *restacker) recovery() *Recovery {
154 r.t.Helper()
155 p, _ := r.plan()
156 if p.Recovery == nil {
157 r.t.Fatal("no journal was decided")
158 }
159 if p.Recovery.Error != "" {
160 r.t.Fatalf("the journal was not read: %s", p.Recovery.Error)
161 }
162 return p.Recovery
163}
164
165// of is the family of the journal whose bottom layer is the change id.
166func of(t *testing.T, j *Journal, id string) JournalFamily {
167 t.Helper()
168 for _, f := range j.Families {
169 if f.Observed.Layers[0].ID == id {
170 return f
171 }
172 }
173 t.Fatalf("the journal has no family on %s", id)
174 return JournalFamily{}
175}
176
177// decision is what recovery decided of one write.
178func decision(t *testing.T, r *Recovery, write, id string) Decision {
179 t.Helper()
180 for _, d := range r.Decisions {
181 if d.Write == write && d.ID == id {
182 return d
183 }
184 }
185 t.Fatalf("recovery decided nothing of %s %s: %+v", write, id, r.Decisions)
186 return Decision{}
187}
188
189// expect holds a decision to its action, its finality, and a word of its
190// reason.
191func expect(t *testing.T, d Decision, action string, final bool, why string) {
192 t.Helper()
193 if d.Action != action || d.Final != final || !strings.Contains(d.Why, why) {
194 t.Errorf("%s %s: %s (final %v): %s; want %s (final %v) saying %q", d.Write, d.ID, d.Action, d.Final, d.Why, action, final, why)
195 }
196}
197
198func branchesOf(t *testing.T, r *Recovery, family JournalFamily, j *Journal) Decision {
199 t.Helper()
200 for i, f := range j.Families {
201 if reflect.DeepEqual(f.Observed, family.Observed) {
202 for _, d := range r.Decisions {
203 if d.Family == i && d.Write == "branches" {
204 return d
205 }
206 }
207 }
208 }
209 t.Fatal("recovery decided nothing of the family's branches")
210 return Decision{}
211}
212
213// Every write a pass would make is built and kept before any push: the
214// journal holds each family's branch push, each version, lower layers
215// first, with its active title and leased on the record read, and each
216// recorded change's report. Origin is untouched, the journal reads back
217// as kept, and every object a write would push is kept reachable under
218// the operation's refs. A family a plain branch holds gets a blocked
219// report and no other write.
220func TestTheJournalKeepsEveryWriteBeforeAnyPush(t *testing.T) {
221 f := newFixture(t, "")
222 f.readyAs(idA, "alice", "a", "main", "A's title")
223 f.readyAs(idB, "bob", "b", "main", "B's title")
224 f.readyAs(idC, "bob", "c", "b", "C's title")
225 f.readyAs(idE, "alice", "e", "main", "E's title")
226 f.plainBranch("e-plain", "e")
227 f.moveMain()
228 before := f.refs()
229 r := newRestacker(t, f)
230 j := r.journal()
231 if after := f.refs(); after != before {
232 t.Fatalf("building the writes moved something on origin:\n%s\nnow:\n%s", before, after)
233 }
234
235 kept, err := loadJournal(r.c.state, r.c.binding())
236 if err != nil || !reflect.DeepEqual(kept, j) {
237 t.Fatalf("the journal reads back as %+v, %v", kept, err)
238 }
239 a := of(t, j, idA)
240 if a.Branches == nil || len(a.Branches.Updates) != 1 || a.Branches.Updates[0].Old != f.at("refs/heads/a") || a.Branches.Tip != f.at("refs/heads/main") {
241 t.Errorf("a's branch push is %+v", a.Branches)
242 }
243 if len(a.Versions) != 1 || a.Versions[0].Old != f.at(change.Ref(rebase.Target, idA)) || !a.Versions[0].Restack() ||
244 a.Versions[0].Record.ActiveVersion().Title != "A's title" || a.Versions[0].Head != a.Branches.Updates[0].New {
245 t.Errorf("a's version is %+v", a.Versions)
246 }
247 if len(a.Reports) != 1 || a.Reports[0].Pending.Report.Result != change.RestackComplete || a.Reports[0].Pending.Old != "" {
248 t.Errorf("a's report is %+v", a.Reports)
249 }
250 bc := of(t, j, idB)
251 if len(bc.Branches.Updates) != 2 || len(bc.Versions) != 2 || bc.Versions[0].ID != idB || bc.Versions[1].ID != idC || len(bc.Reports) != 2 {
252 t.Errorf("b and c's writes are %+v", bc)
253 }
254 for _, rep := range bc.Reports {
255 if l := rep.Pending.Report.Layers; len(l) != 2 || l[1].Published == nil || *l[1].Published.Record != change.HeadPrefix+bc.Versions[1].Commit {
256 t.Errorf("%s's report does not say what the family published: %+v", rep.Pending.ID, l)
257 }
258 }
259 e := of(t, j, idE)
260 if e.Branches != nil || len(e.Versions) != 0 || len(e.Reports) != 1 || e.Reports[0].Pending.Report.Result != change.RestackBlocked ||
261 !strings.Contains(*e.Reports[0].Pending.Report.Refusal, "e-plain is a plain branch") {
262 t.Errorf("e's writes are %+v", e)
263 }
264
265 var want []string
266 for ref, oid := range j.retained() {
267 if !strings.HasPrefix(ref, retainPrefix+j.Families[0].Operation+"/") {
268 t.Errorf("%s is not kept under the operation's refs", ref)
269 }
270 want = append(want, ref+" "+oid)
271 }
272 got := strings.Split(gitOutT(t, r.g, "for-each-ref", "--format=%(refname) %(objectname)", retainPrefix), "\n")
273 sort.Strings(want)
274 sort.Strings(got)
275 if !reflect.DeepEqual(got, want) {
276 t.Errorf("the scratch repository keeps %v, and the journal's writes push %v", got, want)
277 }
278 if left := gitOutT(t, r.g, "for-each-ref", "refs/valley-rebase/"); left != "" {
279 t.Errorf("the prepared heads' own refs were not let go:\n%s", left)
280 }
281}
282
283func gitOutT(t *testing.T, g rebase.Git, args ...string) string {
284 t.Helper()
285 out, err := gitOut(context.Background(), g, args...)
286 if err != nil {
287 t.Fatal(err)
288 }
289 return strings.TrimSpace(out)
290}
291
292// Recovery follows each write as the pass would make it. Before any push,
293// every write is still valid to finish. Once a family's branches are
294// pushed, they are done, and its versions are still to finish; once a
295// version and a report are pushed, they are done too. An author who
296// pushes past a prepared head stops that change's version for good, and
297// with it each report that says the version was added, while the version
298// below it is still finished.
299func TestRecoveryFollowsEachWrite(t *testing.T) {
300 f := newFixture(t, "")
301 f.readyAs(idA, "alice", "a", "main", "A's title")
302 f.readyAs(idB, "bob", "b", "main", "B's title")
303 f.readyAs(idC, "bob", "c", "b", "C's title")
304 f.moveMain()
305 r := newRestacker(t, f)
306 j := r.journal()
307 a, bc := of(t, j, idA), of(t, j, idB)
308 ctx := context.Background()
309
310 rec := r.recovery()
311 for _, d := range rec.Decisions {
312 if d.Action != writeFinish {
313 t.Errorf("before any push, %s %s is %s: %s", d.Write, d.ID, d.Action, d.Why)
314 }
315 }
316 if rec.Settled || len(rec.Decisions) != 8 {
317 t.Errorf("recovery decided %d writes, settled %v", len(rec.Decisions), rec.Settled)
318 }
319
320 if push, _ := a.Branches.Push(ctx, r.g); push != rebase.Pushed {
321 t.Fatal("a's branches were not pushed")
322 }
323 rec = r.recovery()
324 expect(t, branchesOf(t, rec, a, j), writeDone, false, "origin took the branch push")
325 expect(t, decision(t, rec, "version", idA), writeFinish, false, "at the prepared head")
326 expect(t, decision(t, rec, "report", idA), writeFinish, false, "once the writes it reports are pushed")
327 if ap := a.Versions[0].Push(ctx, r.g); ap.Err != nil {
328 t.Fatal(ap.Err)
329 }
330 if w := a.Reports[0].Pending.Push(ctx, r.g); w.Push != rebase.Pushed {
331 t.Fatalf("a's report: %+v", w)
332 }
333 rec = r.recovery()
334 expect(t, decision(t, rec, "version", idA), writeDone, false, "holds v2")
335 expect(t, decision(t, rec, "report", idA), writeDone, false, "origin holds the report")
336
337 if push, _ := bc.Branches.Push(ctx, r.g); push != rebase.Pushed {
338 t.Fatal("b and c's branches were not pushed")
339 }
340 f.ownerPushes("c")
341 rec = r.recovery()
342 expect(t, branchesOf(t, rec, bc, j), writeDone, false, "or past them")
343 expect(t, decision(t, rec, "version", idB), writeFinish, false, "at the prepared head")
344 expect(t, decision(t, rec, "version", idC), writeStop, true, "its author moved it")
345 expect(t, decision(t, rec, "report", idB), writeStop, true, "did not end as this report says")
346 expect(t, decision(t, rec, "report", idC), writeStop, true, "did not end as this report says")
347 if rec.Settled {
348 t.Error("recovery is settled with b's version still to finish")
349 }
350}
351
352// A version stops for good on a withdrawal, an unready, a record moved
353// on by its author, and a deleted record, which is a terminal failure
354// that keeps its diagnostics: the report it cannot push is described. A
355// family whose writes stopped does not stop another's.
356func TestRecoveryStopsForGood(t *testing.T) {
357 f := newFixture(t, "")
358 f.readyAs(idA, "alice", "a", "main", "A's title")
359 f.readyAs(idB, "bob", "b", "main", "B's title")
360 f.readyAs(idC, "bob", "c", "b", "C's title")
361 f.readyAs(idE, "alice", "e", "main", "E's title")
362 f.moveMain()
363 r := newRestacker(t, f)
364 j := r.journal()
365 ctx := context.Background()
366 bc := of(t, j, idB)
367 if push, _ := bc.Branches.Push(ctx, r.g); push != rebase.Pushed {
368 t.Fatal("b and c's branches were not pushed")
369 }
370 f.setState(idB, change.Draft)
371 f.onOrigin("update-ref", "-d", change.Ref(rebase.Target, idC))
372 f.setState(idE, change.Withdrawn)
373
374 rec := r.recovery()
375 expect(t, decision(t, rec, "version", idB), writeStop, true, "is draft, not ready")
376 c := decision(t, rec, "version", idC)
377 expect(t, c, writeStop, true, "no longer holds a record")
378 cr := decision(t, rec, "report", idC)
379 expect(t, cr, writeStop, true, "the hook takes no report about a change it does not record")
380 if !c.Terminal || !cr.Terminal || !strings.Contains(cr.Why, "complete, on main at") {
381 t.Errorf("a deleted record is not a terminal failure with its diagnostics: %+v %+v", c, cr)
382 }
383 expect(t, branchesOf(t, rec, of(t, j, idE), j), writeStop, true, "was withdrawn")
384 expect(t, decision(t, rec, "version", idE), writeStop, true, "was withdrawn")
385 expect(t, decision(t, rec, "report", idE), writeStop, true, "branches were not pushed")
386 for _, d := range rec.Decisions {
387 if d.ID == idA && d.Action != writeFinish {
388 t.Errorf("an unrelated family's %s is %s: %s", d.Write, d.Action, d.Why)
389 }
390 }
391 expect(t, branchesOf(t, rec, of(t, j, idA), j), writeFinish, false, "has not moved")
392}
393
394// A branch push not yet made is finished only while main is where the
395// family was rebased onto: once main moves, it stops, and the next pass
396// prepares the family again. Once the branches are pushed, main moving on
397// does not stop the versions. A main that no longer descends from the tip
398// stops every write left.
399func TestRecoveryAndTheTarget(t *testing.T) {
400 f := newFixture(t, "")
401 f.readyAs(idA, "alice", "a", "main", "A's title")
402 f.readyAs(idB, "bob", "b", "main", "B's title")
403 f.moveMain()
404 r := newRestacker(t, f)
405 j := r.journal()
406 ctx := context.Background()
407 a := of(t, j, idA)
408 if push, _ := a.Branches.Push(ctx, r.g); push != rebase.Pushed {
409 t.Fatal("a's branches were not pushed")
410 }
411 tip := f.at("refs/heads/main")
412 f.git("checkout", "--quiet", "main")
413 f.commit("main moves on again", "again.txt")
414 f.git("push", "--quiet", "origin", "main")
415
416 rec := r.recovery()
417 expect(t, decision(t, rec, "version", idA), writeFinish, false, "at the prepared head")
418 expect(t, branchesOf(t, rec, of(t, j, idB), j), writeStop, true, "before the branches were pushed")
419 expect(t, decision(t, rec, "version", idB), writeStop, true, "its branch push stopped")
420
421 f.onOrigin("update-ref", "refs/heads/main", tip+"~1")
422 rec = r.recovery()
423 expect(t, decision(t, rec, "version", idA), writeStop, true, "no longer descends")
424 expect(t, decision(t, rec, "report", idA), writeStop, true, "did not end as this report says")
425}
426
427// A related request that might still land holds the branch push, and
428// pauses the versions once the branches are pushed. Neither stop is
429// final. A request is related by any version head, the prepared heads
430// included, whatever its name.
431func TestARequestHoldsRecovery(t *testing.T) {
432 f := newFixture(t, "")
433 was := f.readyAs(idA, "alice", "a", "main", "A's title")
434 f.moveMain()
435 r := newRestacker(t, f)
436 j := r.journal()
437 a := of(t, j, idA)
438 request := rebase.RequestPrefix + "zz-any-name"
439
440 f.onOrigin("update-ref", request, was)
441 rec := r.recovery()
442 expect(t, branchesOf(t, rec, a, j), writeStop, false, "request zz-any-name might still land")
443 f.onOrigin("update-ref", "-d", request)
444 if push, _ := a.Branches.Push(context.Background(), r.g); push != rebase.Pushed {
445 t.Fatal("a's branches were not pushed")
446 }
447 f.onOrigin("update-ref", request, a.Versions[0].Head)
448 rec = r.recovery()
449 expect(t, decision(t, rec, "version", idA), writeStop, false, "paused: request zz-any-name might still land")
450 f.onOrigin("update-ref", "-d", request)
451 rec = r.recovery()
452 expect(t, decision(t, rec, "version", idA), writeFinish, false, "at the prepared head")
453}
454
455// Nothing is inferred from a journal that is lost, another's, or not in
456// its form. A lost journal leaves the change whose branch the pass moved
457// held by the planner, its branch not at its recorded head. A journal
458// another principal wrote, or one with a field it does not have, is
459// refused, and nothing in it is decided.
460func TestNothingIsInferredFromALostOrForeignJournal(t *testing.T) {
461 f := newFixture(t, "")
462 f.readyAs(idA, "alice", "a", "main", "A's title")
463 f.moveMain()
464 r := newRestacker(t, f)
465 j := r.journal()
466 path := filepath.Join(r.c.state, journalFile)
467 data, err := os.ReadFile(path)
468 if err != nil {
469 t.Fatal(err)
470 }
471
472 for what, form := range map[string]string{
473 "another principal's": strings.Replace(string(data), `"principal": "restacker"`, `"principal": "requester"`, 1),
474 "an unknown field": strings.Replace(string(data), `"schema"`, `"pushed": true, "schema"`, 1),
475 "a field twice": strings.Replace(string(data), `"target": "main",`, `"target": "main", "target": "main",`, 1),
476 "another version": strings.Replace(string(data), journalSchema, "valley-restack-journal/v2", 1),
477 "cut short": string(data[:len(data)/2]),
478 } {
479 if form == string(data) {
480 t.Fatalf("%s: the edit changed nothing", what)
481 }
482 if err := os.WriteFile(path, []byte(form), 0o600); err != nil {
483 t.Fatal(err)
484 }
485 p, _ := r.plan()
486 if p.Recovery == nil || p.Recovery.Error == "" || len(p.Recovery.Decisions) != 0 {
487 t.Errorf("%s journal was decided: %+v", what, p.Recovery)
488 }
489 }
490
491 if push, _ := of(t, j, idA).Branches.Push(context.Background(), r.g); push != rebase.Pushed {
492 t.Fatal("a's branches were not pushed")
493 }
494 if err := os.Remove(path); err != nil {
495 t.Fatal(err)
496 }
497 p, _ := r.plan()
498 if p.Recovery != nil {
499 t.Errorf("a lost journal was decided: %+v", p.Recovery)
500 }
501 if len(p.Families) != 1 || p.Families[0].Action != hold || !strings.Contains(strings.Join(p.Families[0].Reasons, "\n"), "records the head") {
502 t.Errorf("the change whose branch moved with no journal is planned as %+v", p.Families)
503 }
504}
505
506// --report-only decides a journal holding a branch push, versions and
507// reports still to make, and pushes none of them: no ref on origin moves,
508// and the journal is left as it was. The decisions are in the plan.
509func TestReportOnlyRecoveryPushesNothing(t *testing.T) {
510 f := newFixture(t, "")
511 f.readyAs(idA, "alice", "a", "main", "A's title")
512 f.readyAs(idB, "bob", "b", "main", "B's title")
513 f.moveMain()
514 r := newRestacker(t, f)
515 j := r.journal()
516 if push, _ := of(t, j, idB).Branches.Push(context.Background(), r.g); push != rebase.Pushed {
517 t.Fatal("b's branches were not pushed")
518 }
519 path := filepath.Join(r.c.state, journalFile)
520 journal, err := os.ReadFile(path)
521 if err != nil {
522 t.Fatal(err)
523 }
524 before := f.refs()
525
526 var out, errOut bytes.Buffer
527 if err := once(context.Background(), reportOnly(t, r.c, "--json"), &out, &errOut); err != nil {
528 t.Fatalf("once: %v\n%s", err, errOut.String())
529 }
530 if after := f.refs(); after != before {
531 t.Errorf("a --report-only pass moved something on origin:\n%s\nnow:\n%s", before, after)
532 }
533 if now, _ := os.ReadFile(path); !bytes.Equal(now, journal) {
534 t.Error("a --report-only pass changed the journal")
535 }
536 var p Plan
537 if err := json.Unmarshal(out.Bytes(), &p); err != nil {
538 t.Fatal(err)
539 }
540 if p.Recovery == nil || len(p.Recovery.Decisions) == 0 || p.Recovery.Decisions[0].Operation != j.Families[0].Operation {
541 t.Fatalf("the plan holds no recovery of the journal: %s", out.String())
542 }
543 finish := map[string]int{}
544 for _, d := range p.Recovery.Decisions {
545 if d.Action == writeFinish {
546 finish[d.Write]++
547 }
548 }
549 if finish["branches"] != 1 || finish["version"] != 2 || finish["report"] != 2 {
550 t.Errorf("recovery would finish %v, and pushed none", finish)
551 }
552}
553
554// reportOnly is the arguments of a --report-only pass with c's
555// configuration and a stand-in for cue (fakePolicy).
556func reportOnly(t *testing.T, c config, more ...string) []string {
557 t.Helper()
558 schema, floor := fakePolicy(t)
559 return append([]string{"--report-only", "--repo", c.repo, "--state", c.state, "--principal", c.principal,
560 "--commit-name", c.commitName, "--commit-email", c.commitEmail, "--schema", schema, "--instance", floor}, more...)
561}
562
563// fakePolicy puts a stand-in for cue on the path, which composes every
564// policy to a cap of 64, and returns a schema and a floor for it. It keeps
565// the process's environment as it was, since a pass controls its own.
566func fakePolicy(t *testing.T) (schema, floor string) {
567 t.Helper()
568 return fakePolicyCap(t, 64)
569}
570
571// fakePolicyCap is fakePolicy with the cap given.
572func fakePolicyCap(t *testing.T, cap int) (schema, floor string) {
573 t.Helper()
574 keepEnvironment(t)
575 dir := t.TempDir()
576 bin := filepath.Join(dir, "bin")
577 if err := os.MkdirAll(bin, 0o755); err != nil {
578 t.Fatal(err)
579 }
580 cue := fmt.Sprintf("#!/bin/sh\necho '{\"checks\": {}, \"restack\": {\"maxAutomaticVersions\": %d}}'\n", cap)
581 if err := os.WriteFile(filepath.Join(bin, "cue"), []byte(cue), 0o755); err != nil {
582 t.Fatal(err)
583 }
584 os.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
585 floor = filepath.Join(dir, "floor")
586 schema = filepath.Join(dir, "schema.cue")
587 if err := os.MkdirAll(floor, 0o755); err != nil {
588 t.Fatal(err)
589 }
590 for _, path := range []string{schema, filepath.Join(floor, "floor.cue")} {
591 if err := os.WriteFile(path, []byte("package verification\n"), 0o644); err != nil {
592 t.Fatal(err)
593 }
594 }
595 return schema, floor
596}
597
598// keepEnvironment puts the process's environment back as it was once the
599// test ends.
600func keepEnvironment(t *testing.T) {
601 t.Helper()
602 was := os.Environ()
603 t.Cleanup(func() {
604 os.Clearenv()
605 for _, kv := range was {
606 name, value, _ := strings.Cut(kv, "=")
607 os.Setenv(name, value)
608 }
609 })
610}
611
612// A journal in its form whose writes do not agree with each other is
613// refused, and nothing in it is decided: a version that is null, a family
614// that would restack with one change's version left out and its reports
615// kept, a report that says a version was published other than as the
616// family adds it, a report whose result is not the family's, two
617// families that share a change, a branch push accepted that the family
618// does not have, a version accepted before its branch push or twice, and
619// a replacement kept before the branch push is accepted. Planning with
620// any of them is an error of recovery, never a crash.
621func TestAJournalWhoseWritesDisagreeIsRefused(t *testing.T) {
622 f := newFixture(t, "")
623 f.readyAs(idB, "bob", "b", "main", "B's title")
624 f.readyAs(idC, "bob", "c", "b", "C's title")
625 f.readyAs(idE, "alice", "e", "main", "E's title")
626 f.plainBranch("e-plain", "e")
627 f.moveMain()
628 r := newRestacker(t, f)
629 r.journal()
630 path := filepath.Join(r.c.state, journalFile)
631 kept, err := os.ReadFile(path)
632 if err != nil {
633 t.Fatal(err)
634 }
635 family := func(j *Journal, id string) *JournalFamily {
636 for i := range j.Families {
637 if j.Families[i].Observed.Layers[0].ID == id {
638 return &j.Families[i]
639 }
640 }
641 t.Fatalf("the journal has no family on %s", id)
642 return nil
643 }
644 other := change.HeadPrefix + strings.Repeat("0", 40)
645
646 for _, c := range []struct {
647 what, refused string
648 edit func(j *Journal)
649 }{
650 {"a null version", "holds an empty version", func(j *Journal) { family(j, idB).Versions[1] = nil }},
651 {"a change's version left out", "adds a version to 1 of them", func(j *Journal) {
652 bc := family(j, idB)
653 bc.Versions = bc.Versions[:1]
654 }},
655 {"a report naming another record", "says " + idC + " was published as other than v2", func(j *Journal) {
656 family(j, idB).Reports[0].Pending.Report.Layers[1].Published.Record = &other
657 }},
658 {"a report of another result", "says blocked, and the family's result is conflict", func(j *Journal) {
659 family(j, idE).Observed.Result = change.RestackConflict
660 }},
661 {"two families on one change", "share the change " + idE, func(j *Journal) {
662 j.Families = append(j.Families, *family(j, idE))
663 }},
664 {"a branch push accepted that the family does not have", "origin took a branch push it does not have", func(j *Journal) {
665 family(j, idE).Accepted.Branches = true
666 }},
667 {"a version accepted before the branch push", "is not known to have taken its branch push", func(j *Journal) {
668 family(j, idB).Accepted.Versions = []string{idB}
669 }},
670 {"a version accepted twice", "not lower layers first, once each", func(j *Journal) {
671 family(j, idB).Accepted = Accepted{Branches: true, Versions: []string{idB, idB}}
672 }},
673 {"a replacement before the branch push is accepted", "is not known to have taken its branch push", func(j *Journal) {
674 bc := family(j, idB)
675 bc.Replacements = append(bc.Replacements, bc.Reports[0])
676 }},
677 } {
678 var j Journal
679 if err := strictly(kept, &j); err != nil {
680 t.Fatal(err)
681 }
682 c.edit(&j)
683 data, err := json.MarshalIndent(&j, "", " ")
684 if err != nil {
685 t.Fatalf("%s: %v", c.what, err)
686 }
687 if err := os.WriteFile(path, data, 0o600); err != nil {
688 t.Fatal(err)
689 }
690 p, _ := r.plan()
691 if p.Recovery == nil || !strings.Contains(p.Recovery.Error, c.refused) || len(p.Recovery.Decisions) != 0 {
692 t.Errorf("a journal with %s was decided: %+v", c.what, p.Recovery)
693 }
694 }
695}
696
697// A journal that would not read back as written is not kept: nothing is
698// kept for it in the scratch repository, and the journal before it stays.
699// JSON holds only UTF-8, so a reason in Latin-1 is such a journal.
700func TestAJournalThatWouldNotReadBackIsNotKept(t *testing.T) {
701 f := newFixture(t, "")
702 f.readyAs(idE, "alice", "e", "main", "E's title")
703 f.plainBranch("e-plain", "e")
704 f.moveMain()
705 r := newRestacker(t, f)
706 j := r.journal()
707 path := filepath.Join(r.c.state, journalFile)
708 before, err := os.ReadFile(path)
709 if err != nil {
710 t.Fatal(err)
711 }
712 ctx := context.Background()
713 if err := letGo(ctx, r.g, nil); err != nil {
714 t.Fatal(err)
715 }
716 j.Families[0].Observed.Reasons = append(j.Families[0].Observed.Reasons, "a reason in Latin-1: caf\xe9")
717 if err := keep(ctx, r.g, r.c.state, j); err == nil || !strings.Contains(err.Error(), "would not read back") {
718 t.Fatalf("a journal that would not read back was kept: %v", err)
719 }
720 if now, _ := os.ReadFile(path); !bytes.Equal(now, before) {
721 t.Error("the journal before it was replaced")
722 }
723 if left := gitOutT(t, r.g, "for-each-ref", retainPrefix); left != "" {
724 t.Errorf("objects were kept for a journal that was not:\n%s", left)
725 }
726}
727
728// A family of more than 64 changes whose top version was not added gets a
729// replacement for each change, saying partial, and each keeps only its
730// own layer. A change whose version was added is then named with its
731// version alone, and the change whose version was not is among the
732// layers its replacement leaves out. The journal takes every such
733// replacement, and refuses one that says partial while naming every
734// change of the family with its version.
735func TestATruncatedPartialReportIsKept(t *testing.T) {
736 const n = 65
737 oid := func(kind, i int) string { return fmt.Sprintf("%02x%038x", kind, i) }
738 tip := oid(9, 0)
739 f := JournalFamily{
740 Operation: "op-1", Tip: tip, Evidence: strings.Repeat("0", 16),
741 Observed: Observation{Action: restack, Result: change.RestackComplete, Requests: []RequestPlan{}, Reasons: []string{},
742 Notes: []string{}, Conflicts: []string{}},
743 Branches: &rebase.PendingBranches{Tip: tip}, Versions: []*rebase.PendingVersion{}, Reports: []JournalReport{},
744 Replacements: []JournalReport{}, Accepted: Accepted{Branches: true, Versions: []string{}},
745 }
746 for i := 0; i < n; i++ {
747 branch := fmt.Sprintf("stack/%02d", i)
748 l := ObservedLayer{Name: id(i)[:8], ID: id(i), Branch: branch, BranchTip: oid(1, i), Record: oid(2, i), Version: 1, Head: oid(1, i), State: "ready"}
749 if i > 0 {
750 l.Below = id(i - 1)[:8]
751 }
752 f.Observed.Layers = append(f.Observed.Layers, l)
753 f.Branches.Updates = append(f.Branches.Updates, rebase.BranchUpdate{Branch: branch, Old: oid(1, i), New: oid(3, i)})
754 f.Versions = append(f.Versions, restackVersion(t, id(i), branch, oid(1, i), oid(2, i), oid(4, i), oid(3, i)))
755 if i < n-1 {
756 f.Accepted.Versions = append(f.Accepted.Versions, id(i))
757 }
758 }
759 o, published := whatHappened(f, func(change string) Decision {
760 if change == id(n-1) {
761 return Decision{Action: writeStop, Final: true, Why: "its author moved it"}
762 }
763 return Decision{Action: writeDone}
764 })
765 for i, l := range o.Layers {
766 rep, omitted, err := bound(fullReport(f.Operation, f.Tip, l.ID, o, published), o.Digest())
767 if err != nil {
768 t.Fatal(err)
769 }
770 f.Replacements = append(f.Replacements, JournalReport{
771 Pending: &rebase.PendingReport{ID: l.ID, Ref: rebase.RestackPrefix + l.ID, Commit: oid(5, i), Report: rep},
772 Omitted: omitted,
773 })
774 }
775 own := f.Replacements[0].Pending.Report
776 if own.Result != change.RestackPartial || len(own.Layers) != 1 || own.Layers[0].Published == nil || own.Layers[0].Published.Version == nil {
777 t.Fatalf("the first change's replacement is not partial with its own version alone: %+v", own)
778 }
779 j := &Journal{Schema: journalSchema, Repository: "origin", Target: rebase.Target, Principal: "restacker", Families: []JournalFamily{f}}
780 b := binding{Repository: j.Repository, Target: j.Target, Principal: j.Principal}
781 if err := j.check(b); err != nil {
782 t.Fatalf("the journal refuses the truncated replacements: %v", err)
783 }
784
785 // The same family of two changes, both versions added: a replacement
786 // that names both with their versions and says partial is refused.
787 small := f
788 small.Observed.Layers = f.Observed.Layers[:2]
789 small.Branches = &rebase.PendingBranches{Tip: tip, Updates: f.Branches.Updates[:2]}
790 small.Versions = f.Versions[:2]
791 small.Accepted = Accepted{Branches: true, Versions: []string{id(0), id(1)}}
792 whole := fullReport(f.Operation, f.Tip, id(0), small.Observed, published)
793 whole.Result = change.RestackPartial
794 small.Replacements = []JournalReport{{Pending: &rebase.PendingReport{ID: id(0), Ref: rebase.RestackPrefix + id(0), Commit: oid(5, 0), Report: whole}, Omitted: []string{}}}
795 j.Families = []JournalFamily{small}
796 if err := j.check(b); err == nil || !strings.Contains(err.Error(), "says partial, and names every change of the family with its version") {
797 t.Errorf("a replacement that says partial while naming every version is taken: %v", err)
798 }
799}
800
801// restackVersion is a restack's version 2 of the change, as the journal
802// keeps it: leased on the record commit old, whose version 1 is at head,
803// and adding the record commit commit, at the prepared head next.
804func restackVersion(t *testing.T, id, branch, head, old, commit, next string) *rebase.PendingVersion {
805 t.Helper()
806 rec, err := json.Marshal(&change.Record{
807 Schema: change.Schema, ChangeID: id, Target: rebase.Target, Owner: "alice", State: change.Ready, Seq: 2, Active: 2,
808 Versions: []change.Version{
809 {N: 1, Head: change.HeadPrefix + head, Title: "a title", Branch: branch, Uploader: "alice"},
810 {N: 2, Head: change.HeadPrefix + next, Title: "a title", Branch: branch, Uploader: "restacker"},
811 },
812 })
813 if err != nil {
814 t.Fatal(err)
815 }
816 form := fmt.Sprintf(`{"schema":"valley-pending-version/v1","mode":"restack","change_id":%q,"handle":%q,"ref":%q,"old":%q,"commit":%q,"version":2,"head":%q,"branch":%q,"record":%s}`,
817 id, id[:8], change.Ref(rebase.Target, id), old, commit, next, branch, rec)
818 var v rebase.PendingVersion
819 if err := json.Unmarshal([]byte(form), &v); err != nil {
820 t.Fatal(err)
821 }
822 return &v
823}