gunk-dev/the-valley

checkbuild_test.go

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