gunk-dev/the-valley

worker_test.go

source01f84ae34d8amain's published tip history
13.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 "strings"
13 "testing"
14 "time"
15
16 "the-valley/telemetry"
17)
18
19// A pass prunes exactly the roots no batch has used for longer than the
20// age it keeps outputs for, and nothing in the directory that is not a
21// root symlink.
22func TestPruneRootsRemovesExactlyTheRootsOlderThanTheAge(t *testing.T) {
23 dir := t.TempDir()
24 now := time.Now().Truncate(time.Second)
25 keep := 7 * 24 * time.Hour
26 used := map[string]time.Time{
27 "aaaa-stale": now.Add(-keep - time.Hour),
28 "bbbb-dangling": now.Add(-30 * 24 * time.Hour),
29 "cccc-recent": now.Add(-keep + time.Hour),
30 "dddd-today": now,
31 "eeee-not-alink": now.Add(-30 * 24 * time.Hour),
32 }
33 for name, at := range used {
34 path := filepath.Join(dir, name)
35 if name == "eeee-not-alink" {
36 if err := os.WriteFile(path, nil, 0o644); err != nil {
37 t.Fatal(err)
38 }
39 } else if err := os.Symlink("/nix/store/"+name, path); err != nil {
40 t.Fatal(err)
41 }
42 if out, err := exec.Command("touch", "-h", "-t", at.Local().Format("200601021504.05"), path).CombinedOutput(); err != nil {
43 t.Fatalf("touch %s: %v: %s", path, err, out)
44 }
45 }
46
47 if err := pruneRoots(dir, keep, now); err != nil {
48 t.Fatal(err)
49 }
50 entries, err := os.ReadDir(dir)
51 if err != nil {
52 t.Fatal(err)
53 }
54 var left []string
55 for _, e := range entries {
56 left = append(left, e.Name())
57 }
58 sort.Strings(left)
59 want := []string{"cccc-recent", "dddd-today", "eeee-not-alink"}
60 if !slices.Equal(left, want) {
61 t.Errorf("pruning left %v, want %v", left, want)
62 }
63
64 if err := pruneRoots(filepath.Join(dir, "missing"), keep, now); err != nil {
65 t.Errorf("pruning a roots directory that does not exist yet: %v", err)
66 }
67}
68
69// testJob is a job in a project, for a change's version first seen in a
70// scan, whose batch would store ref.
71func testJob(project, id string, seen int, ref, key string) *job {
72 return &job{r: listed{source: source{name: project}}, c: jsonChange{ChangeID: id, Handle: id},
73 v: jsonVersion{N: 1, Head: "0123456789"}, seen: seen, ref: ref, key: key}
74}
75
76// A scan's jobs start in the order their versions were first seen ready,
77// then by project, then by change ID, and one job holds each destination:
78// a later job for the same project and ref is the same tree, and is
79// dropped. The same ref in another project is another destination.
80func TestOrderIsFirstSeenThenProjectThenChangeAndOneJobPerDestination(t *testing.T) {
81 w := &worker{said: map[string]map[string]bool{}, stdout: io.Discard}
82 a := testJob("app", "m", 1, "refs/one", "")
83 b := testJob("app", "l", 1, "refs/two", "")
84 c := testJob("site", "a", 1, "refs/one", "")
85 d := testJob("app", "b", 2, "refs/two", "")
86 e := testJob("app", "c", 3, "refs/one", "")
87 f := testJob("app", "d", 2, "refs/three", "")
88 got := w.order([]*job{e, d, c, a, f, b})
89 want := []*job{b, a, c, f}
90 if !slices.Equal(got, want) {
91 var names []string
92 for _, j := range got {
93 names = append(names, j.r.name+"/"+j.c.ChangeID)
94 }
95 t.Errorf("the queue is %v, want app/l app/m site/a app/d", names)
96 }
97}
98
99// A scan that read a project whole forgets the failures it did not meet,
100// except the key of a batch still running there, whose failure is
101// recorded once it ends. Other projects' failures are kept.
102func TestPruneKeepsTheKeysOfRunningBatches(t *testing.T) {
103 record := &failureRecord{Projects: map[string]map[string]backoff{
104 "app": {"build one a": {Failures: 1}, "build two b": {Failures: 1}, "push 0a1b": {Failures: 2}},
105 "site": {"build one a": {Failures: 1}},
106 }}
107 running := testJob("app", "x", 1, "refs/one", "build one a")
108 w := &worker{failures: record, running: map[string]*batch{running.dest(): {job: running}}}
109 w.prune("app", map[string]bool{"push 0a1b": true})
110 var got []string
111 for key := range record.Projects["app"] {
112 got = append(got, key)
113 }
114 sort.Strings(got)
115 if !slices.Equal(got, []string{"build one a", "push 0a1b"}) {
116 t.Errorf("app keeps %v, want the running batch's key and the push the scan met", got)
117 }
118 if len(record.Projects["site"]) != 1 {
119 t.Errorf("pruning app changed site's failures: %v", record.Projects["site"])
120 }
121}
122
123// A pass reads neither the policy nor main where an earlier pass found no
124// follow run to start on the same tip, until main moves or the follow
125// run's wait is over. The record outlives the pass that wrote it.
126func TestQuietMainHoldsUntilMainMovesOrTheWaitEnds(t *testing.T) {
127 path := filepath.Join(t.TempDir(), "main.json")
128 failures := &failureRecord{Projects: map[string]map[string]backoff{}}
129 failures.failed("app", "build t1 e2e", clock(), time.Hour)
130 failures.failed("app", "build t1 old", clock().Add(-2*time.Hour), time.Hour)
131 q := readQuiet(path, io.Discard)
132 for _, m := range []struct{ project, tip, wait string }{
133 {"app", "c1", ""}, {"site", "c1", "build t1 e2e"}, {"web", "c1", "build t1 old"},
134 } {
135 if err := q.set(m.project, quietMain{Tip: m.tip, Wait: m.wait}); err != nil {
136 t.Fatal(err)
137 }
138 }
139 failures.Projects["site"], failures.Projects["web"] = failures.Projects["app"], failures.Projects["app"]
140 q = readQuiet(path, io.Discard)
141 for _, tc := range []struct {
142 project, tip string
143 want bool
144 }{
145 {"app", "c1", true}, {"app", "c2", false}, {"site", "c1", true}, {"web", "c1", false}, {"other", "c1", false},
146 } {
147 if got := q.holds(tc.project, tc.tip, failures); got != tc.want {
148 t.Errorf("%s at %s: quiet %v, want %v", tc.project, tc.tip, got, tc.want)
149 }
150 }
151}
152
153// The time spans the host module passes as --interval read as systemd
154// reads a timer's, and the ones systemd refuses are refused.
155func TestTimeSpanReadsSystemdSpans(t *testing.T) {
156 month, year := 2629800*time.Second, 31557600*time.Second
157 for in, want := range map[string]time.Duration{
158 "1m": time.Minute, "15s": 15 * time.Second, "5min": 5 * time.Minute, "1h 30min": 90 * time.Minute,
159 "1m30s": 90 * time.Second, "90": 90 * time.Second, "2 days": 48 * time.Hour, "1.5h": 90 * time.Minute,
160 "0": 0, " 2months": 2 * month, "1y 1M": year + month, "1 year": year, "3weeks": 21 * 24 * time.Hour,
161 "5ms": 5 * time.Millisecond, "7\u00b5s": 7 * time.Microsecond, "7\u03bcs": 7 * time.Microsecond,
162 ".5s": 500 * time.Millisecond, "1.0000005s": time.Second, "5 3": 8 * time.Second,
163 "infinity": math.MaxInt64, " infinity ": math.MaxInt64,
164 // Longer than a time.Duration holds, but not than systemd reads.
165 "300y": math.MaxInt64, "9223372036854775807us": math.MaxInt64,
166 } {
167 if got, err := timeSpan(in); err != nil || got != want {
168 t.Errorf("timeSpan(%q) = %v, %v; want %v", in, got, err, want)
169 }
170 }
171 for _, in := range []string{
172 "", " ", "m", "5 fortnights", "-1m", "1m x", "5mins", "12.34.56", "3.s", "1.", "+5s", "infinity 1s", "1 infinity",
173 // As many microseconds as systemd's infinity, or more.
174 "18446744073709551615us", "9223372036854775808", "584543y", "500000y 500000y",
175 } {
176 if got, err := timeSpan(in); err == nil {
177 t.Errorf("timeSpan(%q) = %v, want an error", in, got)
178 }
179 }
180}
181
182// A read of origin that fails while two batches run stops the pass from
183// starting anything more: the job queued behind them never starts, and no
184// read follows. The loop still takes both batches' ends, which come after
185// the failed read began, and records each one's failure and wait, with its
186// attest run. The pass then fails with the read's error, and leaves its
187// claim, including the mark it claimed for that read, unacknowledged.
188func TestAFailedReadStopsAdmissionAndDrainsTheRunningBatches(t *testing.T) {
189 state, wakeDir, telDir := t.TempDir(), t.TempDir(), t.TempDir()
190 mark := func() {
191 if err := os.WriteFile(filepath.Join(wakeDir, "due"), nil, 0o600); err != nil {
192 t.Fatal(err)
193 }
194 }
195 mark()
196 claim := claimWake(wakeDir, io.Discard)
197 defer claim.close()
198 // The emitter drops a record it cannot store within its deadline, and
199 // every record emitted while that store is still under way, so on a
200 // loaded machine the records below would be missing. Each record is
201 // waited for instead.
202 tel := openWorkerTelemetry(telDir)
203 tel.tel.SetDeadline(time.Minute)
204 w := &worker{batches: 2, interval: time.Millisecond, wake: claim, stdout: io.Discard, stderr: io.Discard,
205 seen: map[string]int{}, running: map[string]*batch{}, said: map[string]map[string]bool{},
206 tel: tel, failures: readFailures(filepath.Join(state, "failures.json"), io.Discard)}
207 jobs := []*job{testJob("app", "a", 1, "refs/a", "build a"), testJob("app", "b", 1, "refs/b", "build b"),
208 testJob("app", "c", 1, "refs/c", "build c")}
209 var launched []*batch
210 reads := 0
211 w.read = func(git, string) ([]*job, error) {
212 reads++
213 if reads == 1 {
214 mark() // a ready push while the pass reads
215 return jobs, nil
216 }
217 // Both batches end while this read is under way, and fail.
218 for _, b := range launched {
219 go func() { w.done <- completion{b: b, err: errors.New("exit status 1"), ended: time.Now()} }()
220 }
221 return nil, failure("app: origin did not answer; the pass stops here")
222 }
223 w.recheck = func(*job) (bool, error) { return true, nil }
224 w.launch = func(b *batch) { launched = append(launched, b) }
225
226 err := w.pass(git{}, []string{"app"})
227 if err == nil || err.Error() != "app: origin did not answer; the pass stops here" {
228 t.Fatalf("the pass returned %v, want the read's error", err)
229 }
230 if reads != 2 {
231 t.Errorf("the pass read %d times, want 2: none after the read that failed", reads)
232 }
233 if len(launched) != 2 || launched[0].job != jobs[0] || launched[1].job != jobs[1] {
234 t.Errorf("the pass started %d batches, want a's and b's alone", len(launched))
235 }
236 if len(w.running) != 0 {
237 t.Errorf("the pass ended with %d batches running", len(w.running))
238 }
239 record := readFailures(filepath.Join(state, "failures.json"), io.Discard).Projects["app"]
240 for _, key := range []string{"build a", "build b"} {
241 if record[key].Failures != 1 {
242 t.Errorf("failures.json holds %q as %+v, want one failure", key, record[key])
243 }
244 }
245 if _, err := os.Stat(filepath.Join(wakeDir, "claimed")); err != nil {
246 t.Errorf("the claim was acknowledged: %v", err)
247 }
248 if _, err := os.Stat(filepath.Join(wakeDir, "due")); err == nil {
249 t.Error("the mark made during the first read was not claimed before the second")
250 }
251 recs, _, err := (&telemetry.Stream{Dir: w.tel.stream()}).Read(0, 1000, 1<<20)
252 if err != nil {
253 t.Fatal(err)
254 }
255 for _, b := range launched {
256 for _, typ := range []string{"batch.start", "batch.end", "backoff"} {
257 n := 0
258 for _, r := range recs {
259 if r.Type == typ && r.Data["attest_run"] == b.run {
260 n++
261 }
262 }
263 if n != 1 {
264 t.Errorf("the stream holds %d %s records naming attest run %s, want 1", n, typ, b.run)
265 }
266 }
267 }
268}
269
270// The worker reads both layers at main's tip as approve does, and refuses
271// a layer that cannot be read rather than reading it as absent. An
272// unreadable floor is not sent to the owning valley that policy/valley
273// names, though that valley's floor reads, and an unreadable project layer
274// is not derived as the floor alone.
275func TestPolicyLayersRefuseALayerThatCannotBeRead(t *testing.T) {
276 dir := t.TempDir()
277 t.Setenv("HOME", dir)
278 t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
279 commit := func(repo string, files map[string]string) string {
280 t.Helper()
281 run := func(args ...string) string {
282 t.Helper()
283 cmd := exec.Command("git", append([]string{"-c", "user.name=t", "-c", "user.email=t@localhost"}, args...)...)
284 cmd.Dir = repo
285 out, err := cmd.CombinedOutput()
286 if err != nil {
287 t.Fatalf("git %v: %v\n%s", args, err, out)
288 }
289 return strings.TrimSpace(string(out))
290 }
291 if err := os.MkdirAll(repo, 0o755); err != nil {
292 t.Fatal(err)
293 }
294 run("init", "--quiet", "--initial-branch=main")
295 for path, body := range files {
296 full := filepath.Join(repo, path)
297 if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
298 t.Fatal(err)
299 }
300 if err := os.WriteFile(full, []byte(body), 0o644); err != nil {
301 t.Fatal(err)
302 }
303 }
304 run("add", "--all")
305 run("commit", "--quiet", "-m", "layers")
306 return run("rev-parse", "HEAD")
307 }
308 valley := filepath.Join(dir, "valley")
309 commit(valley, map[string]string{"policy/instance/floor.cue": "package verification // the valley's\n"})
310
311 for _, lost := range []string{"", instanceLayer, projectLayer, projectLayer + "/policy.cue"} {
312 t.Run("lost "+lost, func(t *testing.T) {
313 repo := filepath.Join(t.TempDir(), "app")
314 tip := commit(repo, map[string]string{
315 instanceLayer + "/floor.cue": "package verification // its own\n",
316 projectLayer + "/policy.cue": "package verification // the project's\n",
317 valleyPointer: valley + "\n",
318 })
319 if lost != "" {
320 out, err := exec.Command("git", "-C", repo, "rev-parse", tip+":"+lost).Output()
321 if err != nil {
322 t.Fatal(err)
323 }
324 oid := strings.TrimSpace(string(out))
325 if err := os.Remove(filepath.Join(repo, ".git", "objects", oid[:2], oid[2:])); err != nil {
326 t.Fatal(err)
327 }
328 }
329 instance, project, done, err := policyLayers(git{env: os.Environ(), stderr: io.Discard, dir: repo}, tip)
330 defer done()
331 if lost == "" {
332 if err != nil {
333 t.Fatal(err)
334 }
335 for path, want := range map[string]string{
336 filepath.Join(instance, "floor.cue"): "package verification // its own\n",
337 filepath.Join(project, "policy.cue"): "package verification // the project's\n",
338 } {
339 if body, err := os.ReadFile(path); err != nil || string(body) != want {
340 t.Errorf("%s reads %q (%v), not %q", path, body, err, want)
341 }
342 }
343 return
344 }
345 if err == nil {
346 t.Fatalf("an unreadable %s resolved the layers to %s and %s", lost, instance, project)
347 }
348 if !strings.Contains(err.Error(), "reading "+lost) {
349 t.Errorf("the refusal %q does not say that %s could not be read", err, lost)
350 }
351 })
352 }
353}