gunk-dev/the-valley

check.go

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