gunk-dev/the-valley

check.go

source1ef1288a69f6main's published tip history
20.8 KiB
1package main
2
3// Running a check, and the digests a run yields.
4//
5// The nix runner claims purity strongly: it builds a flake check
6// derivation, so the check's inputs, the derivation itself and its output
7// are all named, and any verifier holding the same tree can re-derive
8// them. The command runner claims nothing beyond having run — its
9// statement is a notarization naming the environment and the time
10// (archive/design/verification.md).
11
12import (
13 "bytes"
14 "context"
15 "encoding/json"
16 "fmt"
17 "io"
18 "os"
19 "os/exec"
20 "path/filepath"
21 "regexp"
22 "runtime"
23 "strconv"
24 "strings"
25 "syscall"
26 "time"
27)
28
29type checkSpec struct {
30 name string
31 attribute string // nix runner
32 command string // command runner
33}
34
35func (c checkSpec) runner() string {
36 if c.command != "" {
37 return "command"
38 }
39 return "nix"
40}
41
42// checkOutcome is what running one check produced: whether it passed, the
43// output a reader needs when it did not, how it was satisfied, and the
44// digests of a pure run.
45type checkOutcome struct {
46 spec checkSpec
47 passed bool
48 log string
49 satisfied string
50
51 inputs string
52 derivation string
53 output string
54 observedAt string
55}
56
57// ranCheck is one check as a run ran it: its outcome, or the error that
58// kept it from having one, and when it started and how long it took. eval
59// is how long a pure check took to evaluate, and is zero for a command.
60type ranCheck struct {
61 out checkOutcome
62 err error
63 began time.Time
64 took time.Duration
65 eval time.Duration
66}
67
68// nixSystem is the flake system attribute of the machine running the
69// check. A check is built where the work was written, so this is the
70// runner's own system and never something the caller states about another
71// machine.
72func nixSystem() string {
73 arch := runtime.GOARCH
74 switch arch {
75 case "amd64":
76 arch = "x86_64"
77 case "arm64":
78 arch = "aarch64"
79 case "386":
80 arch = "i686"
81 }
82 return arch + "-" + runtime.GOOS
83}
84
85func nix(dir string, args ...string) (string, string, error) {
86 out, errb, _, err := nixPeak(dir, nil, args...)
87 return out, errb, err
88}
89
90// peak is what an evaluation's nix processes measured: the most memory
91// any of them held, in bytes, and how they ended. The outcome is "ok"
92// when every one exited successfully, "killed" when any was ended by a
93// signal, as the kernel's out-of-memory killer ends one, "failed" when
94// any other failed, and empty when none ran. Only an ok peak is the
95// evaluation's whole high-water mark: one that failed or was killed
96// stopped short of it.
97type peak struct {
98 bytes int64
99 outcome string
100}
101
102// add takes in another process's measure: the larger peak, and the worse
103// outcome.
104func (p peak) add(q peak) peak {
105 rank := map[string]int{"": 0, "ok": 1, "failed": 2, "killed": 3}
106 if rank[q.outcome] > rank[p.outcome] {
107 p.outcome = q.outcome
108 }
109 p.bytes = max(p.bytes, q.bytes)
110 return p
111}
112
113// nixPeak runs nix as nix does, and also measures it: the most memory the
114// nix process held, in bytes, which is its maximum resident set size from
115// its resource usage once it exited, and how it ended. An evaluation runs
116// in the nix process itself, not in the daemon, so this is the
117// evaluation's peak. The process inherits held, the run's locked
118// reservation file when it has one, so the reservation stays held while
119// the process runs (admit), and it is killed if attest dies, so it never
120// outlives the run that counted it (dieWithParent).
121func nixPeak(dir string, held *os.File, args ...string) (string, string, peak, error) {
122 cmd := exec.Command("nix", args...)
123 cmd.Dir = dir
124 var out, errb bytes.Buffer
125 cmd.Stdout = &out
126 cmd.Stderr = &errb
127 cmd.SysProcAttr = dieWithParent()
128 if held != nil {
129 cmd.ExtraFiles = []*os.File{held}
130 }
131 err := cmd.Run()
132 m := peak{bytes: maxRSS(cmd.ProcessState), outcome: "ok"}
133 if err != nil {
134 m.outcome = "failed"
135 if cmd.ProcessState != nil {
136 if ws, ok := cmd.ProcessState.Sys().(syscall.WaitStatus); ok && ws.Signaled() {
137 m.outcome = "killed"
138 }
139 }
140 }
141 return out.String(), errb.String(), m, err
142}
143
144// maxRSS is the maximum resident set size of a process that exited, in
145// bytes, or 0 when it is not known. Linux counts it in kibibytes.
146func maxRSS(ps *os.ProcessState) int64 {
147 if ps == nil {
148 return 0
149 }
150 ru, ok := ps.SysUsage().(*syscall.Rusage)
151 if !ok {
152 return 0
153 }
154 if runtime.GOOS == "darwin" {
155 return ru.Maxrss
156 }
157 return ru.Maxrss * 1024
158}
159
160// nixStore runs nix-store, and stops it when ctx is done.
161func nixStore(ctx context.Context, args ...string) (string, string, error) {
162 cmd := exec.CommandContext(ctx, "nix-store", args...)
163 cmd.WaitDelay = time.Second
164 var out, errb bytes.Buffer
165 cmd.Stdout = &out
166 cmd.Stderr = &errb
167 err := cmd.Run()
168 return out.String(), errb.String(), err
169}
170
171// flakeChecks lists every check attribute a flake defines for a system —
172// what "the repo's canonical checks" means when the caller names none.
173func flakeChecks(tree, system string) ([]string, error) {
174 out, errb, err := nix(tree, "eval", "--json", "--apply", "builtins.attrNames", tree+"#checks."+system)
175 if err != nil {
176 return nil, fmt.Errorf("listing checks: %w: %s", err, strings.TrimSpace(errb))
177 }
178 var names []string
179 if err := json.Unmarshal([]byte(out), &names); err != nil {
180 return nil, fmt.Errorf("listing checks: %w", err)
181 }
182 return names, nil
183}
184
185// closure is what evaluating a pure check names before anything is built:
186// the derivation, and the digest of its input closure. Both are functions
187// of the tree alone, so an integrator can recompute the closure digest on a
188// rebased tree without running the check — which is the whole of the pure
189// transfer rule (dcr-439b771).
190type closure struct {
191 drv string
192 derivation string
193 inputs string
194}
195
196// evalClosure evaluates one flake check over an exported tree and digests
197// what the evaluation named. Nothing is built. It also returns the
198// evaluation's measure, as nixPeak takes it, whose nix process inherits
199// held.
200func evalClosure(tree, system string, spec checkSpec, held *os.File) (closure, peak, error) {
201 attr := tree + "#checks." + system + "." + spec.attribute
202 drv, errb, peak, err := nixPeak(tree, held, "eval", "--raw", attr+".drvPath")
203 if err != nil {
204 return closure{}, peak, fmt.Errorf("evaluating %s: %w: %s", attr, err, strings.TrimSpace(errb))
205 }
206 c, err := closureOf(strings.TrimSpace(drv))
207 return c, peak, err
208}
209
210// closureOf digests a derivation an evaluation named: the derivation file
211// itself, and the store paths it reads.
212func closureOf(drv string) (closure, error) {
213 drvBytes, err := os.ReadFile(drv)
214 if err != nil {
215 return closure{}, err
216 }
217 inputs, err := drvInputs(drv)
218 if err != nil {
219 return closure{}, err
220 }
221 return closure{
222 drv: drv,
223 derivation: fmt.Sprintf("%x", sha256sum(drvBytes)),
224 inputs: inputsDigest(inputs),
225 }, nil
226}
227
228// evaluation is one pure check's evaluation: the closure it named, or why
229// it named none, and how long it took.
230type evaluation struct {
231 closure
232 err error
233 took time.Duration
234}
235
236// plainAttribute is a check attribute the shared evaluation can name in a
237// nix string as it is: one attribute, with no dot, quote, backslash or
238// dollar sign in it.
239var plainAttribute = regexp.MustCompile(`^[A-Za-z0-9_'+-]+$`)
240
241// evalClosures evaluates every pure check over the exported tree. One nix
242// evaluation names the derivations of all of them together, so nixpkgs and
243// whatever else the checks share are evaluated once and not once per
244// check. A check that evaluation could not name is evaluated alone, as
245// evalClosure does, so an error is reported against the check that has it
246// and stops no other. Each check is timed as the shared evaluation plus
247// whatever was done for it alone. The second answer measures every nix
248// evaluation it ran, the shared one and each alone, together (peak.add),
249// so a peak counts as the evaluation's whole high-water mark only when
250// none of them failed. Each nix process inherits held.
251func evalClosures(tree, system string, specs []checkSpec, held *os.File) ([]evaluation, peak) {
252 var attrs []string
253 shared := map[string]bool{}
254 for _, spec := range specs {
255 if plainAttribute.MatchString(spec.attribute) && !shared[spec.attribute] {
256 shared[spec.attribute] = true
257 attrs = append(attrs, spec.attribute)
258 }
259 }
260 began := time.Now()
261 drvs, measured := evalDrvPaths(tree, system, attrs, held)
262 sharedTook := time.Since(began)
263
264 evals := make([]evaluation, len(specs))
265 for i, spec := range specs {
266 began := time.Now()
267 var c closure
268 var err error
269 if drv, ok := drvs[spec.attribute]; ok {
270 c, err = closureOf(drv)
271 } else {
272 var alone peak
273 c, alone, err = evalClosure(tree, system, spec, held)
274 measured = measured.add(alone)
275 }
276 evals[i] = evaluation{closure: c, err: err, took: time.Since(began)}
277 if shared[spec.attribute] {
278 evals[i].took += sharedTook
279 }
280 }
281 return evals, measured
282}
283
284// evalDrvPaths names the derivation of every check attribute given, in one
285// nix evaluation. A check whose evaluation throws, or that is missing or
286// is not a derivation, is left out of the answer. Some evaluation errors
287// cannot be caught inside nix, such as a type error, and they end the
288// whole evaluation; then the answer is empty, and every check is evaluated
289// alone. One attribute has nothing to share, so it is left to be evaluated
290// alone from the start. The second answer is the evaluation's measure,
291// or an empty one when it did not run. Its nix process inherits held.
292func evalDrvPaths(tree, system string, attrs []string, held *os.File) (map[string]string, peak) {
293 drvs := map[string]string{}
294 if len(attrs) < 2 {
295 return drvs, peak{}
296 }
297 quoted := make([]string, len(attrs))
298 for i, a := range attrs {
299 quoted[i] = `"` + a + `"`
300 }
301 apply := `checks: builtins.listToAttrs (map (name: { inherit name; value = ` +
302 `let r = builtins.tryEval (if checks ? ${name} && checks.${name} ? drvPath then checks.${name}.drvPath else null); ` +
303 `in if r.success then r.value else null; }) [ ` + strings.Join(quoted, " ") + ` ])`
304 out, _, peak, err := nixPeak(tree, held, "eval", "--json", "--apply", apply, tree+"#checks."+system)
305 if err != nil {
306 return drvs, peak
307 }
308 var named map[string]any
309 if json.Unmarshal([]byte(out), &named) != nil {
310 return drvs, peak
311 }
312 for _, a := range attrs {
313 if drv, ok := named[a].(string); ok && drv != "" {
314 drvs[a] = drv
315 }
316 }
317 return drvs, peak
318}
319
320// defaultSlots is how many nix build processes attest run starts at once
321// when --slots does not say: one per CPU attest may run on.
322var defaultSlots = runtime.NumCPU()
323
324// runPure runs every pure check and returns their runs in the order given.
325// It evaluates them all together (evalClosures), then builds each
326// derivation that evaluated in a nix build of its own, slots of them at
327// once, so the nix daemon builds them side by side (buildChecks).
328// Checks that evaluate to the same derivation share its one build. With
329// report, it hands each run to report in the order given, as soon as that
330// check and every one before it have ended.
331//
332// Each check's outcome is its own derivation's build: the exit status and
333// standard error of the nix build that built it, exactly as when checks
334// were built one at a time. With probe, it first asks the nix store
335// whether each output is already there, for the check's timing; without,
336// it asks nothing about outputs.
337//
338// A check is timed from the start of the shared evaluation. Its duration
339// is its evaluation, its probe, and its derivation's build. One that does
340// not evaluate ends at its evaluation error.
341//
342// With an admission, the evaluation waits until its estimate fits the
343// memory budget beside the evaluations admitted before it, and its
344// reservation is removed when the evaluation ends, before the builds
345// (admit). The wait is not part of any check's time: eval.end records it
346// apart, as eval_wait_ms. An admission that fails is an error, and then
347// nothing is evaluated or built: no evaluation runs without being counted.
348// eval.end also records the evaluation's peak memory, as
349// eval_max_rss_bytes, and its outcome, as eval_outcome (peak). With
350// peakFile, the peak in bytes and the outcome are written there too, on
351// one line.
352//
353// With roots, every output path a build prints is rooted under that
354// directory (rootOutputs), whether nix built it or found it valid.
355func runPure(tree, system string, specs []checkSpec, probe bool, slots int, roots string, adm *admission, peakFile string, report func(ranCheck), obs *observer) ([]ranCheck, error) {
356 waited, held, release, err := admit(adm)
357 if err != nil {
358 return nil, err
359 }
360 began := time.Now()
361 start := map[string]any{"checks": specNames(specs)}
362 if adm != nil {
363 start["eval_estimate_bytes"], start["eval_budget_bytes"] = adm.estimate, adm.budget
364 }
365 obs.emit("eval.start", "", start)
366 evals, measured := evalClosures(tree, system, specs, held)
367 end := map[string]any{"eval_ms": time.Since(began).Milliseconds(), "eval_wait_ms": waited.Milliseconds(), "eval_max_rss_bytes": measured.bytes}
368 if measured.outcome != "" {
369 end["eval_outcome"] = measured.outcome
370 }
371 obs.emit("eval.end", "", end)
372 release()
373 if peakFile != "" && measured.outcome != "" {
374 if err := os.WriteFile(peakFile, []byte(strconv.FormatInt(measured.bytes, 10)+" "+measured.outcome+"\n"), 0o600); err != nil {
375 fmt.Fprintf(os.Stderr, "attest: warning: could not record the evaluation's peak memory: %v\n", err)
376 }
377 }
378 runs := make([]ranCheck, len(specs))
379 for i, spec := range specs {
380 e := evals[i]
381 runs[i] = ranCheck{out: checkOutcome{spec: spec}, began: began, took: e.took, eval: e.took, err: e.err}
382 if e.err != nil {
383 obs.emit("check.result", spec.name, map[string]any{"result": "error", "error": clipError(e.err.Error()), "eval_ms": e.took.Milliseconds()})
384 continue
385 }
386 runs[i].out.derivation, runs[i].out.inputs = e.derivation, e.inputs
387 if probe {
388 probed := time.Now()
389 runs[i].out.satisfied = outputsCached(e.drv)
390 runs[i].took += time.Since(probed)
391 }
392 obs.name(e.drv, spec.name)
393 obs.emit("check.queued", spec.name, map[string]any{"eval_ms": e.took.Milliseconds(), "probe_ms": (runs[i].took - e.took).Milliseconds()})
394 }
395
396 drvs := make([]string, len(evals))
397 for i, e := range evals {
398 drvs[i] = e.drv
399 }
400 build := func(drv string) (string, string, error) {
401 return nix(tree, "build", "--no-link", "--print-out-paths", drv+"^*")
402 }
403 if obs != nil {
404 build = func(drv string) (string, string, error) { return obs.nixBuild(tree, drv) }
405 }
406 if roots != "" {
407 built := build
408 build = func(drv string) (string, string, error) {
409 out, errText, err := built(drv)
410 rootOutputs(roots, out)
411 return out, errText, err
412 }
413 }
414 buildChecks(runs, drvs, slots, build, report, obs)
415 return runs, nil
416}
417
418// rootOutputs registers an indirect garbage-collector root in dir for each
419// store path in built, which is what nix build --print-out-paths printed.
420// A root is a symlink named by its path's basename, so an output is rooted
421// once however many trees use it. nix-store makes the symlink afresh each
422// time, so its modification time is when the output was last used. The
423// daemon records the root, so a user who is not root can add one. A root
424// that cannot be added is warned about and changes no check's outcome.
425func rootOutputs(dir, built string) {
426 for _, path := range strings.Fields(built) {
427 root := filepath.Join(dir, filepath.Base(path))
428 if _, errText, err := nixStore(context.Background(), "--add-root", root, "--realise", path); err != nil {
429 fmt.Fprintf(os.Stderr, "attest: warning: %s is not rooted: %v: %s\n", path, err, strings.TrimSpace(errText))
430 }
431 }
432}
433
434func specNames(specs []checkSpec) []string {
435 names := make([]string, len(specs))
436 for i, s := range specs {
437 names[i] = s.name
438 }
439 return names
440}
441
442// buildChecks builds the derivation of every run that has no error yet
443// and decides each from its derivation's build (pureOutcome). drvs[i] is
444// runs[i]'s derivation, and build builds one derivation, returning what it
445// printed on standard output and standard error and how it ended. Builds
446// start in the order of runs, at most slots of them at once, and runs that
447// share a derivation share its one build. Each run is handed to report in
448// order, as soon as it and every run before it have ended. With obs, each
449// build's start and end and each run's result are recorded as they
450// happen, whatever the order.
451func buildChecks(runs []ranCheck, drvs []string, slots int, build func(drv string) (string, string, error), report func(ranCheck), obs *observer) {
452 builds := map[string]*drvBuild{}
453 users := map[string][]int{} // the runs each derivation decides
454 pending := make([]bool, len(runs))
455 var order []*drvBuild
456 for i := range runs {
457 if runs[i].err != nil {
458 continue
459 }
460 pending[i] = true
461 users[drvs[i]] = append(users[drvs[i]], i)
462 if builds[drvs[i]] != nil {
463 continue
464 }
465 b := &drvBuild{drv: drvs[i], done: make(chan struct{})}
466 builds[drvs[i]] = b
467 order = append(order, b)
468 }
469 free := make(chan struct{}, max(slots, 1))
470 go func() {
471 for _, b := range order {
472 queued := time.Now()
473 free <- struct{}{}
474 wait := time.Since(queued)
475 go func() {
476 defer close(b.done)
477 defer func() { <-free }()
478 for _, i := range users[b.drv] {
479 obs.emit("check.build-start", runs[i].out.spec.name, map[string]any{"slot_wait_ms": wait.Milliseconds()})
480 }
481 began := time.Now()
482 b.paths, b.log, b.err = build(b.drv)
483 b.took = time.Since(began)
484 ended := time.Now()
485 // Each run the build decides is decided as soon as it
486 // ends, and its result recorded then; it is reported in
487 // order below.
488 for _, i := range users[b.drv] {
489 runs[i].took += b.took
490 runs[i].err = pureOutcome(b, &runs[i].out)
491 if obs != nil {
492 d := buildData(b, wait, began, ended, obs.logOf(b.drv))
493 if obs.capacity != "" {
494 d["capacity"] = obs.capacity
495 }
496 obs.emit("check.build-end", runs[i].out.spec.name, d)
497 d["result"] = resultOf(runs[i])
498 d["eval_ms"] = runs[i].eval.Milliseconds()
499 d["check_ms"] = runs[i].took.Milliseconds()
500 obs.emit("check.result", runs[i].out.spec.name, d)
501 }
502 }
503 }()
504 }
505 }()
506 for i := range runs {
507 if pending[i] {
508 <-builds[drvs[i]].done
509 }
510 if report != nil {
511 report(runs[i])
512 }
513 }
514}
515
516// resultOf is a run's result as a timing and a record name it.
517func resultOf(r ranCheck) string {
518 switch {
519 case r.err != nil:
520 return "error"
521 case !r.out.passed:
522 return "failed"
523 }
524 return "passed"
525}
526
527// drvBuild is the nix build of one derivation: what it printed on standard
528// output and on standard error, how it ended, and how long it took. done
529// is closed once it has ended.
530type drvBuild struct {
531 drv string
532 done chan struct{}
533 paths string
534 log string
535 err error
536 took time.Duration
537}
538
539// pureOutcome decides one pure check from its derivation's build, and
540// digests the output when the build succeeded. Building from the
541// derivation path rather than the attribute a second time guarantees the
542// thing built is the thing recorded. The build's standard error is the
543// check's log. A build that failed with nothing on standard error, as when
544// nix could not be started or was killed by a signal, gets the error that
545// ended it as its log instead.
546func pureOutcome(b *drvBuild, out *checkOutcome) error {
547 out.log = strings.TrimSpace(b.log)
548 if b.err != nil {
549 if out.log == "" {
550 out.log = b.err.Error()
551 }
552 return nil // a failed check is an outcome, not an error
553 }
554 paths := strings.Fields(b.paths)
555 if len(paths) != 1 {
556 return fmt.Errorf("%s produced %d outputs; a check attribute must produce exactly one", out.spec.name, len(paths))
557 }
558 entries, err := fsEntries(paths[0])
559 if err != nil {
560 return err
561 }
562 out.output = treeDigest(entries)
563 out.passed = true
564 return nil
565}
566
567// drvInputs collects the store paths a derivation reads: the derivations
568// it depends on and the sources it takes directly. A .drv's references are
569// exactly that set, and `nix-store --query --references` prints them as
570// lines — a shape that has not changed in the lifetime of nix, unlike the
571// versioned JSON of `nix derivation show`.
572func drvInputs(drv string) ([]string, error) {
573 out, errb, err := nixStore(context.Background(), "--query", "--references", drv)
574 if err != nil {
575 return nil, fmt.Errorf("querying the inputs of %s: %w: %s", drv, err, strings.TrimSpace(errb))
576 }
577 inputs := strings.Fields(out)
578 if len(inputs) == 0 {
579 return nil, fmt.Errorf("%s has no inputs at all", drv)
580 }
581 return inputs, nil
582}
583
584// runEffectful runs a command over the exported tree and notarizes what it
585// observed. No digests: there is nothing to re-derive, which is exactly
586// what the effectful predicate type says.
587func runEffectful(tree string, spec checkSpec, logTo io.Writer) checkOutcome {
588 out := checkOutcome{spec: spec, satisfied: satisfiedRan}
589 cmd := exec.Command("sh", "-c", spec.command)
590 cmd.Dir = tree
591 var log bytes.Buffer
592 if logTo == nil {
593 logTo = io.Discard
594 }
595 cmd.Stdout = io.MultiWriter(&log, logTo)
596 cmd.Stderr = cmd.Stdout
597 err := cmd.Run()
598 out.log = strings.TrimSpace(log.String())
599 out.observedAt = time.Now().UTC().Format("2006-01-02T15:04:05Z")
600 out.passed = err == nil
601 return out
602}