gunk-dev/the-valley

checkbuild_test.go

source58e68be0d151main's published tip history
27.2 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
186func published() workerRecord {
187 return record("publish.end", "p1", rigTree, map[string]any{"result": "passed"})
188}
189
190func TestCheckBuildWaitFlag(t *testing.T) {
191 for _, c := range []struct {
192 args []string
193 want time.Duration
194 bad bool
195 }{
196 {args: []string{"--build"}, want: 2 * time.Hour},
197 {args: []string{"--build", "--wait", "30m"}, want: 30 * time.Minute},
198 {args: []string{"--wait=45s", "--build"}, want: 45 * time.Second},
199 {args: []string{"--build", "--wait", "0s"}, bad: true},
200 {args: []string{"--build", "--names"}, bad: true},
201 } {
202 got, err := buildWait(c.args)
203 if (err != nil) != c.bad || !c.bad && got != c.want {
204 t.Errorf("%q: %v, %v", c.args, got, err)
205 }
206 }
207}
208
209// One complete first read passes without filing or reading the worker.
210func TestCheckBuildPassesWithoutFiling(t *testing.T) {
211 r := newBuildRig(t, "fast", "slow")
212 r.reads = []fakeRead{{covered: []string{"fast", "slow"}}}
213 r.run(0)
214 r.says(&r.out, "✓ "+r.head[:7]+" 2 checks passed")
215 if r.stream.ended != 0 || r.requests() != "" {
216 t.Errorf("the stream was read, or a request filed: %q", r.requests())
217 }
218}
219
220// Only the last read decides: reads that together covered every check do
221// not pass when the last read fails. The request is deleted.
222func TestCheckBuildLastReadDecides(t *testing.T) {
223 r := newBuildRig(t, "fast", "slow")
224 r.a.readEvery = time.Nanosecond
225 r.reads = []fakeRead{{covered: []string{"slow"}}, {covered: []string{"fast"}}, {err: errors.New("origin did not answer")}}
226 r.stream.follows = []fakeFollow{{}, {records: []workerRecord{published()}}}
227 r.run(1)
228 r.says(&r.out, "not established · the worker published for this tree · evidence unreadable")
229 r.saysNot(&r.out, "passed")
230 if r.read != 3 || r.requests() != "" {
231 t.Errorf("%d reads; origin holds %q", r.read, r.requests())
232 }
233}
234
235// Evidence that does not count for a check is no evidence for it, never
236// a failure: the request is filed, and the check has no evidence.
237func TestCheckBuildMismatchIsNoEvidence(t *testing.T) {
238 r := newBuildRig(t, "fast", "slow")
239 r.reads = []fakeRead{{covered: []string{"fast"}, mismatched: []string{"slow"}}}
240 r.stream.follows = []fakeFollow{{records: []workerRecord{published()}}}
241 r.run(1)
242 r.says(&r.out, "◇ slow no evidence on origin", "not established", "1 of 2 with evidence")
243 r.saysNot(&r.out, "fail", "✗")
244 r.says(&r.states, "filing ")
245}
246
247// A pass.end ends the wait only after its pass.start came after the
248// filing: a pass that started before may not have read the request. A
249// batch that passed is no wake-up either: its evidence is on origin only
250// once it publishes.
251func TestCheckBuildPassEndNeedsItsStart(t *testing.T) {
252 r := newBuildRig(t, "fast")
253 r.reads = []fakeRead{{}}
254 waited := false
255 r.stream.follows = []fakeFollow{
256 {records: []workerRecord{{Seq: 11, Type: "pass.end", Run: "p0"}, treeBatchEnd("passed"),
257 {Seq: 5, Type: "pass.start", Run: "p2"}, {Seq: 12, Type: "pass.end", Run: "p2"}}},
258 {before: func() { waited = r.read == 1 }, records: []workerRecord{{Seq: 21, Type: "pass.start", Run: "p1"}, {Seq: 22, Type: "pass.end", Run: "p1"}}},
259 }
260 r.run(1)
261 r.says(&r.out, "not established · a worker pass ended")
262 if !waited {
263 t.Error("the wait ended at a pass.end whose start it did not see")
264 }
265}
266
267// Each wake-up ends the wait in the last read; with every check covered
268// there, it passes.
269func TestCheckBuildWakes(t *testing.T) {
270 for _, c := range []struct {
271 name string
272 follow fakeFollow
273 endErr error
274 last []string
275 status int
276 says string
277 }{
278 {name: "a publish for the tree ends", follow: fakeFollow{records: []workerRecord{published()}},
279 last: []string{"fast"}, status: 0, says: "1 check passed"},
280 {name: "a quick worker's batch fails before the mark", follow: fakeFollow{records: []workerRecord{
281 func() workerRecord { r := treeBatchEnd("failed"); r.Seq = 5; return r }()}},
282 status: 1, says: "not established · the worker's batch for this tree ended with failures"},
283 {name: "a producer lost records", follow: fakeFollow{records: []workerRecord{{Type: "check.output", Data: map[string]any{"dropped_before": float64(2)}}}},
284 status: 1, says: "not established · telemetry lost records"},
285 {name: "the follow fails", follow: fakeFollow{err: errors.New("the host refused")}, status: 1, says: "not established · telemetry unreadable"},
286 {name: "the stream cannot be read", endErr: errors.New("no observe grant"), status: 1, says: "not established · telemetry unreadable"},
287 } {
288 t.Run(c.name, func(t *testing.T) {
289 r := newBuildRig(t, "fast")
290 r.reads = []fakeRead{{}, {covered: c.last}}
291 r.stream.endErr, r.stream.follows = c.endErr, []fakeFollow{c.follow}
292 r.run(c.status)
293 r.says(&r.out, c.says)
294 if r.requests() != "" || r.read != 2 {
295 t.Errorf("origin holds %q; %d reads, want the first and the last", r.requests(), r.read)
296 }
297 })
298 }
299}
300
301// What the worker wrote for the tree is printed as its records, not this
302// request's result: each check.result, and for each failed check the nix
303// log command for the derivation its result names, the error and build
304// error it records, escaped, or with neither a derivation nor an error the
305// command that builds it here. A drv that is
306// not a derivation's store path is never printed as a command.
307func TestCheckBuildReportsTheTreesRecords(t *testing.T) {
308 r := newBuildRig(t, "fast", "slow", "lint", "docs")
309 r.reads = []fakeRead{{}}
310 drv := "/nix/store/0123456789abcdfghijklmnpqrsvwxyz-slow-check.drv"
311 result := func(check, res string, ms float64, data map[string]any) workerRecord {
312 rec := record("check.result", "attest-1", rigTree, map[string]any{"result": res, "check_ms": ms})
313 for k, v := range data {
314 rec.Data[k] = v
315 }
316 rec.Check = check
317 return rec
318 }
319 other := result("fast", "failed", 1, nil)
320 other.Tree = "0the4"
321 r.stream.follows = []fakeFollow{{records: []workerRecord{
322 record("batch.start", "p1", rigTree, map[string]any{"attest_run": "attest-1"}),
323 other, result("fast", "passed", 1000, map[string]any{"drv": drv}),
324 result("slow", "failed", 2000, map[string]any{"drv": drv, "build_error": "signal: killed\nsettled"}),
325 result("lint", "error", 3000, map[string]any{"error": "evaluating lint: \x1b[31mno\nsuch check", "build_error": "exit status 1"}),
326 result("docs", "failed", 4000, map[string]any{"drv": "/nix/store/x.drv; touch pwned"}),
327 treeBatchEnd("failed"),
328 }}}
329 r.run(1)
330 r.says(&r.out, "not established · the worker's batch for this tree ended with failures",
331 "the worker's recent records for this tree, not this request's result:",
332 " fast passed · 1s", " slow failed · 2s",
333 ` slow · failed · the worker's build error, untrusted: signal: killed\nsettled`+"\n run: nix log "+drv+"\n",
334 ` lint · error · the worker's error, untrusted: evaluating lint: \x1b[31mno\nsuch check · the worker's build error, untrusted: exit status 1`+"\n slow",
335 " docs · failed\n run: nix build --no-link -L .#checks."+buildSystem()+".docs\n",
336 "see: valley telemetry read --source worker --logs · when nix log has none")
337 r.saysNot(&r.out, "fast failed", "\x1b[31m", "pwned", "nix log /nix/store/x")
338}
339
340// A push that dies in transport leaves the request's existence unknown:
341// the leased delete is tried, and printed when origin cannot confirm it.
342func TestCheckBuildPushDiesInTransport(t *testing.T) {
343 r := newBuildRig(t, "fast")
344 r.reads = []fakeRead{{}}
345 hook := "#!/bin/sh\nkill -9 $PPID\n"
346 if err := os.WriteFile(filepath.Join(r.origin, "hooks", "pre-receive"), []byte(hook), 0o755); err != nil {
347 t.Fatal(err)
348 }
349 r.run(1)
350 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)
351 r.says(&r.out, "not established · the request's push did not finish")
352 r.saysNot(&r.errs, "refused", "not filed")
353}
354
355// A push origin refuses files nothing, and leaves nothing to delete.
356func TestCheckBuildRefused(t *testing.T) {
357 r := newBuildRig(t, "fast")
358 r.reads = []fakeRead{{}}
359 hook := "#!/bin/sh\necho 'not this one' >&2\nexit 1\n"
360 if err := os.WriteFile(filepath.Join(r.origin, "hooks", "pre-receive"), []byte(hook), 0o755); err != nil {
361 t.Fatal(err)
362 }
363 r.run(1)
364 r.says(&r.errs, "origin refused the check request: not this one")
365 r.saysNot(&r.errs, "is not established")
366}
367
368// The worktree's token is read or made, and its earlier requests deleted,
369// only under its lock: while another holds it, the command makes no token
370// and deletes nothing.
371func TestCheckBuildTokenAndRecoveryUnderTheLock(t *testing.T) {
372 r := newBuildRig(t, "fast")
373 r.reads = []fakeRead{{}}
374 lock, err := os.OpenFile(filepath.Join(r.gitDir, requestLockFile), os.O_CREATE|os.O_RDWR, 0o600)
375 if err != nil {
376 t.Fatal(err)
377 }
378 defer lock.Close()
379 if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX); err != nil {
380 t.Fatal(err)
381 }
382 r.run(1)
383 r.says(&r.errs, "another valley checks --build is running in this worktree")
384 if _, err := os.Stat(filepath.Join(r.gitDir, worktreeTokenFile)); err == nil {
385 t.Error("a token was made without the lock")
386 }
387
388 r = newBuildRig(t, "fast")
389 r.reads = []fakeRead{{}}
390 token := "0123456789abcdef"
391 os.WriteFile(filepath.Join(r.gitDir, worktreeTokenFile), []byte(token+"\n"), 0o600)
392 earlier, _ := change.CheckRequestRef("alice", token, "00000000000000aa")
393 r.git(r.work, "push", "--quiet", "origin", "HEAD:"+earlier)
394 lock, err = os.OpenFile(filepath.Join(r.gitDir, requestLockFile), os.O_CREATE|os.O_RDWR, 0o600)
395 if err != nil {
396 t.Fatal(err)
397 }
398 defer lock.Close()
399 syscall.Flock(int(lock.Fd()), syscall.LOCK_EX)
400 r.run(1)
401 if got := r.requests(); got != earlier+" "+r.head {
402 t.Errorf("origin holds %q, want the earlier request untouched", got)
403 }
404}
405
406// With the lock, the worktree's earlier requests go, each leased, and
407// another worktree's stays.
408func TestCheckBuildRecoversEarlierRequests(t *testing.T) {
409 r := newBuildRig(t, "fast")
410 r.reads = []fakeRead{{}, {covered: []string{"fast"}}}
411 token := "0123456789abcdef"
412 os.WriteFile(filepath.Join(r.gitDir, worktreeTokenFile), []byte(token+"\n"), 0o600)
413 earlier, _ := change.CheckRequestRef("alice", token, "00000000000000aa")
414 other, _ := change.CheckRequestRef("alice", "fedcba9876543210", "00000000000000bb")
415 r.git(r.work, "push", "--quiet", "origin", "HEAD:"+earlier, "HEAD:"+other)
416 r.stream.follows = []fakeFollow{{before: func() {
417 if got := r.requests(); got != other+" "+r.head+"\n"+r.a.ref+" "+r.head && got != r.a.ref+" "+r.head+"\n"+other+" "+r.head {
418 t.Errorf("while waiting, origin holds %q", got)
419 }
420 }, records: []workerRecord{published()}}}
421 r.run(0)
422 if got := r.requests(); got != other+" "+r.head {
423 t.Errorf("origin holds %q, want only the other worktree's", got)
424 }
425}
426
427// The deadline kills every program the command started, here the git
428// listing coverageOf runs to read origin's evidence, hung in its
429// transport, and the outcome is not established. The command is the
430// real one, run by the watchdog as a child: it derives the checks under a
431// floor, fetches main, and reads the evidence through coverageOf.
432func TestCheckBuildDeadline(t *testing.T) {
433 if _, err := exec.LookPath("cue"); err != nil {
434 if os.Getenv("VALLEY_TEST_TOOLS") == "required" {
435 t.Fatal("no cue on PATH, and VALLEY_TEST_TOOLS=required")
436 }
437 t.Skip("no cue to derive the checks with; the nix check provides one")
438 }
439 schema, err := filepath.Abs(filepath.Join("..", "schema", "verification.cue"))
440 if err != nil {
441 t.Fatal(err)
442 }
443 self, err := filepath.Abs(os.Args[0])
444 if err != nil {
445 t.Fatal(err)
446 }
447 dir := t.TempDir()
448 t.Setenv("HOME", dir)
449 t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "config"))
450 t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
451 t.Setenv("VALLEY_VERIFICATION_SCHEMA", schema)
452 r := &buildRig{t: t, origin: filepath.Join(dir, "origin.git"), work: filepath.Join(dir, "work")}
453 r.git(dir, "init", "--quiet", "--bare", "--initial-branch=main", r.origin)
454 r.git(dir, "clone", "--quiet", r.origin, r.work)
455 for _, kv := range [][2]string{{"user.name", "build-test"}, {"user.email", "build-test@localhost"}, {"valley.principal", "alice"}} {
456 r.git(r.work, "config", kv[0], kv[1])
457 }
458 write := func(path, body string) {
459 os.MkdirAll(filepath.Dir(path), 0o755)
460 if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
461 t.Fatal(err)
462 }
463 }
464 write(filepath.Join(r.work, "policy", "instance", "floor.cue"), "package verification\nfloor: {\n"+
465 "\tchecks: \"c-docs\": {runner: \"nix\", attribute: \"c-docs\"}\n\tunclassified: \"c-docs\": true\n}\n")
466 write(filepath.Join(r.work, "docs", "a.md"), "base\n")
467 r.git(r.work, "add", "-A")
468 r.git(r.work, "commit", "--quiet", "-m", "base")
469 r.git(r.work, "push", "--quiet", "origin", "HEAD:refs/heads/main")
470 write(filepath.Join(r.work, "docs", "b.md"), "draft\n")
471 r.git(r.work, "add", "-A")
472 r.git(r.work, "commit", "--quiet", "-m", "draft")
473 r.git(r.work, "remote", "set-url", "origin", "ssh://valley-host"+r.origin)
474
475 // ssh and attest are this test binary (TestMain): ssh serves origin
476 // for the first upload-pack, main's fetch, and hangs at the next, the
477 // listing; attest digests any tree.
478 bin, fake := filepath.Join(dir, "bin"), filepath.Join(dir, "fake")
479 os.Mkdir(bin, 0o755)
480 os.Mkdir(fake, 0o755)
481 for _, name := range []string{"ssh", "attest"} {
482 if err := os.Symlink(self, filepath.Join(bin, name)); err != nil {
483 t.Fatal(err)
484 }
485 }
486 t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
487 t.Setenv("FAKE_SSH_UPLOAD", fake)
488 t.Setenv("GIT_SSH_VARIANT", "ssh")
489 t.Chdir(r.work)
490
491 var out, errs bytes.Buffer
492 began := time.Now()
493 wait := 6 * time.Second
494 status := watch(git{env: gitEnvironment(os.Environ()), stderr: &errs}, self, wait, &out, &errs, make(chan os.Signal))
495 if status != 1 || !strings.Contains(out.String(), "not established · time limit") {
496 t.Errorf("exit %d\nstdout:\n%s\nstderr:\n%s", status, out.String(), errs.String())
497 }
498 if took := time.Since(began); took > wait+cleanupBound {
499 t.Errorf("the command took %s", took)
500 }
501 pid, err := os.ReadFile(filepath.Join(fake, "hung.pid"))
502 if err != nil {
503 t.Fatalf("the listing never reached origin: %v\nstderr:\n%s", err, errs.String())
504 }
505 if stat, err := os.ReadFile("/proc/" + strings.TrimSpace(string(pid)) + "/stat"); err == nil {
506 if f := strings.Fields(string(stat[bytes.LastIndexByte(stat, ')')+1:])); len(f) > 0 && f[0] != "Z" {
507 t.Errorf("the hung listing outlived the command: %s", stat)
508 }
509 }
510}
511
512// fakeUpload is ssh for TestCheckBuildDeadline: it serves the repository
513// an upload-pack names for the first one, and hangs at every later one.
514func fakeUpload(dir string, args []string) int {
515 path, ok := strings.CutPrefix(args[len(args)-1], "git-upload-pack ")
516 if !ok {
517 return 0
518 }
519 seen, _ := os.ReadFile(filepath.Join(dir, "uploads"))
520 os.WriteFile(filepath.Join(dir, "uploads"), append(seen, '.'), 0o600)
521 if len(seen) == 0 {
522 gitPath, err := exec.LookPath("git")
523 if err != nil {
524 return 255
525 }
526 syscall.Exec(gitPath, []string{"git", "upload-pack", strings.Trim(path, "'")}, os.Environ())
527 return 255
528 }
529 os.WriteFile(filepath.Join(dir, "hung.pid"), []byte(strconv.Itoa(os.Getpid())), 0o600)
530 time.Sleep(time.Hour)
531 return 255
532}
533
534// fakeAttest is attest for TestCheckBuildDeadline: every tree has one
535// digest.
536func fakeAttest() int {
537 fmt.Println("valley-tree-v1:" + strings.Repeat("ab", 32))
538 return 0
539}
540
541// No check required passes at once, with nothing filed.
542func TestCheckBuildNoRequiredChecks(t *testing.T) {
543 r := newBuildRig(t)
544 r.run(0)
545 r.says(&r.out, "no checks required")
546 if r.stream.ended != 0 || r.requests() != "" {
547 t.Errorf("the stream was read, or a request filed: %q", r.requests())
548 }
549}
550
551// A telemetry record cannot speak for the child: one whose fields are not
552// a required check, a known result and a run name is dropped, and no value
553// holding a newline or space reaches the state pipe, so a crafted result
554// cannot tell the parent the request is settled.
555func TestCheckBuildStateCannotBeInjected(t *testing.T) {
556 r := newBuildRig(t, "fast")
557 r.a.derive()
558 r.a.tree = rigTree
559 for _, c := range []struct{ check, result, run string }{
560 {"fast", "failed\nsettled\n", "attest-1"},
561 {"fast\nsettled", "failed", "attest-1"},
562 {"lint", "failed", "attest-1"},
563 {"fast", "failed", "attest-1\nsettled"},
564 } {
565 rec := record("check.result", c.run, rigTree, map[string]any{"result": c.result})
566 rec.Check = c.check
567 r.a.wake(rec, map[string]bool{}, map[string]bool{})
568 }
569 r.a.state("filing", "refs/x", "abc")
570 r.a.state("result", "x\nsettled")
571 raw := r.states.String()
572 var s childState
573 s.read(&r.states)
574 if len(r.a.results) != 0 || s.settled || raw != "filing refs/x abc\n" {
575 t.Errorf("results %v, state pipe %q", r.a.results, raw)
576 }
577
578 // A result's derivation and errors reach the parent; an error, which
579 // can hold anything, goes encoded and arrives as the worker wrote it.
580 drv := "/nix/store/0123456789abcdfghijklmnpqrsvwxyz-fast.drv"
581 for _, data := range []map[string]any{{"result": "failed", "drv": drv, "build_error": "signal: killed\nsettled"}, {"result": "error", "error": "no\nsettled such check"}} {
582 rec := record("check.result", "attest-1", rigTree, data)
583 rec.Check = "fast"
584 r.a.wake(rec, map[string]bool{}, map[string]bool{})
585 }
586 s = childState{}
587 s.read(&r.states)
588 want := []treeResult{
589 {run: "attest-1", check: "fast", result: "failed", ms: -1, drv: drv, buildErr: "signal: killed\nsettled"},
590 {run: "attest-1", check: "fast", result: "error", ms: -1, err: "no\nsettled such check"},
591 }
592 if s.settled || !reflect.DeepEqual(s.results, want) {
593 t.Errorf("the parent read %+v, settled %v; want %+v", s.results, s.settled, want)
594 }
595}
596
597// Names and results print as one escaped line each, and a derivation
598// whose name a shell would expand prints quoted. A failed check that
599// names its derivation still points at the worker's output, which names
600// a dependency that failed; a report with no failed check does not.
601func TestCheckBuildReportEscapes(t *testing.T) {
602 var out bytes.Buffer
603 drv := "/nix/store/0123456789abcdfghijklmnpqrsvwxyz-a?b=c.drv"
604 report(&out, []treeResult{{run: "attest-1", check: "fa\x1b[31mst\nsettled", result: "failed", ms: 1000, drv: drv}}, nil)
605 for _, want := range []string{` fa\x1b[31mst\nsettled failed · 1s`, " run: nix log '" + drv + "'\n",
606 " see: valley telemetry read --source worker --logs · when nix log has none\n"} {
607 if !strings.Contains(out.String(), want) {
608 t.Errorf("%q lacks %q", out.String(), want)
609 }
610 }
611 out.Reset()
612 report(&out, []treeResult{{run: "attest-1", check: "fast", result: "passed", ms: 1000, drv: drv}}, nil)
613 if strings.Contains(out.String(), "see:") {
614 t.Errorf("a report with no failed check points at the worker's output: %q", out.String())
615 }
616}
617
618// Only a line rejecting the request's own ref is a rejection; a remote that
619// failed to report status, or another ref's rejection, leaves it unknown.
620func TestPushStatus(t *testing.T) {
621 ref := "refs/the-valley/check-requests/alice/0123456789abcdef/0123456789abcdef"
622 for _, c := range []struct{ out, want string }{
623 {"To origin\n!\tabc:" + ref + "\t[remote rejected] (pre-receive hook declined)\nDone\n", "rejected"},
624 {"!\tabc:" + ref + "\t[rejected] (stale info)\n", "rejected"},
625 {"!\tabc:" + ref + "\t[remote failure] (remote failed to report status)\n", "unknown"},
626 {"!\tabc:refs/heads/other\t[remote rejected] (no)\n", "unknown"},
627 {"", "unknown"},
628 } {
629 if got := pushStatus(c.out, ref); got != c.want {
630 t.Errorf("%q: %s, want %s", c.out, got, c.want)
631 }
632 }
633}
634
635// The parent exits 0 only when the child reported a pass: a child that
636// exits 0 without one is no pass.
637func TestCheckBuildFailsClosed(t *testing.T) {
638 self, err := exec.LookPath("true")
639 if err != nil {
640 t.Skip("no true on PATH")
641 }
642 var out, errs bytes.Buffer
643 if status := watch(git{env: os.Environ()}, self, time.Minute, &out, &errs, make(chan os.Signal)); status != 1 ||
644 !strings.Contains(errs.String(), "ended without an outcome") {
645 t.Errorf("exit %d\n%s%s", status, out.String(), errs.String())
646 }
647}
648
649// A token that does not read is reported, never replaced.
650func TestCheckBuildKeepsAMalformedToken(t *testing.T) {
651 r := newBuildRig(t, "fast")
652 r.reads = []fakeRead{{}}
653 path := filepath.Join(r.gitDir, worktreeTokenFile)
654 os.WriteFile(path, []byte("not a token\n"), 0o600)
655 r.run(1)
656 r.says(&r.errs, "holds no check request token")
657 if data, _ := os.ReadFile(path); string(data) != "not a token\n" || r.requests() != "" {
658 t.Errorf("the token is %q; origin holds %q", data, r.requests())
659 }
660}
661
662// An earlier request whose delete the child started and did not end is the
663// parent's to delete, leased; one the child cleared is not.
664func TestCheckBuildParentDeletesAStaleTarget(t *testing.T) {
665 r := newBuildRig(t, "fast")
666 cut, _ := change.CheckRequestRef("alice", "0123456789abcdef", "00000000000000aa")
667 done, _ := change.CheckRequestRef("alice", "0123456789abcdef", "00000000000000bb")
668 r.git(r.work, "push", "--quiet", "origin", "HEAD:"+cut, "HEAD:"+done)
669 var s childState
670 s.read(strings.NewReader("stale " + cut + " " + r.head + "\nstale " + done + " " + r.head + "\ncleared " + done + "\n"))
671 s.settle(git{env: gitEnvironment(os.Environ()), dir: r.work}, &r.errs, make(chan os.Signal))
672 if got := r.requests(); got != done+" "+r.head {
673 t.Errorf("origin holds %q, want only the cleared one", got)
674 }
675}
676
677// A diagnostic from the host prints as one escaped line, so it cannot
678// forge a verdict line of its own.
679func TestCheckBuildDiagnosticsStayOnOneLine(t *testing.T) {
680 r := newBuildRig(t, "fast")
681 r.reads = []fakeRead{{}}
682 r.stream.endErr = errors.New("denied\n✓ HEAD 1 check passed")
683 r.run(1)
684 r.says(&r.errs, `denied\n✓ HEAD 1 check passed`)
685 if strings.Contains(r.errs.String()+r.out.String(), "\n✓ HEAD") {
686 t.Errorf("a diagnostic broke its line:\n%s%s", r.out.String(), r.errs.String())
687 }
688}
689
690// A listed ref under the worktree's prefix that is no check request is
691// skipped, and never reaches the state pipe, however long.
692func TestCheckBuildSkipsAMalformedStaleRef(t *testing.T) {
693 r := newBuildRig(t, "fast")
694 r.reads = []fakeRead{{}, {covered: []string{"fast"}}}
695 token := "0123456789abcdef"
696 os.WriteFile(filepath.Join(r.gitDir, worktreeTokenFile), []byte(token+"\n"), 0o600)
697 long := change.CheckRequestPrefix + "alice/" + token + "/" + strings.Repeat("a", 60000)
698 if err := os.WriteFile(filepath.Join(r.origin, "packed-refs"), []byte(r.head+" "+long+"\n"), 0o644); err != nil {
699 t.Fatal(err)
700 }
701 r.stream.follows = []fakeFollow{{records: []workerRecord{published()}}}
702 r.run(0)
703 r.says(&r.errs, "is no check request, so it is skipped")
704 for _, line := range strings.Split(r.states.String(), "\n") {
705 if len(line) > 1000 {
706 t.Errorf("a %d-byte state line reached the pipe", len(line))
707 }
708 }
709}