gunk-dev/the-valley

worker_test.go

sourcebc00697b19b5main's published tip history
43.5 KiB
1package main
2
3import (
4 "cmp"
5 "errors"
6 "io"
7 "math"
8 "os"
9 "os/exec"
10 "path/filepath"
11 "slices"
12 "sort"
13 "strings"
14 "sync"
15 "testing"
16 "time"
17
18 "the-valley/change"
19 "the-valley/telemetry"
20)
21
22// A pass prunes exactly the roots no batch has used for longer than the
23// age it keeps outputs for, and nothing in the directory that is not a
24// root symlink.
25func TestPruneRootsRemovesExactlyTheRootsOlderThanTheAge(t *testing.T) {
26 dir := t.TempDir()
27 now := time.Now().Truncate(time.Second)
28 keep := 7 * 24 * time.Hour
29 used := map[string]time.Time{
30 "aaaa-stale": now.Add(-keep - time.Hour),
31 "bbbb-dangling": now.Add(-30 * 24 * time.Hour),
32 "cccc-recent": now.Add(-keep + time.Hour),
33 "dddd-today": now,
34 "eeee-not-alink": now.Add(-30 * 24 * time.Hour),
35 }
36 for name, at := range used {
37 path := filepath.Join(dir, name)
38 if name == "eeee-not-alink" {
39 if err := os.WriteFile(path, nil, 0o644); err != nil {
40 t.Fatal(err)
41 }
42 } else if err := os.Symlink("/nix/store/"+name, path); err != nil {
43 t.Fatal(err)
44 }
45 if out, err := exec.Command("touch", "-h", "-t", at.Local().Format("200601021504.05"), path).CombinedOutput(); err != nil {
46 t.Fatalf("touch %s: %v: %s", path, err, out)
47 }
48 }
49
50 if err := pruneRoots(dir, keep, now); err != nil {
51 t.Fatal(err)
52 }
53 entries, err := os.ReadDir(dir)
54 if err != nil {
55 t.Fatal(err)
56 }
57 var left []string
58 for _, e := range entries {
59 left = append(left, e.Name())
60 }
61 sort.Strings(left)
62 want := []string{"cccc-recent", "dddd-today", "eeee-not-alink"}
63 if !slices.Equal(left, want) {
64 t.Errorf("pruning left %v, want %v", left, want)
65 }
66
67 if err := pruneRoots(filepath.Join(dir, "missing"), keep, now); err != nil {
68 t.Errorf("pruning a roots directory that does not exist yet: %v", err)
69 }
70}
71
72// testJob is a job in a project, for a change's version first seen in a
73// scan, whose batch would store ref.
74func testJob(project, id string, seen int, ref, key string) *job {
75 return &job{r: listed{source: source{name: project}}, c: jsonChange{ChangeID: id, Handle: id},
76 v: jsonVersion{N: 1, Head: "0123456789"}, seen: seen, ref: ref, key: key}
77}
78
79// A scan's jobs start in the order their versions were first seen ready,
80// then by project, then by change ID, and one job holds each destination:
81// a later job for the same project and ref is the same tree, and is
82// dropped. The same ref in another project is another destination.
83func TestOrderIsFirstSeenThenProjectThenChangeAndOneJobPerDestination(t *testing.T) {
84 w := &worker{said: map[string]map[string]bool{}, stdout: io.Discard}
85 a := testJob("app", "m", 1, "refs/one", "")
86 b := testJob("app", "l", 1, "refs/two", "")
87 c := testJob("site", "a", 1, "refs/one", "")
88 d := testJob("app", "b", 2, "refs/two", "")
89 e := testJob("app", "c", 3, "refs/one", "")
90 f := testJob("app", "d", 2, "refs/three", "")
91 got := w.order([]*job{e, d, c, a, f, b})
92 want := []*job{b, a, c, f}
93 if !slices.Equal(got, want) {
94 var names []string
95 for _, j := range got {
96 names = append(names, j.r.name+"/"+j.c.ChangeID)
97 }
98 t.Errorf("the queue is %v, want app/l app/m site/a app/d", names)
99 }
100}
101
102// A scan that read a project whole forgets the failures it did not meet,
103// except the key of a batch still running there, whose failure is
104// recorded once it ends. Other projects' failures are kept.
105func TestPruneKeepsTheKeysOfRunningBatches(t *testing.T) {
106 record := &failureRecord{Projects: map[string]map[string]backoff{
107 "app": {"build one a": {Failures: 1}, "build two b": {Failures: 1}, "push 0a1b": {Failures: 2}},
108 "site": {"build one a": {Failures: 1}},
109 }}
110 running := testJob("app", "x", 1, "refs/one", "build one a")
111 w := &worker{failures: record, running: map[string]*batch{running.dest(): {job: running}}}
112 w.prune("app", map[string]bool{"push 0a1b": true}, false)
113 var got []string
114 for key := range record.Projects["app"] {
115 got = append(got, key)
116 }
117 sort.Strings(got)
118 if !slices.Equal(got, []string{"build one a", "push 0a1b"}) {
119 t.Errorf("app keeps %v, want the running batch's key and the push the scan met", got)
120 }
121 if len(record.Projects["site"]) != 1 {
122 t.Errorf("pruning app changed site's failures: %v", record.Projects["site"])
123 }
124}
125
126// A pass reads neither the policy nor main where an earlier pass found no
127// follow run to start on the same tip, until main moves or the follow
128// run's wait is over. The record outlives the pass that wrote it.
129func TestQuietMainHoldsUntilMainMovesOrTheWaitEnds(t *testing.T) {
130 path := filepath.Join(t.TempDir(), "main.json")
131 failures := &failureRecord{Projects: map[string]map[string]backoff{}}
132 failures.failed("app", "build t1 e2e", clock(), time.Hour)
133 failures.failed("app", "build t1 old", clock().Add(-2*time.Hour), time.Hour)
134 q := readQuiet(path, io.Discard)
135 for _, m := range []struct{ project, tip, wait string }{
136 {"app", "c1", ""}, {"site", "c1", "build t1 e2e"}, {"web", "c1", "build t1 old"},
137 } {
138 if err := q.set(m.project, quietMain{Tip: m.tip, Wait: m.wait}); err != nil {
139 t.Fatal(err)
140 }
141 }
142 failures.Projects["site"], failures.Projects["web"] = failures.Projects["app"], failures.Projects["app"]
143 q = readQuiet(path, io.Discard)
144 for _, tc := range []struct {
145 project, tip string
146 want bool
147 }{
148 {"app", "c1", true}, {"app", "c2", false}, {"site", "c1", true}, {"web", "c1", false}, {"other", "c1", false},
149 } {
150 if got := q.holds(tc.project, tc.tip, failures); got != tc.want {
151 t.Errorf("%s at %s: quiet %v, want %v", tc.project, tc.tip, got, tc.want)
152 }
153 }
154}
155
156// The time spans the host module passes as --interval read as systemd
157// reads a timer's, and the ones systemd refuses are refused.
158func TestTimeSpanReadsSystemdSpans(t *testing.T) {
159 month, year := 2629800*time.Second, 31557600*time.Second
160 for in, want := range map[string]time.Duration{
161 "1m": time.Minute, "15s": 15 * time.Second, "5min": 5 * time.Minute, "1h 30min": 90 * time.Minute,
162 "1m30s": 90 * time.Second, "90": 90 * time.Second, "2 days": 48 * time.Hour, "1.5h": 90 * time.Minute,
163 "0": 0, " 2months": 2 * month, "1y 1M": year + month, "1 year": year, "3weeks": 21 * 24 * time.Hour,
164 "5ms": 5 * time.Millisecond, "7\u00b5s": 7 * time.Microsecond, "7\u03bcs": 7 * time.Microsecond,
165 ".5s": 500 * time.Millisecond, "1.0000005s": time.Second, "5 3": 8 * time.Second,
166 "infinity": math.MaxInt64, " infinity ": math.MaxInt64,
167 // Longer than a time.Duration holds, but not than systemd reads.
168 "300y": math.MaxInt64, "9223372036854775807us": math.MaxInt64,
169 } {
170 if got, err := timeSpan(in); err != nil || got != want {
171 t.Errorf("timeSpan(%q) = %v, %v; want %v", in, got, err, want)
172 }
173 }
174 for _, in := range []string{
175 "", " ", "m", "5 fortnights", "-1m", "1m x", "5mins", "12.34.56", "3.s", "1.", "+5s", "infinity 1s", "1 infinity",
176 // As many microseconds as systemd's infinity, or more.
177 "18446744073709551615us", "9223372036854775808", "584543y", "500000y 500000y",
178 } {
179 if got, err := timeSpan(in); err == nil {
180 t.Errorf("timeSpan(%q) = %v, want an error", in, got)
181 }
182 }
183}
184
185// A read of origin that fails while two batches run stops the pass from
186// starting anything more: the job queued behind them never starts, and no
187// read follows. The loop still takes both batches' ends, which come after
188// the failed read began, and records each one's failure and wait, with its
189// attest run. The pass then fails with the read's error, and leaves its
190// claim, including the mark it claimed for that read, unacknowledged.
191func TestAFailedReadStopsAdmissionAndDrainsTheRunningBatches(t *testing.T) {
192 state, wakeDir, telDir := t.TempDir(), t.TempDir(), t.TempDir()
193 mark := func() {
194 if err := os.WriteFile(filepath.Join(wakeDir, "due"), nil, 0o600); err != nil {
195 t.Fatal(err)
196 }
197 }
198 mark()
199 claim := claimWake(wakeDir, io.Discard)
200 defer claim.close()
201 // The emitter drops a record it cannot store within its deadline, and
202 // every record emitted while that store is still under way, so on a
203 // loaded machine the records below would be missing. Each record is
204 // waited for instead.
205 tel := openWorkerTelemetry(telDir)
206 tel.tel.SetDeadline(time.Minute)
207 w := &worker{batches: 2, interval: time.Millisecond, wake: claim, stdout: io.Discard, stderr: io.Discard,
208 seen: map[string]int{}, running: map[string]*batch{}, said: map[string]map[string]bool{},
209 tel: tel, failures: readFailures(filepath.Join(state, "failures.json"), io.Discard)}
210 jobs := []*job{testJob("app", "a", 1, "refs/a", "build a"), testJob("app", "b", 1, "refs/b", "build b"),
211 testJob("app", "c", 1, "refs/c", "build c")}
212 var launched []*batch
213 reads := 0
214 w.read = func(git, string) (projectRead, error) {
215 reads++
216 if reads == 1 {
217 mark() // a ready push while the pass reads
218 return projectRead{jobs: jobs}, nil
219 }
220 // Both batches end while this read is under way, and fail.
221 for _, b := range launched {
222 go func() { w.done <- completion{b: b, err: errors.New("exit status 1"), ended: time.Now()} }()
223 }
224 return projectRead{}, failure("app: origin did not answer; the pass stops here")
225 }
226 w.recheck = func(*job) (bool, error) { return true, nil }
227 w.launch = func(b *batch) { launched = append(launched, b) }
228
229 err := w.pass(git{}, []string{"app"})
230 if err == nil || err.Error() != "app: origin did not answer; the pass stops here" {
231 t.Fatalf("the pass returned %v, want the read's error", err)
232 }
233 if reads != 2 {
234 t.Errorf("the pass read %d times, want 2: none after the read that failed", reads)
235 }
236 if len(launched) != 2 || launched[0].job != jobs[0] || launched[1].job != jobs[1] {
237 t.Errorf("the pass started %d batches, want a's and b's alone", len(launched))
238 }
239 if len(w.running) != 0 {
240 t.Errorf("the pass ended with %d batches running", len(w.running))
241 }
242 record := readFailures(filepath.Join(state, "failures.json"), io.Discard).Projects["app"]
243 for _, key := range []string{"build a", "build b"} {
244 if record[key].Failures != 1 {
245 t.Errorf("failures.json holds %q as %+v, want one failure", key, record[key])
246 }
247 }
248 if _, err := os.Stat(filepath.Join(wakeDir, "claimed")); err != nil {
249 t.Errorf("the claim was acknowledged: %v", err)
250 }
251 if _, err := os.Stat(filepath.Join(wakeDir, "due")); err == nil {
252 t.Error("the mark made during the first read was not claimed before the second")
253 }
254 recs, _, err := (&telemetry.Stream{Dir: w.tel.stream()}).Read(0, 1000, 1<<20)
255 if err != nil {
256 t.Fatal(err)
257 }
258 for _, b := range launched {
259 for _, typ := range []string{"batch.start", "batch.end", "backoff"} {
260 n := 0
261 for _, r := range recs {
262 if r.Type == typ && r.Data["attest_run"] == b.run {
263 n++
264 }
265 }
266 if n != 1 {
267 t.Errorf("the stream holds %d %s records naming attest run %s, want 1", n, typ, b.run)
268 }
269 }
270 }
271}
272
273// The worker reads both layers at main's tip as approve does, and refuses
274// a layer that cannot be read rather than reading it as absent. An
275// unreadable floor is not sent to the owning valley that policy/valley
276// names, though that valley's floor reads, and an unreadable project layer
277// is not derived as the floor alone.
278func TestPolicyLayersRefuseALayerThatCannotBeRead(t *testing.T) {
279 dir := t.TempDir()
280 t.Setenv("HOME", dir)
281 t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
282 commit := func(repo string, files map[string]string) string {
283 t.Helper()
284 run := func(args ...string) string {
285 t.Helper()
286 cmd := exec.Command("git", append([]string{"-c", "user.name=t", "-c", "user.email=t@localhost"}, args...)...)
287 cmd.Dir = repo
288 out, err := cmd.CombinedOutput()
289 if err != nil {
290 t.Fatalf("git %v: %v\n%s", args, err, out)
291 }
292 return strings.TrimSpace(string(out))
293 }
294 if err := os.MkdirAll(repo, 0o755); err != nil {
295 t.Fatal(err)
296 }
297 run("init", "--quiet", "--initial-branch=main")
298 for path, body := range files {
299 full := filepath.Join(repo, path)
300 if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
301 t.Fatal(err)
302 }
303 if err := os.WriteFile(full, []byte(body), 0o644); err != nil {
304 t.Fatal(err)
305 }
306 }
307 run("add", "--all")
308 run("commit", "--quiet", "-m", "layers")
309 return run("rev-parse", "HEAD")
310 }
311 valley := filepath.Join(dir, "valley")
312 commit(valley, map[string]string{"policy/instance/floor.cue": "package verification // the valley's\n"})
313
314 for _, lost := range []string{"", instanceLayer, projectLayer, projectLayer + "/policy.cue"} {
315 t.Run("lost "+lost, func(t *testing.T) {
316 repo := filepath.Join(t.TempDir(), "app")
317 tip := commit(repo, map[string]string{
318 instanceLayer + "/floor.cue": "package verification // its own\n",
319 projectLayer + "/policy.cue": "package verification // the project's\n",
320 valleyPointer: valley + "\n",
321 })
322 if lost != "" {
323 out, err := exec.Command("git", "-C", repo, "rev-parse", tip+":"+lost).Output()
324 if err != nil {
325 t.Fatal(err)
326 }
327 oid := strings.TrimSpace(string(out))
328 if err := os.Remove(filepath.Join(repo, ".git", "objects", oid[:2], oid[2:])); err != nil {
329 t.Fatal(err)
330 }
331 }
332 instance, project, done, err := policyLayers(git{env: os.Environ(), stderr: io.Discard, dir: repo}, tip)
333 defer done()
334 if lost == "" {
335 if err != nil {
336 t.Fatal(err)
337 }
338 for path, want := range map[string]string{
339 filepath.Join(instance, "floor.cue"): "package verification // its own\n",
340 filepath.Join(project, "policy.cue"): "package verification // the project's\n",
341 } {
342 if body, err := os.ReadFile(path); err != nil || string(body) != want {
343 t.Errorf("%s reads %q (%v), not %q", path, body, err, want)
344 }
345 }
346 return
347 }
348 if err == nil {
349 t.Fatalf("an unreadable %s resolved the layers to %s and %s", lost, instance, project)
350 }
351 if !strings.Contains(err.Error(), "reading "+lost) {
352 t.Errorf("the refusal %q does not say that %s could not be read", err, lost)
353 }
354 })
355 }
356}
357
358// world is what one project holds in a scheduler test: its ready
359// changes, the head on main a follow run is due on, or "", origin's refs
360// under the check-request prefix, the tree of each head, the checks each
361// head requires, given, when not the one check "check", the checks whose notes do
362// not count, and the error reading a head's evidence ends in, if any. The
363// evidence itself is on a scratch origin. The test changes the world
364// while the loop runs.
365type world struct {
366 mu sync.Mutex
367 ready []testVersion
368 follow string
369 refs map[string]string
370 trees map[string]string
371 asks map[string][]string
372 uncounted map[string]bool
373 broken map[string]error
374}
375
376// testVersion is a ready change's active version.
377type testVersion struct {
378 change string
379 n int
380 head string
381}
382
383// checks are the nix checks a head requires.
384func (wd *world) checks(head string) []nixCheck {
385 names, ok := wd.asks[head]
386 if !ok {
387 names = []string{"check"}
388 }
389 var checks []nixCheck
390 for _, name := range names {
391 checks = append(checks, nixCheck{name, name})
392 }
393 return checks
394}
395
396// scheduler runs a worker's loop over the worlds of its projects, with no
397// attest, in a clone of a scratch origin that the state directory keeps
398// across passes. Each batch the loop starts is sent on launched, and each
399// it stops on stops; a batch ends when the test hands the loop its
400// completion, having stored or added its notes as attest would. reads
401// gets the scan's number after each read of the last project. A request
402// batch started while a batch of a higher class ran is kept in wrong.
403type scheduler struct {
404 t *testing.T
405 w *worker
406 g git // the worker's clone
407 origin string // the scratch origin's directory
408 worlds map[string]*world
409 last string
410 launched chan *batch
411 stops chan *batch
412 reads chan int
413 ended chan error
414 wrong []string
415 assessed []string // the requests assessed, by ref, in order
416 during func() // run once, at the start of the next read of requests
417}
418
419// newScheduler starts a pass over the worlds, running batches at once
420// and reading every project again every interval while batches run, or
421// every millisecond when interval is 0. The origin refuses a push while
422// it holds a file named refuse, counts every push it is offered in
423// attempts, and marks the pass's wake directory after each push it takes,
424// as a host's hook does.
425func newScheduler(t *testing.T, batches int, interval time.Duration, state string, worlds map[string]*world) *scheduler {
426 t.Helper()
427 env := append(os.Environ(), "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null")
428 origin, clone := filepath.Join(state, "origin.git"), filepath.Join(state, "clone")
429 s := &scheduler{t: t, g: git{env: env, stderr: io.Discard, dir: clone}, origin: origin, worlds: worlds,
430 launched: make(chan *batch, 100), stops: make(chan *batch, 100), reads: make(chan int, 100), ended: make(chan error, 1)}
431 wakeDir := filepath.Join(state, "wake")
432 if _, err := os.Stat(clone); err != nil {
433 s.run(git{env: env, dir: state}, "init", "--quiet", "--bare", origin)
434 s.run(git{env: env, dir: state}, "init", "--quiet", clone)
435 s.run(s.g, "remote", "add", "origin", origin)
436 for name, hook := range map[string]string{
437 "pre-receive": "#!/bin/sh\necho attempt >> attempts\ntest ! -e refuse\n",
438 "post-receive": "#!/bin/sh\n: > '" + filepath.Join(wakeDir, "due") + "'\n",
439 } {
440 if err := os.WriteFile(filepath.Join(origin, "hooks", name), []byte(hook), 0o755); err != nil {
441 t.Fatal(err)
442 }
443 }
444 if err := os.Mkdir(wakeDir, 0o700); err != nil {
445 t.Fatal(err)
446 }
447 }
448 claim := claimWake(wakeDir, io.Discard)
449 projects := slices.Sorted(maps2keys(worlds))
450 s.last = projects[len(projects)-1]
451 s.w = &worker{batches: batches, interval: cmp.Or(interval, time.Millisecond), stdout: io.Discard, stderr: io.Discard,
452 seen: map[string]int{}, running: map[string]*batch{}, said: map[string]map[string]bool{},
453 failures: readFailures(filepath.Join(state, "failures.json"), io.Discard),
454 quiet: readQuiet(filepath.Join(state, "main.json"), io.Discard), keyhash: "deadbeef", wake: claim}
455 s.w.read = func(_ git, name string) (projectRead, error) {
456 return s.read(listed{source: source{name: name, g: s.g}})
457 }
458 s.w.cover = s.cover
459 s.w.recheck = func(j *job) (bool, error) {
460 needed, _, err := s.w.assess(j, nil)
461 return needed, err
462 }
463 s.w.launch = func(b *batch) {
464 if b.job.class() == classRequest && s.w.runningAbove(classRequest) {
465 s.wrong = append(s.wrong, b.job.version()+" started beside a batch of a higher class")
466 }
467 b.stop = func() { s.stops <- b }
468 s.launched <- b
469 }
470 go func() {
471 err := s.w.loop(git{}, projects)
472 claim.close()
473 s.ended <- err
474 }()
475 return s
476}
477
478// maps2keys yields a map's keys.
479func maps2keys[V any](m map[string]V) func(func(string) bool) {
480 return func(yield func(string) bool) {
481 for k := range m {
482 if !yield(k) {
483 return
484 }
485 }
486 }
487}
488
489// run runs git, and fails the test when it fails.
490func (s *scheduler) run(g git, args ...string) string {
491 out, err := g.output(true, args...)
492 if err != nil {
493 s.t.Errorf("git %s: %v", strings.Join(args, " "), err)
494 }
495 return out
496}
497
498// onOrigin is the object origin's ref names, or "".
499func (s *scheduler) onOrigin(ref string) string {
500 out, err := git{env: s.g.env, dir: s.origin}.output(true, "rev-parse", "--quiet", "--verify", ref)
501 if err != nil {
502 return ""
503 }
504 return out
505}
506
507// noted is the checks the notes tree object holds a note for.
508func (s *scheduler) noted(object string) []string {
509 return strings.Fields(s.run(s.g, "ls-tree", "--name-only", object))
510}
511
512// cover reads a job's evidence as coverage does: this worker's ref for
513// the head's tree on origin, fetched here, and the checks it holds a
514// note for that counts.
515func (s *scheduler) cover(j *job) (evidence, error) {
516 wd := s.worlds[j.r.name]
517 wd.mu.Lock()
518 defer wd.mu.Unlock()
519 if j.req != "" {
520 s.assessed = append(s.assessed, j.req)
521 }
522 if err := wd.broken[j.v.Head]; err != nil {
523 return evidence{}, err
524 }
525 e := evidence{digest: wd.trees[j.v.Head], listed: map[string]string{}, covered: map[string]string{}}
526 ref := attestationRefs + e.digest + "/" + s.w.keyhash
527 if object := s.onOrigin(ref); object != "" {
528 e.listed[ref] = object
529 s.run(s.g, "fetch", "--quiet", "--no-write-fetch-head", "origin", ref)
530 for _, name := range s.noted(object) {
531 if !wd.uncounted[name] {
532 e.covered[name] = ref
533 }
534 }
535 }
536 return e, nil
537}
538
539// read is project over a world: the ready changes, then the follow run,
540// each read only as project reads it, then the stops and the pruning of a
541// whole read, and the reader of the check requests, which runs during
542// before it assesses any.
543func (s *scheduler) read(r listed) (projectRead, error) {
544 wd, w := s.worlds[r.name], s.w
545 wd.mu.Lock()
546 refs, follow := map[string]string{}, wd.follow
547 for ref, head := range wd.refs {
548 refs[ref] = head
549 }
550 ready := slices.Clone(wd.ready)
551 asks := map[string][]nixCheck{}
552 for _, v := range ready {
553 asks[v.head] = wd.checks(v.head)
554 }
555 for _, head := range refs {
556 asks[head] = wd.checks(head)
557 }
558 asks[follow] = wd.checks(follow)
559 wd.mu.Unlock()
560 if r.name == s.last {
561 defer func() { s.reads <- w.scans }()
562 }
563 listed, pending := w.listRequests(r, refs)
564 met := map[string]bool{}
565 whole := true
566 var jobs []*job
567 var changes []jsonChange
568 for _, v := range ready {
569 c := jsonChange{ChangeID: v.change, Handle: v.change, Active: 1, Versions: []jsonVersion{{N: v.n, Head: v.head}}}
570 changes = append(changes, c)
571 j := &job{r: r, c: c, v: c.Versions[0], asked: asks[v.head]}
572 w.ready[j.version()] = true
573 if _, ok := w.seen[j.version()]; !ok {
574 w.seen[j.version()] = w.scans
575 }
576 j.seen = w.seen[j.version()]
577 needed, read, err := w.assess(j, met)
578 if err != nil {
579 return projectRead{}, err
580 }
581 whole = whole && read
582 if needed {
583 jobs = append(jobs, j)
584 }
585 }
586 if len(jobs) == 0 && !w.gating() && follow != "" {
587 j, read, err := w.followRun(&job{r: r, v: jsonVersion{Head: follow}, main: true, seen: w.scans, asked: asks[follow]}, met)
588 if err != nil {
589 return projectRead{}, err
590 }
591 whole = whole && read
592 if j != nil {
593 jobs = append(jobs, j)
594 }
595 }
596 if whole {
597 w.prune(r.name, met, len(listed) > 0)
598 w.stopSuperseded(r.name, changes, listed)
599 }
600 pr := projectRead{jobs: jobs}
601 if len(pending) > 0 {
602 pr.done = func() {}
603 pr.requests = func() ([]*job, error) {
604 wd.mu.Lock()
605 f := s.during
606 s.during = nil
607 wd.mu.Unlock()
608 if f != nil {
609 f()
610 }
611 var jobs []*job
612 for _, q := range pending {
613 j := &job{r: r, v: jsonVersion{Head: q.head}, req: q.ref, seen: w.seen[checkRequestName(r.name, q.ref, q.head)], asked: asks[q.head]}
614 needed, _, err := w.assess(j, met)
615 if err != nil {
616 return nil, err
617 }
618 if needed {
619 jobs = append(jobs, j)
620 }
621 }
622 if whole {
623 w.prune(r.name, met, false)
624 }
625 return jobs, nil
626 }
627 }
628 return pr, nil
629}
630
631// alter changes a world while the loop runs.
632func (s *scheduler) alter(project string, f func(wd *world)) {
633 wd := s.worlds[project]
634 wd.mu.Lock()
635 defer wd.mu.Unlock()
636 f(wd)
637}
638
639// reread waits for two reads of every project to end, the second of which
640// began after the call.
641func (s *scheduler) reread() {
642 s.t.Helper()
643 for range 2 {
644 select {
645 case <-s.reads:
646 case err := <-s.ended:
647 s.t.Fatalf("the pass ended (%v) before it read every project again", err)
648 case <-time.After(10 * time.Second):
649 s.t.Fatal("the pass did not read every project again")
650 }
651 }
652}
653
654// started waits for the next batch to start, and requires it to be for
655// want: a change's ID, main, or a request's ref.
656func (s *scheduler) started(want string) *batch {
657 s.t.Helper()
658 select {
659 case b := <-s.launched:
660 got := cmp.Or(b.job.c.ChangeID, b.job.req)
661 if b.job.main {
662 got = "main"
663 }
664 if got != want {
665 s.t.Fatalf("the batch for %s started, want %s", got, want)
666 }
667 return b
668 case err := <-s.ended:
669 s.t.Fatalf("the pass ended (%v) before %s started", err, want)
670 case <-time.After(10 * time.Second):
671 s.t.Fatalf("no batch started, want %s", want)
672 }
673 return nil
674}
675
676// stopped waits for the loop to stop b.
677func (s *scheduler) stopped(b *batch) {
678 s.t.Helper()
679 select {
680 case got := <-s.stops:
681 if got != b {
682 s.t.Fatalf("the loop stopped %s, want %s", got.job.version(), b.job.version())
683 }
684 case <-time.After(10 * time.Second):
685 s.t.Fatalf("the loop did not stop %s", b.job.version())
686 }
687}
688
689// idle requires that no batch started or was stopped since the test last
690// looked, after two more reads.
691func (s *scheduler) idle(what string) {
692 s.t.Helper()
693 s.reread()
694 select {
695 case b := <-s.launched:
696 s.t.Fatalf("%s: the batch for %s started", what, b.job.version())
697 case b := <-s.stops:
698 s.t.Fatalf("%s: the batch for %s was stopped", what, b.job.version())
699 default:
700 }
701}
702
703// end hands the loop b's completion, failed with err, or else passed
704// having done what attest does: store a ref of one note for each check it
705// built, or for a batch that adds its notes, add them to origin's ref.
706func (s *scheduler) end(b *batch, err error) {
707 s.t.Helper()
708 c := completion{b: b, err: err, ended: time.Now()}
709 if err == nil {
710 j := b.job
711 var entries []string
712 for _, q := range j.missing {
713 blob := strings.TrimSpace(s.input("note "+j.digest+" "+q.name+"\n", "hash-object", "-w", "--stdin"))
714 sub := strings.TrimSpace(s.input("100644 blob "+blob+"\tstatement.note\n", "mktree"))
715 entries = append(entries, "040000 tree "+sub+"\t"+q.name)
716 }
717 if j.main || j.additive {
718 if held := s.onOrigin(j.ref); held != "" {
719 s.run(s.g, "fetch", "--quiet", "--no-write-fetch-head", "origin", j.ref)
720 entries = append(entries, strings.Split(strings.TrimSpace(s.run(s.g, "ls-tree", held)), "\n")...)
721 }
722 }
723 tree := strings.TrimSpace(s.input(strings.Join(entries, "\n")+"\n", "mktree"))
724 s.run(s.g, "update-ref", j.ref, tree)
725 if j.main || j.additive {
726 s.run(s.g, "push", "--quiet", "--force", "origin", tree+":"+j.ref)
727 } else {
728 c.stored = tree
729 }
730 if j.main {
731 s.alter(j.r.name, func(wd *world) { wd.follow = "" })
732 }
733 }
734 s.w.done <- c
735}
736
737// input runs git with stdin, and fails the test when it fails.
738func (s *scheduler) input(stdin string, args ...string) string {
739 out, err := s.g.input(true, strings.NewReader(stdin), args...)
740 if err != nil {
741 s.t.Errorf("git %s: %v", strings.Join(args, " "), err)
742 }
743 return out
744}
745
746// finish waits for the pass to end, and requires that it started and
747// stopped nothing the test did not take, and kept the class order.
748func (s *scheduler) finish() {
749 s.t.Helper()
750 select {
751 case err := <-s.ended:
752 if err != nil {
753 s.t.Fatalf("the pass returned %v", err)
754 }
755 case <-time.After(10 * time.Second):
756 s.t.Fatal("the pass did not end")
757 }
758 select {
759 case b := <-s.launched:
760 s.t.Errorf("the batch for %s started, and the test did not take it", b.job.version())
761 case b := <-s.stops:
762 s.t.Errorf("the batch for %s was stopped, and the test did not take it", b.job.version())
763 default:
764 }
765 for _, w := range s.wrong {
766 s.t.Error(w)
767 }
768}
769
770// testRequest is the ref of a check request in a scheduler test.
771func testRequest(attempt string) string {
772 return change.CheckRequestPrefix + "alice/0123456789abcdef/" + attempt
773}
774
775// newWorld is a world whose heads hold the trees given, head to tree.
776func newWorld(trees ...string) *world {
777 wd := &world{refs: map[string]string{}, trees: map[string]string{}, asks: map[string][]string{},
778 uncounted: map[string]bool{}, broken: map[string]error{}}
779 for i := 0; i+1 < len(trees); i += 2 {
780 wd.trees[trees[i]] = trees[i+1]
781 }
782 return wd
783}
784
785const (
786 changeK = "kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk"
787 changeL = "llllllllllllllllllllllllllllllll"
788)
789
790// Ready changes come first, then follow runs, then check requests,
791// whichever projects they are in. A request starts only once no ready
792// change or follow run waits or runs, whatever slots are free. A request
793// batch that runs goes on to its end beside a follow run or ready work
794// that arrives meanwhile, and a request that arrives then waits for the
795// ready work to end.
796func TestARequestStartsAfterReadyChangesAndFollowRuns(t *testing.T) {
797 r1, r2 := testRequest("1111111111111111"), testRequest("2222222222222222")
798 app := newWorld("h2", "t2", "h3", "t3", "h4", "t4", "h5", "t5", "h6", "t6")
799 app.follow, app.refs[r1] = "h2", "h3"
800 site := newWorld("h1", "t1")
801 site.ready = []testVersion{{changeK, 1, "h1"}}
802 s := newScheduler(t, 2, 0, t.TempDir(), map[string]*world{"app": app, "site": site})
803 ready := s.started(changeK)
804 s.idle("beside a ready batch, with a slot free")
805 s.end(ready, nil)
806 follow := s.started("main")
807 s.idle("beside a follow run, with a slot free")
808 s.end(follow, nil)
809 request := s.started(r1)
810 s.alter("app", func(wd *world) { wd.follow = "h6" })
811 s.end(s.started("main"), nil)
812
813 s.alter("app", func(wd *world) {
814 wd.ready = append(wd.ready, testVersion{changeL, 1, "h4"})
815 wd.refs[r2] = "h5"
816 })
817 later := s.started(changeL)
818 s.idle("a request batch beside a ready one that started after it")
819 s.end(request, nil)
820 s.idle("a slot freed while a ready batch runs and a request waits")
821 s.end(later, nil)
822 s.end(s.started(r2), nil)
823 s.finish()
824}
825
826// A slot a request batch frees goes to the next request only after a read
827// of every project: a ready change readied meanwhile takes it.
828func TestAFreedSlotWaitsForAReadBeforeTheNextRequest(t *testing.T) {
829 r1, r2 := testRequest("1111111111111111"), testRequest("2222222222222222")
830 app := newWorld("h1", "t1", "h2", "t2", "h3", "t3")
831 app.refs[r1], app.refs[r2] = "h1", "h2"
832 s := newScheduler(t, 1, time.Hour, t.TempDir(), map[string]*world{"app": app})
833 first := s.started(r1)
834 s.alter("app", func(wd *world) { wd.ready = []testVersion{{changeK, 1, "h3"}} })
835 s.end(first, nil)
836 s.end(s.started(changeK), nil)
837 s.end(s.started(r2), nil)
838 s.finish()
839}
840
841// A request whose batch failed is not built again, in this pass or the
842// next, until a listing finds its ref moved or gone. A rerun is a new
843// attempt, which builds at once though it names the same commit.
844func TestAFailedRequestIsNotBuiltAgainUntilItsRefMoves(t *testing.T) {
845 state := t.TempDir()
846 first, rerun := testRequest("1111111111111111"), testRequest("2222222222222222")
847 app := newWorld("h1", "t1", "h2", "t2")
848 app.refs[first] = "h1"
849 worlds := map[string]*world{"app": app}
850 s := newScheduler(t, 1, 0, state, worlds)
851 s.end(s.started(first), errors.New("exit status 1"))
852 s.finish()
853 if got := readFailures(filepath.Join(state, "failures.json"), io.Discard).Requests["app"]; len(got) != 1 || got[first] != "h1" {
854 t.Fatalf("failures.json marks %v, want the failed request at its commit", got)
855 }
856 if _, waiting := s.w.failures.Projects["app"]; waiting {
857 t.Errorf("the request's failure waits as a ready change's would: %v", s.w.failures.Projects)
858 }
859
860 s = newScheduler(t, 1, 0, state, worlds) // a pass that starts afresh, as after a restart
861 s.finish()
862
863 app.refs[rerun] = "h1"
864 s = newScheduler(t, 1, 0, state, worlds)
865 s.end(s.started(rerun), nil)
866 s.finish()
867
868 app.refs[first] = "h2"
869 s = newScheduler(t, 1, 0, state, worlds)
870 s.end(s.started(first), nil)
871 s.finish()
872 if got := readFailures(filepath.Join(state, "failures.json"), io.Discard).Requests; len(got) != 0 {
873 t.Errorf("failures.json still marks %v once the ref moved", got)
874 }
875}
876
877// A request batch is stopped once a whole read finds its ref moved or
878// gone, and the request at its new commit is built. A stopped batch
879// records no failure. A batch whose ref went runs on while a ready
880// change's active version holds its tree, and another request with the
881// same tree does not keep it: that request may need checks the batch
882// does not build, and the worker's ref for the tree, once published,
883// takes no more.
884func TestARequestThatMovesOrGoesLosesItsBatch(t *testing.T) {
885 state := t.TempDir()
886 moved, kept, rerun := testRequest("1111111111111111"), testRequest("2222222222222222"), testRequest("3333333333333333")
887 app := newWorld("h1", "t1", "h2", "t2", "h3", "t3", "h4", "t3")
888 app.refs[moved] = "h1"
889 worlds := map[string]*world{"app": app}
890 s := newScheduler(t, 2, 0, state, worlds)
891 b := s.started(moved)
892 s.alter("app", func(wd *world) { wd.refs[moved] = "h2" })
893 s.stopped(b)
894 s.end(b, errors.New("signal: killed"))
895 if again := s.started(moved); again.job.v.Head != "h2" {
896 t.Errorf("the request started again at %s, want h2", again.job.v.Head)
897 } else {
898 s.end(again, nil)
899 }
900 s.finish()
901 if len(s.w.failures.Requests) != 0 || len(s.w.failures.Projects) != 0 {
902 t.Errorf("the stopped batch recorded a failure: %v %v", s.w.failures.Requests, s.w.failures.Projects)
903 }
904
905 app.refs = map[string]string{kept: "h3"}
906 s = newScheduler(t, 2, 0, state, worlds)
907 b = s.started(kept)
908 s.alter("app", func(wd *world) {
909 delete(wd.refs, kept)
910 wd.ready = []testVersion{{changeK, 1, "h4"}}
911 })
912 s.idle("a request gone whose tree a ready version holds")
913 s.alter("app", func(wd *world) {
914 wd.ready = nil
915 wd.refs[rerun] = "h3"
916 })
917 s.stopped(b)
918 s.end(b, errors.New("signal: killed"))
919 s.end(s.started(rerun), nil)
920 s.finish()
921}
922
923// A check request whose commit's evidence cannot be read, as when attest
924// cannot digest a tree holding a submodule, is marked and said once, and
925// the scan goes on to build the rest; so does a ready change's, which is
926// said. Neither is read again in the next pass. Only a failed read of
927// origin ends a scan.
928func TestAnUnreadableHeadEndsNoScan(t *testing.T) {
929 state := t.TempDir()
930 r1, r2 := testRequest("1111111111111111"), testRequest("2222222222222222")
931 app := newWorld("h1", "t1", "h2", "t2")
932 app.refs[r1], app.refs[r2] = "h1", "h2"
933 app.broken = map[string]error{"h1": failure("could not digest the tree of h1")}
934 site := newWorld("h3", "t3", "h4", "t4")
935 site.ready = []testVersion{{changeK, 1, "h3"}, {changeL, 1, "h4"}}
936 site.broken = map[string]error{"h3": failure("could not digest the tree of h3")}
937 worlds := map[string]*world{"app": app, "site": site}
938 s := newScheduler(t, 1, 0, state, worlds)
939 s.end(s.started(changeL), nil)
940 s.end(s.started(r2), nil)
941 s.finish()
942 if got := readFailures(filepath.Join(state, "failures.json"), io.Discard).Requests["app"]; len(got) != 1 || got[r1] != "h1" {
943 t.Errorf("failures.json marks %v, want the unreadable request at its commit", got)
944 }
945
946 s = newScheduler(t, 1, 0, state, worlds)
947 s.finish()
948 if slices.Contains(s.assessed, r1) {
949 t.Error("the marked request was read again")
950 }
951
952 site.broken["h4"] = originFailure{failure("could not list the evidence origin holds for this tree")}
953 s = newScheduler(t, 1, 0, state, worlds)
954 select {
955 case err := <-s.ended:
956 if err == nil || !strings.Contains(err.Error(), "the pass stops here") {
957 t.Errorf("a failed read of origin ended the pass with %v", err)
958 }
959 case <-time.After(10 * time.Second):
960 t.Fatal("a failed read of origin did not end the pass")
961 }
962}
963
964// A scan reads check requests only once it has read every project's ready
965// changes and follow run: an earlier project's requests are not assessed
966// while a later project's ready change waits or builds.
967func TestRequestsWaitForEveryProjectsReadyWork(t *testing.T) {
968 r1 := testRequest("1111111111111111")
969 app := newWorld("h1", "t1")
970 app.refs[r1] = "h1"
971 site := newWorld("h2", "t2")
972 site.ready = []testVersion{{changeK, 1, "h2"}}
973 s := newScheduler(t, 2, 0, t.TempDir(), map[string]*world{"app": app, "site": site})
974 ready := s.started(changeK)
975 s.idle("a request beside a ready batch, with a slot free")
976 app.mu.Lock()
977 assessed := slices.Clone(s.assessed)
978 app.mu.Unlock()
979 if len(assessed) != 0 {
980 t.Errorf("requests %v were assessed while a ready change waited or built", assessed)
981 }
982 s.end(ready, nil)
983 s.end(s.started(r1), nil)
984 s.finish()
985}
986
987// A request whose batch ends in failure while a scan reads the requests
988// is not built again from that scan: its marker is read again when it is
989// assessed.
990func TestAMarkerWrittenDuringAReadHoldsTheRequest(t *testing.T) {
991 r1 := testRequest("1111111111111111")
992 app := newWorld("h1", "t1")
993 app.refs[r1] = "h1"
994 s := newScheduler(t, 1, 0, t.TempDir(), map[string]*world{"app": app})
995 b := s.started(r1)
996 app.mu.Lock()
997 s.during = func() {
998 go func() { s.w.done <- completion{b: b, err: errors.New("exit status 1"), ended: time.Now()} }()
999 for s.w.running[b.job.dest()] != nil {
1000 if err := s.w.reap(); err != nil {
1001 t.Error(err)
1002 return
1003 }
1004 }
1005 }
1006 app.mu.Unlock()
1007 s.finish()
1008 if got := s.w.failures.Requests["app"][r1]; got != "h1" {
1009 t.Errorf("the failed request is marked at %q, want h1", got)
1010 }
1011}
1012
1013// notesOn are the checks origin holds this worker's notes for at a tree.
1014func (s *scheduler) notesOn(tree string) []string {
1015 object := s.onOrigin(attestationRefs + tree + "/" + s.w.keyhash)
1016 if object == "" {
1017 return nil
1018 }
1019 s.run(s.g, "fetch", "--quiet", "--no-write-fetch-head", "origin", object)
1020 return s.noted(object)
1021}
1022
1023// built requires a batch to build exactly the checks named, and says
1024// whether it adds them to the ref origin holds.
1025func built(t *testing.T, b *batch, additive bool, names ...string) {
1026 t.Helper()
1027 if got := b.job.names(); !slices.Equal(got, names) || b.job.additive != additive {
1028 t.Errorf("the batch for %s builds %v (additive %v), want %v (additive %v)", b.job.version(), got, b.job.additive, names, additive)
1029 }
1030}
1031
1032// When origin holds this worker's evidence for a tree and it lacks a
1033// check a head there requires, the worker builds that check alone and
1034// adds its note to the ref: for a ready change waiting on a request's
1035// batch for its tree, and for a ready change whose policy came to require
1036// another check after its evidence was published. Nothing is built twice.
1037func TestPublishedEvidenceIsExtended(t *testing.T) {
1038 asked := testRequest("1111111111111111")
1039 app := newWorld("h1", "t1", "h2", "t1")
1040 app.refs[asked] = "h1"
1041 app.asks["h1"], app.asks["h2"] = []string{"x"}, []string{"x", "y"}
1042 s := newScheduler(t, 2, 0, t.TempDir(), map[string]*world{"app": app})
1043 request := s.started(asked)
1044 s.alter("app", func(wd *world) { wd.ready = []testVersion{{changeK, 1, "h2"}} })
1045 s.idle("a ready change whose tree a request's batch builds")
1046 s.end(request, nil)
1047 added := s.started(changeK)
1048 built(t, request, false, "x")
1049 built(t, added, true, "y")
1050 s.end(added, nil)
1051 s.finish()
1052 if got := s.notesOn("t1"); !slices.Equal(got, []string{"x", "y"}) {
1053 t.Errorf("origin holds notes for %v, want x and y", got)
1054 }
1055
1056 gained := newWorld("h3", "t3")
1057 gained.ready = []testVersion{{changeL, 1, "h3"}}
1058 gained.asks["h3"] = []string{"x"}
1059 s = newScheduler(t, 1, 0, t.TempDir(), map[string]*world{"app": gained})
1060 first := s.started(changeL)
1061 s.alter("app", func(wd *world) { wd.asks["h3"] = []string{"x", "y"} })
1062 s.end(first, nil)
1063 second := s.started(changeL)
1064 built(t, first, false, "x")
1065 built(t, second, true, "y")
1066 s.end(second, nil)
1067 s.finish()
1068 if got := s.notesOn("t3"); !slices.Equal(got, []string{"x", "y"}) {
1069 t.Errorf("origin holds notes for %v, want x and y", got)
1070 }
1071}
1072
1073// A ref a request's batch stored before the request went is published as
1074// it stands for a ready change with the same tree, and then extended with
1075// the check that change also requires.
1076func TestAStoredRefIsPublishedThenExtended(t *testing.T) {
1077 state := t.TempDir()
1078 asked := testRequest("1111111111111111")
1079 app := newWorld("h1", "t1", "h2", "t1")
1080 app.refs[asked] = "h1"
1081 app.asks["h1"], app.asks["h2"] = []string{"x"}, []string{"x", "y"}
1082 worlds := map[string]*world{"app": app}
1083 s := newScheduler(t, 1, 0, state, worlds)
1084 request := s.started(asked)
1085 sub := strings.TrimSpace(s.input("100644 blob "+strings.TrimSpace(s.input("x\n", "hash-object", "-w", "--stdin"))+"\tstatement.note\n", "mktree"))
1086 s.run(s.g, "update-ref", request.job.ref, strings.TrimSpace(s.input("040000 tree "+sub+"\tx\n", "mktree")))
1087 s.alter("app", func(wd *world) { delete(wd.refs, asked) })
1088 s.stopped(request)
1089 s.end(request, errors.New("signal: killed"))
1090 s.finish()
1091 if got := s.notesOn("t1"); got != nil {
1092 t.Fatalf("origin holds %v before any change needs the tree", got)
1093 }
1094
1095 app.ready = []testVersion{{changeK, 1, "h2"}}
1096 s = newScheduler(t, 1, 0, state, worlds)
1097 added := s.started(changeK)
1098 built(t, added, true, "y")
1099 s.end(added, nil)
1100 s.finish()
1101 if got := s.notesOn("t1"); !slices.Equal(got, []string{"x", "y"}) {
1102 t.Errorf("origin holds notes for %v, want x and y", got)
1103 }
1104}
1105
1106// A note this worker's ref on origin holds for a check that does not
1107// count, as one for another attribute, cannot be replaced by another note
1108// of the same signer, so the check is not built again: a ready change
1109// waits for approve to build it, and a request is done with.
1110func TestANoteThatDoesNotCountIsNotBuiltAgain(t *testing.T) {
1111 state := t.TempDir()
1112 asked := testRequest("1111111111111111")
1113 app := newWorld("h1", "t1", "h2", "t1")
1114 app.ready = []testVersion{{changeK, 1, "h1"}}
1115 app.asks["h1"], app.asks["h2"] = []string{"x"}, []string{"x"}
1116 worlds := map[string]*world{"app": app}
1117 s := newScheduler(t, 1, 0, state, worlds)
1118 s.end(s.started(changeK), nil)
1119 s.finish()
1120
1121 app.uncounted["x"] = true
1122 app.refs[asked] = "h2"
1123 s = newScheduler(t, 1, 0, state, worlds)
1124 s.finish()
1125 if got := s.w.failures.Requests["app"][asked]; got != "h2" {
1126 t.Errorf("the request is marked at %q, want h2", got)
1127 }
1128}
1129
1130// A head whose evidence does not read is not read: its project's records
1131// are not pruned, so its own batch's failure still waits once it reads
1132// again; its batches are not stopped for want of it; and a main tip whose
1133// evidence does not read is not recorded as quiet.
1134func TestAnUnreadHeadKeepsItsProjectsRecordsAndBatches(t *testing.T) {
1135 state := t.TempDir()
1136 r := readFailures(filepath.Join(state, "failures.json"), io.Discard)
1137 r.failed("app", "build t1 check", time.Now(), time.Hour)
1138 if err := r.save(); err != nil {
1139 t.Fatal(err)
1140 }
1141 app := newWorld("h1", "t1", "h2", "t1", "h3", "t3")
1142 app.ready = []testVersion{{changeK, 1, "h2"}}
1143 app.broken["h2"] = failure("could not digest the tree of h2")
1144 worlds := map[string]*world{"app": app}
1145 s := newScheduler(t, 1, 0, state, worlds)
1146 s.finish()
1147 delete(app.broken, "h2")
1148 s = newScheduler(t, 1, 0, state, worlds)
1149 s.finish()
1150
1151 app.ready = []testVersion{{changeL, 1, "h1"}}
1152 s = newScheduler(t, 1, 0, t.TempDir(), worlds)
1153 b := s.started(changeL)
1154 s.alter("app", func(wd *world) {
1155 wd.ready = []testVersion{{changeL, 2, "h2"}}
1156 wd.broken["h2"] = failure("could not digest the tree of h2")
1157 })
1158 s.idle("a superseded batch whose tree the new version, unread, holds")
1159 s.end(b, nil)
1160 s.finish()
1161
1162 app.ready, app.follow = nil, "h3"
1163 app.broken["h3"] = failure("could not digest the tree of h3")
1164 s = newScheduler(t, 1, 0, state, worlds)
1165 s.finish()
1166 if m, ok := readQuiet(filepath.Join(state, "main.json"), io.Discard).Projects["app"]; ok {
1167 t.Errorf("a main tip whose evidence did not read is recorded quiet: %+v", m)
1168 }
1169}
1170
1171// A scan that finds no higher-class work empties the queue before it
1172// reads requests, so a request batch that ends while they are read frees
1173// its slot to nothing an earlier scan queued, such as a version since
1174// superseded.
1175func TestTheRequestPhaseStartsNothingAnEarlierScanQueued(t *testing.T) {
1176 asked := testRequest("1111111111111111")
1177 app := newWorld("h1", "t1", "h2", "t2", "h3", "t3")
1178 app.refs[asked] = "h1"
1179 s := newScheduler(t, 1, 0, t.TempDir(), map[string]*world{"app": app})
1180 b := s.started(asked)
1181 s.alter("app", func(wd *world) { wd.ready = []testVersion{{changeK, 1, "h2"}} })
1182 s.idle("a ready change waiting for the slot a request batch holds")
1183 s.alter("app", func(wd *world) {
1184 wd.ready = []testVersion{{changeK, 2, "h3"}}
1185 wd.asks["h3"] = []string{}
1186 s.during = func() {
1187 go func() { s.w.done <- completion{b: b, err: errors.New("exit status 1"), ended: time.Now()} }()
1188 for s.w.running[b.job.dest()] != nil {
1189 if err := s.w.reap(); err != nil {
1190 t.Error(err)
1191 return
1192 }
1193 }
1194 }
1195 })
1196 s.finish()
1197}
1198
1199// A request's failed push waits out its backoff: the scans and passes
1200// after it do not push the stored ref again before its wait is over.
1201func TestARequestsFailedPushWaitsOutItsBackoff(t *testing.T) {
1202 state := t.TempDir()
1203 asked := testRequest("1111111111111111")
1204 app := newWorld("h1", "t1")
1205 app.refs[asked] = "h1"
1206 worlds := map[string]*world{"app": app}
1207 s := newScheduler(t, 1, 0, state, worlds)
1208 if err := os.WriteFile(filepath.Join(s.origin, "refuse"), nil, 0o644); err != nil {
1209 t.Fatal(err)
1210 }
1211 s.end(s.started(asked), nil)
1212 s.finish()
1213 s = newScheduler(t, 1, 0, state, worlds)
1214 s.finish()
1215 attempts, err := os.ReadFile(filepath.Join(s.origin, "attempts"))
1216 if err != nil {
1217 t.Fatal(err)
1218 }
1219 if n := strings.Count(string(attempts), "attempt\n"); n != 1 {
1220 t.Errorf("origin was offered %d pushes, want 1", n)
1221 }
1222}