gunk-dev/the-valley

check.go

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