gunk-dev/the-valley

worker_test.go

source60224096edd0main's published tip history
8.8 KiB
1package main
2
3import (
4 "errors"
5 "io"
6 "math"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "slices"
11 "sort"
12 "testing"
13 "time"
14
15 "the-valley/telemetry"
16)
17
18// A pass prunes exactly the roots no batch has used for longer than the
19// age it keeps outputs for, and nothing in the directory that is not a
20// root symlink.
21func TestPruneRootsRemovesExactlyTheRootsOlderThanTheAge(t *testing.T) {
22 dir := t.TempDir()
23 now := time.Now().Truncate(time.Second)
24 keep := 7 * 24 * time.Hour
25 used := map[string]time.Time{
26 "aaaa-stale": now.Add(-keep - time.Hour),
27 "bbbb-dangling": now.Add(-30 * 24 * time.Hour),
28 "cccc-recent": now.Add(-keep + time.Hour),
29 "dddd-today": now,
30 "eeee-not-alink": now.Add(-30 * 24 * time.Hour),
31 }
32 for name, at := range used {
33 path := filepath.Join(dir, name)
34 if name == "eeee-not-alink" {
35 if err := os.WriteFile(path, nil, 0o644); err != nil {
36 t.Fatal(err)
37 }
38 } else if err := os.Symlink("/nix/store/"+name, path); err != nil {
39 t.Fatal(err)
40 }
41 if out, err := exec.Command("touch", "-h", "-t", at.Local().Format("200601021504.05"), path).CombinedOutput(); err != nil {
42 t.Fatalf("touch %s: %v: %s", path, err, out)
43 }
44 }
45
46 if err := pruneRoots(dir, keep, now); err != nil {
47 t.Fatal(err)
48 }
49 entries, err := os.ReadDir(dir)
50 if err != nil {
51 t.Fatal(err)
52 }
53 var left []string
54 for _, e := range entries {
55 left = append(left, e.Name())
56 }
57 sort.Strings(left)
58 want := []string{"cccc-recent", "dddd-today", "eeee-not-alink"}
59 if !slices.Equal(left, want) {
60 t.Errorf("pruning left %v, want %v", left, want)
61 }
62
63 if err := pruneRoots(filepath.Join(dir, "missing"), keep, now); err != nil {
64 t.Errorf("pruning a roots directory that does not exist yet: %v", err)
65 }
66}
67
68// testJob is a job in a project, for a change's version first seen in a
69// scan, whose batch would store ref.
70func testJob(project, id string, seen int, ref, key string) *job {
71 return &job{r: listed{source: source{name: project}}, c: jsonChange{ChangeID: id, Handle: id},
72 v: jsonVersion{N: 1, Head: "0123456789"}, seen: seen, ref: ref, key: key}
73}
74
75// A scan's jobs start in the order their versions were first seen ready,
76// then by project, then by change ID, and one job holds each destination:
77// a later job for the same project and ref is the same tree, and is
78// dropped. The same ref in another project is another destination.
79func TestOrderIsFirstSeenThenProjectThenChangeAndOneJobPerDestination(t *testing.T) {
80 w := &worker{said: map[string]map[string]bool{}, stdout: io.Discard}
81 a := testJob("app", "m", 1, "refs/one", "")
82 b := testJob("app", "l", 1, "refs/two", "")
83 c := testJob("site", "a", 1, "refs/one", "")
84 d := testJob("app", "b", 2, "refs/two", "")
85 e := testJob("app", "c", 3, "refs/one", "")
86 f := testJob("app", "d", 2, "refs/three", "")
87 got := w.order([]*job{e, d, c, a, f, b})
88 want := []*job{b, a, c, f}
89 if !slices.Equal(got, want) {
90 var names []string
91 for _, j := range got {
92 names = append(names, j.r.name+"/"+j.c.ChangeID)
93 }
94 t.Errorf("the queue is %v, want app/l app/m site/a app/d", names)
95 }
96}
97
98// A scan that read a project whole forgets the failures it did not meet,
99// except the key of a batch still running there, whose failure is
100// recorded once it ends. Other projects' failures are kept.
101func TestPruneKeepsTheKeysOfRunningBatches(t *testing.T) {
102 record := &failureRecord{Projects: map[string]map[string]backoff{
103 "app": {"build one a": {Failures: 1}, "build two b": {Failures: 1}, "push 0a1b": {Failures: 2}},
104 "site": {"build one a": {Failures: 1}},
105 }}
106 running := testJob("app", "x", 1, "refs/one", "build one a")
107 w := &worker{failures: record, running: map[string]*batch{running.dest(): {job: running}}}
108 w.prune("app", map[string]bool{"push 0a1b": true})
109 var got []string
110 for key := range record.Projects["app"] {
111 got = append(got, key)
112 }
113 sort.Strings(got)
114 if !slices.Equal(got, []string{"build one a", "push 0a1b"}) {
115 t.Errorf("app keeps %v, want the running batch's key and the push the scan met", got)
116 }
117 if len(record.Projects["site"]) != 1 {
118 t.Errorf("pruning app changed site's failures: %v", record.Projects["site"])
119 }
120}
121
122// The time spans the host module passes as --interval read as systemd
123// reads a timer's, and the ones systemd refuses are refused.
124func TestTimeSpanReadsSystemdSpans(t *testing.T) {
125 month, year := 2629800*time.Second, 31557600*time.Second
126 for in, want := range map[string]time.Duration{
127 "1m": time.Minute, "15s": 15 * time.Second, "5min": 5 * time.Minute, "1h 30min": 90 * time.Minute,
128 "1m30s": 90 * time.Second, "90": 90 * time.Second, "2 days": 48 * time.Hour, "1.5h": 90 * time.Minute,
129 "0": 0, " 2months": 2 * month, "1y 1M": year + month, "1 year": year, "3weeks": 21 * 24 * time.Hour,
130 "5ms": 5 * time.Millisecond, "7\u00b5s": 7 * time.Microsecond, "7\u03bcs": 7 * time.Microsecond,
131 ".5s": 500 * time.Millisecond, "1.0000005s": time.Second, "5 3": 8 * time.Second,
132 "infinity": math.MaxInt64, " infinity ": math.MaxInt64,
133 // Longer than a time.Duration holds, but not than systemd reads.
134 "300y": math.MaxInt64, "9223372036854775807us": math.MaxInt64,
135 } {
136 if got, err := timeSpan(in); err != nil || got != want {
137 t.Errorf("timeSpan(%q) = %v, %v; want %v", in, got, err, want)
138 }
139 }
140 for _, in := range []string{
141 "", " ", "m", "5 fortnights", "-1m", "1m x", "5mins", "12.34.56", "3.s", "1.", "+5s", "infinity 1s", "1 infinity",
142 // As many microseconds as systemd's infinity, or more.
143 "18446744073709551615us", "9223372036854775808", "584543y", "500000y 500000y",
144 } {
145 if got, err := timeSpan(in); err == nil {
146 t.Errorf("timeSpan(%q) = %v, want an error", in, got)
147 }
148 }
149}
150
151// A read of origin that fails while two batches run stops the pass from
152// starting anything more: the job queued behind them never starts, and no
153// read follows. The loop still takes both batches' ends, which come after
154// the failed read began, and records each one's failure and wait, with its
155// attest run. The pass then fails with the read's error, and leaves its
156// claim, including the mark it claimed for that read, unacknowledged.
157func TestAFailedReadStopsAdmissionAndDrainsTheRunningBatches(t *testing.T) {
158 state, wakeDir, telDir := t.TempDir(), t.TempDir(), t.TempDir()
159 mark := func() {
160 if err := os.WriteFile(filepath.Join(wakeDir, "due"), nil, 0o600); err != nil {
161 t.Fatal(err)
162 }
163 }
164 mark()
165 claim := claimWake(wakeDir, io.Discard)
166 defer claim.close()
167 w := &worker{batches: 2, interval: time.Millisecond, wake: claim, stdout: io.Discard, stderr: io.Discard,
168 seen: map[string]int{}, running: map[string]*batch{}, said: map[string]map[string]bool{},
169 tel: openWorkerTelemetry(telDir), failures: readFailures(filepath.Join(state, "failures.json"), io.Discard)}
170 jobs := []*job{testJob("app", "a", 1, "refs/a", "build a"), testJob("app", "b", 1, "refs/b", "build b"),
171 testJob("app", "c", 1, "refs/c", "build c")}
172 var launched []*batch
173 reads := 0
174 w.read = func(git, string) ([]*job, error) {
175 reads++
176 if reads == 1 {
177 mark() // a ready push while the pass reads
178 return jobs, nil
179 }
180 // Both batches end while this read is under way, and fail.
181 for _, b := range launched {
182 go func() { w.done <- completion{b: b, err: errors.New("exit status 1"), ended: time.Now()} }()
183 }
184 return nil, failure("app: origin did not answer; the pass stops here")
185 }
186 w.recheck = func(*job) (bool, error) { return true, nil }
187 w.launch = func(b *batch) { launched = append(launched, b) }
188
189 err := w.pass(git{}, []string{"app"})
190 if err == nil || err.Error() != "app: origin did not answer; the pass stops here" {
191 t.Fatalf("the pass returned %v, want the read's error", err)
192 }
193 if reads != 2 {
194 t.Errorf("the pass read %d times, want 2: none after the read that failed", reads)
195 }
196 if len(launched) != 2 || launched[0].job != jobs[0] || launched[1].job != jobs[1] {
197 t.Errorf("the pass started %d batches, want a's and b's alone", len(launched))
198 }
199 if len(w.running) != 0 {
200 t.Errorf("the pass ended with %d batches running", len(w.running))
201 }
202 record := readFailures(filepath.Join(state, "failures.json"), io.Discard).Projects["app"]
203 for _, key := range []string{"build a", "build b"} {
204 if record[key].Failures != 1 {
205 t.Errorf("failures.json holds %q as %+v, want one failure", key, record[key])
206 }
207 }
208 if _, err := os.Stat(filepath.Join(wakeDir, "claimed")); err != nil {
209 t.Errorf("the claim was acknowledged: %v", err)
210 }
211 if _, err := os.Stat(filepath.Join(wakeDir, "due")); err == nil {
212 t.Error("the mark made during the first read was not claimed before the second")
213 }
214 recs, _, err := (&telemetry.Stream{Dir: w.tel.stream()}).Read(0, 1000, 1<<20)
215 if err != nil {
216 t.Fatal(err)
217 }
218 for _, b := range launched {
219 for _, typ := range []string{"batch.start", "batch.end", "backoff"} {
220 n := 0
221 for _, r := range recs {
222 if r.Type == typ && r.Data["attest_run"] == b.run {
223 n++
224 }
225 }
226 if n != 1 {
227 t.Errorf("the stream holds %d %s records naming attest run %s, want 1", n, typ, b.run)
228 }
229 }
230 }
231}