gunk-dev/the-valley

checkbuild_test.go

sourcecfedff357a41main's published tip history
36.5 KiB
1package main
2
3import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "os"
9 "os/exec"
10 "path/filepath"
11 "reflect"
12 "strconv"
13 "strings"
14 "syscall"
15 "testing"
16 "time"
17
18 "the-valley/change"
19 "the-valley/telemetry"
20)
21
22const rigTree = "71ee"
23
24// buildRig is a worktree whose origin is a bare repository, and the
25// command's work in it, with the evidence reads and the worker stream the
26// test's: each read takes the next of reads, and the stream plays follows.
27type buildRig struct {
28 t *testing.T
29 origin, work, gitDir string
30 base, head string
31 a *asking
32 out, errs, states bytes.Buffer
33 reads []fakeRead
34 read int
35 stream *fakeStream
36}
37
38// fakeRead is one read of origin's evidence: the checks it covers, those
39// whose evidence does not count, or an error.
40type fakeRead struct {
41 covered, mismatched []string
42 err error
43}
44
45func newBuildRig(t *testing.T, nix ...string) *buildRig {
46 t.Helper()
47 dir := t.TempDir()
48 t.Setenv("HOME", dir)
49 t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "config"))
50 t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
51 r := &buildRig{t: t, origin: filepath.Join(dir, "origin.git"), work: filepath.Join(dir, "work")}
52 r.git(dir, "init", "--quiet", "--bare", "--initial-branch=main", r.origin)
53 r.git(dir, "clone", "--quiet", r.origin, r.work)
54 r.git(r.work, "config", "user.name", "build-test")
55 r.git(r.work, "config", "user.email", "build-test@localhost")
56 r.git(r.work, "config", "valley.principal", "alice")
57 r.git(r.work, "commit", "--quiet", "--allow-empty", "-m", "base")
58 r.base = r.git(r.work, "rev-parse", "HEAD")
59 r.git(r.work, "push", "--quiet", "origin", "HEAD:refs/heads/main")
60 r.git(r.work, "commit", "--quiet", "--allow-empty", "-m", "draft")
61 r.head = r.git(r.work, "rev-parse", "HEAD")
62 r.gitDir = r.git(r.work, "rev-parse", "--absolute-git-dir")
63 r.stream = &fakeStream{t: t}
64
65 a := newAsking(git{env: gitEnvironment(os.Environ()), stderr: &r.errs, dir: r.work}, &r.out, &r.errs)
66 a.states, a.readEvery = &r.states, time.Hour
67 a.derive = func() error {
68 a.head, a.short, a.project = r.head, r.head[:7], "app"
69 a.required = len(nix)
70 for _, name := range nix {
71 a.nix = append(a.nix, nixCheck{name, name})
72 }
73 return nil
74 }
75 a.cover = func([]nixCheck) (evidence, error) {
76 f := r.reads[min(r.read, len(r.reads)-1)]
77 r.read++
78 e := evidence{digest: rigTree, covered: map[string]string{}, failed: map[string]string{}}
79 for _, name := range f.covered {
80 e.covered[name] = "ref worker"
81 }
82 for _, name := range f.mismatched {
83 e.failed[name] = "ref worker"
84 }
85 return e, f.err
86 }
87 a.stream = r.stream
88 r.a = a
89 return r
90}
91
92func (r *buildRig) git(dir string, args ...string) string {
93 r.t.Helper()
94 cmd := exec.Command("git", args...)
95 cmd.Dir = dir
96 out, err := cmd.CombinedOutput()
97 if err != nil {
98 r.t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
99 }
100 return strings.TrimSpace(string(out))
101}
102
103// requests is every check request origin holds, as "<ref> <commit>".
104func (r *buildRig) requests() string {
105 return r.git(r.origin, "for-each-ref", "--format=%(refname) %(objectname)", change.CheckRequestPrefix)
106}
107
108// run runs the work and checks its exit status.
109func (r *buildRig) run(want int) {
110 r.t.Helper()
111 if got := r.a.run(); got != want {
112 r.t.Errorf("exit %d, want %d\nstdout:\n%s\nstderr:\n%s", got, want, r.out.String(), r.errs.String())
113 }
114}
115
116func (r *buildRig) says(out *bytes.Buffer, lines ...string) {
117 r.t.Helper()
118 for _, line := range lines {
119 if !strings.Contains(out.String(), line) {
120 r.t.Errorf("output lacks %q:\n%s", line, out.String())
121 }
122 }
123}
124
125func (r *buildRig) saysNot(out *bytes.Buffer, lines ...string) {
126 r.t.Helper()
127 for _, line := range lines {
128 if strings.Contains(out.String(), line) {
129 r.t.Errorf("output holds %q:\n%s", line, out.String())
130 }
131 }
132}
133
134// fakeStream plays each follow in turn: before, then its records, then
135// its cursor or err. Past the last follow it waits for the follow's end.
136type fakeStream struct {
137 t *testing.T
138 endErr error
139 follows []fakeFollow
140 ended int
141}
142
143type fakeFollow struct {
144 before func()
145 records []workerRecord
146 err error
147}
148
149// end is the cursor before the filing, seq 1, and then the mark after
150// it, seq 10.
151func (s *fakeStream) end(context.Context) (string, error) {
152 s.ended++
153 if s.ended == 1 {
154 return "worker=0123456789abcdef:1", s.endErr
155 }
156 return "worker=0123456789abcdef:10", s.endErr
157}
158
159func (s *fakeStream) follow(ctx context.Context, cursor string, seconds int, records chan<- workerRecord) (string, error) {
160 if len(s.follows) == 0 {
161 <-ctx.Done()
162 return "", ctx.Err()
163 }
164 f := s.follows[0]
165 s.follows = s.follows[1:]
166 if f.before != nil {
167 f.before()
168 }
169 for _, r := range f.records {
170 select {
171 case records <- r:
172 case <-ctx.Done():
173 return "", ctx.Err()
174 }
175 }
176 return cursor, f.err
177}
178
179func record(typ, run, tree string, data map[string]any) workerRecord {
180 return workerRecord{Type: typ, Run: run, Project: "app", Tree: tree, Data: data}
181}
182
183func treeBatchEnd(result string) workerRecord {
184 return record("batch.end", "p1", rigTree, map[string]any{"attest_run": "attest-1", "result": result})
185}
186
187// resultFor is a check.result for the tree, with data.
188func resultFor(check string, data map[string]any) workerRecord {
189 rec := record("check.result", "attest-1", rigTree, data)
190 rec.Check = check
191 return rec
192}
193
194func published() workerRecord {
195 return record("publish.end", "p1", rigTree, map[string]any{"result": "passed"})
196}
197
198func TestCheckBuildWaitFlag(t *testing.T) {
199 for _, c := range []struct {
200 args []string
201 want time.Duration
202 bad bool
203 }{
204 {args: []string{"--build"}, want: 2 * time.Hour},
205 {args: []string{"--build", "--wait", "30m"}, want: 30 * time.Minute},
206 {args: []string{"--wait=45s", "--build"}, want: 45 * time.Second},
207 {args: []string{"--build", "--wait", "0s"}, bad: true},
208 {args: []string{"--build", "--names"}, bad: true},
209 } {
210 got, err := buildWait(c.args)
211 if (err != nil) != c.bad || !c.bad && got != c.want {
212 t.Errorf("%q: %v, %v", c.args, got, err)
213 }
214 }
215}
216
217// One complete first read passes without filing or reading the worker.
218func TestCheckBuildPassesWithoutFiling(t *testing.T) {
219 r := newBuildRig(t, "fast", "slow")
220 r.reads = []fakeRead{{covered: []string{"fast", "slow"}}}
221 r.run(0)
222 r.says(&r.out, "✓ "+r.head[:7]+" 2 checks passed")
223 if r.stream.ended != 0 || r.requests() != "" {
224 t.Errorf("the stream was read, or a request filed: %q", r.requests())
225 }
226}
227
228// Only the last read decides: reads that together covered every check do
229// not pass when the last read fails. The request is deleted.
230func TestCheckBuildLastReadDecides(t *testing.T) {
231 r := newBuildRig(t, "fast", "slow")
232 r.a.readEvery = time.Nanosecond
233 r.reads = []fakeRead{{covered: []string{"slow"}}, {covered: []string{"fast"}}, {err: errors.New("origin did not answer")}}
234 r.stream.follows = []fakeFollow{{}, {records: []workerRecord{published()}}}
235 r.run(1)
236 r.says(&r.out, "not established · the worker published for this tree · evidence unreadable")
237 r.saysNot(&r.out, "passed")
238 if r.read != 3 || r.requests() != "" {
239 t.Errorf("%d reads; origin holds %q", r.read, r.requests())
240 }
241}
242
243// Evidence that does not count for a check is no evidence for it, never
244// a failure: the request is filed, and the check has no evidence.
245func TestCheckBuildMismatchIsNoEvidence(t *testing.T) {
246 r := newBuildRig(t, "fast", "slow")
247 r.reads = []fakeRead{{covered: []string{"fast"}, mismatched: []string{"slow"}}}
248 r.stream.follows = []fakeFollow{{records: []workerRecord{published()}}}
249 r.run(1)
250 r.says(&r.out, "◇ slow no evidence on origin", "not established", "1 of 2 with evidence")
251 r.saysNot(&r.out, "fail", "✗")
252 r.says(&r.states, "filing ")
253}
254
255// A pass.end ends the wait only after its pass.start came after the
256// filing: a pass that started before may not have read the request. A
257// batch that passed is no wake-up either: its evidence is on origin only
258// once it publishes.
259func TestCheckBuildPassEndNeedsItsStart(t *testing.T) {
260 r := newBuildRig(t, "fast")
261 r.reads = []fakeRead{{}}
262 waited := false
263 r.stream.follows = []fakeFollow{
264 {records: []workerRecord{{Seq: 11, Type: "pass.end", Run: "p0"}, treeBatchEnd("passed"),
265 {Seq: 5, Type: "pass.start", Run: "p2"}, {Seq: 12, Type: "pass.end", Run: "p2"}}},
266 {before: func() { waited = r.read == 1 }, records: []workerRecord{{Seq: 21, Type: "pass.start", Run: "p1"}, {Seq: 22, Type: "pass.end", Run: "p1"}}},
267 }
268 r.run(1)
269 r.says(&r.out, "not established · a worker pass ended")
270 if !waited {
271 t.Error("the wait ended at a pass.end whose start it did not see")
272 }
273}
274
275// A pass ends only once none of its batches runs, so its end settles the
276// batches for the tree it started, even one whose batch.end the stream
277// lost. Another pass's end does not: another worker writing to the same
278// stream can end a pass while this one builds the tree.
279func TestCheckBuildPassEndSettlesItsOwnBatches(t *testing.T) {
280 r := newBuildRig(t, "fast")
281 r.reads = []fakeRead{{}}
282 waited := false
283 r.stream.follows = []fakeFollow{
284 {records: []workerRecord{{Seq: 11, Type: "pass.start", Run: "pa"},
285 record("batch.start", "pa", rigTree, map[string]any{"attest_run": "attest-1"}),
286 {Seq: 13, Type: "pass.start", Run: "pb"}, {Seq: 14, Type: "pass.end", Run: "pb"}}},
287 {before: func() { waited = true }, records: []workerRecord{{Seq: 20, Type: "pass.end", Run: "pa"}}},
288 {records: []workerRecord{published()}},
289 }
290 r.run(1)
291 r.says(&r.out, "not established · a worker pass ended")
292 if !waited {
293 t.Error("another pass's end ended the wait while a batch for the tree ran")
294 }
295}
296
297// Each wake-up ends the wait in the last read; with every check covered
298// there, it passes.
299func TestCheckBuildWakes(t *testing.T) {
300 for _, c := range []struct {
301 name string
302 follow fakeFollow
303 endErr error
304 last []string
305 status int
306 says string
307 }{
308 {name: "a publish for the tree ends", follow: fakeFollow{records: []workerRecord{published()}},
309 last: []string{"fast"}, status: 0, says: "1 check passed"},
310 {name: "a quick worker's batch fails before the mark", follow: fakeFollow{records: []workerRecord{
311 func() workerRecord { r := treeBatchEnd("failed"); r.Seq = 5; return r }()}},
312 status: 1, says: "not established · the worker's batch for this tree ended with failures"},
313 {name: "the follow fails", follow: fakeFollow{err: errors.New("the host refused")}, status: 1, says: "not established · telemetry unreadable"},
314 {name: "the stream cannot be read", endErr: errors.New("no observe grant"), status: 1, says: "not established · telemetry unreadable"},
315 } {
316 t.Run(c.name, func(t *testing.T) {
317 r := newBuildRig(t, "fast")
318 r.reads = []fakeRead{{}, {covered: c.last}}
319 r.stream.endErr, r.stream.follows = c.endErr, []fakeFollow{c.follow}
320 r.run(c.status)
321 r.says(&r.out, c.says)
322 if r.requests() != "" || r.read != 2 {
323 t.Errorf("origin holds %q; %d reads, want the first and the last", r.requests(), r.read)
324 }
325 })
326 }
327}
328
329// A gap in the stream, before, between or after the tree's results, a
330// producer's dropped_before or the host's gap, ends nothing, and the wait
331// passes on evidence that covers every check once the worker publishes.
332// Reads for gaps and the periodic reads keep one pace, never two within
333// readEvery: the first gap is read for, the gaps that follow it are not,
334// the periodic read comes a readEvery later, and a gap just after that
335// read is not read for either.
336func TestCheckBuildWaitsThroughGaps(t *testing.T) {
337 r := newBuildRig(t, "fast", "slow")
338 r.reads = []fakeRead{{}}
339 clock := time.Unix(1_000_000, 0)
340 r.a.readEvery, r.a.now = time.Minute, func() time.Time { return clock }
341 readsBefore := 0
342 r.stream.follows = []fakeFollow{
343 {before: func() { clock = clock.Add(time.Second) }, records: []workerRecord{{gap: true}}},
344 {records: []workerRecord{resultFor("fast", map[string]any{"result": "passed", "dropped_before": float64(2)})}},
345 {records: []workerRecord{resultFor("slow", map[string]any{"result": "passed"})}},
346 {records: []workerRecord{{gap: true}}},
347 {before: func() { clock = clock.Add(time.Minute) }},
348 {before: func() { clock = clock.Add(time.Second) }, records: []workerRecord{{gap: true}}},
349 {before: func() {
350 readsBefore, r.reads = r.read, []fakeRead{{covered: []string{"fast", "slow"}}}
351 }, records: []workerRecord{published()}},
352 }
353 r.run(0)
354 r.says(&r.out, "✓ "+r.head[:7]+" 2 checks passed")
355 r.says(&r.states, "lost\n")
356 if readsBefore != 3 || r.requests() != "" {
357 t.Errorf("%d reads before the publish, want the first, the first gap's and the periodic one; origin holds %q", readsBefore, r.requests())
358 }
359}
360
361// A gap's read passes when it covers every check: the publish's record
362// the gap hid is no longer needed.
363func TestCheckBuildGapReadPasses(t *testing.T) {
364 r := newBuildRig(t, "fast")
365 r.reads = []fakeRead{{}, {covered: []string{"fast"}}}
366 r.stream.follows = []fakeFollow{
367 {records: []workerRecord{resultFor("fast", map[string]any{"result": "passed"})}},
368 {records: []workerRecord{{gap: true}}},
369 }
370 r.run(0)
371 r.says(&r.out, "✓ "+r.head[:7]+" 1 check passed")
372 if r.read != 2 || r.requests() != "" {
373 t.Errorf("%d reads, want the first and the gap's; origin holds %q", r.read, r.requests())
374 }
375}
376
377// A gap does not hide a failure the stream still carries: the wait ends
378// at the failed batch, prints the failed check, and says the worker's
379// records may be incomplete, as the parent does from the state pipe.
380func TestCheckBuildFailureAfterAGap(t *testing.T) {
381 r := newBuildRig(t, "fast", "slow")
382 r.reads = []fakeRead{{}, {covered: []string{"slow"}}}
383 failed := record("check.result", "attest-1", rigTree, map[string]any{"result": "failed", "dropped_before": float64(1)})
384 failed.Check = "fast"
385 r.stream.follows = []fakeFollow{{records: []workerRecord{failed, treeBatchEnd("failed")}}}
386 r.run(1)
387 lost := " the worker's stream lost records, so those for this tree may be incomplete\n"
388 r.says(&r.out, "not established · the worker's batch for this tree ended with failures", lost,
389 " fast failed", " fast · failed\n")
390 var s childState
391 s.read(strings.NewReader(r.states.String()))
392 var out bytes.Buffer
393 report(&out, s.results, s.attrs, s.lost)
394 if !strings.HasPrefix(out.String(), lost) {
395 t.Errorf("the parent's report does not say the records may be incomplete:\n%s", out.String())
396 }
397}
398
399// On the wire, a gap the host reports in a follow reaches the wait in its
400// place among the records, and the follow reads on to its end; a refusal
401// still ends it, and one for lack of a slot, of any kind an observe
402// request draws on, is told from the others, as is other text that ends
403// the same way.
404func TestWorkerStreamHandsOnGaps(t *testing.T) {
405 dir, bin := t.TempDir(), t.TempDir()
406 self, err := filepath.Abs(os.Args[0])
407 if err != nil {
408 t.Fatal(err)
409 }
410 if err := os.Symlink(self, filepath.Join(bin, "ssh")); err != nil {
411 t.Fatal(err)
412 }
413 t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
414 t.Setenv("FAKE_SSH_DIR", dir)
415 answer := filepath.Join(dir, "valley-host.answer")
416 follow := func(lines ...string) ([]workerRecord, string, error) {
417 os.WriteFile(answer, []byte(strings.Join(lines, "\n")+"\n"), 0o600)
418 records := make(chan workerRecord, 8)
419 cursor, err := sshStream{sshDest{host: "valley-host"}}.follow(context.Background(), "worker=0123456789abcdef:4", 10, records)
420 close(records)
421 var got []workerRecord
422 for r := range records {
423 got = append(got, r)
424 }
425 return got, cursor, err
426 }
427 got, cursor, err := follow(`{"kind":"header","format":"valley-telemetry/v1"}`,
428 `{"kind":"record","stream":"worker","seq":5,"type":"pass.start","run":"p1"}`,
429 `{"kind":"gap","stream":"worker","reason":"retention","from":6,"to":8}`,
430 `{"kind":"record","stream":"worker","seq":9,"type":"pass.end","run":"p1"}`,
431 `{"kind":"end","cursor":"worker=0123456789abcdef:9"}`)
432 if err != nil || cursor != "worker=0123456789abcdef:9" || len(got) != 3 ||
433 got[0].Seq != 5 || got[0].gap || !got[1].gap || got[2].Seq != 9 || got[2].gap {
434 t.Errorf("the follow handed %+v, ended at %q, %v", got, cursor, err)
435 }
436 var busy noSlot
437 for _, why := range []string{"no observe grant", "the host is busy; try again when one ends"} {
438 if _, _, err := follow(`{"kind":"error","error":"` + why + `"}`); err == nil || !strings.Contains(err.Error(), "the host refused") || errors.As(err, &busy) {
439 t.Errorf("a refusal ended the follow with %v", err)
440 }
441 }
442 for _, why := range []string{
443 telemetry.SlotRefusal("operator", telemetry.FollowSlots, "follow"),
444 "operator already has 4 observe requests open; try again when one ends",
445 } {
446 if _, _, err := follow(`{"kind":"error","error":"` + why + `"}`); !errors.As(err, &busy) {
447 t.Errorf("a refusal for lack of a slot ended the follow with %v", err)
448 }
449 }
450}
451
452// A follow the host refuses for lack of a slot, at the start or when the
453// wait follows again, ends nothing: the wait says so once, reads origin
454// every readEvery, follows again after each read, and passes once origin
455// holds the evidence. With no follow, a request gone from origin ends the
456// wait, and any other error ends it as telemetry unreadable.
457func TestCheckBuildWaitsThroughARefusedFollow(t *testing.T) {
458 busy := noSlot{"the host refused: " + telemetry.SlotRefusal("alice", telemetry.FollowSlots, "follow")}
459 for _, c := range []struct {
460 name string
461 follows func(r *buildRig) []fakeFollow
462 reads []fakeRead
463 status int
464 says string
465 paced time.Duration
466 }{
467 {name: "refused at the start and again, it passes on origin's evidence",
468 follows: func(*buildRig) []fakeFollow { return []fakeFollow{{err: busy}, {}, {err: busy}} },
469 reads: []fakeRead{{}, {}, {covered: []string{"fast"}}},
470 status: 0, says: "1 check passed", paced: 2 * time.Minute},
471 {name: "refused, and then refused for another reason",
472 follows: func(*buildRig) []fakeFollow {
473 return []fakeFollow{{err: busy}, {err: errors.New("the host refused: alice does not hold the telemetry observe grant")}}
474 },
475 reads: []fakeRead{{}},
476 status: 1, says: "not established · telemetry unreadable", paced: time.Minute},
477 {name: "refused, and the request deleted from origin",
478 follows: func(r *buildRig) []fakeFollow {
479 return []fakeFollow{{err: busy, before: func() {
480 r.git(r.origin, "update-ref", "-d", strings.Fields(r.requests())[0])
481 }}}
482 },
483 reads: []fakeRead{{}},
484 status: 1, says: "not established · the check request is gone from origin", paced: time.Minute},
485 } {
486 t.Run(c.name, func(t *testing.T) {
487 r := newBuildRig(t, "fast")
488 r.reads, r.stream.follows = c.reads, c.follows(r)
489 clock, paced := time.Unix(1_000_000, 0), time.Duration(0)
490 r.a.readEvery, r.a.now = time.Minute, func() time.Time { return clock }
491 r.a.sleep = func(d time.Duration) { clock, paced = clock.Add(d), paced+d }
492 r.run(c.status)
493 r.says(&r.out, c.says)
494 if n := strings.Count(r.errs.String(), "follow requests open"); n != 1 {
495 t.Errorf("the refusal was said %d times:\n%s", n, r.errs.String())
496 }
497 if paced != c.paced || r.requests() != "" {
498 t.Errorf("the wait slept %s, want %s; origin holds %q", paced, c.paced, r.requests())
499 }
500 r.saysNot(&r.states, "lost\n")
501 })
502 }
503}
504
505// What the worker wrote for the tree is printed as its records, not this
506// request's result: each check.result, and for each failed check the nix
507// log command for the derivation its result names, the error and build
508// error it records, escaped, or with neither a derivation nor an error the
509// command that builds it here. A drv that is
510// not a derivation's store path is never printed as a command.
511func TestCheckBuildReportsTheTreesRecords(t *testing.T) {
512 r := newBuildRig(t, "fast", "slow", "lint", "docs")
513 r.reads = []fakeRead{{}}
514 drv := "/nix/store/0123456789abcdfghijklmnpqrsvwxyz-slow-check.drv"
515 result := func(check, res string, ms float64, data map[string]any) workerRecord {
516 rec := record("check.result", "attest-1", rigTree, map[string]any{"result": res, "check_ms": ms})
517 for k, v := range data {
518 rec.Data[k] = v
519 }
520 rec.Check = check
521 return rec
522 }
523 other := result("fast", "failed", 1, nil)
524 other.Tree = "0the4"
525 r.stream.follows = []fakeFollow{{records: []workerRecord{
526 record("batch.start", "p1", rigTree, map[string]any{"attest_run": "attest-1"}),
527 other, result("fast", "passed", 1000, map[string]any{"drv": drv}),
528 result("slow", "failed", 2000, map[string]any{"drv": drv, "build_error": "signal: killed\nsettled"}),
529 result("lint", "error", 3000, map[string]any{"error": "evaluating lint: \x1b[31mno\nsuch check", "build_error": "exit status 1"}),
530 result("docs", "failed", 4000, map[string]any{"drv": "/nix/store/x.drv; touch pwned"}),
531 treeBatchEnd("failed"),
532 }}}
533 r.run(1)
534 r.says(&r.out, "not established · the worker's batch for this tree ended with failures",
535 "the worker's recent records for this tree, not this request's result:",
536 " fast passed · 1s", " slow failed · 2s",
537 ` slow · failed · the worker's build error, untrusted: signal: killed\nsettled`+"\n run: nix log "+drv+"\n",
538 ` lint · error · the worker's error, untrusted: evaluating lint: \x1b[31mno\nsuch check · the worker's build error, untrusted: exit status 1`+"\n slow",
539 " docs · failed\n run: nix build --no-link -L .#checks."+buildSystem()+".docs\n",
540 "see: valley telemetry read --source worker --logs · when nix log has none")
541 r.saysNot(&r.out, "fast failed", "\x1b[31m", "pwned", "nix log /nix/store/x")
542}
543
544// A push that dies in transport leaves the request's existence unknown:
545// the leased delete is tried, and printed when origin cannot confirm it.
546func TestCheckBuildPushDiesInTransport(t *testing.T) {
547 r := newBuildRig(t, "fast")
548 r.reads = []fakeRead{{}}
549 hook := "#!/bin/sh\nkill -9 $PPID\n"
550 if err := os.WriteFile(filepath.Join(r.origin, "hooks", "pre-receive"), []byte(hook), 0o755); err != nil {
551 t.Fatal(err)
552 }
553 r.run(1)
554 r.says(&r.errs, "push did not finish", "is not established", "run: git push --force-with-lease="+r.a.ref+":"+r.head+" origin :"+r.a.ref)
555 r.says(&r.out, "not established · the request's push did not finish")
556 r.saysNot(&r.errs, "refused", "not filed")
557}
558
559// A push origin refuses files nothing, and leaves nothing to delete.
560func TestCheckBuildRefused(t *testing.T) {
561 r := newBuildRig(t, "fast")
562 r.reads = []fakeRead{{}}
563 hook := "#!/bin/sh\necho 'not this one' >&2\nexit 1\n"
564 if err := os.WriteFile(filepath.Join(r.origin, "hooks", "pre-receive"), []byte(hook), 0o755); err != nil {
565 t.Fatal(err)
566 }
567 r.run(1)
568 r.says(&r.errs, "origin refused the check request: not this one")
569 r.saysNot(&r.errs, "is not established")
570}
571
572// The worktree's token is read or made, and its earlier requests deleted,
573// only under its lock: while another holds it, the command makes no token
574// and deletes nothing.
575func TestCheckBuildTokenAndRecoveryUnderTheLock(t *testing.T) {
576 r := newBuildRig(t, "fast")
577 r.reads = []fakeRead{{}}
578 lock, err := os.OpenFile(filepath.Join(r.gitDir, requestLockFile), os.O_CREATE|os.O_RDWR, 0o600)
579 if err != nil {
580 t.Fatal(err)
581 }
582 defer lock.Close()
583 if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX); err != nil {
584 t.Fatal(err)
585 }
586 r.run(1)
587 r.says(&r.errs, "another valley checks --build is running in this worktree")
588 if _, err := os.Stat(filepath.Join(r.gitDir, worktreeTokenFile)); err == nil {
589 t.Error("a token was made without the lock")
590 }
591
592 r = newBuildRig(t, "fast")
593 r.reads = []fakeRead{{}}
594 token := "0123456789abcdef"
595 os.WriteFile(filepath.Join(r.gitDir, worktreeTokenFile), []byte(token+"\n"), 0o600)
596 earlier, _ := change.CheckRequestRef("alice", token, "00000000000000aa")
597 r.git(r.work, "push", "--quiet", "origin", "HEAD:"+earlier)
598 lock, err = os.OpenFile(filepath.Join(r.gitDir, requestLockFile), os.O_CREATE|os.O_RDWR, 0o600)
599 if err != nil {
600 t.Fatal(err)
601 }
602 defer lock.Close()
603 syscall.Flock(int(lock.Fd()), syscall.LOCK_EX)
604 r.run(1)
605 if got := r.requests(); got != earlier+" "+r.head {
606 t.Errorf("origin holds %q, want the earlier request untouched", got)
607 }
608}
609
610// With the lock, the worktree's earlier requests go, each leased, and
611// another worktree's stays.
612func TestCheckBuildRecoversEarlierRequests(t *testing.T) {
613 r := newBuildRig(t, "fast")
614 r.reads = []fakeRead{{}, {covered: []string{"fast"}}}
615 token := "0123456789abcdef"
616 os.WriteFile(filepath.Join(r.gitDir, worktreeTokenFile), []byte(token+"\n"), 0o600)
617 earlier, _ := change.CheckRequestRef("alice", token, "00000000000000aa")
618 other, _ := change.CheckRequestRef("alice", "fedcba9876543210", "00000000000000bb")
619 r.git(r.work, "push", "--quiet", "origin", "HEAD:"+earlier, "HEAD:"+other)
620 r.stream.follows = []fakeFollow{{before: func() {
621 if got := r.requests(); got != other+" "+r.head+"\n"+r.a.ref+" "+r.head && got != r.a.ref+" "+r.head+"\n"+other+" "+r.head {
622 t.Errorf("while waiting, origin holds %q", got)
623 }
624 }, records: []workerRecord{published()}}}
625 r.run(0)
626 if got := r.requests(); got != other+" "+r.head {
627 t.Errorf("origin holds %q, want only the other worktree's", got)
628 }
629}
630
631// The deadline kills every program the command started, here the git
632// listing coverageOf runs to read origin's evidence, hung in its
633// transport, and the outcome is not established. The command is the
634// real one, run by the watchdog as a child: it derives the checks under a
635// floor, fetches main, and reads the evidence through coverageOf.
636func TestCheckBuildDeadline(t *testing.T) {
637 if _, err := exec.LookPath("cue"); err != nil {
638 if os.Getenv("VALLEY_TEST_TOOLS") == "required" {
639 t.Fatal("no cue on PATH, and VALLEY_TEST_TOOLS=required")
640 }
641 t.Skip("no cue to derive the checks with; the nix check provides one")
642 }
643 schema, err := filepath.Abs(filepath.Join("..", "schema", "verification.cue"))
644 if err != nil {
645 t.Fatal(err)
646 }
647 self, err := filepath.Abs(os.Args[0])
648 if err != nil {
649 t.Fatal(err)
650 }
651 dir := t.TempDir()
652 t.Setenv("HOME", dir)
653 t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "config"))
654 t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
655 t.Setenv("VALLEY_VERIFICATION_SCHEMA", schema)
656 r := &buildRig{t: t, origin: filepath.Join(dir, "origin.git"), work: filepath.Join(dir, "work")}
657 r.git(dir, "init", "--quiet", "--bare", "--initial-branch=main", r.origin)
658 r.git(dir, "clone", "--quiet", r.origin, r.work)
659 for _, kv := range [][2]string{{"user.name", "build-test"}, {"user.email", "build-test@localhost"}, {"valley.principal", "alice"}} {
660 r.git(r.work, "config", kv[0], kv[1])
661 }
662 write := func(path, body string) {
663 os.MkdirAll(filepath.Dir(path), 0o755)
664 if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
665 t.Fatal(err)
666 }
667 }
668 write(filepath.Join(r.work, "policy", "instance", "floor.cue"), "package verification\nfloor: {\n"+
669 "\tchecks: \"c-docs\": {runner: \"nix\", attribute: \"c-docs\"}\n\tunclassified: \"c-docs\": true\n}\n")
670 write(filepath.Join(r.work, "docs", "a.md"), "base\n")
671 r.git(r.work, "add", "-A")
672 r.git(r.work, "commit", "--quiet", "-m", "base")
673 r.git(r.work, "push", "--quiet", "origin", "HEAD:refs/heads/main")
674 write(filepath.Join(r.work, "docs", "b.md"), "draft\n")
675 r.git(r.work, "add", "-A")
676 r.git(r.work, "commit", "--quiet", "-m", "draft")
677 r.git(r.work, "remote", "set-url", "origin", "ssh://valley-host"+r.origin)
678
679 // ssh and attest are this test binary (TestMain): ssh serves origin
680 // for the first upload-pack, main's fetch, and hangs at the next, the
681 // listing; attest digests any tree.
682 bin, fake := filepath.Join(dir, "bin"), filepath.Join(dir, "fake")
683 os.Mkdir(bin, 0o755)
684 os.Mkdir(fake, 0o755)
685 for _, name := range []string{"ssh", "attest"} {
686 if err := os.Symlink(self, filepath.Join(bin, name)); err != nil {
687 t.Fatal(err)
688 }
689 }
690 t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
691 t.Setenv("FAKE_SSH_UPLOAD", fake)
692 t.Setenv("GIT_SSH_VARIANT", "ssh")
693 t.Chdir(r.work)
694
695 var out, errs bytes.Buffer
696 began := time.Now()
697 wait := 6 * time.Second
698 status := watch(git{env: gitEnvironment(os.Environ()), stderr: &errs}, self, wait, &out, &errs, make(chan os.Signal))
699 if status != 1 || !strings.Contains(out.String(), "not established · time limit") {
700 t.Errorf("exit %d\nstdout:\n%s\nstderr:\n%s", status, out.String(), errs.String())
701 }
702 if took := time.Since(began); took > wait+cleanupBound {
703 t.Errorf("the command took %s", took)
704 }
705 pid, err := os.ReadFile(filepath.Join(fake, "hung.pid"))
706 if err != nil {
707 t.Fatalf("the listing never reached origin: %v\nstderr:\n%s", err, errs.String())
708 }
709 if stat, err := os.ReadFile("/proc/" + strings.TrimSpace(string(pid)) + "/stat"); err == nil {
710 if f := strings.Fields(string(stat[bytes.LastIndexByte(stat, ')')+1:])); len(f) > 0 && f[0] != "Z" {
711 t.Errorf("the hung listing outlived the command: %s", stat)
712 }
713 }
714}
715
716// fakeUpload is ssh for TestCheckBuildDeadline: it serves the repository
717// an upload-pack names for the first one, and hangs at every later one.
718func fakeUpload(dir string, args []string) int {
719 path, ok := strings.CutPrefix(args[len(args)-1], "git-upload-pack ")
720 if !ok {
721 return 0
722 }
723 seen, _ := os.ReadFile(filepath.Join(dir, "uploads"))
724 os.WriteFile(filepath.Join(dir, "uploads"), append(seen, '.'), 0o600)
725 if len(seen) == 0 {
726 gitPath, err := exec.LookPath("git")
727 if err != nil {
728 return 255
729 }
730 syscall.Exec(gitPath, []string{"git", "upload-pack", strings.Trim(path, "'")}, os.Environ())
731 return 255
732 }
733 os.WriteFile(filepath.Join(dir, "hung.pid"), []byte(strconv.Itoa(os.Getpid())), 0o600)
734 time.Sleep(time.Hour)
735 return 255
736}
737
738// fakeAttest is attest for TestCheckBuildDeadline: every tree has one
739// digest. With VALLEY_TEST_ATTEST_VERIFY set, its verify is fakeVerify.
740func fakeAttest() int {
741 if mode := os.Getenv("VALLEY_TEST_ATTEST_VERIFY"); mode != "" && len(os.Args) > 1 && os.Args[1] == "verify" {
742 return fakeVerify(mode, os.Args[2:])
743 }
744 fmt.Println("valley-tree-v1:" + strings.Repeat("ab", 32))
745 return 0
746}
747
748// No check required passes at once, with nothing filed.
749func TestCheckBuildNoRequiredChecks(t *testing.T) {
750 r := newBuildRig(t)
751 r.run(0)
752 r.says(&r.out, "no checks required")
753 if r.stream.ended != 0 || r.requests() != "" {
754 t.Errorf("the stream was read, or a request filed: %q", r.requests())
755 }
756}
757
758// A telemetry record cannot speak for the child: one whose fields are not
759// a required check, a known result and a run name is dropped, and no value
760// holding a newline or space reaches the state pipe, so a crafted result
761// cannot tell the parent the request is settled.
762func TestCheckBuildStateCannotBeInjected(t *testing.T) {
763 r := newBuildRig(t, "fast")
764 r.a.derive()
765 r.a.tree = rigTree
766 for _, c := range []struct{ check, result, run string }{
767 {"fast", "failed\nsettled\n", "attest-1"},
768 {"fast\nsettled", "failed", "attest-1"},
769 {"lint", "failed", "attest-1"},
770 {"fast", "failed", "attest-1\nsettled"},
771 } {
772 rec := record("check.result", c.run, rigTree, map[string]any{"result": c.result})
773 rec.Check = c.check
774 r.a.wake(rec, map[string]bool{}, map[string]map[string]bool{})
775 }
776 r.a.state("filing", "refs/x", "abc")
777 r.a.state("result", "x\nsettled")
778 raw := r.states.String()
779 var s childState
780 s.read(&r.states)
781 if len(r.a.results) != 0 || s.settled || raw != "filing refs/x abc\n" {
782 t.Errorf("results %v, state pipe %q", r.a.results, raw)
783 }
784
785 // A result's derivation and errors reach the parent; an error, which
786 // can hold anything, goes encoded and arrives as the worker wrote it.
787 drv := "/nix/store/0123456789abcdfghijklmnpqrsvwxyz-fast.drv"
788 for _, data := range []map[string]any{{"result": "failed", "drv": drv, "build_error": "signal: killed\nsettled"}, {"result": "error", "error": "no\nsettled such check"}} {
789 rec := record("check.result", "attest-1", rigTree, data)
790 rec.Check = "fast"
791 r.a.wake(rec, map[string]bool{}, map[string]map[string]bool{})
792 }
793 s = childState{}
794 s.read(&r.states)
795 want := []treeResult{
796 {run: "attest-1", check: "fast", result: "failed", ms: -1, drv: drv, buildErr: "signal: killed\nsettled"},
797 {run: "attest-1", check: "fast", result: "error", ms: -1, err: "no\nsettled such check"},
798 }
799 if s.settled || !reflect.DeepEqual(s.results, want) {
800 t.Errorf("the parent read %+v, settled %v; want %+v", s.results, s.settled, want)
801 }
802}
803
804// Names and results print as one escaped line each, and a derivation
805// whose name a shell would expand prints quoted. A failed check that
806// names its derivation still points at the worker's output, which names
807// a dependency that failed; a report with no failed check does not.
808func TestCheckBuildReportEscapes(t *testing.T) {
809 var out bytes.Buffer
810 drv := "/nix/store/0123456789abcdfghijklmnpqrsvwxyz-a?b=c.drv"
811 report(&out, []treeResult{{run: "attest-1", check: "fa\x1b[31mst\nsettled", result: "failed", ms: 1000, drv: drv}}, nil, false)
812 for _, want := range []string{` fa\x1b[31mst\nsettled failed · 1s`, " run: nix log '" + drv + "'\n",
813 " see: valley telemetry read --source worker --logs · when nix log has none\n"} {
814 if !strings.Contains(out.String(), want) {
815 t.Errorf("%q lacks %q", out.String(), want)
816 }
817 }
818 out.Reset()
819 report(&out, []treeResult{{run: "attest-1", check: "fast", result: "passed", ms: 1000, drv: drv}}, nil, false)
820 if strings.Contains(out.String(), "see:") {
821 t.Errorf("a report with no failed check points at the worker's output: %q", out.String())
822 }
823}
824
825// Only a line rejecting the request's own ref is a rejection; a remote that
826// failed to report status, or another ref's rejection, leaves it unknown.
827func TestPushStatus(t *testing.T) {
828 ref := "refs/the-valley/check-requests/alice/0123456789abcdef/0123456789abcdef"
829 for _, c := range []struct{ out, want string }{
830 {"To origin\n!\tabc:" + ref + "\t[remote rejected] (pre-receive hook declined)\nDone\n", "rejected"},
831 {"!\tabc:" + ref + "\t[rejected] (stale info)\n", "rejected"},
832 {"!\tabc:" + ref + "\t[remote failure] (remote failed to report status)\n", "unknown"},
833 {"!\tabc:refs/heads/other\t[remote rejected] (no)\n", "unknown"},
834 {"", "unknown"},
835 } {
836 if got := pushStatus(c.out, ref); got != c.want {
837 t.Errorf("%q: %s, want %s", c.out, got, c.want)
838 }
839 }
840}
841
842// The parent exits 0 only when the child reported a pass: a child that
843// exits 0 without one is no pass.
844func TestCheckBuildFailsClosed(t *testing.T) {
845 self, err := exec.LookPath("true")
846 if err != nil {
847 t.Skip("no true on PATH")
848 }
849 var out, errs bytes.Buffer
850 if status := watch(git{env: os.Environ()}, self, time.Minute, &out, &errs, make(chan os.Signal)); status != 1 ||
851 !strings.Contains(errs.String(), "ended without an outcome") {
852 t.Errorf("exit %d\n%s%s", status, out.String(), errs.String())
853 }
854}
855
856// A token that does not read is reported, never replaced.
857func TestCheckBuildKeepsAMalformedToken(t *testing.T) {
858 r := newBuildRig(t, "fast")
859 r.reads = []fakeRead{{}}
860 path := filepath.Join(r.gitDir, worktreeTokenFile)
861 os.WriteFile(path, []byte("not a token\n"), 0o600)
862 r.run(1)
863 r.says(&r.errs, "holds no check request token")
864 if data, _ := os.ReadFile(path); string(data) != "not a token\n" || r.requests() != "" {
865 t.Errorf("the token is %q; origin holds %q", data, r.requests())
866 }
867}
868
869// An earlier request whose delete the child started and did not end is the
870// parent's to delete, leased; one the child cleared is not.
871func TestCheckBuildParentDeletesAStaleTarget(t *testing.T) {
872 r := newBuildRig(t, "fast")
873 cut, _ := change.CheckRequestRef("alice", "0123456789abcdef", "00000000000000aa")
874 done, _ := change.CheckRequestRef("alice", "0123456789abcdef", "00000000000000bb")
875 r.git(r.work, "push", "--quiet", "origin", "HEAD:"+cut, "HEAD:"+done)
876 var s childState
877 s.read(strings.NewReader("stale " + cut + " " + r.head + "\nstale " + done + " " + r.head + "\ncleared " + done + "\n"))
878 s.settle(git{env: gitEnvironment(os.Environ()), dir: r.work}, &r.errs, make(chan os.Signal))
879 if got := r.requests(); got != done+" "+r.head {
880 t.Errorf("origin holds %q, want only the cleared one", got)
881 }
882}
883
884// A diagnostic from the host prints as one escaped line, so it cannot
885// forge a verdict line of its own.
886func TestCheckBuildDiagnosticsStayOnOneLine(t *testing.T) {
887 r := newBuildRig(t, "fast")
888 r.reads = []fakeRead{{}}
889 r.stream.endErr = errors.New("denied\n✓ HEAD 1 check passed")
890 r.run(1)
891 r.says(&r.errs, `denied\n✓ HEAD 1 check passed`)
892 if strings.Contains(r.errs.String()+r.out.String(), "\n✓ HEAD") {
893 t.Errorf("a diagnostic broke its line:\n%s%s", r.out.String(), r.errs.String())
894 }
895}
896
897// A listed ref under the worktree's prefix that is no check request is
898// skipped, and never reaches the state pipe, however long.
899func TestCheckBuildSkipsAMalformedStaleRef(t *testing.T) {
900 r := newBuildRig(t, "fast")
901 r.reads = []fakeRead{{}, {covered: []string{"fast"}}}
902 token := "0123456789abcdef"
903 os.WriteFile(filepath.Join(r.gitDir, worktreeTokenFile), []byte(token+"\n"), 0o600)
904 long := change.CheckRequestPrefix + "alice/" + token + "/" + strings.Repeat("a", 60000)
905 if err := os.WriteFile(filepath.Join(r.origin, "packed-refs"), []byte(r.head+" "+long+"\n"), 0o644); err != nil {
906 t.Fatal(err)
907 }
908 r.stream.follows = []fakeFollow{{records: []workerRecord{published()}}}
909 r.run(0)
910 r.says(&r.errs, "is no check request, so it is skipped")
911 for _, line := range strings.Split(r.states.String(), "\n") {
912 if len(line) > 1000 {
913 t.Errorf("a %d-byte state line reached the pipe", len(line))
914 }
915 }
916}