gunk-dev/the-valley

records_test.go

sourced9f7bacd171bmain's published tip history
16.3 KiB
1package main
2
3// What the change records refuse, read from a real repository: a request
4// named for a change lands only while that change is ready at the
5// request's head, a request of any name is held back by a record that is
6// not ready at its head, and a request whose commits hold a merge is
7// refused. The records are written by hand, the way anyone holding a key
8// could write one where no hook guards the repository.
9
10import (
11 "maps"
12 "os"
13 "strings"
14 "testing"
15 "time"
16
17 "the-valley/change"
18)
19
20// scratchRepo is a repository with a main, and a way to make commits and
21// records in it.
22type scratchRepo struct {
23 t *testing.T
24 repo string
25}
26
27func newScratchRepo(t *testing.T) *scratchRepo {
28 s := &scratchRepo{t: t, repo: t.TempDir()}
29 s.git("init", "--quiet", "--initial-branch=main")
30 s.git("commit", "--quiet", "--allow-empty", "-m", "base")
31 return s
32}
33
34func (s *scratchRepo) git(args ...string) string {
35 s.t.Helper()
36 out, err := git(s.repo, append([]string{"-c", "user.name=t", "-c", "user.email=t@localhost"}, args...)...)
37 if err != nil {
38 s.t.Fatal(err)
39 }
40 return strings.TrimSpace(out)
41}
42
43func (s *scratchRepo) input(stdin string, args ...string) string {
44 s.t.Helper()
45 out, err := gitInput(s.repo, []byte(stdin), append([]string{"-c", "user.name=t", "-c", "user.email=t@localhost"}, args...)...)
46 if err != nil {
47 s.t.Fatal(err)
48 }
49 return strings.TrimSpace(string(out))
50}
51
52// commit is a new commit on parents, each with a tree of its own.
53func (s *scratchRepo) commit(subject string, parents ...string) string {
54 s.t.Helper()
55 blob := s.input(subject+"\n", "hash-object", "-w", "--stdin")
56 tree := s.input("100644 blob "+blob+"\t"+subject+".txt\n", "mktree")
57 args := []string{"commit-tree", tree, "-m", subject}
58 for _, p := range parents {
59 args = append(args, "-p", p)
60 }
61 return s.git(args...)
62}
63
64// record writes a record of the change at the heads given, in the state
65// given, as the ref for id.
66func (s *scratchRepo) record(id, state string, heads ...string) {
67 s.t.Helper()
68 r := &change.Record{
69 Schema: change.Schema, ChangeID: id, Target: "main", Owner: "owner", State: state,
70 Seq: len(heads) + 1, Active: len(heads),
71 }
72 for i, h := range heads {
73 r.Versions = append(r.Versions, change.Version{
74 N: i + 1, Head: change.HeadPrefix + h, Title: "a version", Branch: "topic", Uploader: "owner",
75 })
76 }
77 data, err := change.Encode(r)
78 if err != nil {
79 s.t.Fatal(err)
80 }
81 s.recordText(change.Ref("main", id), string(data), heads...)
82}
83
84// recordText writes a record commit holding text as its record.json, at ref.
85func (s *scratchRepo) recordText(ref, text string, parents ...string) {
86 s.t.Helper()
87 blob := s.input(text, "hash-object", "-w", "--stdin")
88 tree := s.input("100644 blob "+blob+"\trecord.json\n", "mktree")
89 args := []string{"commit-tree", tree, "-m", "a change record"}
90 for _, p := range parents {
91 args = append(args, "-p", p)
92 }
93 s.git("update-ref", ref, s.git(args...))
94}
95
96const (
97 readyID = "kkkkllllmmmmnnnnooooppppqqqqrrrr"
98 draftID = "zzzzyyyyxxxxwwwwvvvvuuuuttttssss"
99 goneID = "ppppppppppppppppqqqqqqqqqqqqqqqq"
100)
101
102func TestTheRecordsRefuseARequestForAChangeThatIsNotReady(t *testing.T) {
103 s := newScratchRepo(t)
104 base := s.git("rev-parse", "HEAD")
105 v1 := s.commit("v1", base)
106 v2 := s.commit("v2", base)
107 drafted := s.commit("drafted", base)
108 child := s.commit("child of drafted", drafted)
109 loose := s.commit("loose", base)
110 s.record(readyID, change.Ready, v1, v2)
111 s.record(draftID, change.Draft, drafted)
112 // A record that does not read, and one whose ref names another change.
113 s.recordText(change.Ref("main", goneID), "{}\n", loose)
114 s.recordText(change.Ref("main", "kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk"),
115 strings.Replace(recordJSON(t, readyID, change.Draft, loose), readyID, draftID, 1), loose)
116
117 in := &integrator{repo: s.repo}
118 idx, err := in.readRecords()
119 if err != nil {
120 t.Fatal(err)
121 }
122 if len(idx.unreadable) != 2 {
123 t.Fatalf("unreadable = %q, want the two records that do not read", idx.unreadable)
124 }
125 if len(idx.byHead[v1]) != 1 || len(idx.byHead[v2]) != 1 || len(idx.byHead[drafted]) != 1 || len(idx.byHead[loose]) != 0 {
126 t.Fatalf("the index by head is %v", idx.byHead)
127 }
128
129 for _, c := range []struct {
130 name, change, head string
131 refused bool
132 says string
133 }{
134 {"its change's request at a version head", change.RequestName(readyID), v2, false, ""},
135 {"its change's request at an older version head", change.RequestName(readyID), v1, false, ""},
136 {"its change's request at a head no version records", change.RequestName(readyID), loose, true, "is no version of change " + readyID},
137 {"a draft's request", change.RequestName(draftID), drafted, true, "change " + draftID + " is draft, not ready"},
138 {"a request for a change with no record", change.RequestName("llllllllllllllllllllllllllllllll"), loose, true, "holds no record of it"},
139 {"a request for a change whose record does not read", change.RequestName(goneID), loose, true, "does not read"},
140 {"a branch's request at a draft's head", "topic", drafted, true, "is v1 of change " + draftID + ", which is draft, not ready"},
141 {"a request for a ready change at a draft's head", change.RequestName(readyID), drafted, true, ""},
142 {"a branch's request at a ready change's head", "topic", v1, false, ""},
143 {"a branch's request no record knows", "loose", loose, false, ""},
144 {"a branch named like a request but not one", "c-" + readyID[:31], drafted, true, "which is draft"},
145 // A line of commits above a draft's head brings the draft with it.
146 {"another name's request for a child of a draft's head", "other", child, true,
147 "the commit " + drafted[:12] + " it brings is v1 of change " + draftID + ", which is draft, not ready"},
148 } {
149 r := request{ref: requestPrefix + "/main/" + c.change, change: c.change, target: "refs/heads/main", head: c.head}
150 outcome, why, err := in.recordRefusal(r, idx, base)
151 if err != nil {
152 t.Fatalf("%s: %v", c.name, err)
153 }
154 if refused := outcome != ""; refused != c.refused || (refused && outcome != refusedNotReady) {
155 t.Errorf("%s: refused %q (%s), want refused %v", c.name, outcome, why, c.refused)
156 }
157 if !strings.Contains(why, c.says) {
158 t.Errorf("%s: refused saying %q, without %q", c.name, why, c.says)
159 }
160 }
161 // Once the draft has landed, its head is on the tip and brings nothing.
162 r := request{change: "other", target: "refs/heads/main", head: child}
163 if outcome, why, _ := in.recordRefusal(r, idx, drafted); outcome != "" {
164 t.Errorf("a draft's head already on the tip still refuses its child: %s", why)
165 }
166
167 // The final check reads every record again: the draft readied lets its
168 // head through, the ready change unreadied holds its heads back, and a
169 // record that newly names a head the pass's index did not know holds
170 // that head back too.
171 s.record(draftID, change.Ready, drafted)
172 s.record(readyID, change.Draft, v1, v2)
173 newID := "lllllllllllllllllllllllllllllllk"
174 s.record(newID, change.Draft, loose)
175 for _, c := range []struct {
176 head string
177 refused bool
178 }{{drafted, false}, {v1, true}, {loose, true}} {
179 r := request{change: "topic", target: "refs/heads/main", head: c.head}
180 outcome, why, err := in.finalRefusal(r, base)
181 if err != nil {
182 t.Fatal(err)
183 }
184 if (outcome == refusedNotReady) != c.refused {
185 t.Errorf("the final check of %s: refused %q (%s), want refused %v", c.head[:12], outcome, why, c.refused)
186 }
187 }
188}
189
190// A record that does not read may name only commits its record commit
191// reaches, so a request is flagged when a commit it brings is one of
192// those, and not otherwise.
193func TestARecordThatDoesNotReadIsReportedWhereItMayMatter(t *testing.T) {
194 s := newScratchRepo(t)
195 base := s.git("rev-parse", "HEAD")
196 named := s.commit("named", base)
197 above := s.commit("above", named)
198 elsewhere := s.commit("elsewhere", base)
199 s.recordText(change.Ref("main", draftID), "{}\n", named)
200 in := &integrator{repo: s.repo}
201 idx, err := in.readRecords()
202 if err != nil {
203 t.Fatal(err)
204 }
205 for _, c := range []struct {
206 name, head, tip string
207 flagged bool
208 }{
209 {"its own head", named, base, true},
210 {"a child of its head", above, base, true},
211 {"a head it cannot reach", elsewhere, base, false},
212 {"a child of its head, once its head is on the tip", above, named, false},
213 } {
214 r := request{change: "topic", target: "refs/heads/main", head: c.head}
215 if got := len(in.uncheckable(r, idx, c.tip)) == 1; got != c.flagged {
216 t.Errorf("%s: flagged %v, want %v", c.name, got, c.flagged)
217 }
218 if outcome, _, _ := in.recordRefusal(r, idx, c.tip); outcome != "" {
219 t.Errorf("%s: a record that does not read refused it", c.name)
220 }
221 }
222}
223
224// The index keeps the commit each record ref held when it read it, the
225// ref of a record that does not read included, and indexes, refuses and
226// reports exactly as it would without them.
227func TestTheIndexKeepsTheCommitEachRecordRefHeld(t *testing.T) {
228 s := newScratchRepo(t)
229 base := s.git("rev-parse", "HEAD")
230 head := s.commit("ready head", base)
231 named := s.commit("named", base)
232 s.record(readyID, "ready", head)
233 s.recordText(change.Ref("main", draftID), "{}\n", named)
234 in := &integrator{repo: s.repo}
235 idx, err := in.readRecords()
236 if err != nil {
237 t.Fatal(err)
238 }
239 want := map[string]string{}
240 for _, id := range []string{readyID, draftID} {
241 ref := change.Ref("main", id)
242 want[ref] = s.git("rev-parse", ref)
243 }
244 if !maps.Equal(idx.observed, want) {
245 t.Errorf("the index observed %v, want %v", idx.observed, want)
246 }
247 if len(idx.byRef) != 1 || idx.byRef[change.Ref("main", readyID)] == nil {
248 t.Errorf("the index reads %v", idx.byRef)
249 }
250 if len(idx.unreadable) != 1 || idx.unreadable[0].commit != want[change.Ref("main", draftID)] {
251 t.Errorf("the index reports %+v as unreadable", idx.unreadable)
252 }
253 if got := idx.byHead[head]; len(got) != 1 || got[0].ref != change.Ref("main", readyID) {
254 t.Errorf("the ready head is indexed as %+v", got)
255 }
256}
257
258// A withdrawn change's requests are deleted, named for it or at one of its
259// version heads, each only while the change is still withdrawn and the
260// request still where the pass found it.
261func TestAWithdrawnChangeVoidsItsRequests(t *testing.T) {
262 s := newScratchRepo(t)
263 base := s.git("rev-parse", "HEAD")
264 h := s.commit("withdrawn", base)
265 other := s.commit("other", base)
266 readied := s.commit("readied", base)
267 s.record(draftID, change.Withdrawn, h)
268 s.record(readyID, change.Withdrawn, readied)
269 ref := func(name string) string { return requestPrefix + "/main/" + name }
270 for name, head := range map[string]string{
271 change.RequestName(draftID): h, "topic": h, "unrelated": other, "moved": h, "readied": readied,
272 } {
273 s.git("update-ref", ref(name), head)
274 }
275 in := &integrator{repo: s.repo, out: devNull(t)}
276 idx, err := in.readRecords()
277 if err != nil {
278 t.Fatal(err)
279 }
280 // Between the index and the voiding, one request is approved again at
281 // another head, and one change is readied again.
282 s.git("update-ref", ref("moved"), other)
283 s.record(readyID, change.Ready, readied)
284 var requests []request
285 for _, name := range []string{change.RequestName(draftID), "topic", "unrelated", "moved", "readied"} {
286 head := h
287 switch name {
288 case "unrelated":
289 head = other
290 case "readied":
291 head = readied
292 }
293 requests = append(requests, request{ref: ref(name), change: name, target: "refs/heads/main", head: head})
294 }
295 kept := in.voidWithdrawn(requests, idx)
296 var names []string
297 for _, r := range kept {
298 names = append(names, r.change)
299 }
300 if strings.Join(names, " ") != "unrelated moved readied" {
301 t.Fatalf("kept %v, want the unrelated request, the one approved again, and the readied change's", names)
302 }
303 for name, gone := range map[string]bool{
304 change.RequestName(draftID): true, "topic": true, "unrelated": false, "moved": false, "readied": false,
305 } {
306 if _, there := gitTry(s.repo, "rev-parse", "--verify", "--quiet", ref(name)); there == gone {
307 t.Errorf("the request %s: deleted %v, want %v", name, !there, gone)
308 }
309 }
310 memo, _ := gitTry(s.repo, "cat-file", "blob", outcomePrefix+"/main/topic")
311 if fields := strings.Fields(memo); len(fields) != 4 || fields[3] != string(voidedWithdrawn) {
312 t.Errorf("the voided request's outcome record is %q", memo)
313 }
314}
315
316func recordJSON(t *testing.T, id, state, head string) string {
317 t.Helper()
318 data, err := change.Encode(&change.Record{
319 Schema: change.Schema, ChangeID: id, Target: "main", Owner: "owner", State: state, Seq: 1, Active: 1,
320 Versions: []change.Version{{N: 1, Head: change.HeadPrefix + head, Title: "a version", Branch: "topic", Uploader: "owner"}},
321 })
322 if err != nil {
323 t.Fatal(err)
324 }
325 return string(data)
326}
327
328// A record past a bound is not read, so it names no head.
329func TestARecordPastItsBoundsIsNotRead(t *testing.T) {
330 s := newScratchRepo(t)
331 head := s.commit("head", s.git("rev-parse", "HEAD"))
332 text := recordJSON(t, draftID, change.Draft, head)
333 s.recordText(change.Ref("main", draftID), text+strings.Repeat(" ", change.MaxRecordBlob), head)
334 in := &integrator{repo: s.repo}
335 idx, err := in.readRecords()
336 if err != nil {
337 t.Fatal(err)
338 }
339 if len(idx.byHead[head]) != 0 || len(idx.unreadable) != 1 || !strings.Contains(idx.unreadable[0].why, "more than the 65536") {
340 t.Fatalf("an oversized record read as %v, unreadable %q", idx.byHead, idx.unreadable)
341 }
342}
343
344func TestARequestWhoseCommitsHoldAMergeIsRefused(t *testing.T) {
345 s := newScratchRepo(t)
346 base := s.git("rev-parse", "HEAD")
347 side := s.commit("side", base)
348 line := s.commit("line", base)
349 merged := s.commit("merged", line, side)
350 above := s.commit("above", merged)
351 // main itself merged once, below where the change begins.
352 tip := s.commit("main merged", base, side)
353 onTip := s.commit("on the tip", tip)
354
355 in := &integrator{repo: s.repo}
356 for _, c := range []struct {
357 name, head string
358 refused bool
359 }{
360 {"a line of commits", line, false},
361 {"a merge at the head", merged, true},
362 {"a merge below the head", above, true},
363 {"a line above a merge main already holds", onTip, false},
364 } {
365 r := request{change: "topic", target: "refs/heads/main", head: c.head}
366 outcome, why, err := in.mergeRefusal(r, tip)
367 if err != nil {
368 t.Fatalf("%s: %v", c.name, err)
369 }
370 if refused := outcome == refusedMerge; refused != c.refused {
371 t.Errorf("%s: refused %v (%s), want %v", c.name, refused, why, c.refused)
372 }
373 }
374}
375
376// A refusal is decided again on every pass, so its memo never stands as
377// the answer: a draft readied is judged on the next pass though its head,
378// the tip and the evidence have not moved.
379func TestARefusalIsNeverTheStandingAnswer(t *testing.T) {
380 in := &integrator{}
381 memo := "h t e"
382 for outcome, stands := range map[string]bool{
383 "land": true, "stale": true, "reject": true,
384 string(refusedNotReady): false, string(refusedMerge): false,
385 } {
386 if got := in.answered(memo+" "+outcome, memo, "i", "i"); got != stands {
387 t.Errorf("a %s memo stands: %v, want %v", outcome, got, stands)
388 }
389 }
390 if in.answered("other t e land", memo, "i", "i") {
391 t.Errorf("a memo about another head stands")
392 }
393}
394
395// An answer stands only under the inputs it was reached under. An outcome
396// record with no inputs record beside it, as one written before inputs
397// were remembered, stands under none. When an input does not read, no
398// verdict stands, and a failure stands for its window as any failure does.
399func TestAnAnswerStandsOnlyUnderItsInputs(t *testing.T) {
400 now := time.Date(2026, 10, 31, 12, 0, 0, 0, time.UTC)
401 in := &integrator{clock: now}
402 memo := "h t e"
403 recent := memo + " " + failedMemo + " " + now.Add(-time.Minute).Format(time.RFC3339)
404 expired := memo + " " + failedMemo + " " + now.Add(-retryAfter).Format(time.RFC3339)
405 for _, c := range []struct {
406 name string
407 last, before, now string
408 stands bool
409 }{
410 {"a verdict under the same inputs", memo + " stale", "i", "i", true},
411 {"a verdict under other inputs", memo + " stale", "i", "j", false},
412 {"a verdict with no inputs record", memo + " stale", "", "i", false},
413 {"a verdict while an input does not read", memo + " stale", unreadInputs, unreadInputs, false},
414 {"a recent failure while an input does not read", recent, unreadInputs, unreadInputs, true},
415 {"an expired failure while an input does not read", expired, unreadInputs, unreadInputs, false},
416 {"a recent failure once the input reads", recent, unreadInputs, "i", false},
417 {"a recent failure under the same inputs", recent, "i", "i", true},
418 } {
419 if got := in.answered(c.last, memo, c.before, c.now); got != c.stands {
420 t.Errorf("%s stands: %v, want %v", c.name, got, c.stands)
421 }
422 }
423}
424
425func devNull(t *testing.T) *os.File {
426 f, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0)
427 if err != nil {
428 t.Fatal(err)
429 }
430 t.Cleanup(func() { f.Close() })
431 return f
432}