gunk-dev/the-valley

worker.go

sourceed90d7ad0634main's published tip history
51.9 KiB
1package main
2
3// work is one pass of a check worker. It builds the nix checks that ready
4// changes require before anyone approves them, and publishes the evidence
5// on origin, where approve (bin/valley) reuses it instead of building it,
6// and where the integrator finds it for a request approve filed without it.
7// A timer starts a pass, and so does a wake mark. A pass keeps nothing
8// between passes but its record of failures.
9//
10// A pass reads each project named with --repo, and works out what each
11// of the project's ready changes needs:
12//
13// 1. It lists the ready changes whose active version has not landed, as
14// valley pending does (pending.go), and pins each one's active head.
15// 2. It derives the checks the head requires, as valley-go checks does
16// (checks.go), over the head's merge base with main. Both policy
17// layers are read at main's tip on origin, as approve reads them,
18// never from the change.
19// 3. It asks coverage (coverage.go) which of the head's nix checks origin
20// already holds evidence for. Command checks are left to approve.
21// 4. The rest is one batch: attest run --rev <head> under the worker's
22// key, which stores one attestation ref, and a push of that ref alone.
23// Given --slots, the batch builds that many checks at once; without
24// it, attest's own default decides.
25//
26// That read of every project is a scan. A pass is one loop, the
27// scheduler, which runs scans and batches until there is nothing left to
28// do. The loop alone starts batches, publishes, writes the failure record
29// and the telemetry, and claims wake marks. Each batch is one attest run,
30// which a goroutine waits for. When attest ends, the goroutine hands the
31// loop what the batch did, and changes nothing itself.
32//
33// Up to --batches batches run at once; without it, one. The loop starts
34// the batches a scan found in the order their versions became ready.
35// Batches overlap their builds, and their evaluations are admitted by a
36// memory budget (evalbudget.go). One evaluation can need most of the
37// memory the worker's slice has, so evaluations that together need more
38// than the slice holds could get one of them killed. A batch's evaluation
39// starts when its estimate fits the budget beside the evaluations
40// admitted before it, and otherwise waits. attest admits it through
41// reservations in the state directory, which a pass or an attest killed
42// during an evaluation does not leave counting once the evaluation is
43// gone. An attest that cannot make its reservation evaluates nothing and
44// fails, and its batch backs off like any other that failed. The time a batch waits to
45// be admitted is recorded apart from its evaluation's.
46// Change records carry no time, so that order is the order in which this
47// pass first saw each version ready. Versions first seen in the same scan
48// go by project name, then by change ID. A pass started by a timer or a
49// mark sees all the versions ready then in its first scan.
50//
51// One batch at a time builds a tree's evidence. A batch's destination is
52// the ref it stores and pushes: the project, the tree's digest and this
53// worker's key hash. A destination is held from the moment its batch
54// starts until its push has been tried, and no second batch for it starts
55// meanwhile. attest stores its ref with a plain update-ref, so two
56// batches for one ref must never run at once. Two changes whose heads
57// hold the same tree, or two versions of a change with the same tree,
58// share one batch. Right before it starts a batch, the loop reads the
59// head's evidence on origin and the refs stored here again, as a scan
60// does. Evidence that arrived since the scan is not built again.
61//
62// The loop scans again when a batch ends, when a wake mark arrives, and
63// every --interval while batches run. It drops a job that has not
64// started when a later scan does not find it: its version was superseded,
65// landed, or has the evidence it lacked. A batch that runs goes on to its
66// end, and its evidence is published: it is about the head's tree, so it
67// stays true if the change moves on meanwhile. The pass ends when nothing
68// runs and a scan finds nothing to start.
69//
70// When a batch ends, its slot takes the next job from the last scan's
71// queue at once, and the scan comes after. So a version superseded since
72// that scan can build once. That is accepted: its evidence is true of its
73// tree, and a free slot does not wait for a read of every project.
74//
75// A scan forgets each version it did not find ready that no batch builds:
76// when the pass first saw it, and the notes said about it. A pass lives as
77// long as work keeps arriving, and holds no more than the versions it
78// still meets.
79//
80// The attestation namespace admits creations only, so the worker never
81// builds what it could not publish. When origin already holds this
82// worker's ref for a tree and the ref lacks a required check, the pass
83// reports it and builds nothing. approve --build-here builds the rest
84// under the operator's key (bd-7b7d58f). When the worker's ref is stored
85// here but not on origin, an earlier batch built it and its push was
86// lost, so the pass pushes that same ref again rather than building it
87// again.
88//
89// A batch that fails is not run again at once, and neither is a push that
90// fails. The pass records each failure in failures.json in the state
91// directory, under its project, as soon as it happens: a batch by the
92// tree and the checks it runs, and a push by the object it publishes. A
93// failed batch waits firstBuildWait before it runs again, and a failed
94// push waits firstPushWait. Each wait doubles with every failure in a
95// row, up to longestWait. A wait runs from when the attempt ended, so a
96// long build does not use up its own wait. A scan in a pass that is still
97// busy starts a batch whose wait is over. A new version is a new batch,
98// and runs at once. VALLEY_NOW, when set, is the time the pass reads as
99// now (main.go's clock). Deleting the record lets everything run again at
100// once.
101//
102// A scan forgets the failures it did not meet in a project, but only for
103// a project it read whole: every ready change's checks derived and its
104// evidence read. It never forgets the failure key of a batch still
105// running. A scan over other projects, or one that could not read this
106// one, leaves this one's record as it is.
107//
108// Passes that share a state directory take turns: each holds the lock
109// file there while it runs, and a pass that finds it held waits for it.
110// Every attest is handed the lock too, so it stays held while a batch
111// runs even when the pass that started the batch is killed. A stop of
112// the unit stops the pass and every attest it started.
113//
114// A read of origin that fails stops the pass, because a read that did not
115// happen must not read as no changes or no evidence. The loop starts
116// nothing more, lets the running batches end, publishes and records what
117// they did, and then fails. Anything else that goes wrong with one change
118// or one batch is reported, and the pass goes on with the rest. The pass
119// exits 1 when anything went wrong.
120//
121// Given --wake, a pass claims that wake directory's due mark before it
122// reads anything, and claims again each mark made while it runs, before
123// the scan that mark starts (wake.go). It acknowledges the claim when it
124// ends having handled what it read. A pass has handled it when every scan
125// read every project whole and everything that went wrong was a failed
126// batch or push whose wait it recorded: those are retried when their
127// wait is over, and a new mark for the same refs would only find them
128// still waiting. Anything else that went wrong (a policy that did not
129// read, checks that did not derive, a read that stopped the pass, a
130// record that was not written) leaves the claim unacknowledged. The
131// worker's own pushes mark due, so a pass that publishes scans once more,
132// finds nothing new, and ends. A pass that could not claim due reads and
133// builds all the same, and then exits claimFailedStatus instead of 0 or
134// 1.
135//
136// Given --telemetry, or VALLEY_TELEMETRY_DIR in its environment, which is
137// how the host module names it, a pass says what it is doing as it does
138// it, and keeps its recent attempts, its running batches and the failures
139// waiting out their backoff with what each was about
140// (workertelemetry.go). It hands attest the same stream for each batch's
141// progress, and the capacity it builds on (capacity.go), which each check
142// build's records carry.
143//
144// Given --keep-outputs, a pass keeps the outputs of the checks it builds
145// alive against nix's garbage collection, so a later batch whose checks
146// have the same derivations finds them built. It hands attest
147// --gc-roots with the directory roots in its state directory, where
148// attest makes one indirect root per output, named by the output's store
149// path basename, and makes it afresh whenever a batch uses the output.
150// Before its batches, the pass removes each root there that no batch has
151// used for longer than the age --keep-outputs gives (pruneRoots). It
152// removes only the symlink; nix's own garbage collection frees the output
153// later. Without --keep-outputs, attest roots nothing and the pass prunes
154// nothing.
155
156import (
157 "cmp"
158 "context"
159 "encoding/json"
160 "errors"
161 "fmt"
162 "io"
163 "math"
164 "os"
165 "os/exec"
166 "path/filepath"
167 "sort"
168 "strconv"
169 "strings"
170 "sync"
171 "syscall"
172 "time"
173
174 "the-valley/change"
175 "the-valley/composed"
176 "the-valley/telemetry"
177)
178
179const workUsage = "usage: valley-go work --repo <name>... --key <file> [--name <name>] [--state <dir>] [--wake <dir>] [--telemetry <dir>] [--slots <n>] [--batches <n>] [--interval <span>] [--keep-outputs <age>] [--eval-budget <size>] [--eval-share <fraction>]"
180
181// projectLayer is the project's own policy layer, in main's tree.
182const projectLayer = "policy/project"
183
184// The waits after a failure before the same thing is tried again: the
185// first after a failed batch, the first after a failed push, and the
186// longest either grows to by doubling.
187const (
188 firstBuildWait = 15 * time.Minute
189 firstPushWait = time.Minute
190 longestWait = 24 * time.Hour
191)
192
193// defaultInterval is how often a pass with batches running scans again
194// when --interval is not given: the host module's own default.
195const defaultInterval = time.Minute
196
197// markPoll is how often a pass with batches running looks for a new wake
198// mark.
199const markPoll = time.Second
200
201// worker is one pass: the signer it attests as, the lock it holds, what it
202// says, what it has found going wrong, and the scheduler's state. Only the
203// loop reads or changes any of it once the first batch starts.
204type worker struct {
205 key, name string
206 slots int // how many checks a batch builds at once, or 0 for attest's default
207 batches int // how many batches run at once
208 interval time.Duration // how often a pass with batches running scans again
209 roots string // the directory attest roots the outputs it builds in, or "" to root nothing
210 evals *evaluations // the evaluation budget and the record of peaks, or nil to admit evaluations by nothing
211 keyhash string // the key hash an attestation ref of this signer ends in
212 lock *os.File // the state directory's lock, held for the pass
213 wake *wake // the wake directory's claim, or nil without --wake
214 tel *workerTelemetry
215 failures *failureRecord
216 stdout io.Writer
217 stderr io.Writer
218 out, errs io.Writer // the files attest writes to: the pass's own stdout and stderr
219 troubles int // things that went wrong that did not stop the pass
220 waits int // of the troubles, the failures whose wait was recorded
221
222 capacity string // what the pass builds on (capacity.go), or "" without telemetry
223
224 scans int // the scans so far
225 seen map[string]int // the scan that first saw each version ready, by job.version
226 ready map[string]bool // the versions the scan under way has found ready, by job.version
227 running map[string]*batch // the batches running, by job.dest
228 queue []*job // what the last scan found to build and has not started, in order
229 said map[string]map[string]bool // the notes said about each version or project since the pass last acted on it
230 fresh map[string]map[string]bool // the failure keys recorded since the scan began, by project
231 done chan completion // how a batch's goroutine hands the loop what the batch did
232
233 // How the loop reads a project, reassesses a job right before its
234 // batch starts, and starts a batch's attest run: project, assess and
235 // attest, unless a test gives its own.
236 read func(g git, name string) ([]*job, error)
237 recheck func(j *job) (bool, error)
238 launch func(b *batch)
239}
240
241// job is one ready version as a scan read it: its head, the nix checks the
242// head requires and the ones origin holds no evidence for, and the batch
243// that would build them.
244type job struct {
245 r listed
246 c jsonChange
247 v jsonVersion
248 asked []nixCheck // every nix check the head requires
249 missing []nixCheck // the ones origin holds no evidence for
250 digest string // the head's tree digest
251 ref string // this worker's attestation ref for the tree
252 key string // the batch's key in the failure record
253 seen int // the scan that first saw the version ready
254}
255
256// version names the job's change version, project by project.
257func (j *job) version() string { return versionName(j.r.name, j.c.ChangeID, j.v.N) }
258
259// versionName names a change version, project by project.
260func versionName(project, change string, n int) string {
261 return project + " " + change + " " + strconv.Itoa(n)
262}
263
264// dest is the batch's destination: the project and the ref it stores.
265func (j *job) dest() string { return j.r.name + " " + j.ref }
266
267func (j *job) names() []string {
268 var names []string
269 for _, q := range j.missing {
270 names = append(names, q.name)
271 }
272 return names
273}
274
275// line opens every line said about the job's version.
276func (j *job) line() string {
277 return fmt.Sprintf("%s: %s v%d at %s", j.r.name, j.c.Handle, j.v.N, j.v.Head[:min(7, len(j.v.Head))])
278}
279
280func (j *job) identity() identity {
281 return identity{project: j.r.name, change: j.c.ChangeID, cv: j.v.N, head: j.v.Head, tree: j.digest}
282}
283
284// jobBefore orders jobs: by the scan that first saw each version ready, then
285// by project name, then by change ID.
286func jobBefore(a, b *job) bool {
287 if a.seen != b.seen {
288 return a.seen < b.seen
289 }
290 if a.r.name != b.r.name {
291 return a.r.name < b.r.name
292 }
293 return a.c.ChangeID < b.c.ChangeID
294}
295
296// batch is a job whose attest run has started.
297type batch struct {
298 job *job
299 run string // the attest run's ID
300 mark int64 // the newest record in the telemetry stream when it started
301 estimate int64 // the peak memory its evaluation is expected to need, in bytes
302 budget int64 // the budget its attest is handed beside the estimate, in bytes
303 attempt *attempt
304}
305
306// completion is what a batch did, as its goroutine hands it to the loop:
307// how attest ended and when, the object it stored at the job's ref, and
308// the checks it recorded as not passing. It is not changed once sent.
309type completion struct {
310 b *batch
311 err error
312 ended time.Time
313 stored string // "" when attest stored nothing there
314 failed []string
315 peak int64 // the evaluation's peak memory in bytes, or 0 when attest did not say
316 outcome string // how the evaluation ended, as attest said: "ok", "failed" or "killed", or empty when it did not say
317}
318
319func runWork(g git, args []string, stdout, stderr io.Writer) (err error) {
320 var repos []string
321 var key, name, state, wakeDir, telemetryDir string
322 slots, batches := 0, 1
323 interval := defaultInterval
324 var keep time.Duration
325 var evalBudget int64
326 evalShare := defaultEvalShare
327 for i := 0; i < len(args); i++ {
328 opt, value, inline := strings.Cut(args[i], "=")
329 switch opt {
330 case "--repo", "--key", "--name", "--state", "--wake", "--telemetry", "--slots", "--batches", "--interval", "--keep-outputs", "--eval-budget", "--eval-share":
331 default:
332 return failure(workUsage)
333 }
334 if !inline {
335 if i+1 == len(args) {
336 return failure(workUsage)
337 }
338 i++
339 value = args[i]
340 }
341 switch opt {
342 case "--repo":
343 if !change.ValidPrincipal(value) {
344 return failure(fmt.Sprintf("--repo %s: not a project name", value))
345 }
346 repos = append(repos, value)
347 case "--key":
348 key = value
349 case "--name":
350 name = value
351 case "--state":
352 state = value
353 case "--wake":
354 wakeDir = value
355 case "--telemetry":
356 telemetryDir = value
357 case "--slots", "--batches":
358 n, err := strconv.Atoi(value)
359 if err != nil || n < 1 {
360 return failure(fmt.Sprintf("%s %s: not a whole number of at least 1", opt, value))
361 }
362 if opt == "--slots" {
363 slots = n
364 } else {
365 batches = n
366 }
367 case "--interval":
368 d, err := timeSpan(value)
369 if err != nil {
370 return failure(fmt.Sprintf("--interval: %v; give a systemd time span, such as 1m, 15s or 5min", err))
371 }
372 // A pass reads its projects no more often than it looks for
373 // a mark, so a span of 0, which a timer takes, does not spin.
374 interval = max(d, markPoll)
375 case "--keep-outputs":
376 d, err := time.ParseDuration(value)
377 if err != nil || d <= 0 {
378 return failure(fmt.Sprintf("--keep-outputs %s: not a positive duration, such as 168h", value))
379 }
380 keep = d
381 case "--eval-budget":
382 n, err := parseSize(value)
383 if err != nil {
384 return failure(fmt.Sprintf("--eval-budget %s: %v", value, err))
385 }
386 evalBudget = n
387 case "--eval-share":
388 f, err := strconv.ParseFloat(value, 64)
389 if err != nil || !(f > 0 && f <= 1) {
390 return failure(fmt.Sprintf("--eval-share %s: not a fraction greater than 0 and at most 1, such as 0.6", value))
391 }
392 evalShare = f
393 }
394 }
395 if len(repos) == 0 || key == "" {
396 return failure(workUsage)
397 }
398 if telemetryDir == "" {
399 telemetryDir = os.Getenv("VALLEY_TELEMETRY_DIR")
400 }
401 // The pass's own lines go out whole, one Write each; every attest
402 // writes to the files beneath.
403 files, errFiles := stdout, stderr
404 stdout, stderr = &lineSink{to: stdout}, &lineSink{to: stderr}
405 // From here on, a pass given --wake that ends without having claimed
406 // due exits claimFailedStatus, however it ends, so whatever started
407 // it for that due holds off before it starts another.
408 var claim *wake
409 if wakeDir != "" {
410 defer func() {
411 if claim != nil && claim.err == nil {
412 return
413 }
414 why := "due was not claimed"
415 if claim != nil {
416 why = claim.err.Error()
417 }
418 if err != nil {
419 fmt.Fprintf(stderr, "valley: %s\n", err)
420 }
421 err = claimFailure{fmt.Sprintf("%s, so the pass exits %d", why, claimFailedStatus)}
422 }()
423 }
424 // attest runs in the repository a project is read through, which may
425 // be a cache clone, so a key named relative to here is made absolute.
426 abs, err := filepath.Abs(key)
427 if err != nil {
428 return failure(fmt.Sprintf("--key %s: %v", key, err))
429 }
430 key = abs
431 if state == "" {
432 if state, err = stateDirectory(); err != nil {
433 return failure("no state directory: name one with --state")
434 }
435 }
436 if err := os.MkdirAll(state, 0o700); err != nil {
437 return failure(fmt.Sprintf("could not make the state directory %s", state))
438 }
439
440 lock, err := lockState(filepath.Join(state, "lock"), stderr)
441 if err != nil {
442 return failure(fmt.Sprintf("could not take the lock in %s: %v", state, err))
443 }
444 defer lock.Close() // close drops the flock; every attest handed it has ended by then
445
446 // The claim comes before any read, so a move marked after it is
447 // either read by this pass or left marked for the next.
448 if wakeDir != "" {
449 claim = claimWake(wakeDir, stderr)
450 defer claim.close()
451 if claim.err != nil {
452 fmt.Fprintf(stderr, "valley: %v; the pass reads everything all the same\n", claim.err)
453 }
454 }
455
456 // The signer is read before anything else is done, so a pass that
457 // could only end in "no key" says so before it reads anything.
458 keyArgs := []string{"key", "--key", key}
459 if name != "" {
460 keyArgs = append(keyArgs, "--name", name)
461 }
462 out, err := attestTool(g, keyArgs...)
463 fields := strings.SplitN(strings.TrimSpace(out), "+", 3)
464 if err != nil || len(fields) != 3 || len(fields[1]) != 8 {
465 return failure(fmt.Sprintf("could not read the signing key at %s: %s", key, refusalOf(out)))
466 }
467
468 w := &worker{key: key, name: name, slots: slots, batches: batches, interval: interval, keyhash: fields[1],
469 lock: lock, wake: claim, stdout: stdout, stderr: stderr, out: files, errs: errFiles,
470 seen: map[string]int{}, running: map[string]*batch{}, said: map[string]map[string]bool{}}
471 w.read, w.launch = w.project, w.attest
472 w.recheck = func(j *job) (bool, error) { return w.assess(j, nil) }
473 w.tel = openWorkerTelemetry(telemetryDir)
474 if w.tel != nil {
475 w.capacity = measureCapacity(slots, batches)
476 }
477 // The loop returns only once no batch runs, so nothing changes the
478 // state the telemetry finishes with.
479 defer func() { w.tel.finish(w.failures, w.troubles, err) }()
480 w.failures = readFailures(filepath.Join(state, "failures.json"), stderr)
481 // attest runs in each project's repository, so the state directory is
482 // named absolutely for the reservations, as it is for the roots.
483 abState, err := filepath.Abs(state)
484 if err != nil {
485 return failure(fmt.Sprintf("--state %s: %v", state, err))
486 }
487 if w.evals, err = openEvaluations(abState, evalBudget, evalShare); err != nil {
488 return failure(fmt.Sprintf("the evaluation budget: %v", err))
489 }
490 if w.evals.budget == 0 {
491 fmt.Fprintf(stderr, "valley: the evaluation budget could not be found (%s), so this pass evaluates one batch at a time. "+
492 "Give the memory evaluations may hold together with services.valley.worker.evalMemoryBudget, such as \"12G\" (--eval-budget 12G)\n", w.evals.source)
493 }
494 if keep > 0 {
495 // attest runs in each project's repository, so the roots are
496 // named absolutely, where this pass prunes them.
497 if w.roots, err = filepath.Abs(filepath.Join(state, "roots")); err != nil {
498 return failure(fmt.Sprintf("--state %s: %v", state, err))
499 }
500 if err := pruneRoots(w.roots, keep, clock()); err != nil {
501 fmt.Fprintf(stderr, "valley: could not prune the roots in %s: %v\n", w.roots, err)
502 w.troubles++
503 }
504 }
505 return w.pass(g, repos)
506}
507
508// pass runs the loop, writes the failure record, and acknowledges the
509// wake claim when the pass handled what it read. It returns the error of
510// a read of origin that failed, and otherwise says how many things went
511// wrong.
512func (w *worker) pass(g git, repos []string) error {
513 stop := w.loop(g, repos)
514 w.save()
515 if stop != nil {
516 return stop
517 }
518 if w.wake != nil && w.troubles == w.waits {
519 if err := w.wake.ack(); err != nil {
520 fmt.Fprintf(w.stderr, "valley: could not acknowledge %s: %v\n", filepath.Join(w.wake.dir, "claimed"), err)
521 w.troubles++
522 }
523 }
524 if w.troubles > 0 {
525 return failure(fmt.Sprintf("the pass finished, but %s went wrong in it; each is said above", counted(w.troubles, "thing")))
526 }
527 return nil
528}
529
530// spanUnits are the units of a systemd time span in microseconds, in the
531// order systemd tries them (extract_multiplier in its time-util.c): the
532// first a span's text starts with is its unit. A month is 30.44 days and a
533// year 365.25 days, as systemd counts them.
534var spanUnits = []struct {
535 name string
536 usec uint64
537}{
538 {"seconds", 1e6}, {"second", 1e6}, {"sec", 1e6}, {"s", 1e6},
539 {"minutes", 60e6}, {"minute", 60e6}, {"min", 60e6},
540 {"months", 2629800e6}, {"month", 2629800e6}, {"M", 2629800e6},
541 {"msec", 1e3}, {"ms", 1e3}, {"m", 60e6},
542 {"hours", 3600e6}, {"hour", 3600e6}, {"hr", 3600e6}, {"h", 3600e6},
543 {"days", 86400e6}, {"day", 86400e6}, {"d", 86400e6},
544 {"weeks", 604800e6}, {"week", 604800e6}, {"w", 604800e6},
545 {"years", 31557600e6}, {"year", 31557600e6}, {"y", 31557600e6},
546 {"usec", 1}, {"us", 1}, {"\u03bcs", 1}, {"\u00b5s", 1},
547}
548
549// timeSpan reads a time span as systemd reads a timer's (parse_sec in its
550// time-util.c), such as 1m, 15s, 5min, "1h 30min", 1.5h, 2months or
551// infinity. A number with no unit is seconds. Like systemd, it counts
552// whole microseconds, and refuses a span of 2^64-1 microseconds or more.
553// A span longer than a time.Duration holds, about 292 years, reads as the
554// longest one, as infinity does.
555func timeSpan(s string) (time.Duration, error) {
556 const space = " \t\n\r"
557 bad := fmt.Errorf("%q is not a time span", s)
558 long := fmt.Errorf("%q is longer than systemd reads", s)
559 rest := strings.TrimLeft(s, space)
560 if after, ok := strings.CutPrefix(rest, "infinity"); ok {
561 if strings.TrimLeft(after, space) != "" {
562 return 0, bad
563 }
564 return math.MaxInt64, nil
565 }
566 digits := func(s string) string { return s[:len(s)-len(strings.TrimLeft(s, "0123456789"))] }
567 if rest == "" {
568 return 0, bad
569 }
570 var usec uint64
571 for ; rest != ""; rest = strings.TrimLeft(rest, space) {
572 whole := digits(rest)
573 after := rest[len(whole):]
574 fraction := ""
575 if tail, dot := strings.CutPrefix(after, "."); dot {
576 if fraction = digits(tail); fraction == "" {
577 return 0, bad
578 }
579 after = tail[len(fraction):]
580 } else if whole == "" {
581 return 0, bad
582 }
583 // The unit may follow a space. A number followed at once by
584 // anything else, such as 12.34.56, is not a span.
585 unit, mult := strings.TrimLeft(after, space), uint64(1e6)
586 matched := false
587 for _, u := range spanUnits {
588 if strings.HasPrefix(unit, u.name) {
589 unit, mult, matched = unit[len(u.name):], u.usec, true
590 break
591 }
592 }
593 if !matched && unit == after && after != "" {
594 return 0, bad
595 }
596 rest = unit
597 n, err := strconv.ParseInt(cmp.Or(whole, "0"), 10, 64)
598 if err != nil || uint64(n) >= math.MaxUint64/mult {
599 return 0, long
600 }
601 if k := uint64(n) * mult; k < math.MaxUint64-usec {
602 usec += k
603 } else {
604 return 0, long
605 }
606 for i, m := 0, mult/10; i < len(fraction); i, m = i+1, m/10 {
607 k := uint64(fraction[i]-'0') * m
608 if k >= math.MaxUint64-usec {
609 return 0, long
610 }
611 usec += k
612 }
613 }
614 if usec > math.MaxInt64/uint64(time.Microsecond) {
615 return math.MaxInt64, nil
616 }
617 return time.Duration(usec) * time.Microsecond, nil
618}
619
620// lineSink passes on the pass's own lines, so that no two of its Writes
621// overlap.
622type lineSink struct {
623 mu sync.Mutex
624 to io.Writer
625}
626
627func (s *lineSink) Write(p []byte) (int, error) {
628 s.mu.Lock()
629 defer s.mu.Unlock()
630 return s.to.Write(p)
631}
632
633// stateDirectory is where the worker keeps its lock and its record of
634// failed batches by default: $XDG_STATE_HOME/valley/worker, or
635// ~/.local/state/valley/worker, beside attest's timing log.
636func stateDirectory() (string, error) {
637 state := os.Getenv("XDG_STATE_HOME")
638 if !filepath.IsAbs(state) {
639 home, err := os.UserHomeDir()
640 if err != nil {
641 return "", err
642 }
643 state = filepath.Join(home, ".local", "state")
644 }
645 return filepath.Join(state, "valley", "worker"), nil
646}
647
648// pruneRoots removes each symlink in dir whose modification time is more
649// than keep before now. attest makes a root afresh each time a batch uses
650// its output, so that time is the output's last use. Only symlinks are
651// removed, never what they point to, and a dir that does not exist yet
652// holds nothing to prune.
653func pruneRoots(dir string, keep time.Duration, now time.Time) error {
654 entries, err := os.ReadDir(dir)
655 if errors.Is(err, os.ErrNotExist) {
656 return nil
657 }
658 if err != nil {
659 return err
660 }
661 var errs []error
662 for _, e := range entries {
663 if e.Type()&os.ModeSymlink == 0 {
664 continue
665 }
666 info, err := e.Info()
667 if errors.Is(err, os.ErrNotExist) {
668 continue
669 }
670 if err != nil {
671 errs = append(errs, err)
672 continue
673 }
674 if now.Sub(info.ModTime()) > keep {
675 if err := os.Remove(filepath.Join(dir, e.Name())); err != nil && !errors.Is(err, os.ErrNotExist) {
676 errs = append(errs, err)
677 }
678 }
679 }
680 return errors.Join(errs...)
681}
682
683// lockState takes the lock file at path, waiting for whoever holds it, and
684// returns the open file, whose closing releases it. The lock is flock's,
685// as self-update's is. It belongs to the open file, so it is released when
686// every process holding that file has closed it or ended, however each
687// ends.
688func lockState(path string, stderr io.Writer) (*os.File, error) {
689 f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600)
690 if err != nil {
691 return nil, err
692 }
693 err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
694 if errors.Is(err, syscall.EWOULDBLOCK) {
695 fmt.Fprintf(stderr, "valley: another pass holds %s; waiting for it to end\n", path)
696 err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
697 }
698 if err != nil {
699 f.Close()
700 return nil, err
701 }
702 return f, nil
703}
704
705// loop is the pass's scheduler. It scans, starts what the scan found, and
706// handles each batch as it ends, until nothing runs and a scan finds
707// nothing to start. It returns the error of a read of origin that failed,
708// once every batch running then has ended and been handled. It never
709// returns while a batch runs.
710func (w *worker) loop(g git, repos []string) error {
711 w.done = make(chan completion)
712 tick := time.NewTicker(w.interval)
713 defer tick.Stop()
714 poll := time.NewTicker(markPoll)
715 defer poll.Stop()
716 var stop error
717 scan := true
718 for {
719 if scan && stop == nil {
720 scan = false
721 // A mark made since the last claim is claimed before the
722 // scan reads anything, as the first is.
723 w.wake.again(w.stderr)
724 if stop = w.scan(g, repos); stop == nil {
725 stop = w.admit()
726 }
727 w.tel.settle()
728 }
729 if len(w.running) == 0 {
730 if stop != nil || !w.wake.marked() {
731 return stop
732 }
733 scan = true
734 continue
735 }
736 select {
737 case c := <-w.done:
738 w.complete(c)
739 // A freed slot takes the next job from the last scan's
740 // queue at once, before the scan that follows finds what
741 // changed meanwhile. A version superseded since that scan
742 // can build once this way; its evidence is about its tree,
743 // so it is still true.
744 if err := w.reap(); stop == nil {
745 if stop = err; stop == nil {
746 stop = w.admit()
747 }
748 }
749 scan = true
750 case <-tick.C:
751 scan = true
752 case <-poll.C:
753 scan = scan || w.wake.marked()
754 }
755 }
756}
757
758// scan reads every project, and makes the queue what it found to build,
759// in order. It returns an error only when a read of origin failed.
760func (w *worker) scan(g git, repos []string) error {
761 w.scans++
762 w.fresh = map[string]map[string]bool{}
763 w.ready = map[string]bool{}
764 var found []*job
765 for _, name := range repos {
766 jobs, err := w.read(g, name)
767 if err != nil {
768 w.queue = nil
769 return err
770 }
771 found = append(found, jobs...)
772 }
773 w.queue = w.order(found)
774 w.forget(repos)
775 return nil
776}
777
778// forget drops what the pass keeps about each version that the scan just
779// ended did not find ready and no batch builds: when it was first seen,
780// and the notes said about it. A pass lives as long as work keeps
781// arriving, and this keeps what it holds to the versions it still meets.
782// A version found ready again later is seen anew.
783func (w *worker) forget(repos []string) {
784 keep := map[string]bool{}
785 for v := range w.ready {
786 keep[v] = true
787 }
788 for _, b := range w.running {
789 keep[b.job.version()] = true
790 }
791 for v := range w.seen {
792 if !keep[v] {
793 delete(w.seen, v)
794 }
795 }
796 for _, name := range repos {
797 keep[name] = true // the notes said about a project as a whole
798 }
799 for about := range w.said {
800 if !keep[about] {
801 delete(w.said, about)
802 }
803 }
804}
805
806// order sorts what a scan found, and keeps the first job for each
807// destination. A later job for the same destination is the same tree
808// under the same signer, which the first job's batch builds.
809func (w *worker) order(found []*job) []*job {
810 sort.SliceStable(found, func(a, b int) bool { return jobBefore(found[a], found[b]) })
811 first := map[string]*job{}
812 var queue []*job
813 for _, j := range found {
814 if f, ok := first[j.dest()]; ok {
815 w.note(j, "the batch for %s v%d builds the same tree", f.c.Handle, f.v.N)
816 continue
817 }
818 first[j.dest()] = j
819 queue = append(queue, j)
820 }
821 return queue
822}
823
824// project reads one project's ready changes, and returns the jobs that
825// need a batch. It returns an error only when a read of origin failed.
826// When it has read the project whole, it forgets the project's failures
827// it did not meet.
828func (w *worker) project(g git, name string) ([]*job, error) {
829 list, _, err := sources(g, listing{repo: name}, w.stderr)
830 if err != nil {
831 return nil, failure(fmt.Sprintf("%s: %v; the pass stops here", name, err))
832 }
833 repos := readSources(list, newVerifier())
834 r := repos[0]
835 if r.err != nil {
836 return nil, failure(fmt.Sprintf("%s: %v; the pass stops here", name, r.err))
837 }
838 view := r.pendingView(handles(repos))
839 for _, c := range view.Changes {
840 w.ready[versionName(name, c.ChangeID, c.Versions[c.Active-1].N)] = true
841 }
842 met := map[string]bool{} // the failures this scan met, by key
843 if len(view.Changes) == 0 {
844 w.prune(name, met)
845 return nil, nil
846 }
847 if r.snap.tip == "" {
848 if w.noteAs(name, name+": origin has no main to read the policy at, so nothing is built") {
849 w.troubles++
850 }
851 return nil, nil
852 }
853 instance, project, done, err := policyLayers(r.g, r.snap.tip)
854 defer done()
855 if err != nil {
856 if w.noteAs(name, fmt.Sprintf("%s: the policy at main did not read, so nothing is built: %v", name, err)) {
857 w.troubles++
858 }
859 return nil, nil
860 }
861 delete(w.said, name)
862 whole := true
863 var jobs []*job
864 for _, c := range view.Changes {
865 // A scan reads one change after another, which can take a while,
866 // so a batch that ended meanwhile is handled between them.
867 if err := w.reap(); err != nil {
868 return nil, err
869 }
870 j, read, err := w.change(r, instance, project, c, met)
871 if err != nil {
872 return nil, err
873 }
874 whole = whole && read
875 if j != nil {
876 jobs = append(jobs, j)
877 }
878 }
879 if whole {
880 w.prune(name, met)
881 }
882 return jobs, nil
883}
884
885// prune forgets the project's failures that a scan which read the project
886// whole did not meet. It never forgets the key of a batch still running,
887// nor a failure recorded since the scan began, which the scan's reads may
888// have come too early to meet.
889func (w *worker) prune(project string, met map[string]bool) {
890 for _, b := range w.running {
891 if b.job.r.name == project {
892 met[b.job.key] = true
893 }
894 }
895 for key := range w.fresh[project] {
896 met[key] = true
897 }
898 w.failures.keep(project, met)
899}
900
901// failed records a failure, and that it was recorded during this scan.
902func (w *worker) failed(project, key string, at time.Time, first time.Duration) backoff {
903 if w.fresh != nil {
904 if w.fresh[project] == nil {
905 w.fresh[project] = map[string]bool{}
906 }
907 w.fresh[project][key] = true
908 }
909 return w.failures.failed(project, key, at, first)
910}
911
912// reap handles every batch that has ended and not been handled, and then
913// starts what the queue holds in the slots they freed. It returns an
914// error only when a read of origin failed.
915func (w *worker) reap() error {
916 ended := false
917 for {
918 select {
919 case c := <-w.done:
920 w.complete(c)
921 ended = true
922 continue
923 default:
924 }
925 break
926 }
927 if !ended {
928 return nil
929 }
930 return w.admit()
931}
932
933// change reads one ready change, and returns its job when it needs a
934// batch. read says whether it read the change through: derived its
935// checks, and read the evidence origin holds for them.
936func (w *worker) change(r listed, instance, project string, c jsonChange, met map[string]bool) (j *job, read bool, err error) {
937 v := c.Versions[c.Active-1]
938 j = &job{r: r, c: c, v: v}
939 first, ok := w.seen[j.version()]
940 if !ok {
941 first = w.scans
942 w.seen[j.version()] = first
943 }
944 j.seen = first
945 w.tel.reading(r.name, c, v, !ok)
946 base, err := r.g.output(true, "merge-base", r.snap.tip, v.Head)
947 if err != nil {
948 if w.note(j, "shares no history with main, so nothing is built") {
949 w.troubles++
950 }
951 return nil, false, nil
952 }
953 doc, err := derivedChecks(r.g, "", instance, project, base, v.Head)
954 if err != nil {
955 if w.note(j, "its checks did not derive, so nothing is built: %v", err) {
956 w.troubles++
957 }
958 return nil, false, nil
959 }
960 for _, q := range doc.Required {
961 if q.Runner == "nix" {
962 j.asked = append(j.asked, nixCheck{q.Name, q.Attribute})
963 }
964 }
965 if len(j.asked) == 0 {
966 w.note(j, "requires no nix check")
967 return nil, true, nil
968 }
969 needed, err := w.assess(j, met)
970 if err != nil || !needed {
971 return nil, err == nil, err
972 }
973 return j, true, nil
974}
975
976// assess reads the evidence origin holds for a job's head, and reports
977// whether the job needs a batch now. It does not when origin covers every
978// check, when a batch for its destination runs, when origin already holds
979// this worker's ref for the tree, when its batch is waiting out a
980// failure, or when a batch stored the ref here and origin lacks it, which
981// it publishes. met, when given, gets the failure keys it meets. It
982// returns an error only when a read of origin failed.
983func (w *worker) assess(j *job, met map[string]bool) (bool, error) {
984 e, err := coverageOf(j.r.g, j.v.Head, j.asked, w.stderr)
985 if err != nil {
986 return false, failure(fmt.Sprintf("%s: %s v%d: %v; the pass stops here", j.r.name, j.c.Handle, j.v.N, err))
987 }
988 j.digest, j.missing = e.digest, nil
989 j.ref = attestationRefs + e.digest + "/" + w.keyhash
990 for _, q := range j.asked {
991 if _, ok := e.covered[q.name]; !ok {
992 j.missing = append(j.missing, q)
993 }
994 }
995 if len(j.missing) == 0 {
996 w.note(j, "origin holds evidence for every nix check it requires")
997 return false, nil
998 }
999 if b, ok := w.running[j.dest()]; ok {
1000 if b.job.version() != j.version() {
1001 w.note(j, "the batch for %s v%d builds the same tree", b.job.c.Handle, b.job.v.N)
1002 }
1003 return false, nil
1004 }
1005 names := strings.Join(j.names(), ", ")
1006 if _, ok := e.listed[j.ref]; ok {
1007 w.note(j, "origin already holds %s, this worker's evidence for its tree, and it does not cover %s. "+
1008 "That namespace admits creations only, so approve --build-here builds the rest (bd-7b7d58f)", j.ref, names)
1009 return false, nil
1010 }
1011 if stored, found, err := j.r.g.ref(j.ref); err == nil && found {
1012 w.note(j, "an earlier pass stored %s, and origin does not hold it", j.ref)
1013 w.publish(j, stored, met)
1014 return false, nil
1015 }
1016 j.key = "build " + e.digest + " " + strings.Join(j.names(), ",")
1017 if met != nil {
1018 met[j.key] = true
1019 }
1020 if f, waiting := w.failures.waiting(j.r.name, j.key, clock()); waiting {
1021 w.note(j, "its batch %s failed %s in a row, so it is not built again before %s", names, counted(f.Failures, "time"), f.Retry.Format(time.RFC3339))
1022 return false, nil
1023 }
1024 return true, nil
1025}
1026
1027// admit starts the queue's jobs in order while fewer than w.batches run.
1028// It assesses each job again right before it starts it, so evidence that
1029// arrived since the scan is not built again. A job whose destination a
1030// batch holds, or that finds no slot, stays queued for the next scan to
1031// find again. It returns an error only when a read of origin failed.
1032func (w *worker) admit() error {
1033 var left []*job
1034 for i, j := range w.queue {
1035 if len(w.running) >= w.batches {
1036 left = append(left, w.queue[i:]...)
1037 break
1038 }
1039 if _, held := w.running[j.dest()]; held {
1040 left = append(left, j)
1041 continue
1042 }
1043 needed, err := w.recheck(j)
1044 if err != nil {
1045 w.queue = nil
1046 return err
1047 }
1048 if needed {
1049 w.start(j)
1050 }
1051 }
1052 w.queue = left
1053 return nil
1054}
1055
1056// start runs a job's batch: it holds the job's destination, starts attest
1057// run, and leaves a goroutine to wait for it. The goroutine reads what
1058// attest stored and recorded, and hands it to the loop; it changes
1059// nothing the loop owns.
1060//
1061// attest is handed the lock file as well, and holds it until it ends, and
1062// the wake directory's lock with it. The flock belongs to the open file,
1063// so the lock stays held while attest runs, and while anything it started
1064// that inherited the file runs, even when this pass is killed. A later
1065// pass waits for all of it, and then finds the ref attest stored.
1066//
1067// The batch's evaluation is estimated from its project's record of peaks.
1068// An estimate larger than the whole budget cannot fit beside anything, so
1069// the evaluation runs alone, and the pass says so, once for the batch, in
1070// its output and as a capacity record. A pass that found no budget hands
1071// attest a budget equal to the estimate, so each evaluation runs alone,
1072// and said so once when it began.
1073func (w *worker) start(j *job) {
1074 b := &batch{job: j, run: telemetry.NewRunID(), mark: w.tel.streamEnd()}
1075 w.say(j, "building %s", strings.Join(j.names(), ", "))
1076 data := map[string]any{"attest_run": b.run}
1077 if w.evals != nil {
1078 b.estimate = w.evals.estimate(j.r.name)
1079 b.budget = w.evals.handed(b.estimate)
1080 data["eval_estimate_bytes"], data["eval_budget_bytes"] = b.estimate, b.budget
1081 if w.evals.budget > 0 && b.estimate > w.evals.budget {
1082 w.say(j, "its evaluation is estimated at %s, more than the evaluation budget of %s (%s), so it evaluates alone; give the worker more memory, or a larger --eval-budget or --eval-share",
1083 bytesText(b.estimate), bytesText(w.evals.budget), w.evals.source)
1084 w.tel.capacity(j.identity(), b.estimate, w.evals.budget, w.evals.source)
1085 }
1086 }
1087 b.attempt = w.tel.begin("build", j.identity(), j.names(), b.run, data)
1088 w.running[j.dest()] = b
1089 w.launch(b)
1090}
1091
1092// attest starts a batch's attest run, and a goroutine that waits for it
1093// and hands the loop its completion.
1094func (w *worker) attest(b *batch) {
1095 j := b.job
1096 repo := j.r.g.dir
1097 if repo == "" {
1098 repo = "."
1099 }
1100 args := []string{"run", "--repo", repo, "--rev", j.v.Head, "--key", w.key}
1101 if w.name != "" {
1102 args = append(args, "--name", w.name)
1103 }
1104 if w.slots > 0 {
1105 args = append(args, "--slots", strconv.Itoa(w.slots))
1106 }
1107 if w.roots != "" {
1108 args = append(args, "--gc-roots", w.roots)
1109 }
1110 peak := ""
1111 if w.evals != nil {
1112 peak = filepath.Join(w.evals.dir, b.run+".peak")
1113 args = append(args, "--eval-reservations", w.evals.dir, "--eval-estimate", strconv.FormatInt(b.estimate, 10),
1114 "--eval-budget", strconv.FormatInt(b.budget, 10), "--eval-peak", peak)
1115 }
1116 for _, q := range j.missing {
1117 args = append(args, "--check", q.name+"="+q.attribute)
1118 }
1119 stream := ""
1120 if w.tel != nil {
1121 stream = w.tel.stream()
1122 args = append(args, "--telemetry", stream, "--telemetry-run", b.run, "--project", j.r.name,
1123 "--change", j.c.ChangeID, "--change-version", strconv.Itoa(j.v.N), "--capacity", w.capacity)
1124 }
1125 // attest writes to the pass's own output files, not through a pipe the
1126 // pass reads: an attest that outlives a killed pass must still be able
1127 // to write, and store its ref.
1128 cmd := exec.Command("attest", args...)
1129 cmd.Env = j.r.g.env
1130 cmd.Dir = j.r.g.dir
1131 cmd.Stdout, cmd.Stderr = w.out, w.errs
1132 cmd.ExtraFiles = []*os.File{w.lock}
1133 if w.wake != nil && w.wake.lock != nil {
1134 cmd.ExtraFiles = append(cmd.ExtraFiles, w.wake.lock)
1135 }
1136 if err := cmd.Start(); err != nil {
1137 go func() { w.done <- completion{b: b, err: err, ended: clock()} }()
1138 return
1139 }
1140 g, ref, run, mark := j.r.g, j.ref, b.run, b.mark
1141 go func() {
1142 err := cmd.Wait()
1143 c := completion{b: b, err: err, ended: clock()}
1144 if peak != "" {
1145 if text, rerr := os.ReadFile(peak); rerr == nil {
1146 c.peak, c.outcome = readPeak(string(text))
1147 }
1148 os.Remove(peak)
1149 }
1150 if err != nil {
1151 c.failed = failedChecks(stream, run, mark)
1152 } else if stored, found, rerr := g.ref(ref); rerr == nil && found {
1153 c.stored = stored
1154 }
1155 w.done <- c
1156 }()
1157}
1158
1159// complete handles what one batch did: it records a failure at once, with
1160// its wait measured from when the batch ended, or publishes what the batch
1161// stored. The batch's destination is held until its push has been tried.
1162func (w *worker) complete(c completion) {
1163 b, j := c.b, c.b.job
1164 defer func() {
1165 delete(w.running, j.dest())
1166 w.tel.settle()
1167 }()
1168 outcome := c.outcome
1169 if outcome == "" && endedBySignal(c.err) {
1170 // attest was killed before it said how its evaluation ended,
1171 // which may have been during the evaluation.
1172 outcome = "killed"
1173 }
1174 if outcome != "" && w.evals != nil {
1175 if err := w.evals.record(j.r.name, c.peak, outcome); err != nil {
1176 fmt.Fprintf(w.stderr, "valley: could not record the evaluation's peak memory in %s: %v\n", w.evals.path, err)
1177 }
1178 }
1179 if c.err != nil {
1180 f := w.failed(j.r.name, j.key, c.ended, firstBuildWait)
1181 reason := fmt.Sprintf("attest run %s: %v", b.run, c.err)
1182 if len(c.failed) > 0 {
1183 reason += "; " + strings.Join(c.failed, ", ")
1184 }
1185 w.tel.end(b.attempt, c.err, reason, j.key, &f)
1186 w.say(j, "the batch did not pass (%v); it is not built again before %s", c.err, f.Retry.Format(time.RFC3339))
1187 w.troubles++
1188 w.waits++
1189 w.save()
1190 return
1191 }
1192 w.failures.passed(j.r.name, j.key)
1193 w.tel.end(b.attempt, nil, "", j.key, nil)
1194 w.save()
1195 if c.stored == "" {
1196 w.say(j, "attest stored no %s, so nothing is published", j.ref)
1197 w.troubles++
1198 return
1199 }
1200 w.publish(j, c.stored, nil)
1201}
1202
1203// publish pushes a job's attestation ref to origin, and nothing else. The
1204// hook verifies the notes against the tree and the signer whoever pushes
1205// them. A push that fails leaves the ref stored here, and the same object
1206// is not pushed again until its wait is over: by any pass, and for any
1207// change whose tree it is about. met, when given, gets the push's key.
1208func (w *worker) publish(j *job, object string, met map[string]bool) {
1209 key := "push " + object
1210 if met != nil {
1211 met[key] = true
1212 }
1213 if f, waiting := w.failures.waiting(j.r.name, key, clock()); waiting {
1214 w.note(j, "publishing %s failed %s in a row, so it is not pushed again before %s", j.ref, counted(f.Failures, "time"), f.Retry.Format(time.RFC3339))
1215 return
1216 }
1217 a := w.tel.begin("push", j.identity(), nil, "", map[string]any{"ref": j.ref, "object": object})
1218 if _, err := j.r.g.output(false, "push", "--quiet", "origin", object+":"+j.ref); err != nil {
1219 f := w.failed(j.r.name, key, clock(), firstPushWait)
1220 w.tel.end(a, err, fmt.Sprintf("pushing %s to origin: %v", j.ref, err), key, &f)
1221 w.say(j, "could not publish %s; it is not pushed again before %s", j.ref, f.Retry.Format(time.RFC3339))
1222 w.troubles++
1223 w.waits++
1224 w.save()
1225 return
1226 }
1227 w.failures.passed(j.r.name, key)
1228 w.tel.end(a, nil, "", key, nil)
1229 w.say(j, "published %s", j.ref)
1230}
1231
1232// say prints a line about what the pass did with a version. The version's
1233// notes may be said again after it.
1234func (w *worker) say(j *job, format string, args ...any) {
1235 delete(w.said, j.version())
1236 fmt.Fprintf(w.stdout, "%s: %s\n", j.line(), fmt.Sprintf(format, args...))
1237}
1238
1239// note prints a line about how a version stands, unless the pass has said
1240// that line of it since it last did something with it, so a scan that
1241// finds things as they were says nothing new. It reports whether it
1242// printed.
1243func (w *worker) note(j *job, format string, args ...any) bool {
1244 return w.noteAs(j.version(), j.line()+": "+fmt.Sprintf(format, args...))
1245}
1246
1247func (w *worker) noteAs(about, line string) bool {
1248 if w.said[about][line] {
1249 return false
1250 }
1251 if w.said[about] == nil {
1252 w.said[about] = map[string]bool{}
1253 }
1254 w.said[about][line] = true
1255 fmt.Fprintln(w.stdout, line)
1256 return true
1257}
1258
1259// save writes the failure record, and counts a write that fails as
1260// something that went wrong.
1261func (w *worker) save() {
1262 if err := w.failures.save(); err != nil {
1263 fmt.Fprintf(w.stderr, "valley: could not write %s: %v\n", w.failures.path, err)
1264 w.troubles++
1265 }
1266}
1267
1268// policyLayers resolves the two policy layers a project's changes are
1269// derived under, as approve resolves them (bin/valley's
1270// resolve_instance_layer and resolve_project_layer), and returns what
1271// removes them. Both are read at main's tip on origin. The floor is that
1272// tip's own policy/instance when it carries one, and otherwise
1273// policy/instance at the tip of main in the owning valley that
1274// policy/valley names. A tip with no policy/project is derived under the
1275// floor alone.
1276func policyLayers(g git, tip string) (instance, project string, done func(), err error) {
1277 ctx := context.Background()
1278 var ends []func()
1279 done = func() {
1280 for _, end := range ends {
1281 end()
1282 }
1283 }
1284 repo := g.dir
1285 if repo == "" {
1286 repo = "."
1287 }
1288 floor := composed.Floor{Repo: repo, Ref: tip, Dir: instanceLayer}
1289 if !g.succeeds(true, "cat-file", "-e", tip+":"+instanceLayer) {
1290 pointer, err := g.output(true, "cat-file", "blob", tip+":"+valleyPointer)
1291 if err != nil {
1292 return "", "", done, fmt.Errorf("main names no owning valley at %s", valleyPointer)
1293 }
1294 url := pointerURL(pointer)
1295 if url == "" {
1296 return "", "", done, fmt.Errorf("%s on main names no repository", valleyPointer)
1297 }
1298 if err := checkURL(url); err != nil {
1299 return "", "", done, err
1300 }
1301 scratch, err := os.MkdirTemp("", "valley-work-valley-")
1302 if err != nil {
1303 return "", "", done, err
1304 }
1305 ends = append(ends, func() { _ = os.RemoveAll(scratch) })
1306 v := git{env: cacheEnvironment(g.env), stderr: g.stderr, dir: scratch}
1307 if _, err := v.output(true, "init", "--quiet", "--bare"); err != nil {
1308 return "", "", done, errors.New("no scratch repository to fetch the floor into")
1309 }
1310 // The valley's main is read by its exact name, and fetched by the
1311 // object it names: given a ref name the valley lacks, fetch takes
1312 // another ref whose name ends in it, such as
1313 // refs/heads/refs/heads/main.
1314 at, err := remoteRef(v, url, "refs/heads/main")
1315 if err != nil {
1316 return "", "", done, fmt.Errorf("could not fetch the owning valley %s", url)
1317 } else if at == "" {
1318 return "", "", done, fmt.Errorf("the owning valley %s has no refs/heads/main", url)
1319 }
1320 if _, err := v.output(true, "fetch", "--quiet", "--depth", "1", "--no-tags", "--end-of-options", url, at); err != nil {
1321 return "", "", done, fmt.Errorf("could not fetch the owning valley %s", url)
1322 }
1323 floor = composed.Floor{Repo: scratch, Ref: at, Dir: instanceLayer}
1324 }
1325 instance, end, err := floor.Open(ctx, "valley-work-floor")
1326 ends = append(ends, end)
1327 if err != nil {
1328 return "", "", done, err
1329 }
1330 project, _, end, err = composed.Project(ctx, repo, tip, projectLayer, "valley-work-project")
1331 ends = append(ends, end)
1332 return instance, project, done, err
1333}
1334
1335// failureRecord is the worker's record of what failed, project by
1336// project: each batch, keyed "build <tree digest> <check>,<check>", and
1337// each push, keyed "push <object ID>". For each it holds how many times in
1338// a row it failed, and the time before which it is not tried again. It is
1339// kept as JSON at path.
1340type failureRecord struct {
1341 path string
1342 Projects map[string]map[string]backoff `json:"projects"`
1343}
1344
1345type backoff struct {
1346 Failures int `json:"failures"`
1347 Retry time.Time `json:"retry"`
1348}
1349
1350// readFailures reads the record at path. A record that is not there is
1351// empty. One that does not read is said, and started again empty: the
1352// worst it costs is one more try of each thing it held.
1353func readFailures(path string, stderr io.Writer) *failureRecord {
1354 r := &failureRecord{path: path}
1355 data, err := os.ReadFile(path)
1356 if err == nil {
1357 err = json.Unmarshal(data, r)
1358 }
1359 if err != nil && !errors.Is(err, os.ErrNotExist) {
1360 fmt.Fprintf(stderr, "valley: %s does not read, so everything it held is tried again\n", path)
1361 r.Projects = nil
1362 }
1363 if r.Projects == nil {
1364 r.Projects = map[string]map[string]backoff{}
1365 }
1366 return r
1367}
1368
1369// waiting reports whether something failed and its wait is not over.
1370func (r *failureRecord) waiting(project, key string, now time.Time) (backoff, bool) {
1371 f, ok := r.Projects[project][key]
1372 return f, ok && now.Before(f.Retry)
1373}
1374
1375// failed records one more failure in a row, and the time it may be tried
1376// again: first after the first failure, doubled for each one after it, and
1377// never more than longestWait.
1378func (r *failureRecord) failed(project, key string, now time.Time, first time.Duration) backoff {
1379 if r.Projects[project] == nil {
1380 r.Projects[project] = map[string]backoff{}
1381 }
1382 f := r.Projects[project][key]
1383 f.Failures++
1384 wait := first
1385 for i := 1; i < f.Failures && wait < longestWait; i++ {
1386 wait *= 2
1387 }
1388 f.Retry = now.Add(min(wait, longestWait))
1389 r.Projects[project][key] = f
1390 return f
1391}
1392
1393func (r *failureRecord) passed(project, key string) { delete(r.Projects[project], key) }
1394
1395// keep forgets every failure of the project that is not in met. Other
1396// projects' failures are kept.
1397func (r *failureRecord) keep(project string, met map[string]bool) {
1398 for key := range r.Projects[project] {
1399 if !met[key] {
1400 delete(r.Projects[project], key)
1401 }
1402 }
1403 if len(r.Projects[project]) == 0 {
1404 delete(r.Projects, project)
1405 }
1406}
1407
1408// save writes the record whole, through a file renamed into place, so a
1409// pass that is killed leaves the last record or the new one. An empty
1410// record is no file.
1411func (r *failureRecord) save() error {
1412 for project, failures := range r.Projects {
1413 if len(failures) == 0 {
1414 delete(r.Projects, project)
1415 }
1416 }
1417 if len(r.Projects) == 0 {
1418 if err := os.Remove(r.path); err != nil && !errors.Is(err, os.ErrNotExist) {
1419 return err
1420 }
1421 return nil
1422 }
1423 data, err := json.MarshalIndent(r, "", " ") // in key order
1424 if err != nil {
1425 return err
1426 }
1427 tmp, err := os.CreateTemp(filepath.Dir(r.path), ".failures-*")
1428 if err != nil {
1429 return err
1430 }
1431 _, err = tmp.Write(append(data, '\n'))
1432 if cerr := tmp.Close(); err == nil {
1433 err = cerr
1434 }
1435 if err == nil {
1436 err = os.Rename(tmp.Name(), r.path)
1437 }
1438 if err != nil {
1439 os.Remove(tmp.Name())
1440 }
1441 return err
1442}