gunk-dev/the-valley

checkbuild.go

source69d7baef1f04main's published tip history
33.5 KiB
1package main
2
3// checks --build asks one question: does origin hold passing evidence for
4// every nix check HEAD requires? It asks the host's check worker to build
5// what is missing, and waits.
6//
7// It derives HEAD's checks as the worker derives a check request's
8// (worker.go): over HEAD's merge base with main as origin holds it now,
9// under both policy layers read there (checks.go). It reads origin's
10// evidence for HEAD's tree as approve does (coverage.go); evidence that
11// does not count for a check, whatever it records, is no evidence for it.
12// When one read covers every check, it passes without filing anything.
13//
14// Otherwise it takes the worktree's lock, reads or makes the worktree's
15// token under it, deletes the requests the worktree left on origin, each
16// leased on the commit listed, takes a cursor at the end of the worker's
17// telemetry, and files a check request (../change/checkrequest.go) for
18// HEAD with a new attempt token. It follows the telemetry from the cursor
19// as a wake-up only: the wait ends when a batch for HEAD's tree fails or
20// ends unpassed, when a publish for the tree ends (a batch that passed
21// publishes before the evidence is on origin, so its batch.end is no
22// wake-up), when a pass ends whose pass.start came after the stream's end
23// read once the push returned, with no batch for the tree running, when a
24// record says its producer lost records (dropped_before), or when the
25// stream cannot be read. The cursor comes before the filing so a worker
26// quick to finish is not missed. It also reads origin's evidence every
27// evidenceEvery. No record is taken as this request's result.
28//
29// It has two outcomes. Passed (exit 0) only when one read, the last,
30// completes and covers every check. Anything else is not established
31// (exit 1): it says why it stopped, and prints the check.result records
32// the worker wrote for HEAD's tree, labelled as such, with each failed
33// check's build output where a --logs read holds it, or else the command
34// that builds that check here.
35//
36// The command runs as a child of itself in a process group of its own.
37// The parent fixes the deadline (--wait) before the child starts, and
38// kills the child's group when the child ends, the deadline passes or a
39// signal comes; a program that made a group of its own escapes that. The
40// child tells the parent on a pipe, in validated values only, what it
41// filed or is deleting, and whether it passed; the parent deletes, leased,
42// what the child left, and exits 0 only on a reported pass. A push that
43// did not report success leaves the request's existence unknown: it is
44// deleted, leased, and unless origin then lists it absent after a push
45// origin refused, the leased delete is printed.
46
47import (
48 "bufio"
49 "bytes"
50 "context"
51 "encoding/json"
52 "errors"
53 "fmt"
54 "io"
55 "os"
56 "os/exec"
57 "os/signal"
58 "path/filepath"
59 "regexp"
60 "runtime"
61 "sort"
62 "strconv"
63 "strings"
64 "syscall"
65 "time"
66
67 "the-valley/change"
68 "the-valley/telemetry"
69)
70
71const checkBuildUsage = "usage: valley checks --build [--wait <duration>]"
72
73const (
74 // checkBuildChild is the verb the parent runs the command as, with
75 // the state pipe at the descriptor checkBuildState names.
76 checkBuildChild = "checks-build-child"
77 checkBuildState = "VALLEY_CHECK_BUILD_STATE"
78 // What the command keeps in a worktree's git directory.
79 worktreeTokenFile = "valley-check-request"
80 requestLockFile = "valley-check-request.lock"
81)
82
83// defaultWait is --wait's default. A ready change has first claim on the
84// worker, so a request can wait behind the host's whole queue; two hours
85// outlasts a busy host's queue and one cold build of a large check set.
86const defaultWait = 2 * time.Hour
87
88// evidenceEvery is how often the wait reads origin's evidence whatever the
89// telemetry says, since the stream can drop a wake-up unseen; cleanupBound
90// is how long deleting the request may take.
91const (
92 evidenceEvery = 3 * time.Minute
93 cleanupBound = 30 * time.Second
94)
95
96// tailLines is how much of a failed check's build output is printed.
97const tailLines = 60
98
99// runCheckBuild is valley checks --build: the parent, which watches the
100// child that does the work.
101func runCheckBuild(g git, args []string, stdout, stderr io.Writer) int {
102 wait, err := buildWait(args)
103 if err != nil {
104 fmt.Fprintf(stderr, "valley: %v\n%s\n", err, checkBuildUsage)
105 return 1
106 }
107 self, err := os.Executable()
108 if err != nil {
109 fmt.Fprintf(stderr, "valley: %v\n", err)
110 return 1
111 }
112 signals := make(chan os.Signal, 2)
113 signal.Notify(signals, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)
114 defer signal.Stop(signals)
115 return watch(g, self, wait, stdout, stderr, signals)
116}
117
118// buildMode reports whether a checks command line asks for --build.
119func buildMode(args []string) bool {
120 for _, a := range args {
121 if a == "--" {
122 return false
123 }
124 if a == "--build" {
125 return true
126 }
127 }
128 return false
129}
130
131// buildWait reads a checks --build command line: --build, and --wait with
132// a positive duration.
133func buildWait(args []string) (time.Duration, error) {
134 wait := defaultWait
135 for i := 0; i < len(args); i++ {
136 opt, value, inline := strings.Cut(args[i], "=")
137 switch {
138 case args[i] == "--build":
139 case opt == "--wait":
140 if !inline {
141 if i+1 >= len(args) {
142 return 0, errors.New("--wait needs a duration, such as 30m")
143 }
144 i++
145 value = args[i]
146 }
147 d, err := time.ParseDuration(value)
148 if err != nil || d <= 0 {
149 return 0, fmt.Errorf("--wait takes a positive duration, such as 30m or 2h, not %q", value)
150 }
151 wait = d
152 default:
153 return 0, errors.New("--build works on HEAD, and takes no option but --wait and no revision")
154 }
155 }
156 return wait, nil
157}
158
159// watch runs self as the child, and returns the exit status. When wait
160// passes or a signal comes first, it kills the child's process group,
161// deletes the request the child filed and did not delete, and says the
162// outcome is not established.
163func watch(g git, self string, wait time.Duration, stdout, stderr io.Writer, signals <-chan os.Signal) int {
164 deadline := time.NewTimer(wait)
165 defer deadline.Stop()
166 r, w, err := os.Pipe()
167 if err != nil {
168 fmt.Fprintf(stderr, "valley: %v\n", err)
169 return 1
170 }
171 defer r.Close()
172 cmd := exec.Command(self, checkBuildChild)
173 cmd.Env = append(os.Environ(), checkBuildState+"=3")
174 cmd.Stdout, cmd.Stderr, cmd.ExtraFiles = stdout, stderr, []*os.File{w}
175 cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
176 err = cmd.Start()
177 w.Close()
178 if err != nil {
179 fmt.Fprintf(stderr, "valley: %v\n", err)
180 return 1
181 }
182 // The pipe ends when the child does, since no program it starts holds
183 // it. The child is then unreaped, so its group can still be killed,
184 // with whatever the child left running.
185 var s childState
186 read := make(chan struct{})
187 go func() { s.read(r); close(read) }()
188 why := ""
189 select {
190 case <-read:
191 case <-deadline.C:
192 why = "time limit"
193 case <-signals:
194 why = "interrupted"
195 }
196 syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
197 err = cmd.Wait()
198 <-read
199 s.settle(g, stderr, signals)
200 var exit *exec.ExitError
201 switch {
202 case s.err != nil || err != nil && !errors.As(err, &exit):
203 fmt.Fprintf(stderr, "valley: the command did not end cleanly (%v), so whether its requests are deleted is not established\n", oneLine(errors.Join(err, s.err).Error()))
204 return 1
205 case why == "" && err == nil && s.passed:
206 return 0
207 case why == "" && err == nil:
208 fmt.Fprintln(stderr, "valley: the command ended without an outcome")
209 return 1
210 case why == "":
211 return exit.ExitCode()
212 }
213 t := terminalOf(stdout)
214 subject := s.short
215 if subject == "" {
216 subject = "HEAD"
217 }
218 fmt.Fprintln(stdout, t.tint(colourWaiting, "◇")+" "+t.strong(subject)+" not established · "+why)
219 report(stdout, s.results, s.attrs, nil)
220 if why == "interrupted" {
221 return interruptedStatus
222 }
223 return 1
224}
225
226// childState is what the child told the parent. settled means the child
227// tried to delete its request, and said so when it could not; stale is
228// each earlier request whose delete the child started and did not end.
229type childState struct {
230 short, ref, head, pushed string
231 settled, passed bool
232 attrs, stale map[string]string
233 results []treeResult
234 err error
235}
236
237// treeResult is a check.result the worker wrote for HEAD's tree.
238type treeResult struct {
239 run, check, result string
240 ms int64
241}
242
243func (s *childState) read(r io.Reader) {
244 s.attrs, s.stale = map[string]string{}, map[string]string{}
245 sc := bufio.NewScanner(r)
246 defer func() { s.err = sc.Err() }()
247 for sc.Scan() {
248 f := strings.Fields(sc.Text())
249 switch {
250 case len(f) == 2 && f[0] == "head":
251 s.short = f[1]
252 case len(f) == 3 && f[0] == "check":
253 s.attrs[f[1]] = f[2]
254 case len(f) == 5 && f[0] == "result":
255 ms, _ := strconv.ParseInt(f[4], 10, 64)
256 s.results = append(s.results, treeResult{f[1], f[2], f[3], ms})
257 case len(f) == 3 && f[0] == "filing":
258 s.ref, s.head, s.pushed, s.settled = f[1], f[2], "unknown", false
259 case len(f) == 2 && f[0] == "pushed":
260 s.pushed = f[1]
261 case len(f) == 1 && f[0] == "settled":
262 s.settled = true
263 case len(f) == 1 && f[0] == "passed":
264 s.passed = true
265 case len(f) == 3 && f[0] == "stale":
266 s.stale[f[1]] = f[2]
267 case len(f) == 2 && f[0] == "cleared":
268 delete(s.stale, f[1])
269 }
270 }
271}
272
273// settle deletes the requests the child left, within cleanupBound or until
274// a second signal.
275func (s *childState) settle(g git, stderr io.Writer, signals <-chan os.Signal) {
276 if (s.ref == "" || s.settled) && len(s.stale) == 0 {
277 return
278 }
279 ctx, cancel := context.WithTimeout(context.Background(), cleanupBound)
280 defer cancel()
281 go func() {
282 select {
283 case <-signals:
284 cancel()
285 case <-ctx.Done():
286 }
287 }()
288 if s.ref != "" && !s.settled && !deleteRequest(ctx, g, true, s.ref, s.head, s.pushed) {
289 unsettled(stderr, s.ref, s.head)
290 }
291 for ref, oid := range s.stale {
292 if !deleteRequest(ctx, g, true, ref, oid, "ok") {
293 unsettled(stderr, ref, oid)
294 }
295 }
296}
297
298// deleteRequest deletes ref on origin, leased on head, after a push that
299// reported pushed: ok, rejected or unknown. It reports whether origin is
300// known not to hold the request: the delete went through, or origin lists
301// it absent and the push did not leave its existence unknown.
302func deleteRequest(ctx context.Context, g git, group bool, ref, head, pushed string) bool {
303 if pushed != "rejected" {
304 if result, _ := pushOrigin(ctx, g, group, "--force-with-lease="+ref+":"+head, ":"+ref); result == "ok" {
305 return true
306 }
307 }
308 out, _, err := gitIn(ctx, g, group, "ls-remote", "--refs", "origin", ref)
309 return err == nil && !strings.Contains(out, "\t"+ref+"\n") && pushed != "unknown"
310}
311
312func unsettled(stderr io.Writer, ref, head string) {
313 fmt.Fprintf(stderr, "valley: whether origin still holds the check request is not established\n run: git push --force-with-lease=%s:%s origin :%s\n", ref, head, ref)
314}
315
316// pushOrigin pushes spec to origin, and says what origin reported: ok,
317// rejected when it refused the update, or unknown when the push ended
318// without saying, as a transport that failed does.
319func pushOrigin(ctx context.Context, g git, group bool, lease, spec string) (string, error) {
320 out, errs, err := gitIn(ctx, g, group, "push", "--porcelain", lease, "origin", spec)
321 if err == nil {
322 return "ok", nil
323 }
324 var said []string
325 for _, line := range strings.Split(errs, "\n") {
326 if remote, ok := strings.CutPrefix(line, "remote: "); ok && strings.TrimSpace(remote) != "" {
327 said = append(said, strings.TrimSpace(remote))
328 }
329 }
330 if len(said) == 0 {
331 said = []string{strings.TrimSpace(errs)}
332 }
333 return pushStatus(out, spec[strings.Index(spec, ":")+1:]), errors.New(strings.Join(said, "; "))
334}
335
336// pushStatus is what git push --porcelain reported for ref: rejected only
337// when its line rejects that ref, and unknown otherwise, as for a remote
338// that failed to report status.
339func pushStatus(out, ref string) string {
340 for _, line := range strings.Split(out, "\n") {
341 f := strings.SplitN(line, "\t", 3)
342 if len(f) == 3 && f[0] == "!" && strings.HasSuffix(f[1], ":"+ref) &&
343 (strings.HasPrefix(f[2], "[rejected]") || strings.HasPrefix(f[2], "[remote rejected]")) {
344 return "rejected"
345 }
346 }
347 return "unknown"
348}
349
350// gitIn runs git under ctx. In a group of its own, ending ctx kills the
351// group; the parent runs its git so, while the child runs its git in the
352// child's group, which the parent kills whole.
353func gitIn(ctx context.Context, g git, group bool, args ...string) (stdout, stderr string, err error) {
354 cmd := exec.CommandContext(ctx, "git", args...)
355 cmd.Env, cmd.Dir = g.env, g.dir
356 if group {
357 cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
358 cmd.Cancel = func() error { return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) }
359 }
360 cmd.WaitDelay = 2 * time.Second
361 var out, errs bytes.Buffer
362 cmd.Stdout, cmd.Stderr = &out, &errs
363 processStarted()
364 err = cmd.Run()
365 return out.String(), errs.String(), err
366}
367
368// runCheckBuildChild is the child: the command's work.
369func runCheckBuildChild(g git, args []string, stdout, stderr io.Writer) int {
370 if os.Getenv(checkBuildState) != "3" || len(args) != 0 {
371 fmt.Fprintf(stderr, "valley: unknown verb: %s\n", checkBuildChild)
372 return 1
373 }
374 syscall.CloseOnExec(3)
375 a := newAsking(g, stdout, stderr)
376 a.states = os.NewFile(3, "state")
377 status := a.run()
378 if status == 0 {
379 a.state("passed")
380 }
381 return status
382}
383
384// asking is the child's work.
385type asking struct {
386 g git
387 stdout, stderr io.Writer
388 t terminal
389 states io.Writer // the pipe to the parent
390 began time.Time
391 readEvery time.Duration
392 lock *os.File // the worktree's lock, held while the process runs
393
394 head, short, project, tree string
395 mark int64 // the stream's newest record once the request was filed
396 required int
397 nix []nixCheck
398 commands []string
399 ref string
400 results []treeResult
401
402 derive func() error
403 cover func(checks []nixCheck) (evidence, error)
404 stream workerStream
405}
406
407func newAsking(g git, stdout, stderr io.Writer) *asking {
408 a := &asking{g: g, stdout: stdout, stderr: stderr, t: terminalOf(stdout), states: io.Discard,
409 began: time.Now(), readEvery: evidenceEvery}
410 a.derive = a.prepare
411 a.cover = func(checks []nixCheck) (evidence, error) {
412 if _, err := exec.LookPath("attest"); err != nil {
413 return evidence{}, failure("the attest helper is not installed; nix run .#valley bundles it")
414 }
415 quiet := a.g
416 quiet.stderr = io.Discard
417 return coverageOf(quiet, a.head, checks, io.Discard)
418 }
419 return a
420}
421
422func (a *asking) run() int {
423 if err := a.derive(); err != nil {
424 return a.fail(err)
425 }
426 a.state("head", a.short)
427 if a.required == 0 {
428 a.say("✓", colourDone, a.short, "no checks required")
429 return 0
430 }
431 for _, c := range a.nix {
432 a.state("check", c.name, c.attribute)
433 }
434 covered, err := a.read()
435 if err != nil {
436 return a.fail(err)
437 }
438 if len(covered) == len(a.nix) {
439 return a.verdict(covered, nil, "")
440 }
441 principal, err := a.g.output(true, "config", "valley.principal")
442 if err != nil || !change.ValidPrincipal(principal) {
443 return a.fail(failure("a check request is filed under the principal your key pushes as, and git config valley.principal names none; set it with git config valley.principal <name>"))
444 }
445 token, err := a.claim(principal)
446 if err != nil {
447 return a.fail(err)
448 }
449 a.recoverStale(principal, token)
450 a.say("◐", colourWorking, a.short, countOf(len(a.nix), "nix check")+" required",
451 fmt.Sprintf("%d with evidence", len(covered)), "asking the worker")
452 cursor, err := a.stream.end(context.Background())
453 if err != nil {
454 fmt.Fprintf(a.stderr, "valley: %s\n", oneLine(err.Error()))
455 covered, err = a.read()
456 return a.verdict(covered, err, "telemetry unreadable")
457 }
458 attempt, err := change.NewCheckRequestToken()
459 if err != nil {
460 return a.fail(err)
461 }
462 a.ref, _ = change.CheckRequestRef(principal, token, attempt)
463 a.state("filing", a.ref, a.head)
464 pushed, err := pushOrigin(context.Background(), a.g, false, "--force-with-lease="+a.ref+":", a.head+":"+a.ref)
465 a.state("pushed", pushed)
466 why := ""
467 covered = nil
468 switch pushed {
469 case "rejected":
470 fmt.Fprintf(a.stderr, "valley: origin refused the check request: %s\n", oneLine(err.Error()))
471 why = "the request was refused"
472 case "unknown":
473 fmt.Fprintf(a.stderr, "valley: the check request's push did not finish: %s\n", oneLine(err.Error()))
474 why = "the request's push did not finish"
475 default:
476 why, covered = a.wait(cursor)
477 }
478 var readErr error
479 if covered == nil {
480 covered, readErr = a.read()
481 }
482 ctx, cancel := context.WithTimeout(context.Background(), cleanupBound)
483 defer cancel()
484 if !deleteRequest(ctx, a.g, false, a.ref, a.head, pushed) {
485 unsettled(a.stderr, a.ref, a.head)
486 }
487 a.state("settled")
488 return a.verdict(covered, readErr, why)
489}
490
491// state tells the parent one fact. A value outside stateValue, which no
492// newline or space is in, is never sent.
493func (a *asking) state(fields ...string) {
494 for _, f := range fields {
495 if !stateValue.MatchString(f) {
496 return
497 }
498 }
499 fmt.Fprintln(a.states, strings.Join(fields, " "))
500}
501
502var (
503 stateValue = regexp.MustCompile(`^[A-Za-z0-9._/:@+-]+$`)
504 runName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`) // telemetry's run names
505)
506
507// read reads origin's evidence for HEAD's tree, and returns the checks it
508// covers.
509func (a *asking) read() (map[string]bool, error) {
510 e, err := a.cover(a.nix)
511 if err != nil {
512 return nil, fmt.Errorf("could not read the evidence origin holds for HEAD's tree: %v", err)
513 }
514 a.tree = e.digest
515 covered := map[string]bool{}
516 for _, c := range a.nix {
517 if _, ok := e.covered[c.name]; ok {
518 covered[c.name] = true
519 }
520 }
521 return covered, nil
522}
523
524// claim takes the worktree's lock, held until the process ends, and reads
525// or makes the worktree's token under it.
526func (a *asking) claim(principal string) (string, error) {
527 gitDir, err := a.g.output(true, "rev-parse", "--absolute-git-dir")
528 if err != nil {
529 return "", failure("not a git repository")
530 }
531 lock, err := os.OpenFile(filepath.Join(gitDir, requestLockFile), os.O_CREATE|os.O_RDWR, 0o600)
532 if err != nil {
533 return "", err
534 }
535 if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
536 lock.Close()
537 return "", failure("another valley checks --build is running in this worktree")
538 }
539 a.lock = lock
540 path := filepath.Join(gitDir, worktreeTokenFile)
541 if data, err := os.ReadFile(path); err == nil {
542 token := strings.TrimSpace(string(data))
543 if _, ok := change.CheckRequestRef(principal, token, token); ok {
544 return token, nil
545 }
546 return "", failure(path + " holds no check request token; remove it, and the next run makes one")
547 } else if !os.IsNotExist(err) {
548 return "", err
549 }
550 token, err := change.NewCheckRequestToken()
551 if err != nil {
552 return "", err
553 }
554 if err := os.WriteFile(path+".new", []byte(token+"\n"), 0o600); err != nil {
555 return "", err
556 }
557 return token, os.Rename(path+".new", path)
558}
559
560// recoverStale deletes the requests origin lists under the worktree's
561// token, each leased on the commit listed. One it cannot delete is said,
562// with the leased delete.
563func (a *asking) recoverStale(principal, token string) {
564 prefix, _ := change.CheckRequestRef(principal, token, token)
565 prefix = strings.TrimSuffix(prefix, token)
566 out, err := a.g.output(true, "ls-remote", "--refs", "origin", prefix+"*")
567 if err != nil {
568 fmt.Fprintf(a.stderr, "valley: could not list this worktree's earlier check requests on origin: %s\n", oneLine(err.Error()))
569 return
570 }
571 for _, line := range strings.Split(out, "\n") {
572 oid, ref, ok := strings.Cut(line, "\t")
573 if !ok || !strings.HasPrefix(ref, prefix) {
574 continue
575 }
576 if _, _, _, valid := change.ParseCheckRequestRef(ref); !valid || !isObjectID(oid) {
577 fmt.Fprintf(a.stderr, "valley: %s is no check request, so it is skipped\n", oneLine(ref))
578 continue
579 }
580 a.state("stale", ref, oid)
581 if result, _ := pushOrigin(context.Background(), a.g, false, "--force-with-lease="+ref+":"+oid, ":"+ref); result != "ok" {
582 unsettled(a.stderr, ref, oid)
583 }
584 a.state("cleared", ref)
585 }
586}
587
588// wait follows the worker's telemetry from cursor, taken before the
589// filing, until a wake-up, reading origin's evidence every a.readEvery. It
590// returns why it stopped, or the read that covered every check.
591func (a *asking) wait(cursor string) (string, map[string]bool) {
592 // Where the stream ended once the push returned: a pass that starts
593 // after it started after the filing.
594 mark, err := a.stream.end(context.Background())
595 if c, perr := telemetry.ParseCursor(mark); err == nil && perr == nil && c[workerSource] != (telemetry.Position{}) {
596 a.mark = c[workerSource].Seq
597 } else {
598 fmt.Fprintf(a.stderr, "valley: the worker's stream gave no position after the filing: %s\n", oneLine(fmt.Sprint(err)))
599 return "telemetry unreadable", nil
600 }
601 a.say("◇", colourWaiting, a.short, "waiting for the worker")
602 started, running := map[string]bool{}, map[string]bool{}
603 last := time.Now()
604 for {
605 seconds := int(max(a.readEvery-time.Since(last), 0)/time.Second) + 1
606 ctx, cancel := context.WithCancel(context.Background())
607 records := make(chan workerRecord, 256)
608 var next string
609 var ferr error
610 go func() {
611 defer close(records)
612 next, ferr = a.stream.follow(ctx, cursor, seconds, records)
613 }()
614 why := ""
615 for r := range records {
616 if why == "" {
617 if why = a.wake(r, started, running); why != "" {
618 cancel()
619 }
620 }
621 }
622 cancel()
623 switch {
624 case why != "":
625 return why, nil
626 case ferr != nil:
627 fmt.Fprintf(a.stderr, "valley: %s\n", oneLine(ferr.Error()))
628 return "telemetry unreadable", nil
629 }
630 cursor = next
631 if time.Since(last) >= a.readEvery {
632 last = time.Now()
633 if covered, err := a.read(); err == nil && len(covered) == len(a.nix) {
634 return "", covered
635 }
636 }
637 }
638}
639
640// wake takes one worker record, keeps a check.result for the tree, and
641// says why the wait should end, or "".
642func (a *asking) wake(r workerRecord, started, running map[string]bool) string {
643 if n, _ := r.Data["dropped_before"].(float64); n > 0 {
644 return "telemetry lost records"
645 }
646 switch r.Type {
647 case "pass.start":
648 started[r.Run] = r.Seq > a.mark
649 return ""
650 case "pass.end":
651 if started[r.Run] && len(running) == 0 {
652 return "a worker pass ended"
653 }
654 return ""
655 }
656 if r.Project != a.project || r.Tree != a.tree {
657 return ""
658 }
659 run, _ := r.Data["attest_run"].(string)
660 result, _ := r.Data["result"].(string)
661 switch r.Type {
662 case "batch.start":
663 running[run] = true
664 case "check.result":
665 if _, required := a.attrs()[r.Check]; !required || !runName.MatchString(r.Run) ||
666 result != checkPassed && result != checkFailed && result != "error" {
667 return ""
668 }
669 ms := int64(-1)
670 for _, key := range []string{"check_ms", "build_ms"} {
671 if v, ok := r.Data[key].(float64); ok {
672 ms = int64(v)
673 break
674 }
675 }
676 a.results = append(a.results, treeResult{r.Run, r.Check, result, ms})
677 a.state("result", r.Run, r.Check, result, strconv.FormatInt(ms, 10))
678 case "batch.end":
679 // A batch that passed publishes next, and its publish.end says so.
680 delete(running, run)
681 if result == checkFailed {
682 return "the worker's batch for this tree ended with failures"
683 } else if result != checkPassed {
684 return "the worker's batch for this tree ended"
685 }
686 case "publish.end":
687 if result == checkPassed {
688 return "the worker published for this tree"
689 }
690 return "the worker could not publish for this tree"
691 }
692 return ""
693}
694
695// verdict prints the outcome, and returns the exit status.
696func (a *asking) verdict(covered map[string]bool, readErr error, why string) int {
697 took := time.Since(a.began).Round(time.Second).String()
698 if readErr == nil && len(covered) == len(a.nix) {
699 clauses := []string{countOf(len(a.nix), "check") + " passed"}
700 if len(a.nix) == 0 {
701 clauses = []string{"no nix checks required"}
702 }
703 if len(a.commands) > 0 {
704 clauses = append(clauses, fmt.Sprintf("%d run at approval", len(a.commands)))
705 }
706 a.say("✓", colourDone, a.short, append(clauses, took)...)
707 return 0
708 }
709 if readErr != nil {
710 fmt.Fprintf(a.stderr, "valley: %s\n", oneLine(readErr.Error()))
711 why = strings.TrimPrefix(why+" · evidence unreadable", " · ")
712 }
713 for _, c := range a.nix {
714 if !covered[c.name] {
715 a.say("◇", colourWaiting, c.name, "no evidence on origin")
716 }
717 }
718 a.say("◇", colourWaiting, a.short, "not established", why,
719 fmt.Sprintf("%d of %d with evidence", len(covered), len(a.nix)), took)
720 var tails map[[2]string]string
721 for _, r := range a.results {
722 if r.result != checkPassed && a.stream != nil {
723 if tails, readErr = a.stream.logs(context.Background()); readErr != nil {
724 fmt.Fprintf(a.stderr, "valley: could not read the worker's build output: %s\n", oneLine(readErr.Error()))
725 }
726 break
727 }
728 }
729 report(a.stdout, a.results, a.attrs(), tails)
730 return 1
731}
732
733// attrs is each required nix check's flake attribute, by check.
734func (a *asking) attrs() map[string]string {
735 attrs := map[string]string{}
736 for _, c := range a.nix {
737 attrs[c.name] = c.attribute
738 }
739 return attrs
740}
741
742// report prints the check.results the worker wrote for HEAD's tree while
743// the command waited, which any batch for the tree may have written, and
744// for each failed check the tail of its build output where tails, keyed
745// by attest run and check, holds it, or else the command that builds it
746// here.
747func report(w io.Writer, results []treeResult, attrs map[string]string, tails map[[2]string]string) {
748 if len(results) > 0 {
749 fmt.Fprintln(w, " the worker's recent records for this tree, not this request's result:")
750 }
751 failed := map[string]treeResult{}
752 var order []string
753 for _, r := range results {
754 took := ""
755 if r.ms >= 0 {
756 took = " · " + duration(r.ms)
757 }
758 fmt.Fprintf(w, " %s %s%s\n", oneLine(r.check), oneLine(r.result), took)
759 if r.result != checkPassed {
760 if _, seen := failed[r.check]; !seen {
761 order = append(order, r.check)
762 }
763 failed[r.check] = r
764 }
765 }
766 sort.Strings(order)
767 for _, name := range order {
768 if tail, ok := tails[[2]string{failed[name].run, name}]; ok {
769 lines := strings.Split(strings.TrimRight(telemetry.Sanitize(tail), "\n"), "\n")
770 fmt.Fprintf(w, " %s · the worker's build output, untrusted, its last %d lines:\n", name, min(len(lines), tailLines))
771 for _, line := range lines[max(len(lines)-tailLines, 0):] {
772 fmt.Fprintln(w, " | "+line)
773 }
774 } else if attr := attrs[name]; attr != "" {
775 fmt.Fprintf(w, " run: nix build --no-link -L .#checks.%s.%s\n", buildSystem(), attr)
776 }
777 }
778 fmt.Fprintln(w, " see: valley telemetry read --source worker --logs")
779}
780
781// oneLine is untrusted text made safe to show on one line.
782func oneLine(s string) string {
783 return strings.NewReplacer("\n", `\n`, "\t", `\t`).Replace(telemetry.Sanitize(s))
784}
785
786// buildSystem is the flake system attest builds a check for here
787// (attest/check.go).
788func buildSystem() string {
789 arch := map[string]string{"amd64": "x86_64", "arm64": "aarch64", "386": "i686"}[runtime.GOARCH]
790 if arch == "" {
791 arch = runtime.GOARCH
792 }
793 return arch + "-" + runtime.GOOS
794}
795
796// prepare reads HEAD, fetches main from origin, and derives the checks
797// HEAD requires under the policy at that tip.
798func (a *asking) prepare() error {
799 g := a.g
800 head, err := commitOf(g, "HEAD")
801 if err != nil {
802 return err
803 }
804 a.head = head
805 if a.short, err = g.output(true, "rev-parse", "--short", head); err != nil {
806 return failure("could not read HEAD")
807 }
808 if changed, err := g.output(true, "status", "--porcelain"); err == nil && changed != "" {
809 fmt.Fprintln(a.stderr, "valley: the working tree has uncommitted changes; these are HEAD's checks, not the working tree's")
810 }
811 // The worker derives under main as origin holds it now; a local copy
812 // may be older, with another policy or another merge base.
813 if _, err := g.output(false, "fetch", "--quiet", "origin", "+refs/heads/main:refs/remotes/origin/main"); err != nil {
814 return failure("could not fetch main from origin; nothing derived")
815 }
816 tip, ok, err := g.ref("refs/remotes/origin/main")
817 if err != nil || !ok {
818 return failure("could not read origin/main; nothing derived")
819 }
820 base, err := g.output(true, "merge-base", tip, head)
821 if err != nil || !isObjectID(base) {
822 return failure("HEAD shares no history with main on origin; nothing derived")
823 }
824 instance, layer, done, err := policyLayers(g, tip)
825 defer done()
826 if err != nil {
827 return failure(err.Error() + "; nothing derived")
828 }
829 doc, err := derivedChecks(g, "", instance, layer, base, head)
830 if err != nil {
831 return err
832 }
833 a.required = len(doc.Required)
834 for _, q := range doc.Required {
835 if q.Runner == "nix" {
836 a.nix = append(a.nix, nixCheck{q.Name, q.Attribute})
837 } else {
838 a.commands = append(a.commands, q.Name)
839 }
840 }
841 a.project = project(g)
842 if a.stream == nil {
843 if dest, err := telemetryRemote(g, ""); err == nil {
844 a.stream = sshStream{dest}
845 } else {
846 a.stream = brokenStream{err}
847 }
848 }
849 return nil
850}
851
852// say prints a line: the glyph in its colour, the subject in bold, and the
853// clauses.
854func (a *asking) say(glyph, colour, subject string, clauses ...string) {
855 var kept []string
856 for _, c := range clauses {
857 if c != "" {
858 kept = append(kept, c)
859 }
860 }
861 fmt.Fprintln(a.stdout, a.t.tint(colour, glyph)+" "+a.t.strong(subject)+" "+strings.Join(kept, " · "))
862}
863
864func (a *asking) fail(err error) int {
865 fmt.Fprintf(a.stderr, "valley: %s\n", oneLine(err.Error()))
866 return 1
867}
868
869// workerRecord is one record of the worker's telemetry stream.
870type workerRecord struct {
871 Seq int64 `json:"seq"`
872 Type string `json:"type"`
873 Run string `json:"run"`
874 Project string `json:"project"`
875 Tree string `json:"tree"`
876 Check string `json:"check"`
877 Data map[string]any `json:"data"`
878}
879
880// workerStream reads the worker's telemetry.
881type workerStream interface {
882 // end is a cursor at the stream's newest record.
883 end(ctx context.Context) (string, error)
884 // follow hands records each record stored after cursor, for up to
885 // seconds, and returns the cursor it ended at.
886 follow(ctx context.Context, cursor string, seconds int, records chan<- workerRecord) (string, error)
887 // logs is the tail of each of the stream's newest build logs, by
888 // attest run and check.
889 logs(ctx context.Context) (map[[2]string]string, error)
890}
891
892// brokenStream is a stream that cannot be reached, and why.
893type brokenStream struct{ err error }
894
895func (b brokenStream) end(context.Context) (string, error) { return "", b.err }
896func (b brokenStream) follow(context.Context, string, int, chan<- workerRecord) (string, error) {
897 return "", b.err
898}
899func (b brokenStream) logs(context.Context) (map[[2]string]string, error) { return nil, b.err }
900
901// sshStream reads the worker source of a host over ssh, as valley
902// telemetry does.
903type sshStream struct{ dest sshDest }
904
905func (s sshStream) end(ctx context.Context) (string, error) {
906 cursor, err := s.answer(ctx, telemetry.Request{V: 1, Op: telemetry.OpRead, Source: workerSource, Limit: 1}, time.Minute, nil, nil)
907 if c, perr := telemetry.ParseCursor(cursor); err == nil && (perr != nil || c[workerSource] == (telemetry.Position{})) {
908 err = fmt.Errorf("%s holds no stream for its %s source", s.dest.host, workerSource)
909 }
910 return cursor, err
911}
912
913func (s sshStream) follow(ctx context.Context, cursor string, seconds int, records chan<- workerRecord) (string, error) {
914 req := telemetry.Request{V: 1, Op: telemetry.OpFollow, Source: workerSource, Cursor: cursor, Seconds: min(seconds, telemetry.MaxFollowSeconds)}
915 return s.answer(ctx, req, time.Duration(req.Seconds+60)*time.Second, func(r workerRecord) {
916 select {
917 case records <- r:
918 case <-ctx.Done():
919 }
920 }, nil)
921}
922
923func (s sshStream) logs(ctx context.Context) (map[[2]string]string, error) {
924 tails := map[[2]string]string{}
925 _, err := s.answer(ctx, telemetry.Request{V: 1, Op: telemetry.OpRead, Source: workerSource, Limit: 1, Logs: true}, time.Minute, nil,
926 func(run, check, text string) { tails[[2]string{run, check}] = text })
927 return tails, err
928}
929
930// answer runs one telemetry request on the host, hands each record and
931// build log of the worker's stream it answers with to onRecord and onLog,
932// and returns the cursor it ended at. A refusal, a line that is not JSON,
933// a gap, a source that could not be read, or an answer that never ends is
934// an error.
935func (s sshStream) answer(ctx context.Context, req telemetry.Request, timeout time.Duration, onRecord func(workerRecord), onLog func(run, check, text string)) (string, error) {
936 ctx, cancel := context.WithTimeout(ctx, timeout)
937 defer cancel()
938 cmd := sshCommand(ctx, s.dest, req.Command())
939 out, err := cmd.StdoutPipe()
940 if err != nil {
941 return "", err
942 }
943 var sshErr bytes.Buffer
944 cmd.Stderr = &sshErr
945 processStarted()
946 if err := cmd.Start(); err != nil {
947 return "", fmt.Errorf("could not run ssh: %v", err)
948 }
949 cursor, ended, why := "", false, ""
950 sc := bufio.NewScanner(out)
951 sc.Buffer(make([]byte, 64<<10), telemetry.MaxResponseBytes)
952 for why == "" && sc.Scan() {
953 var m struct {
954 Kind, Error, What, Reason, Cursor, Stream, Text string
955 workerRecord
956 }
957 if json.Unmarshal(sc.Bytes(), &m) != nil {
958 why = "an answer line is not JSON"
959 break
960 }
961 switch {
962 case m.Kind == "error":
963 why = "the host refused: " + telemetry.Sanitize(m.Error)
964 case m.Kind == "unavailable" && m.What != "journal":
965 why = fmt.Sprintf("the host could not read %s: %s", telemetry.Sanitize(m.What), telemetry.Sanitize(m.Error))
966 case m.Kind == "gap":
967 why = fmt.Sprintf("the worker's stream lost records since the cursor (%s)", telemetry.Sanitize(m.Reason))
968 case m.Kind == "record" && m.Stream == workerSource && onRecord != nil:
969 onRecord(m.workerRecord)
970 case m.Kind == "log" && m.Stream == workerSource && onLog != nil:
971 onLog(m.Run, m.Check, m.Text)
972 case m.Kind == "end":
973 cursor, ended = m.Cursor, true
974 }
975 }
976 if why != "" {
977 cancel()
978 }
979 waitErr := cmd.Wait()
980 switch {
981 case why != "":
982 return "", errors.New(why)
983 case !ended:
984 why = strings.TrimSpace(telemetry.Sanitize(sshErr.String()))
985 if why == "" && waitErr != nil {
986 why = waitErr.Error()
987 }
988 return "", fmt.Errorf("the telemetry answer from %s did not end: %s", s.dest.host, why)
989 }
990 return cursor, nil
991}