gunk-dev/the-valley

check.go

sourced6ff7d88653bmain's published tip history
13.0 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.
213func evalDrvPaths(tree, system string, attrs []string) map[string]string {
214 drvs := map[string]string{}
215 if len(attrs) == 0 {
216 return drvs
217 }
218 quoted := make([]string, len(attrs))
219 for i, a := range attrs {
220 quoted[i] = `"` + a + `"`
221 }
222 apply := `checks: builtins.listToAttrs (map (name: { inherit name; value = ` +
223 `let r = builtins.tryEval (if checks ? ${name} && checks.${name} ? drvPath then checks.${name}.drvPath else null); ` +
224 `in if r.success then r.value else null; }) [ ` + strings.Join(quoted, " ") + ` ])`
225 out, _, err := nix(tree, "eval", "--json", "--apply", apply, tree+"#checks."+system)
226 if err != nil {
227 return drvs
228 }
229 var named map[string]any
230 if json.Unmarshal([]byte(out), &named) != nil {
231 return drvs
232 }
233 for _, a := range attrs {
234 if drv, ok := named[a].(string); ok && drv != "" {
235 drvs[a] = drv
236 }
237 }
238 return drvs
239}
240
241// buildSlots is how many nix build processes runPure runs at once.
242var buildSlots = runtime.NumCPU()
243
244// runPure runs every pure check and returns their runs in the order given.
245// It evaluates them all together (evalClosures), then builds each
246// derivation that evaluated in a nix build of its own, buildSlots of them
247// at once, so the nix daemon builds them side by side (buildChecks).
248// Checks that evaluate to the same derivation share its one build. With
249// report, it hands each run to report in the order given, as soon as that
250// check and every one before it have ended.
251//
252// Each check's outcome is its own derivation's build: the exit status and
253// standard error of the nix build that built it, exactly as when checks
254// were built one at a time. With probe, it first asks the nix store
255// whether each output is already there, for the check's timing; without,
256// it asks nothing about outputs.
257//
258// A check is timed from the start of the shared evaluation. Its duration
259// is its evaluation, its probe, and its derivation's build. One that does
260// not evaluate ends at its evaluation error.
261func runPure(tree, system string, specs []checkSpec, probe bool, report func(ranCheck)) []ranCheck {
262 began := time.Now()
263 evals := evalClosures(tree, system, specs)
264 runs := make([]ranCheck, len(specs))
265 for i, spec := range specs {
266 e := evals[i]
267 runs[i] = ranCheck{out: checkOutcome{spec: spec}, began: began, took: e.took, eval: e.took, err: e.err}
268 if e.err != nil {
269 continue
270 }
271 runs[i].out.derivation, runs[i].out.inputs = e.derivation, e.inputs
272 if probe {
273 probed := time.Now()
274 runs[i].out.satisfied = outputsCached(e.drv)
275 runs[i].took += time.Since(probed)
276 }
277 }
278
279 drvs := make([]string, len(evals))
280 for i, e := range evals {
281 drvs[i] = e.drv
282 }
283 buildChecks(runs, drvs, buildSlots, func(drv string) (string, string, error) {
284 return nix(tree, "build", "--no-link", "--print-out-paths", drv+"^*")
285 }, report)
286 return runs
287}
288
289// buildChecks builds the derivation of every run that has no error yet
290// and decides each from its derivation's build (pureOutcome). drvs[i] is
291// runs[i]'s derivation, and build builds one derivation, returning what it
292// printed on standard output and standard error and how it ended. Builds
293// start in the order of runs, at most slots of them at once, and runs that
294// share a derivation share its one build. Each run is handed to report in
295// order, as soon as it and every run before it have ended.
296func buildChecks(runs []ranCheck, drvs []string, slots int, build func(drv string) (string, string, error), report func(ranCheck)) {
297 builds := map[string]*drvBuild{}
298 var order []*drvBuild
299 for i := range runs {
300 if runs[i].err != nil || builds[drvs[i]] != nil {
301 continue
302 }
303 b := &drvBuild{drv: drvs[i], done: make(chan struct{})}
304 builds[drvs[i]] = b
305 order = append(order, b)
306 }
307 free := make(chan struct{}, max(slots, 1))
308 go func() {
309 for _, b := range order {
310 free <- struct{}{}
311 go func() {
312 defer close(b.done)
313 defer func() { <-free }()
314 began := time.Now()
315 b.paths, b.log, b.err = build(b.drv)
316 b.took = time.Since(began)
317 }()
318 }
319 }()
320 for i := range runs {
321 if runs[i].err == nil {
322 b := builds[drvs[i]]
323 <-b.done
324 runs[i].took += b.took
325 runs[i].err = pureOutcome(b, &runs[i].out)
326 }
327 if report != nil {
328 report(runs[i])
329 }
330 }
331}
332
333// drvBuild is the nix build of one derivation: what it printed on standard
334// output and on standard error, how it ended, and how long it took. done
335// is closed once it has ended.
336type drvBuild struct {
337 drv string
338 done chan struct{}
339 paths string
340 log string
341 err error
342 took time.Duration
343}
344
345// pureOutcome decides one pure check from its derivation's build, and
346// digests the output when the build succeeded. Building from the
347// derivation path rather than the attribute a second time guarantees the
348// thing built is the thing recorded. The build's standard error is the
349// check's log. A build that failed with nothing on standard error, as when
350// nix could not be started or was killed by a signal, gets the error that
351// ended it as its log instead.
352func pureOutcome(b *drvBuild, out *checkOutcome) error {
353 out.log = strings.TrimSpace(b.log)
354 if b.err != nil {
355 if out.log == "" {
356 out.log = b.err.Error()
357 }
358 return nil // a failed check is an outcome, not an error
359 }
360 paths := strings.Fields(b.paths)
361 if len(paths) != 1 {
362 return fmt.Errorf("%s produced %d outputs; a check attribute must produce exactly one", out.spec.name, len(paths))
363 }
364 entries, err := fsEntries(paths[0])
365 if err != nil {
366 return err
367 }
368 out.output = treeDigest(entries)
369 out.passed = true
370 return nil
371}
372
373// drvInputs collects the store paths a derivation reads: the derivations
374// it depends on and the sources it takes directly. A .drv's references are
375// exactly that set, and `nix-store --query --references` prints them as
376// lines — a shape that has not changed in the lifetime of nix, unlike the
377// versioned JSON of `nix derivation show`.
378func drvInputs(drv string) ([]string, error) {
379 out, errb, err := nixStore(context.Background(), "--query", "--references", drv)
380 if err != nil {
381 return nil, fmt.Errorf("querying the inputs of %s: %w: %s", drv, err, strings.TrimSpace(errb))
382 }
383 inputs := strings.Fields(out)
384 if len(inputs) == 0 {
385 return nil, fmt.Errorf("%s has no inputs at all", drv)
386 }
387 return inputs, nil
388}
389
390// runEffectful runs a command over the exported tree and notarizes what it
391// observed. No digests: there is nothing to re-derive, which is exactly
392// what the effectful predicate type says.
393func runEffectful(tree string, spec checkSpec) checkOutcome {
394 out := checkOutcome{spec: spec, satisfied: satisfiedRan}
395 cmd := exec.Command("sh", "-c", spec.command)
396 cmd.Dir = tree
397 log, err := cmd.CombinedOutput()
398 out.log = strings.TrimSpace(string(log))
399 out.observedAt = time.Now().UTC().Format("2006-01-02T15:04:05Z")
400 out.passed = err == nil
401 return out
402}