gunk-dev/the-valley

check.go

source8b3dd027213fmain's published tip history
15.3 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 "regexp"
21 "runtime"
22 "strings"
23 "time"
24)
25
26type checkSpec struct {
27 name string
28 attribute string // nix runner
29 command string // command runner
30}
31
32func (c checkSpec) runner() string {
33 if c.command != "" {
34 return "command"
35 }
36 return "nix"
37}
38
39// checkOutcome is what running one check produced: whether it passed, the
40// output a reader needs when it did not, how it was satisfied, and the
41// digests of a pure run.
42type checkOutcome struct {
43 spec checkSpec
44 passed bool
45 log string
46 satisfied string
47
48 inputs string
49 derivation string
50 output string
51 observedAt string
52}
53
54// ranCheck is one check as a run ran it: its outcome, or the error that
55// kept it from having one, and when it started and how long it took. eval
56// is how long a pure check took to evaluate, and is zero for a command.
57type ranCheck struct {
58 out checkOutcome
59 err error
60 began time.Time
61 took time.Duration
62 eval time.Duration
63}
64
65// nixSystem is the flake system attribute of the machine running the
66// check. A check is built where the work was written, so this is the
67// runner's own system and never something the caller states about another
68// machine.
69func nixSystem() string {
70 arch := runtime.GOARCH
71 switch arch {
72 case "amd64":
73 arch = "x86_64"
74 case "arm64":
75 arch = "aarch64"
76 case "386":
77 arch = "i686"
78 }
79 return arch + "-" + runtime.GOOS
80}
81
82func nix(dir string, args ...string) (string, string, error) {
83 cmd := exec.Command("nix", args...)
84 cmd.Dir = dir
85 var out, errb bytes.Buffer
86 cmd.Stdout = &out
87 cmd.Stderr = &errb
88 err := cmd.Run()
89 return out.String(), errb.String(), err
90}
91
92// nixStore runs nix-store, and stops it when ctx is done.
93func nixStore(ctx context.Context, args ...string) (string, string, error) {
94 cmd := exec.CommandContext(ctx, "nix-store", args...)
95 cmd.WaitDelay = time.Second
96 var out, errb bytes.Buffer
97 cmd.Stdout = &out
98 cmd.Stderr = &errb
99 err := cmd.Run()
100 return out.String(), errb.String(), err
101}
102
103// flakeChecks lists every check attribute a flake defines for a system —
104// what "the repo's canonical checks" means when the caller names none.
105func flakeChecks(tree, system string) ([]string, error) {
106 out, errb, err := nix(tree, "eval", "--json", "--apply", "builtins.attrNames", tree+"#checks."+system)
107 if err != nil {
108 return nil, fmt.Errorf("listing checks: %w: %s", err, strings.TrimSpace(errb))
109 }
110 var names []string
111 if err := json.Unmarshal([]byte(out), &names); err != nil {
112 return nil, fmt.Errorf("listing checks: %w", err)
113 }
114 return names, nil
115}
116
117// closure is what evaluating a pure check names before anything is built:
118// the derivation, and the digest of its input closure. Both are functions
119// of the tree alone, so an integrator can recompute the closure digest on a
120// rebased tree without running the check — which is the whole of the pure
121// transfer rule (dcr-439b771).
122type closure struct {
123 drv string
124 derivation string
125 inputs string
126}
127
128// evalClosure evaluates one flake check over an exported tree and digests
129// what the evaluation named. Nothing is built.
130func evalClosure(tree, system string, spec checkSpec) (closure, error) {
131 attr := tree + "#checks." + system + "." + spec.attribute
132 drv, errb, err := nix(tree, "eval", "--raw", attr+".drvPath")
133 if err != nil {
134 return closure{}, fmt.Errorf("evaluating %s: %w: %s", attr, err, strings.TrimSpace(errb))
135 }
136 return closureOf(strings.TrimSpace(drv))
137}
138
139// closureOf digests a derivation an evaluation named: the derivation file
140// itself, and the store paths it reads.
141func closureOf(drv string) (closure, error) {
142 drvBytes, err := os.ReadFile(drv)
143 if err != nil {
144 return closure{}, err
145 }
146 inputs, err := drvInputs(drv)
147 if err != nil {
148 return closure{}, err
149 }
150 return closure{
151 drv: drv,
152 derivation: fmt.Sprintf("%x", sha256sum(drvBytes)),
153 inputs: inputsDigest(inputs),
154 }, nil
155}
156
157// evaluation is one pure check's evaluation: the closure it named, or why
158// it named none, and how long it took.
159type evaluation struct {
160 closure
161 err error
162 took time.Duration
163}
164
165// plainAttribute is a check attribute the shared evaluation can name in a
166// nix string as it is: one attribute, with no dot, quote, backslash or
167// dollar sign in it.
168var plainAttribute = regexp.MustCompile(`^[A-Za-z0-9_'+-]+$`)
169
170// evalClosures evaluates every pure check over the exported tree. One nix
171// evaluation names the derivations of all of them together, so nixpkgs and
172// whatever else the checks share are evaluated once and not once per
173// check. A check that evaluation could not name is evaluated alone, as
174// evalClosure does, so an error is reported against the check that has it
175// and stops no other. Each check is timed as the shared evaluation plus
176// whatever was done for it alone.
177func evalClosures(tree, system string, specs []checkSpec) []evaluation {
178 var attrs []string
179 shared := map[string]bool{}
180 for _, spec := range specs {
181 if plainAttribute.MatchString(spec.attribute) && !shared[spec.attribute] {
182 shared[spec.attribute] = true
183 attrs = append(attrs, spec.attribute)
184 }
185 }
186 began := time.Now()
187 drvs := evalDrvPaths(tree, system, attrs)
188 sharedTook := time.Since(began)
189
190 evals := make([]evaluation, len(specs))
191 for i, spec := range specs {
192 began := time.Now()
193 var c closure
194 var err error
195 if drv, ok := drvs[spec.attribute]; ok {
196 c, err = closureOf(drv)
197 } else {
198 c, err = evalClosure(tree, system, spec)
199 }
200 evals[i] = evaluation{closure: c, err: err, took: time.Since(began)}
201 if shared[spec.attribute] {
202 evals[i].took += sharedTook
203 }
204 }
205 return evals
206}
207
208// evalDrvPaths names the derivation of every check attribute given, in one
209// nix evaluation. A check whose evaluation throws, or that is missing or
210// is not a derivation, is left out of the answer. Some evaluation errors
211// cannot be caught inside nix, such as a type error, and they end the
212// whole evaluation; then the answer is empty, and every check is evaluated
213// alone. One attribute has nothing to share, so it is left to be evaluated
214// alone from the start.
215func evalDrvPaths(tree, system string, attrs []string) map[string]string {
216 drvs := map[string]string{}
217 if len(attrs) < 2 {
218 return drvs
219 }
220 quoted := make([]string, len(attrs))
221 for i, a := range attrs {
222 quoted[i] = `"` + a + `"`
223 }
224 apply := `checks: builtins.listToAttrs (map (name: { inherit name; value = ` +
225 `let r = builtins.tryEval (if checks ? ${name} && checks.${name} ? drvPath then checks.${name}.drvPath else null); ` +
226 `in if r.success then r.value else null; }) [ ` + strings.Join(quoted, " ") + ` ])`
227 out, _, err := nix(tree, "eval", "--json", "--apply", apply, tree+"#checks."+system)
228 if err != nil {
229 return drvs
230 }
231 var named map[string]any
232 if json.Unmarshal([]byte(out), &named) != nil {
233 return drvs
234 }
235 for _, a := range attrs {
236 if drv, ok := named[a].(string); ok && drv != "" {
237 drvs[a] = drv
238 }
239 }
240 return drvs
241}
242
243// defaultSlots is how many nix build processes attest run starts at once
244// when --slots does not say: one per CPU attest may run on.
245var defaultSlots = runtime.NumCPU()
246
247// runPure runs every pure check and returns their runs in the order given.
248// It evaluates them all together (evalClosures), then builds each
249// derivation that evaluated in a nix build of its own, slots of them at
250// once, so the nix daemon builds them side by side (buildChecks).
251// Checks that evaluate to the same derivation share its one build. With
252// report, it hands each run to report in the order given, as soon as that
253// check and every one before it have ended.
254//
255// Each check's outcome is its own derivation's build: the exit status and
256// standard error of the nix build that built it, exactly as when checks
257// were built one at a time. With probe, it first asks the nix store
258// whether each output is already there, for the check's timing; without,
259// it asks nothing about outputs.
260//
261// A check is timed from the start of the shared evaluation. Its duration
262// is its evaluation, its probe, and its derivation's build. One that does
263// not evaluate ends at its evaluation error.
264func runPure(tree, system string, specs []checkSpec, probe bool, slots int, report func(ranCheck), obs *observer) []ranCheck {
265 began := time.Now()
266 obs.emit("eval.start", "", map[string]any{"checks": specNames(specs)})
267 evals := evalClosures(tree, system, specs)
268 obs.emit("eval.end", "", map[string]any{"eval_ms": time.Since(began).Milliseconds()})
269 runs := make([]ranCheck, len(specs))
270 for i, spec := range specs {
271 e := evals[i]
272 runs[i] = ranCheck{out: checkOutcome{spec: spec}, began: began, took: e.took, eval: e.took, err: e.err}
273 if e.err != nil {
274 obs.emit("check.result", spec.name, map[string]any{"result": "error", "error": clipError(e.err.Error()), "eval_ms": e.took.Milliseconds()})
275 continue
276 }
277 runs[i].out.derivation, runs[i].out.inputs = e.derivation, e.inputs
278 if probe {
279 probed := time.Now()
280 runs[i].out.satisfied = outputsCached(e.drv)
281 runs[i].took += time.Since(probed)
282 }
283 obs.name(e.drv, spec.name)
284 obs.emit("check.queued", spec.name, map[string]any{"eval_ms": e.took.Milliseconds(), "probe_ms": (runs[i].took - e.took).Milliseconds()})
285 }
286
287 drvs := make([]string, len(evals))
288 for i, e := range evals {
289 drvs[i] = e.drv
290 }
291 build := func(drv string) (string, string, error) {
292 return nix(tree, "build", "--no-link", "--print-out-paths", drv+"^*")
293 }
294 if obs != nil {
295 build = func(drv string) (string, string, error) { return obs.nixBuild(tree, drv) }
296 }
297 buildChecks(runs, drvs, slots, build, report, obs)
298 return runs
299}
300
301func specNames(specs []checkSpec) []string {
302 names := make([]string, len(specs))
303 for i, s := range specs {
304 names[i] = s.name
305 }
306 return names
307}
308
309// buildChecks builds the derivation of every run that has no error yet
310// and decides each from its derivation's build (pureOutcome). drvs[i] is
311// runs[i]'s derivation, and build builds one derivation, returning what it
312// printed on standard output and standard error and how it ended. Builds
313// start in the order of runs, at most slots of them at once, and runs that
314// share a derivation share its one build. Each run is handed to report in
315// order, as soon as it and every run before it have ended. With obs, each
316// build's start and end and each run's result are recorded as they
317// happen, whatever the order.
318func buildChecks(runs []ranCheck, drvs []string, slots int, build func(drv string) (string, string, error), report func(ranCheck), obs *observer) {
319 builds := map[string]*drvBuild{}
320 users := map[string][]int{} // the runs each derivation decides
321 pending := make([]bool, len(runs))
322 var order []*drvBuild
323 for i := range runs {
324 if runs[i].err != nil {
325 continue
326 }
327 pending[i] = true
328 users[drvs[i]] = append(users[drvs[i]], i)
329 if builds[drvs[i]] != nil {
330 continue
331 }
332 b := &drvBuild{drv: drvs[i], done: make(chan struct{})}
333 builds[drvs[i]] = b
334 order = append(order, b)
335 }
336 free := make(chan struct{}, max(slots, 1))
337 go func() {
338 for _, b := range order {
339 queued := time.Now()
340 free <- struct{}{}
341 wait := time.Since(queued)
342 go func() {
343 defer close(b.done)
344 defer func() { <-free }()
345 for _, i := range users[b.drv] {
346 obs.emit("check.build-start", runs[i].out.spec.name, map[string]any{"slot_wait_ms": wait.Milliseconds()})
347 }
348 began := time.Now()
349 b.paths, b.log, b.err = build(b.drv)
350 b.took = time.Since(began)
351 ended := time.Now()
352 // Each run the build decides is decided as soon as it
353 // ends, and its result recorded then; it is reported in
354 // order below.
355 for _, i := range users[b.drv] {
356 runs[i].took += b.took
357 runs[i].err = pureOutcome(b, &runs[i].out)
358 if obs != nil {
359 d := buildData(b, wait, began, ended, obs.logOf(b.drv))
360 obs.emit("check.build-end", runs[i].out.spec.name, d)
361 d["result"] = resultOf(runs[i])
362 d["eval_ms"] = runs[i].eval.Milliseconds()
363 d["check_ms"] = runs[i].took.Milliseconds()
364 obs.emit("check.result", runs[i].out.spec.name, d)
365 }
366 }
367 }()
368 }
369 }()
370 for i := range runs {
371 if pending[i] {
372 <-builds[drvs[i]].done
373 }
374 if report != nil {
375 report(runs[i])
376 }
377 }
378}
379
380// resultOf is a run's result as a timing and a record name it.
381func resultOf(r ranCheck) string {
382 switch {
383 case r.err != nil:
384 return "error"
385 case !r.out.passed:
386 return "failed"
387 }
388 return "passed"
389}
390
391// drvBuild is the nix build of one derivation: what it printed on standard
392// output and on standard error, how it ended, and how long it took. done
393// is closed once it has ended.
394type drvBuild struct {
395 drv string
396 done chan struct{}
397 paths string
398 log string
399 err error
400 took time.Duration
401}
402
403// pureOutcome decides one pure check from its derivation's build, and
404// digests the output when the build succeeded. Building from the
405// derivation path rather than the attribute a second time guarantees the
406// thing built is the thing recorded. The build's standard error is the
407// check's log. A build that failed with nothing on standard error, as when
408// nix could not be started or was killed by a signal, gets the error that
409// ended it as its log instead.
410func pureOutcome(b *drvBuild, out *checkOutcome) error {
411 out.log = strings.TrimSpace(b.log)
412 if b.err != nil {
413 if out.log == "" {
414 out.log = b.err.Error()
415 }
416 return nil // a failed check is an outcome, not an error
417 }
418 paths := strings.Fields(b.paths)
419 if len(paths) != 1 {
420 return fmt.Errorf("%s produced %d outputs; a check attribute must produce exactly one", out.spec.name, len(paths))
421 }
422 entries, err := fsEntries(paths[0])
423 if err != nil {
424 return err
425 }
426 out.output = treeDigest(entries)
427 out.passed = true
428 return nil
429}
430
431// drvInputs collects the store paths a derivation reads: the derivations
432// it depends on and the sources it takes directly. A .drv's references are
433// exactly that set, and `nix-store --query --references` prints them as
434// lines — a shape that has not changed in the lifetime of nix, unlike the
435// versioned JSON of `nix derivation show`.
436func drvInputs(drv string) ([]string, error) {
437 out, errb, err := nixStore(context.Background(), "--query", "--references", drv)
438 if err != nil {
439 return nil, fmt.Errorf("querying the inputs of %s: %w: %s", drv, err, strings.TrimSpace(errb))
440 }
441 inputs := strings.Fields(out)
442 if len(inputs) == 0 {
443 return nil, fmt.Errorf("%s has no inputs at all", drv)
444 }
445 return inputs, nil
446}
447
448// runEffectful runs a command over the exported tree and notarizes what it
449// observed. No digests: there is nothing to re-derive, which is exactly
450// what the effectful predicate type says.
451func runEffectful(tree string, spec checkSpec, logTo io.Writer) checkOutcome {
452 out := checkOutcome{spec: spec, satisfied: satisfiedRan}
453 cmd := exec.Command("sh", "-c", spec.command)
454 cmd.Dir = tree
455 var log bytes.Buffer
456 if logTo == nil {
457 logTo = io.Discard
458 }
459 cmd.Stdout = io.MultiWriter(&log, logTo)
460 cmd.Stderr = cmd.Stdout
461 err := cmd.Run()
462 out.log = strings.TrimSpace(log.String())
463 out.observedAt = time.Now().UTC().Format("2006-01-02T15:04:05Z")
464 out.passed = err == nil
465 return out
466}