gunk-dev/the-valley

journal_test.go

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