gunk-dev/the-valley

journal_test.go

source122cb02201d1main's published tip history
25.0 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 want := j.objects()
266 got := strings.Fields(gitOutT(t, r.g, "for-each-ref", "--format=%(objectname)", retainPrefix+j.Operation+"/"))
267 sort.Strings(want)
268 sort.Strings(got)
269 if !reflect.DeepEqual(got, want) {
270 t.Errorf("the scratch repository keeps %v, and the journal's writes push %v", got, want)
271 }
272 if left := gitOutT(t, r.g, "for-each-ref", "refs/valley-rebase/"); left != "" {
273 t.Errorf("the prepared heads' own refs were not let go:\n%s", left)
274 }
275}
276
277func gitOutT(t *testing.T, g rebase.Git, args ...string) string {
278 t.Helper()
279 out, err := gitOut(context.Background(), g, args...)
280 if err != nil {
281 t.Fatal(err)
282 }
283 return strings.TrimSpace(out)
284}
285
286// Recovery follows each write as the pass would make it. Before any push,
287// every write is still valid to finish. Once a family's branches are
288// pushed, they are done, and its versions are still to finish; once a
289// version and a report are pushed, they are done too. An author who
290// pushes past a prepared head stops that change's version for good, and
291// with it each report that says the version was added, while the version
292// below it is still finished.
293func TestRecoveryFollowsEachWrite(t *testing.T) {
294 f := newFixture(t, "")
295 f.readyAs(idA, "alice", "a", "main", "A's title")
296 f.readyAs(idB, "bob", "b", "main", "B's title")
297 f.readyAs(idC, "bob", "c", "b", "C's title")
298 f.moveMain()
299 r := newRestacker(t, f)
300 j := r.journal()
301 a, bc := of(t, j, idA), of(t, j, idB)
302 ctx := context.Background()
303
304 rec := r.recovery()
305 for _, d := range rec.Decisions {
306 if d.Action != writeFinish {
307 t.Errorf("before any push, %s %s is %s: %s", d.Write, d.ID, d.Action, d.Why)
308 }
309 }
310 if rec.Settled || len(rec.Decisions) != 8 {
311 t.Errorf("recovery decided %d writes, settled %v", len(rec.Decisions), rec.Settled)
312 }
313
314 if push, _ := a.Branches.Push(ctx, r.g); push != rebase.Pushed {
315 t.Fatal("a's branches were not pushed")
316 }
317 rec = r.recovery()
318 expect(t, branchesOf(t, rec, a, j), writeDone, false, "origin took the branch push")
319 expect(t, decision(t, rec, "version", idA), writeFinish, false, "at the prepared head")
320 expect(t, decision(t, rec, "report", idA), writeFinish, false, "once the writes it reports are pushed")
321 if ap := a.Versions[0].Push(ctx, r.g); ap.Err != nil {
322 t.Fatal(ap.Err)
323 }
324 if w := a.Reports[0].Pending.Push(ctx, r.g); w.Push != rebase.Pushed {
325 t.Fatalf("a's report: %+v", w)
326 }
327 rec = r.recovery()
328 expect(t, decision(t, rec, "version", idA), writeDone, false, "holds v2")
329 expect(t, decision(t, rec, "report", idA), writeDone, false, "origin holds the report")
330
331 if push, _ := bc.Branches.Push(ctx, r.g); push != rebase.Pushed {
332 t.Fatal("b and c's branches were not pushed")
333 }
334 f.ownerPushes("c")
335 rec = r.recovery()
336 expect(t, branchesOf(t, rec, bc, j), writeDone, false, "or past them")
337 expect(t, decision(t, rec, "version", idB), writeFinish, false, "at the prepared head")
338 expect(t, decision(t, rec, "version", idC), writeStop, true, "its author moved it")
339 expect(t, decision(t, rec, "report", idB), writeStop, true, "did not end as this report says")
340 expect(t, decision(t, rec, "report", idC), writeStop, true, "did not end as this report says")
341 if rec.Settled {
342 t.Error("recovery is settled with b's version still to finish")
343 }
344}
345
346// A version stops for good on a withdrawal, an unready, a record moved
347// on by its author, and a deleted record, which is a terminal failure
348// that keeps its diagnostics: the report it cannot push is described. A
349// family whose writes stopped does not stop another's.
350func TestRecoveryStopsForGood(t *testing.T) {
351 f := newFixture(t, "")
352 f.readyAs(idA, "alice", "a", "main", "A's title")
353 f.readyAs(idB, "bob", "b", "main", "B's title")
354 f.readyAs(idC, "bob", "c", "b", "C's title")
355 f.readyAs(idE, "alice", "e", "main", "E's title")
356 f.moveMain()
357 r := newRestacker(t, f)
358 j := r.journal()
359 ctx := context.Background()
360 bc := of(t, j, idB)
361 if push, _ := bc.Branches.Push(ctx, r.g); push != rebase.Pushed {
362 t.Fatal("b and c's branches were not pushed")
363 }
364 f.setState(idB, change.Draft)
365 f.onOrigin("update-ref", "-d", change.Ref(rebase.Target, idC))
366 f.setState(idE, change.Withdrawn)
367
368 rec := r.recovery()
369 expect(t, decision(t, rec, "version", idB), writeStop, true, "is draft, not ready")
370 c := decision(t, rec, "version", idC)
371 expect(t, c, writeStop, true, "no longer holds a record")
372 cr := decision(t, rec, "report", idC)
373 expect(t, cr, writeStop, true, "the hook takes no report about a change it does not record")
374 if !c.Terminal || !cr.Terminal || !strings.Contains(cr.Why, "complete, on main at") {
375 t.Errorf("a deleted record is not a terminal failure with its diagnostics: %+v %+v", c, cr)
376 }
377 expect(t, branchesOf(t, rec, of(t, j, idE), j), writeStop, true, "was withdrawn")
378 expect(t, decision(t, rec, "version", idE), writeStop, true, "was withdrawn")
379 expect(t, decision(t, rec, "report", idE), writeStop, true, "branches were not pushed")
380 for _, d := range rec.Decisions {
381 if d.ID == idA && d.Action != writeFinish {
382 t.Errorf("an unrelated family's %s is %s: %s", d.Write, d.Action, d.Why)
383 }
384 }
385 expect(t, branchesOf(t, rec, of(t, j, idA), j), writeFinish, false, "has not moved")
386}
387
388// A branch push not yet made is finished only while main is where the
389// family was rebased onto: once main moves, it stops, and the next pass
390// prepares the family again. Once the branches are pushed, main moving on
391// does not stop the versions. A main that no longer descends from the tip
392// stops every write left.
393func TestRecoveryAndTheTarget(t *testing.T) {
394 f := newFixture(t, "")
395 f.readyAs(idA, "alice", "a", "main", "A's title")
396 f.readyAs(idB, "bob", "b", "main", "B's title")
397 f.moveMain()
398 r := newRestacker(t, f)
399 j := r.journal()
400 ctx := context.Background()
401 a := of(t, j, idA)
402 if push, _ := a.Branches.Push(ctx, r.g); push != rebase.Pushed {
403 t.Fatal("a's branches were not pushed")
404 }
405 tip := f.at("refs/heads/main")
406 f.git("checkout", "--quiet", "main")
407 f.commit("main moves on again", "again.txt")
408 f.git("push", "--quiet", "origin", "main")
409
410 rec := r.recovery()
411 expect(t, decision(t, rec, "version", idA), writeFinish, false, "at the prepared head")
412 expect(t, branchesOf(t, rec, of(t, j, idB), j), writeStop, true, "before the branches were pushed")
413 expect(t, decision(t, rec, "version", idB), writeStop, true, "its branch push stopped")
414
415 f.onOrigin("update-ref", "refs/heads/main", tip+"~1")
416 rec = r.recovery()
417 expect(t, decision(t, rec, "version", idA), writeStop, true, "no longer descends")
418 expect(t, decision(t, rec, "report", idA), writeStop, true, "did not end as this report says")
419}
420
421// A related request that might still land holds the branch push, and
422// pauses the versions once the branches are pushed. Neither stop is
423// final. A request is related by any version head, the prepared heads
424// included, whatever its name.
425func TestARequestHoldsRecovery(t *testing.T) {
426 f := newFixture(t, "")
427 was := f.readyAs(idA, "alice", "a", "main", "A's title")
428 f.moveMain()
429 r := newRestacker(t, f)
430 j := r.journal()
431 a := of(t, j, idA)
432 request := rebase.RequestPrefix + "zz-any-name"
433
434 f.onOrigin("update-ref", request, was)
435 rec := r.recovery()
436 expect(t, branchesOf(t, rec, a, j), writeStop, false, "request zz-any-name might still land")
437 f.onOrigin("update-ref", "-d", request)
438 if push, _ := a.Branches.Push(context.Background(), r.g); push != rebase.Pushed {
439 t.Fatal("a's branches were not pushed")
440 }
441 f.onOrigin("update-ref", request, a.Versions[0].Head)
442 rec = r.recovery()
443 expect(t, decision(t, rec, "version", idA), writeStop, false, "paused: request zz-any-name might still land")
444 f.onOrigin("update-ref", "-d", request)
445 rec = r.recovery()
446 expect(t, decision(t, rec, "version", idA), writeFinish, false, "at the prepared head")
447}
448
449// Nothing is inferred from a journal that is lost, another's, or not in
450// its form. A lost journal leaves the change whose branch the pass moved
451// held by the planner, its branch not at its recorded head. A journal
452// another principal wrote, or one with a field it does not have, is
453// refused, and nothing in it is decided.
454func TestNothingIsInferredFromALostOrForeignJournal(t *testing.T) {
455 f := newFixture(t, "")
456 f.readyAs(idA, "alice", "a", "main", "A's title")
457 f.moveMain()
458 r := newRestacker(t, f)
459 j := r.journal()
460 path := filepath.Join(r.c.state, journalFile)
461 data, err := os.ReadFile(path)
462 if err != nil {
463 t.Fatal(err)
464 }
465
466 for what, form := range map[string]string{
467 "another principal's": strings.Replace(string(data), `"principal": "restacker"`, `"principal": "requester"`, 1),
468 "an unknown field": strings.Replace(string(data), `"schema"`, `"pushed": true, "schema"`, 1),
469 "a field twice": strings.Replace(string(data), `"target": "main",`, `"target": "main", "target": "main",`, 1),
470 "another version": strings.Replace(string(data), journalSchema, "valley-restack-journal/v2", 1),
471 "cut short": string(data[:len(data)/2]),
472 } {
473 if form == string(data) {
474 t.Fatalf("%s: the edit changed nothing", what)
475 }
476 if err := os.WriteFile(path, []byte(form), 0o600); err != nil {
477 t.Fatal(err)
478 }
479 p, _ := r.plan()
480 if p.Recovery == nil || p.Recovery.Error == "" || len(p.Recovery.Decisions) != 0 {
481 t.Errorf("%s journal was decided: %+v", what, p.Recovery)
482 }
483 }
484
485 if push, _ := of(t, j, idA).Branches.Push(context.Background(), r.g); push != rebase.Pushed {
486 t.Fatal("a's branches were not pushed")
487 }
488 if err := os.Remove(path); err != nil {
489 t.Fatal(err)
490 }
491 p, _ := r.plan()
492 if p.Recovery != nil {
493 t.Errorf("a lost journal was decided: %+v", p.Recovery)
494 }
495 if len(p.Families) != 1 || p.Families[0].Action != hold || !strings.Contains(strings.Join(p.Families[0].Reasons, "\n"), "records the head") {
496 t.Errorf("the change whose branch moved with no journal is planned as %+v", p.Families)
497 }
498}
499
500// --report-only decides a journal holding a branch push, versions and
501// reports still to make, and pushes none of them: no ref on origin moves,
502// and the journal is left as it was. The decisions are in the plan.
503func TestReportOnlyRecoveryPushesNothing(t *testing.T) {
504 f := newFixture(t, "")
505 f.readyAs(idA, "alice", "a", "main", "A's title")
506 f.readyAs(idB, "bob", "b", "main", "B's title")
507 f.moveMain()
508 r := newRestacker(t, f)
509 j := r.journal()
510 if push, _ := of(t, j, idB).Branches.Push(context.Background(), r.g); push != rebase.Pushed {
511 t.Fatal("b's branches were not pushed")
512 }
513 path := filepath.Join(r.c.state, journalFile)
514 journal, err := os.ReadFile(path)
515 if err != nil {
516 t.Fatal(err)
517 }
518 before := f.refs()
519
520 var out, errOut bytes.Buffer
521 if err := once(context.Background(), reportOnly(t, r.c, "--json"), &out, &errOut); err != nil {
522 t.Fatalf("once: %v\n%s", err, errOut.String())
523 }
524 if after := f.refs(); after != before {
525 t.Errorf("a --report-only pass moved something on origin:\n%s\nnow:\n%s", before, after)
526 }
527 if now, _ := os.ReadFile(path); !bytes.Equal(now, journal) {
528 t.Error("a --report-only pass changed the journal")
529 }
530 var p Plan
531 if err := json.Unmarshal(out.Bytes(), &p); err != nil {
532 t.Fatal(err)
533 }
534 if p.Recovery == nil || p.Recovery.Operation != j.Operation {
535 t.Fatalf("the plan holds no recovery of the journal: %s", out.String())
536 }
537 finish := map[string]int{}
538 for _, d := range p.Recovery.Decisions {
539 if d.Action == writeFinish {
540 finish[d.Write]++
541 }
542 }
543 if finish["branches"] != 1 || finish["version"] != 2 || finish["report"] != 2 {
544 t.Errorf("recovery would finish %v, and pushed none", finish)
545 }
546}
547
548// reportOnly is the arguments of a --report-only pass with c's
549// configuration and a stand-in for cue (fakePolicy).
550func reportOnly(t *testing.T, c config, more ...string) []string {
551 t.Helper()
552 schema, floor := fakePolicy(t)
553 return append([]string{"--report-only", "--repo", c.repo, "--state", c.state, "--principal", c.principal,
554 "--commit-name", c.commitName, "--commit-email", c.commitEmail, "--schema", schema, "--instance", floor}, more...)
555}
556
557// fakePolicy puts a stand-in for cue on the path, which composes every
558// policy to a cap of 64, and returns a schema and a floor for it. It keeps
559// the process's environment as it was, since a pass controls its own.
560func fakePolicy(t *testing.T) (schema, floor string) {
561 t.Helper()
562 return fakePolicyCap(t, 64)
563}
564
565// fakePolicyCap is fakePolicy with the cap given.
566func fakePolicyCap(t *testing.T, cap int) (schema, floor string) {
567 t.Helper()
568 keepEnvironment(t)
569 dir := t.TempDir()
570 bin := filepath.Join(dir, "bin")
571 if err := os.MkdirAll(bin, 0o755); err != nil {
572 t.Fatal(err)
573 }
574 cue := fmt.Sprintf("#!/bin/sh\necho '{\"checks\": {}, \"restack\": {\"maxAutomaticVersions\": %d}}'\n", cap)
575 if err := os.WriteFile(filepath.Join(bin, "cue"), []byte(cue), 0o755); err != nil {
576 t.Fatal(err)
577 }
578 os.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
579 floor = filepath.Join(dir, "floor")
580 schema = filepath.Join(dir, "schema.cue")
581 if err := os.MkdirAll(floor, 0o755); err != nil {
582 t.Fatal(err)
583 }
584 for _, path := range []string{schema, filepath.Join(floor, "floor.cue")} {
585 if err := os.WriteFile(path, []byte("package verification\n"), 0o644); err != nil {
586 t.Fatal(err)
587 }
588 }
589 return schema, floor
590}
591
592// keepEnvironment puts the process's environment back as it was once the
593// test ends.
594func keepEnvironment(t *testing.T) {
595 t.Helper()
596 was := os.Environ()
597 t.Cleanup(func() {
598 os.Clearenv()
599 for _, kv := range was {
600 name, value, _ := strings.Cut(kv, "=")
601 os.Setenv(name, value)
602 }
603 })
604}
605
606// A journal in its form whose writes do not agree with each other is
607// refused, and nothing in it is decided: a version that is null, a family
608// that would restack with one change's version left out and its reports
609// kept, a report that says a version was published other than as the
610// family adds it, and a report whose result is not the family's. Planning
611// with any of them is an error of recovery, never a crash.
612func TestAJournalWhoseWritesDisagreeIsRefused(t *testing.T) {
613 f := newFixture(t, "")
614 f.readyAs(idB, "bob", "b", "main", "B's title")
615 f.readyAs(idC, "bob", "c", "b", "C's title")
616 f.readyAs(idE, "alice", "e", "main", "E's title")
617 f.plainBranch("e-plain", "e")
618 f.moveMain()
619 r := newRestacker(t, f)
620 r.journal()
621 path := filepath.Join(r.c.state, journalFile)
622 kept, err := os.ReadFile(path)
623 if err != nil {
624 t.Fatal(err)
625 }
626 family := func(j *Journal, id string) *JournalFamily {
627 for i := range j.Families {
628 if j.Families[i].Observed.Layers[0].ID == id {
629 return &j.Families[i]
630 }
631 }
632 t.Fatalf("the journal has no family on %s", id)
633 return nil
634 }
635 other := change.HeadPrefix + strings.Repeat("0", 40)
636
637 for _, c := range []struct {
638 what, refused string
639 edit func(j *Journal)
640 }{
641 {"a null version", "holds an empty version", func(j *Journal) { family(j, idB).Versions[1] = nil }},
642 {"a change's version left out", "adds a version to 1 of them", func(j *Journal) {
643 bc := family(j, idB)
644 bc.Versions = bc.Versions[:1]
645 }},
646 {"a report naming another record", "says " + idC + " was published as other than v2", func(j *Journal) {
647 family(j, idB).Reports[0].Pending.Report.Layers[1].Published.Record = &other
648 }},
649 {"a report of another result", "says blocked, and the family's result is conflict", func(j *Journal) {
650 family(j, idE).Observed.Result = change.RestackConflict
651 }},
652 } {
653 var j Journal
654 if err := strictly(kept, &j); err != nil {
655 t.Fatal(err)
656 }
657 c.edit(&j)
658 data, err := json.MarshalIndent(&j, "", " ")
659 if err != nil {
660 t.Fatalf("%s: %v", c.what, err)
661 }
662 if err := os.WriteFile(path, data, 0o600); err != nil {
663 t.Fatal(err)
664 }
665 p, _ := r.plan()
666 if p.Recovery == nil || !strings.Contains(p.Recovery.Error, c.refused) || len(p.Recovery.Decisions) != 0 {
667 t.Errorf("a journal with %s was decided: %+v", c.what, p.Recovery)
668 }
669 }
670}
671
672// A journal that would not read back as written is not kept: nothing is
673// kept for it in the scratch repository, and the journal before it stays.
674// JSON holds only UTF-8, so a reason in Latin-1 is such a journal.
675func TestAJournalThatWouldNotReadBackIsNotKept(t *testing.T) {
676 f := newFixture(t, "")
677 f.readyAs(idE, "alice", "e", "main", "E's title")
678 f.plainBranch("e-plain", "e")
679 f.moveMain()
680 r := newRestacker(t, f)
681 j := r.journal()
682 path := filepath.Join(r.c.state, journalFile)
683 before, err := os.ReadFile(path)
684 if err != nil {
685 t.Fatal(err)
686 }
687 ctx := context.Background()
688 if err := release(ctx, r.g, j.Operation); err != nil {
689 t.Fatal(err)
690 }
691 j.Families[0].Observed.Reasons = append(j.Families[0].Observed.Reasons, "a reason in Latin-1: caf\xe9")
692 if err := keep(ctx, r.g, r.c.state, j); err == nil || !strings.Contains(err.Error(), "would not read back") {
693 t.Fatalf("a journal that would not read back was kept: %v", err)
694 }
695 if now, _ := os.ReadFile(path); !bytes.Equal(now, before) {
696 t.Error("the journal before it was replaced")
697 }
698 if left := gitOutT(t, r.g, "for-each-ref", retainPrefix+j.Operation+"/"); left != "" {
699 t.Errorf("objects were kept for a journal that was not:\n%s", left)
700 }
701}