gunk-dev/the-valley

worker_test.go

source171dbbb226c0main's published tip history
10.4 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// A pass reads neither the policy nor main where an earlier pass found no
123// follow run to start on the same tip, until main moves or the follow
124// run's wait is over. The record outlives the pass that wrote it.
125func TestQuietMainHoldsUntilMainMovesOrTheWaitEnds(t *testing.T) {
126 path := filepath.Join(t.TempDir(), "main.json")
127 failures := &failureRecord{Projects: map[string]map[string]backoff{}}
128 failures.failed("app", "build t1 e2e", clock(), time.Hour)
129 failures.failed("app", "build t1 old", clock().Add(-2*time.Hour), time.Hour)
130 q := readQuiet(path, io.Discard)
131 for _, m := range []struct{ project, tip, wait string }{
132 {"app", "c1", ""}, {"site", "c1", "build t1 e2e"}, {"web", "c1", "build t1 old"},
133 } {
134 if err := q.set(m.project, quietMain{Tip: m.tip, Wait: m.wait}); err != nil {
135 t.Fatal(err)
136 }
137 }
138 failures.Projects["site"], failures.Projects["web"] = failures.Projects["app"], failures.Projects["app"]
139 q = readQuiet(path, io.Discard)
140 for _, tc := range []struct {
141 project, tip string
142 want bool
143 }{
144 {"app", "c1", true}, {"app", "c2", false}, {"site", "c1", true}, {"web", "c1", false}, {"other", "c1", false},
145 } {
146 if got := q.holds(tc.project, tc.tip, failures); got != tc.want {
147 t.Errorf("%s at %s: quiet %v, want %v", tc.project, tc.tip, got, tc.want)
148 }
149 }
150}
151
152// The time spans the host module passes as --interval read as systemd
153// reads a timer's, and the ones systemd refuses are refused.
154func TestTimeSpanReadsSystemdSpans(t *testing.T) {
155 month, year := 2629800*time.Second, 31557600*time.Second
156 for in, want := range map[string]time.Duration{
157 "1m": time.Minute, "15s": 15 * time.Second, "5min": 5 * time.Minute, "1h 30min": 90 * time.Minute,
158 "1m30s": 90 * time.Second, "90": 90 * time.Second, "2 days": 48 * time.Hour, "1.5h": 90 * time.Minute,
159 "0": 0, " 2months": 2 * month, "1y 1M": year + month, "1 year": year, "3weeks": 21 * 24 * time.Hour,
160 "5ms": 5 * time.Millisecond, "7\u00b5s": 7 * time.Microsecond, "7\u03bcs": 7 * time.Microsecond,
161 ".5s": 500 * time.Millisecond, "1.0000005s": time.Second, "5 3": 8 * time.Second,
162 "infinity": math.MaxInt64, " infinity ": math.MaxInt64,
163 // Longer than a time.Duration holds, but not than systemd reads.
164 "300y": math.MaxInt64, "9223372036854775807us": math.MaxInt64,
165 } {
166 if got, err := timeSpan(in); err != nil || got != want {
167 t.Errorf("timeSpan(%q) = %v, %v; want %v", in, got, err, want)
168 }
169 }
170 for _, in := range []string{
171 "", " ", "m", "5 fortnights", "-1m", "1m x", "5mins", "12.34.56", "3.s", "1.", "+5s", "infinity 1s", "1 infinity",
172 // As many microseconds as systemd's infinity, or more.
173 "18446744073709551615us", "9223372036854775808", "584543y", "500000y 500000y",
174 } {
175 if got, err := timeSpan(in); err == nil {
176 t.Errorf("timeSpan(%q) = %v, want an error", in, got)
177 }
178 }
179}
180
181// A read of origin that fails while two batches run stops the pass from
182// starting anything more: the job queued behind them never starts, and no
183// read follows. The loop still takes both batches' ends, which come after
184// the failed read began, and records each one's failure and wait, with its
185// attest run. The pass then fails with the read's error, and leaves its
186// claim, including the mark it claimed for that read, unacknowledged.
187func TestAFailedReadStopsAdmissionAndDrainsTheRunningBatches(t *testing.T) {
188 state, wakeDir, telDir := t.TempDir(), t.TempDir(), t.TempDir()
189 mark := func() {
190 if err := os.WriteFile(filepath.Join(wakeDir, "due"), nil, 0o600); err != nil {
191 t.Fatal(err)
192 }
193 }
194 mark()
195 claim := claimWake(wakeDir, io.Discard)
196 defer claim.close()
197 // The emitter drops a record it cannot store within its deadline, and
198 // every record emitted while that store is still under way, so on a
199 // loaded machine the records below would be missing. Each record is
200 // waited for instead.
201 tel := openWorkerTelemetry(telDir)
202 tel.tel.SetDeadline(time.Minute)
203 w := &worker{batches: 2, interval: time.Millisecond, wake: claim, stdout: io.Discard, stderr: io.Discard,
204 seen: map[string]int{}, running: map[string]*batch{}, said: map[string]map[string]bool{},
205 tel: tel, failures: readFailures(filepath.Join(state, "failures.json"), io.Discard)}
206 jobs := []*job{testJob("app", "a", 1, "refs/a", "build a"), testJob("app", "b", 1, "refs/b", "build b"),
207 testJob("app", "c", 1, "refs/c", "build c")}
208 var launched []*batch
209 reads := 0
210 w.read = func(git, string) ([]*job, error) {
211 reads++
212 if reads == 1 {
213 mark() // a ready push while the pass reads
214 return jobs, nil
215 }
216 // Both batches end while this read is under way, and fail.
217 for _, b := range launched {
218 go func() { w.done <- completion{b: b, err: errors.New("exit status 1"), ended: time.Now()} }()
219 }
220 return nil, failure("app: origin did not answer; the pass stops here")
221 }
222 w.recheck = func(*job) (bool, error) { return true, nil }
223 w.launch = func(b *batch) { launched = append(launched, b) }
224
225 err := w.pass(git{}, []string{"app"})
226 if err == nil || err.Error() != "app: origin did not answer; the pass stops here" {
227 t.Fatalf("the pass returned %v, want the read's error", err)
228 }
229 if reads != 2 {
230 t.Errorf("the pass read %d times, want 2: none after the read that failed", reads)
231 }
232 if len(launched) != 2 || launched[0].job != jobs[0] || launched[1].job != jobs[1] {
233 t.Errorf("the pass started %d batches, want a's and b's alone", len(launched))
234 }
235 if len(w.running) != 0 {
236 t.Errorf("the pass ended with %d batches running", len(w.running))
237 }
238 record := readFailures(filepath.Join(state, "failures.json"), io.Discard).Projects["app"]
239 for _, key := range []string{"build a", "build b"} {
240 if record[key].Failures != 1 {
241 t.Errorf("failures.json holds %q as %+v, want one failure", key, record[key])
242 }
243 }
244 if _, err := os.Stat(filepath.Join(wakeDir, "claimed")); err != nil {
245 t.Errorf("the claim was acknowledged: %v", err)
246 }
247 if _, err := os.Stat(filepath.Join(wakeDir, "due")); err == nil {
248 t.Error("the mark made during the first read was not claimed before the second")
249 }
250 recs, _, err := (&telemetry.Stream{Dir: w.tel.stream()}).Read(0, 1000, 1<<20)
251 if err != nil {
252 t.Fatal(err)
253 }
254 for _, b := range launched {
255 for _, typ := range []string{"batch.start", "batch.end", "backoff"} {
256 n := 0
257 for _, r := range recs {
258 if r.Type == typ && r.Data["attest_run"] == b.run {
259 n++
260 }
261 }
262 if n != 1 {
263 t.Errorf("the stream holds %d %s records naming attest run %s, want 1", n, typ, b.run)
264 }
265 }
266 }
267}