gunk-dev/the-valley

worker.go

source6a6791929c36main's published tip history
84.2 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 the ones a check
5// request asks for, and publishes the evidence on origin, where approve
6// (approve.go) reuses it instead of building it, and where the integrator
7// finds it for a request approve filed without it. A timer starts a pass,
8// and so does a wake mark. A pass keeps nothing between passes but its
9// record of failures.
10//
11// A pass reads each project named with --repo, and works out what each
12// of the project's ready changes needs:
13//
14// 1. It lists the ready changes whose active version has not landed, as
15// valley pending does (pending.go), and pins each one's active head.
16// 2. It derives the checks the head requires, as valley checks does
17// (checks.go), over the head's merge base with main. Both policy
18// layers are read at main's tip on origin, as approve reads them,
19// never from the change.
20// 3. It asks coverage (coverage.go) which of the head's nix checks origin
21// already holds evidence for. Command checks are left to approve.
22// 4. The rest is one batch: attest run --rev <head> under the worker's
23// key, which stores one attestation ref, and a push of that ref alone.
24// Given --slots, the batch builds that many checks at once; without
25// it, attest's own default decides.
26//
27// When a project has no ready change to build for, and no batch for a
28// ready change runs, a scan also reads which follow checks are due on the
29// project's main tip (mainstate.go). The due nix checks are one more
30// batch, a follow run: attest run --rev <main's tip> --push origin
31// --ref-only, which adds its notes to this worker's ref for main's tree,
32// beside any a gate batch published there. One run covers every landing
33// since each check's last pass. A scan that finds any ready change to
34// build for queues no follow run, so changes waiting to land always come
35// first. A follow run is never stopped because main moved: it goes on to
36// its end, and a later scan reads the new tip. It takes a slot, a
37// destination, an evaluation and a backoff as any batch does.
38//
39// A check request (../change/checkrequest.go) asks for a commit's checks
40// outside any change: a ref under refs/the-valley/check-requests/ that
41// names the commit. A scan lists each project's requests on origin,
42// sorted by name, and says and skips a ref there that is not a request's.
43// Once it has read every project's ready changes and follow run, and
44// found none to build and no batch of either running, it reads each
45// request as it reads a ready head: the checks the commit requires over
46// its merge base with main, under both layers at main's tip, never from
47// the commit, then coverage, then one batch, published as a ready
48// change's is. The attest run names no change. Evidence lets nothing
49// land: only a ready version and an approval do, and a request is
50// neither.
51//
52// That read of every project is a scan. A pass is one loop, the
53// scheduler, which runs scans and batches until there is nothing left to
54// do. The loop alone starts batches, publishes, writes the failure record
55// and the telemetry, and claims wake marks. Each batch is one attest run,
56// which a goroutine waits for. When attest ends, the goroutine hands the
57// loop what the batch did, and changes nothing itself.
58//
59// A scan queues one class of work, the first it finds of ready changes,
60// follow runs and check requests, so changes waiting to land always come
61// first. A request batch starts only when no batch of a higher class runs,
62// and only from the queue of a scan that has just found nothing of a
63// higher class. It is never stopped for higher-class work, which takes a
64// free slot beside it, or the next one.
65//
66// Up to --batches batches run at once; without it, one. The loop starts
67// the batches a scan found in the order their versions became ready.
68// Batches overlap their builds, and their evaluations are admitted by a
69// memory budget (evalbudget.go). One evaluation can need most of the
70// memory the worker's slice has, so evaluations that together need more
71// than the slice holds could get one of them killed. A batch's evaluation
72// starts when its estimate fits the budget beside the evaluations
73// admitted before it, and otherwise waits. attest admits it through
74// reservations in the state directory, which a pass or an attest killed
75// during an evaluation does not leave counting once the evaluation is
76// gone. An attest that cannot make its reservation evaluates nothing and
77// fails, and its batch backs off like any other that failed. The time a batch waits to
78// be admitted is recorded apart from its evaluation's.
79// Change records carry no time, so that order is the order in which this
80// pass first saw each version ready. Versions first seen in the same scan
81// go by project name, then by change ID. Requests go the same way, by the
82// scan that first listed each at its commit, then by project name, then
83// by name. A pass started by a timer or a mark sees all the versions ready
84// then in its first scan.
85//
86// One batch at a time builds a tree's evidence. A batch's destination is
87// the ref it stores and pushes: the project, the tree's digest and this
88// worker's key hash. A destination is held from the moment its batch
89// starts until its push has been tried, and no second batch for it starts
90// meanwhile. attest stores its ref with a plain update-ref, so two
91// batches for one ref must never run at once. Two changes whose heads
92// hold the same tree, or two versions of a change with the same tree,
93// share one batch. Right before it starts a batch, the loop reads the
94// head's evidence on origin and the refs stored here again, as a scan
95// does. Evidence that arrived since the scan is not built again.
96//
97// The loop scans again when a batch ends, when a wake mark arrives, and
98// every --interval while batches run. It drops a job that has not
99// started when a later scan does not find it: its version was superseded,
100// landed, or has the evidence it lacked. A batch that runs goes on to its
101// end, and its evidence is published: it is about the head's tree, so it
102// stays true if the change moves on meanwhile. The pass ends when nothing
103// runs and a scan finds nothing to start.
104//
105// The exception is a batch whose version a scan finds superseded, as a
106// restack supersedes one, when no ready change's active version holds its
107// tree. An approval lands a change as its active version stands, so that
108// evidence would serve no landing. A scan that read the batch's project
109// whole stops it (stopSuperseded): the loop kills its attest alone, and
110// attest's nix processes die with it, which releases its evaluation's
111// reservation. git, which stores the ref in one update, is left to
112// finish, so no ref is left half written. A stopped batch publishes
113// nothing and records no failure, and its slot and destination are free
114// once attest has ended. A batch whose tree a ready version still holds,
115// as after a restack that left the tree as it was, runs on. The same scan
116// stops a request batch whose ref it lists gone or naming another commit,
117// unless a ready version holds the tree. Another request with the same
118// tree does not keep it, since only a version that may land keeps work
119// that nobody asks for alive. A client that asks again starts a new batch,
120// whose builds the nix store already holds.
121//
122// When a batch ends, its slot takes the next job from the last scan's
123// queue at once, and the scan comes after. So a version superseded since
124// that scan can start a batch, which the next scan stops as above. A free
125// slot does not wait for a read of every project, except for a request,
126// which waits for that scan to find no ready change or follow run first.
127// A scan that goes on to read the requests empties the queue before it
128// does, so a slot freed while it reads them starts nothing an earlier
129// scan queued.
130//
131// A scan forgets each version it did not find ready, and each request it
132// did not list, that no batch builds: when the pass first saw it, and the
133// notes said about it. A pass lives as
134// long as work keeps arriving, and holds no more than the versions it
135// still meets.
136//
137// A batch for a tree origin holds no evidence of this worker's for
138// stores the ref, which holds that batch's notes alone, and the loop
139// publishes it. origin takes an existing attestation ref only with every
140// note it holds kept and at least one added, so when origin already holds
141// this worker's ref for a tree and the ref lacks a check a head there
142// requires, the batch builds the checks it lacks and attest adds their
143// notes to that ref itself (attest run --push origin --ref-only), as a
144// follow run's does. A signer's ref holds one note for each check, so a
145// check the ref holds a note for that does not count, as one for another
146// attribute, is not built again: the pass reports it, approve --build-here
147// builds it under the operator's key (bd-7b7d58f), and a request that
148// lacks nothing else is marked as one whose batch failed, below. When the
149// worker's ref is stored here but not on origin, an earlier batch built it
150// and its push was lost, so the pass pushes that same ref again rather
151// than building it again, and a later scan adds to it what it lacks.
152//
153// A batch that fails is not run again at once, and neither is a push that
154// fails. The pass records each failure in failures.json in the state
155// directory, under its project, as soon as it happens: a batch by the
156// tree and the checks it runs, and a push by the object it publishes. A
157// failed batch waits firstBuildWait before it runs again, and a failed
158// push waits firstPushWait. Each wait doubles with every failure in a
159// row, up to longestWait. A wait runs from when the attempt ended, so a
160// long build does not use up its own wait. A scan in a pass that is still
161// busy starts a batch whose wait is over. A new version is a new batch,
162// and runs at once. VALLEY_NOW, when set, is the time the pass reads as
163// now (main.go's clock). Deleting the record lets everything run again at
164// once.
165//
166// A request whose batch fails waits for no time: failures.json marks it
167// by its ref and the commit the ref names, and no pass builds it again
168// until a listing finds the ref gone or naming another commit, which
169// forgets the marker. The pass reads the marker when it lists the request,
170// and again each time it assesses it, since the batch can end while the
171// scan reads. A request is marked the same way when what its commit holds
172// keeps it from being read: it shares no history with main, its checks do
173// not derive, or its evidence does not read, as when attest cannot digest
174// a tree that holds a submodule. A client asks again with a new ref, which builds at
175// once.
176//
177// A scan forgets the failures it did not meet in a project, but only for
178// a project it read whole: every ready change's checks derived and its
179// evidence read, and the follow run's. It never forgets the failure key of
180// a batch still running. While the project lists check requests, it keeps
181// every failed push until it has read them, since a request's push is met
182// there. A scan over other projects, or one that could not read this one,
183// leaves this one's record as it is. A head whose evidence does not read
184// leaves its project unread: nothing there is forgotten or stopped, and
185// its main tip is not recorded as quiet.
186//
187// Passes that share a state directory take turns: each holds the lock
188// file there while it runs, and a pass that finds it held waits for it.
189// Every attest is handed the lock too, so it stays held while a batch
190// runs even when the pass that started the batch is killed. A stop of
191// the unit stops the pass and every attest it started.
192//
193// A read of origin that fails stops the pass, because a read that did not
194// happen must not read as no changes or no evidence. The loop starts
195// nothing more, lets the running batches end, publishes and records what
196// they did, and then fails. Anything else that goes wrong with one change,
197// request or batch is reported, and the pass goes on with the rest: a head
198// whose evidence does not read for what it holds builds nothing, and a
199// request whose does is marked, above. The pass exits 1 when anything went
200// wrong.
201//
202// Given --wake, a pass claims that wake directory's due mark before it
203// reads anything, and claims again each mark made while it runs, before
204// the scan that mark starts (wake.go). It acknowledges the claim when it
205// ends having handled what it read. A pass has handled it when every scan
206// read every project whole and everything that went wrong was a failed
207// batch or push whose wait it recorded: those are retried when their
208// wait is over, and a new mark for the same refs would only find them
209// still waiting. Anything else that went wrong (a policy that did not
210// read, checks that did not derive, a read that stopped the pass, a
211// record that was not written) leaves the claim unacknowledged. The
212// worker's own pushes mark due, so a pass that publishes scans once more,
213// finds nothing new, and ends. A pass that could not claim due reads and
214// builds all the same, and then exits claimFailedStatus instead of 0 or
215// 1.
216//
217// Given --telemetry, or VALLEY_TELEMETRY_DIR in its environment, which is
218// how the host module names it, a pass says what it is doing as it does
219// it, and keeps its recent attempts, its running batches and the failures
220// waiting out their backoff with what each was about
221// (workertelemetry.go), each batch and push with its class. It hands
222// attest the same stream for each batch's progress, and the capacity it
223// builds on (capacity.go), which each check build's records carry.
224//
225// Given --keep-outputs, a pass keeps the outputs of the checks it builds
226// alive against nix's garbage collection, so a later batch whose checks
227// have the same derivations finds them built. It hands attest
228// --gc-roots with the directory roots in its state directory, where
229// attest makes one indirect root per output, named by the output's store
230// path basename, and makes it afresh whenever a batch uses the output.
231// Before its batches, the pass removes each root there that no batch has
232// used for longer than the age --keep-outputs gives (pruneRoots). It
233// removes only the symlink; nix's own garbage collection frees the output
234// later. Without --keep-outputs, attest roots nothing and the pass prunes
235// nothing.
236
237import (
238 "bytes"
239 "cmp"
240 "context"
241 "encoding/json"
242 "errors"
243 "fmt"
244 "io"
245 "math"
246 "os"
247 "os/exec"
248 "path/filepath"
249 "sort"
250 "strconv"
251 "strings"
252 "sync"
253 "syscall"
254 "time"
255
256 "the-valley/change"
257 "the-valley/composed"
258 "the-valley/telemetry"
259)
260
261const workUsage = "usage: valley 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>]"
262
263// projectLayer is the project's own policy layer, in main's tree.
264const projectLayer = "policy/project"
265
266// The waits after a failure before the same thing is tried again: the
267// first after a failed batch, the first after a failed push, and the
268// longest either grows to by doubling.
269const (
270 firstBuildWait = 15 * time.Minute
271 firstPushWait = time.Minute
272 longestWait = 24 * time.Hour
273)
274
275// pausedPushes is what the host's ssh gate says when it refuses a push
276// because valley-init is converging (valleyhook/shell.go), and
277// pausedPushRetry is how soon the worker tries such a push again.
278const (
279 pausedPushes = "pushes to this host are paused until valley-init converges"
280 pausedPushRetry = 2 * time.Second
281)
282
283// defaultInterval is how often a pass with batches running scans again
284// when --interval is not given: the host module's own default.
285const defaultInterval = time.Minute
286
287// markPoll is how often a pass with batches running looks for a new wake
288// mark.
289const markPoll = time.Second
290
291// A job's class: what its batch is for. A scan queues the first class it
292// finds work in, in this order.
293const (
294 classReady = iota // a ready change's active version
295 classFollow // a follow run on main's tip
296 classRequest // a check request
297)
298
299// classNames name the classes in telemetry.
300var classNames = [...]string{"ready", "follow", "request"}
301
302// worker is one pass: the signer it attests as, the lock it holds, what it
303// says, what it has found going wrong, and the scheduler's state. Only the
304// loop reads or changes any of it once the first batch starts.
305type worker struct {
306 key, name string
307 slots int // how many checks a batch builds at once, or 0 for attest's default
308 batches int // how many batches run at once
309 interval time.Duration // how often a pass with batches running scans again
310 roots string // the directory attest roots the outputs it builds in, or "" to root nothing
311 evals *evaluations // the evaluation budget and the record of peaks, or nil to admit evaluations by nothing
312 keyhash string // the key hash an attestation ref of this signer ends in
313 lock *os.File // the state directory's lock, held for the pass
314 wake *wake // the wake directory's claim, or nil without --wake
315 tel *workerTelemetry
316 failures *failureRecord
317 stdout io.Writer
318 stderr io.Writer
319 out, errs io.Writer // the files attest writes to: the pass's own stdout and stderr
320 troubles int // things that went wrong that did not stop the pass
321 waits int // of the troubles, the failures whose wait was recorded
322
323 capacity string // what the pass builds on (capacity.go), or "" without telemetry
324
325 scans int // the scans so far
326 seen map[string]int // the scan that first saw each version ready, or each request listed, by job.version
327 ready map[string]bool // the versions the scan under way has found ready, and the requests it listed, by job.version
328 wanted map[string]bool // the destinations of the ready versions and follow runs the scan under way assessed, by job.dest
329 running map[string]*batch // the batches running, by job.dest
330 queue []*job // what the last scan found to build and has not started, in order
331 said map[string]map[string]bool // the notes said about each version or project since the pass last acted on it
332 fresh map[string]map[string]bool // the failure keys recorded since the scan began, by project
333 done chan completion // how a batch's goroutine hands the loop what the batch did
334 quiet *quietMains // each project's main tip on which a pass found no follow run to start
335 mains map[string]string // the failure key of the follow run the pass last assessed, by project
336
337 // How the loop reads a project, reads the evidence origin holds for a
338 // job's head, reassesses a job right before its batch starts, and
339 // starts a batch's attest run: project, coverageOf, assess and attest,
340 // unless a test gives its own.
341 read func(g git, name string) (projectRead, error)
342 cover func(j *job) (evidence, error)
343 recheck func(j *job) (bool, error)
344 launch func(b *batch)
345}
346
347// job is one ready version as a scan read it: its head, the nix checks the
348// head requires and the ones origin holds no evidence for, and the batch
349// that would build them.
350type job struct {
351 r listed
352 c jsonChange
353 v jsonVersion
354 asked []nixCheck // every nix check the head requires
355 missing []nixCheck // the ones origin holds no evidence for
356 digest string // the head's tree digest
357 ref string // this worker's attestation ref for the tree
358 key string // the batch's key in the failure record
359 seen int // the scan that first saw the version ready, or the request listed
360 main bool // a follow run on main's tip, which v.Head is; c is empty
361 covers []string // for a follow run, the landings its checks cover, newest first
362 req string // for a check request, its ref, which names v.Head; c is empty
363 // additive says the batch adds its notes to this worker's ref for the
364 // tree on origin, which holds notes already, as a follow run's always
365 // does; otherwise it stores the ref here, and the loop publishes it.
366 additive bool
367}
368
369// class is the job's class.
370func (j *job) class() int {
371 switch {
372 case j.main:
373 return classFollow
374 case j.req != "":
375 return classRequest
376 }
377 return classReady
378}
379
380// version names the job's change version, or its request and the commit
381// the request names, project by project.
382func (j *job) version() string {
383 if j.req != "" {
384 return checkRequestName(j.r.name, j.req, j.v.Head)
385 }
386 return versionName(j.r.name, j.c.ChangeID, j.v.N)
387}
388
389// versionName names a change version, project by project.
390func versionName(project, change string, n int) string {
391 return project + " " + change + " " + strconv.Itoa(n)
392}
393
394// checkRequestName names a check request at the commit it names, project by
395// project.
396func checkRequestName(project, ref, head string) string {
397 return project + " " + ref + " " + head
398}
399
400// label names what the job builds for in a line about another job.
401func (j *job) label() string {
402 switch j.class() {
403 case classFollow:
404 return "main at " + short(j.v.Head)
405 case classRequest:
406 return "request " + strings.TrimPrefix(j.req, change.CheckRequestPrefix)
407 }
408 return fmt.Sprintf("%s v%d", j.c.Handle, j.v.N)
409}
410
411// dest is the batch's destination: the project and the ref it stores.
412func (j *job) dest() string { return j.r.name + " " + j.ref }
413
414func (j *job) names() []string {
415 var names []string
416 for _, q := range j.missing {
417 names = append(names, q.name)
418 }
419 return names
420}
421
422// line opens every line said about the job's version.
423func (j *job) line() string {
424 switch j.class() {
425 case classFollow:
426 return fmt.Sprintf("%s: main at %s", j.r.name, short(j.v.Head))
427 case classRequest:
428 return fmt.Sprintf("%s: %s at %s", j.r.name, j.label(), short(j.v.Head))
429 }
430 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))])
431}
432
433func (j *job) identity() identity {
434 return identity{project: j.r.name, change: j.c.ChangeID, cv: j.v.N, head: j.v.Head, tree: j.digest}
435}
436
437// jobBefore orders jobs: by the scan that first saw each version ready or
438// each request listed, then by project name, then by change ID, then by
439// request name.
440func jobBefore(a, b *job) bool {
441 if a.seen != b.seen {
442 return a.seen < b.seen
443 }
444 if a.r.name != b.r.name {
445 return a.r.name < b.r.name
446 }
447 if a.c.ChangeID != b.c.ChangeID {
448 return a.c.ChangeID < b.c.ChangeID
449 }
450 return a.req < b.req
451}
452
453// batch is a job whose attest run has started.
454type batch struct {
455 job *job
456 run string // the attest run's ID
457 mark int64 // the newest record in the telemetry stream when it started
458 estimate int64 // the peak memory its evaluation is expected to need, in bytes
459 budget int64 // the budget its attest is handed beside the estimate, in bytes
460 attempt *attempt
461 stop func() // kills its attest run, or nil when none started
462 stopped string // why the loop stopped it, or "" when it did not
463}
464
465// completion is what a batch did, as its goroutine hands it to the loop:
466// how attest ended and when, the object it stored at the job's ref, and
467// the checks it recorded as not passing. It is not changed once sent.
468type completion struct {
469 b *batch
470 err error
471 ended time.Time
472 stored string // "" when attest stored nothing there
473 failed []string
474 peak int64 // the evaluation's peak memory in bytes, or 0 when attest did not say
475 outcome string // how the evaluation ended, as attest said: "ok", "failed" or "killed", or empty when it did not say
476}
477
478func runWork(g git, args []string, stdout, stderr io.Writer) (err error) {
479 var repos []string
480 var key, name, state, wakeDir, telemetryDir string
481 slots, batches := 0, 1
482 interval := defaultInterval
483 var keep time.Duration
484 var evalBudget int64
485 evalShare := defaultEvalShare
486 for i := 0; i < len(args); i++ {
487 opt, value, inline := strings.Cut(args[i], "=")
488 switch opt {
489 case "--repo", "--key", "--name", "--state", "--wake", "--telemetry", "--slots", "--batches", "--interval", "--keep-outputs", "--eval-budget", "--eval-share":
490 default:
491 return failure(workUsage)
492 }
493 if !inline {
494 if i+1 == len(args) {
495 return failure(workUsage)
496 }
497 i++
498 value = args[i]
499 }
500 switch opt {
501 case "--repo":
502 if !change.ValidPrincipal(value) {
503 return failure(fmt.Sprintf("--repo %s: not a project name", value))
504 }
505 repos = append(repos, value)
506 case "--key":
507 key = value
508 case "--name":
509 name = value
510 case "--state":
511 state = value
512 case "--wake":
513 wakeDir = value
514 case "--telemetry":
515 telemetryDir = value
516 case "--slots", "--batches":
517 n, err := strconv.Atoi(value)
518 if err != nil || n < 1 {
519 return failure(fmt.Sprintf("%s %s: not a whole number of at least 1", opt, value))
520 }
521 if opt == "--slots" {
522 slots = n
523 } else {
524 batches = n
525 }
526 case "--interval":
527 d, err := timeSpan(value)
528 if err != nil {
529 return failure(fmt.Sprintf("--interval: %v; give a systemd time span, such as 1m, 15s or 5min", err))
530 }
531 // A pass reads its projects no more often than it looks for
532 // a mark, so a span of 0, which a timer takes, does not spin.
533 interval = max(d, markPoll)
534 case "--keep-outputs":
535 d, err := time.ParseDuration(value)
536 if err != nil || d <= 0 {
537 return failure(fmt.Sprintf("--keep-outputs %s: not a positive duration, such as 168h", value))
538 }
539 keep = d
540 case "--eval-budget":
541 n, err := parseSize(value)
542 if err != nil {
543 return failure(fmt.Sprintf("--eval-budget %s: %v", value, err))
544 }
545 evalBudget = n
546 case "--eval-share":
547 f, err := strconv.ParseFloat(value, 64)
548 if err != nil || !(f > 0 && f <= 1) {
549 return failure(fmt.Sprintf("--eval-share %s: not a fraction greater than 0 and at most 1, such as 0.6", value))
550 }
551 evalShare = f
552 }
553 }
554 if len(repos) == 0 || key == "" {
555 return failure(workUsage)
556 }
557 if telemetryDir == "" {
558 telemetryDir = os.Getenv("VALLEY_TELEMETRY_DIR")
559 }
560 // The pass's own lines go out whole, one Write each; every attest
561 // writes to the files beneath.
562 files, errFiles := stdout, stderr
563 stdout, stderr = &lineSink{to: stdout}, &lineSink{to: stderr}
564 // From here on, a pass given --wake that ends without having claimed
565 // due exits claimFailedStatus, however it ends, so whatever started
566 // it for that due holds off before it starts another.
567 var claim *wake
568 if wakeDir != "" {
569 defer func() {
570 if claim != nil && claim.err == nil {
571 return
572 }
573 why := "due was not claimed"
574 if claim != nil {
575 why = claim.err.Error()
576 }
577 if err != nil {
578 fmt.Fprintf(stderr, "valley: %s\n", err)
579 }
580 err = claimFailure{fmt.Sprintf("%s, so the pass exits %d", why, claimFailedStatus)}
581 }()
582 }
583 // attest runs in the repository a project is read through, which may
584 // be a cache clone, so a key named relative to here is made absolute.
585 abs, err := filepath.Abs(key)
586 if err != nil {
587 return failure(fmt.Sprintf("--key %s: %v", key, err))
588 }
589 key = abs
590 if state == "" {
591 if state, err = stateDirectory(); err != nil {
592 return failure("no state directory: name one with --state")
593 }
594 }
595 if err := os.MkdirAll(state, 0o700); err != nil {
596 return failure(fmt.Sprintf("could not make the state directory %s", state))
597 }
598
599 lock, err := lockState(filepath.Join(state, "lock"), stderr)
600 if err != nil {
601 return failure(fmt.Sprintf("could not take the lock in %s: %v", state, err))
602 }
603 defer lock.Close() // close drops the flock; every attest handed it has ended by then
604
605 // The claim comes before any read, so a move marked after it is
606 // either read by this pass or left marked for the next.
607 if wakeDir != "" {
608 claim = claimWake(wakeDir, stderr)
609 defer claim.close()
610 if claim.err != nil {
611 fmt.Fprintf(stderr, "valley: %v; the pass reads everything all the same\n", claim.err)
612 }
613 }
614
615 // The signer is read before anything else is done, so a pass that
616 // could only end in "no key" says so before it reads anything.
617 keyArgs := []string{"key", "--key", key}
618 if name != "" {
619 keyArgs = append(keyArgs, "--name", name)
620 }
621 out, err := attestTool(g, keyArgs...)
622 fields := strings.SplitN(strings.TrimSpace(out), "+", 3)
623 if err != nil || len(fields) != 3 || len(fields[1]) != 8 {
624 return failure(fmt.Sprintf("could not read the signing key at %s: %s", key, refusalOf(out)))
625 }
626
627 w := &worker{key: key, name: name, slots: slots, batches: batches, interval: interval, keyhash: fields[1],
628 lock: lock, wake: claim, stdout: stdout, stderr: stderr, out: files, errs: errFiles,
629 seen: map[string]int{}, running: map[string]*batch{}, said: map[string]map[string]bool{}}
630 w.read, w.launch = w.project, w.attest
631 w.cover = func(j *job) (evidence, error) { return coverageOf(j.r.g, j.v.Head, j.asked, assessEvidence, w.stderr) }
632 w.recheck = func(j *job) (bool, error) {
633 needed, _, err := w.assess(j, nil)
634 return needed, err
635 }
636 w.tel = openWorkerTelemetry(telemetryDir)
637 if w.tel != nil {
638 w.capacity = measureCapacity(slots, batches)
639 }
640 // The loop returns only once no batch runs, so nothing changes the
641 // state the telemetry finishes with.
642 defer func() { w.tel.finish(w.failures, w.troubles, err) }()
643 w.failures = readFailures(filepath.Join(state, "failures.json"), stderr)
644 w.quiet = readQuiet(filepath.Join(state, "main.json"), stderr)
645 // attest runs in each project's repository, so the state directory is
646 // named absolutely for the reservations, as it is for the roots.
647 abState, err := filepath.Abs(state)
648 if err != nil {
649 return failure(fmt.Sprintf("--state %s: %v", state, err))
650 }
651 if w.evals, err = openEvaluations(abState, evalBudget, evalShare); err != nil {
652 return failure(fmt.Sprintf("the evaluation budget: %v", err))
653 }
654 if w.evals.budget == 0 {
655 fmt.Fprintf(stderr, "valley: the evaluation budget could not be found (%s), so this pass evaluates one batch at a time. "+
656 "Give the memory evaluations may hold together with services.valley.worker.evalMemoryBudget, such as \"12G\" (--eval-budget 12G)\n", w.evals.source)
657 }
658 if keep > 0 {
659 // attest runs in each project's repository, so the roots are
660 // named absolutely, where this pass prunes them.
661 if w.roots, err = filepath.Abs(filepath.Join(state, "roots")); err != nil {
662 return failure(fmt.Sprintf("--state %s: %v", state, err))
663 }
664 if err := pruneRoots(w.roots, keep, clock()); err != nil {
665 fmt.Fprintf(stderr, "valley: could not prune the roots in %s: %v\n", w.roots, err)
666 w.troubles++
667 }
668 }
669 return w.pass(g, repos)
670}
671
672// pass runs the loop, writes the failure record, and acknowledges the
673// wake claim when the pass handled what it read. It returns the error of
674// a read of origin that failed, and otherwise says how many things went
675// wrong.
676func (w *worker) pass(g git, repos []string) error {
677 stop := w.loop(g, repos)
678 w.save()
679 if stop != nil {
680 return stop
681 }
682 if w.wake != nil && w.troubles == w.waits {
683 if err := w.wake.ack(); err != nil {
684 fmt.Fprintf(w.stderr, "valley: could not acknowledge %s: %v\n", filepath.Join(w.wake.dir, "claimed"), err)
685 w.troubles++
686 }
687 }
688 if w.troubles > 0 {
689 return failure(fmt.Sprintf("the pass finished, but %s went wrong in it; each is said above", counted(w.troubles, "thing")))
690 }
691 return nil
692}
693
694// spanUnits are the units of a systemd time span in microseconds, in the
695// order systemd tries them (extract_multiplier in its time-util.c): the
696// first a span's text starts with is its unit. A month is 30.44 days and a
697// year 365.25 days, as systemd counts them.
698var spanUnits = []struct {
699 name string
700 usec uint64
701}{
702 {"seconds", 1e6}, {"second", 1e6}, {"sec", 1e6}, {"s", 1e6},
703 {"minutes", 60e6}, {"minute", 60e6}, {"min", 60e6},
704 {"months", 2629800e6}, {"month", 2629800e6}, {"M", 2629800e6},
705 {"msec", 1e3}, {"ms", 1e3}, {"m", 60e6},
706 {"hours", 3600e6}, {"hour", 3600e6}, {"hr", 3600e6}, {"h", 3600e6},
707 {"days", 86400e6}, {"day", 86400e6}, {"d", 86400e6},
708 {"weeks", 604800e6}, {"week", 604800e6}, {"w", 604800e6},
709 {"years", 31557600e6}, {"year", 31557600e6}, {"y", 31557600e6},
710 {"usec", 1}, {"us", 1}, {"\u03bcs", 1}, {"\u00b5s", 1},
711}
712
713// timeSpan reads a time span as systemd reads a timer's (parse_sec in its
714// time-util.c), such as 1m, 15s, 5min, "1h 30min", 1.5h, 2months or
715// infinity. A number with no unit is seconds. Like systemd, it counts
716// whole microseconds, and refuses a span of 2^64-1 microseconds or more.
717// A span longer than a time.Duration holds, about 292 years, reads as the
718// longest one, as infinity does.
719func timeSpan(s string) (time.Duration, error) {
720 const space = " \t\n\r"
721 bad := fmt.Errorf("%q is not a time span", s)
722 long := fmt.Errorf("%q is longer than systemd reads", s)
723 rest := strings.TrimLeft(s, space)
724 if after, ok := strings.CutPrefix(rest, "infinity"); ok {
725 if strings.TrimLeft(after, space) != "" {
726 return 0, bad
727 }
728 return math.MaxInt64, nil
729 }
730 digits := func(s string) string { return s[:len(s)-len(strings.TrimLeft(s, "0123456789"))] }
731 if rest == "" {
732 return 0, bad
733 }
734 var usec uint64
735 for ; rest != ""; rest = strings.TrimLeft(rest, space) {
736 whole := digits(rest)
737 after := rest[len(whole):]
738 fraction := ""
739 if tail, dot := strings.CutPrefix(after, "."); dot {
740 if fraction = digits(tail); fraction == "" {
741 return 0, bad
742 }
743 after = tail[len(fraction):]
744 } else if whole == "" {
745 return 0, bad
746 }
747 // The unit may follow a space. A number followed at once by
748 // anything else, such as 12.34.56, is not a span.
749 unit, mult := strings.TrimLeft(after, space), uint64(1e6)
750 matched := false
751 for _, u := range spanUnits {
752 if strings.HasPrefix(unit, u.name) {
753 unit, mult, matched = unit[len(u.name):], u.usec, true
754 break
755 }
756 }
757 if !matched && unit == after && after != "" {
758 return 0, bad
759 }
760 rest = unit
761 n, err := strconv.ParseInt(cmp.Or(whole, "0"), 10, 64)
762 if err != nil || uint64(n) >= math.MaxUint64/mult {
763 return 0, long
764 }
765 if k := uint64(n) * mult; k < math.MaxUint64-usec {
766 usec += k
767 } else {
768 return 0, long
769 }
770 for i, m := 0, mult/10; i < len(fraction); i, m = i+1, m/10 {
771 k := uint64(fraction[i]-'0') * m
772 if k >= math.MaxUint64-usec {
773 return 0, long
774 }
775 usec += k
776 }
777 }
778 if usec > math.MaxInt64/uint64(time.Microsecond) {
779 return math.MaxInt64, nil
780 }
781 return time.Duration(usec) * time.Microsecond, nil
782}
783
784// lineSink passes on the pass's own lines, so that no two of its Writes
785// overlap.
786type lineSink struct {
787 mu sync.Mutex
788 to io.Writer
789}
790
791func (s *lineSink) Write(p []byte) (int, error) {
792 s.mu.Lock()
793 defer s.mu.Unlock()
794 return s.to.Write(p)
795}
796
797// stateDirectory is where the worker keeps its lock and its record of
798// failed batches by default: $XDG_STATE_HOME/valley/worker, or
799// ~/.local/state/valley/worker, beside attest's timing log.
800func stateDirectory() (string, error) {
801 state := os.Getenv("XDG_STATE_HOME")
802 if !filepath.IsAbs(state) {
803 home, err := os.UserHomeDir()
804 if err != nil {
805 return "", err
806 }
807 state = filepath.Join(home, ".local", "state")
808 }
809 return filepath.Join(state, "valley", "worker"), nil
810}
811
812// pruneRoots removes each symlink in dir whose modification time is more
813// than keep before now. attest makes a root afresh each time a batch uses
814// its output, so that time is the output's last use. Only symlinks are
815// removed, never what they point to, and a dir that does not exist yet
816// holds nothing to prune.
817func pruneRoots(dir string, keep time.Duration, now time.Time) error {
818 entries, err := os.ReadDir(dir)
819 if errors.Is(err, os.ErrNotExist) {
820 return nil
821 }
822 if err != nil {
823 return err
824 }
825 var errs []error
826 for _, e := range entries {
827 if e.Type()&os.ModeSymlink == 0 {
828 continue
829 }
830 info, err := e.Info()
831 if errors.Is(err, os.ErrNotExist) {
832 continue
833 }
834 if err != nil {
835 errs = append(errs, err)
836 continue
837 }
838 if now.Sub(info.ModTime()) > keep {
839 if err := os.Remove(filepath.Join(dir, e.Name())); err != nil && !errors.Is(err, os.ErrNotExist) {
840 errs = append(errs, err)
841 }
842 }
843 }
844 return errors.Join(errs...)
845}
846
847// lockState takes the lock file at path, waiting for whoever holds it, and
848// returns the open file, whose closing releases it. The lock is flock's,
849// as self-update's is. It belongs to the open file, so it is released when
850// every process holding that file has closed it or ended, however each
851// ends.
852func lockState(path string, stderr io.Writer) (*os.File, error) {
853 f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600)
854 if err != nil {
855 return nil, err
856 }
857 err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
858 if errors.Is(err, syscall.EWOULDBLOCK) {
859 fmt.Fprintf(stderr, "valley: another pass holds %s; waiting for it to end\n", path)
860 err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
861 }
862 if err != nil {
863 f.Close()
864 return nil, err
865 }
866 return f, nil
867}
868
869// loop is the pass's scheduler. It scans, starts what the scan found, and
870// handles each batch as it ends, until nothing runs and a scan finds
871// nothing to start. It returns the error of a read of origin that failed,
872// once every batch running then has ended and been handled. It never
873// returns while a batch runs.
874func (w *worker) loop(g git, repos []string) error {
875 w.done = make(chan completion)
876 tick := time.NewTicker(w.interval)
877 defer tick.Stop()
878 poll := time.NewTicker(markPoll)
879 defer poll.Stop()
880 var stop error
881 scan := true
882 for {
883 if scan && stop == nil {
884 scan = false
885 // A mark made since the last claim is claimed before the
886 // scan reads anything, as the first is.
887 w.wake.again(w.stderr)
888 if stop = w.scan(g, repos); stop == nil {
889 stop = w.admit(true)
890 }
891 w.tel.settle()
892 }
893 if len(w.running) == 0 {
894 if stop != nil || !w.wake.marked() {
895 return stop
896 }
897 scan = true
898 continue
899 }
900 select {
901 case c := <-w.done:
902 w.complete(c)
903 // A freed slot takes the next job from the last scan's
904 // queue at once, before the scan that follows finds what
905 // changed meanwhile. A version superseded since that scan
906 // can start a batch this way, which that scan stops. A
907 // request waits for that scan, which finds any ready change
908 // or follow run that came meanwhile.
909 if err := w.reap(); stop == nil {
910 if stop = err; stop == nil {
911 stop = w.admit(false)
912 }
913 }
914 scan = true
915 case <-tick.C:
916 scan = true
917 case <-poll.C:
918 scan = scan || w.wake.marked()
919 }
920 }
921}
922
923// scan reads every project, and makes the queue what it found to build,
924// in order. It returns an error only when a read of origin failed.
925func (w *worker) scan(g git, repos []string) error {
926 w.scans++
927 w.fresh = map[string]map[string]bool{}
928 w.ready = map[string]bool{}
929 w.wanted = map[string]bool{}
930 var found []*job
931 var reads []projectRead
932 for _, name := range repos {
933 pr, err := w.read(g, name)
934 if err != nil {
935 for _, pr := range reads {
936 pr.release()
937 }
938 w.queue = nil
939 return err
940 }
941 reads = append(reads, pr)
942 found = append(found, pr.jobs...)
943 }
944 // Check requests come last: the scan reads them only once every
945 // project's ready changes and follow run are read, when none of those
946 // needs a batch and no batch of theirs runs.
947 readRequests := len(found) == 0 && !w.runningAbove(classRequest)
948 if readRequests {
949 // The request phase handles batches that end meanwhile, and a slot
950 // one frees takes the queue's next job at once, so the queue is
951 // what this scan found first, which is nothing.
952 w.queue = nil
953 }
954 var stop error
955 for _, pr := range reads {
956 if pr.requests == nil {
957 continue
958 }
959 if !readRequests || stop != nil {
960 pr.release()
961 continue
962 }
963 jobs, err := pr.requests()
964 stop = err
965 found = append(found, jobs...)
966 }
967 if stop != nil {
968 w.queue = nil
969 return stop
970 }
971 // Changes waiting to land come first, then follow runs on main, then
972 // check requests: the scan queues the first class it found work in.
973 first := classRequest
974 for _, j := range found {
975 first = min(first, j.class())
976 }
977 var queued []*job
978 for _, j := range found {
979 if j.class() == first {
980 queued = append(queued, j)
981 }
982 }
983 w.queue = w.order(queued)
984 w.forget(repos)
985 return nil
986}
987
988// forget drops what the pass keeps about each version that the scan just
989// ended did not find ready and no batch builds: when it was first seen,
990// and the notes said about it. A pass lives as long as work keeps
991// arriving, and this keeps what it holds to the versions it still meets.
992// A version found ready again later is seen anew.
993func (w *worker) forget(repos []string) {
994 keep := map[string]bool{}
995 for v := range w.ready {
996 keep[v] = true
997 }
998 for _, b := range w.running {
999 keep[b.job.version()] = true
1000 }
1001 for v := range w.seen {
1002 if !keep[v] {
1003 delete(w.seen, v)
1004 }
1005 }
1006 for _, name := range repos {
1007 keep[name] = true // the notes said about a project as a whole
1008 }
1009 for about := range w.said {
1010 if !keep[about] {
1011 delete(w.said, about)
1012 }
1013 }
1014}
1015
1016// order sorts what a scan found, and keeps the first job for each
1017// destination. A later job for the same destination is the same tree
1018// under the same signer, which the first job's batch builds.
1019func (w *worker) order(found []*job) []*job {
1020 sort.SliceStable(found, func(a, b int) bool { return jobBefore(found[a], found[b]) })
1021 first := map[string]*job{}
1022 var queue []*job
1023 for _, j := range found {
1024 if f, ok := first[j.dest()]; ok {
1025 w.note(j, "the batch for %s builds the same tree", f.label())
1026 continue
1027 }
1028 first[j.dest()] = j
1029 queue = append(queue, j)
1030 }
1031 return queue
1032}
1033
1034// projectRead is what a scan's read of one project found: the jobs its
1035// ready changes or follow run need, and, when it lists check requests a
1036// batch may build, how to read them. The scan calls requests or release
1037// once, and either removes the policy layers the read holds for them.
1038type projectRead struct {
1039 jobs []*job
1040 requests func() ([]*job, error)
1041 done func()
1042}
1043
1044// release removes what the read holds for its requests, unread.
1045func (pr projectRead) release() {
1046 if pr.done != nil {
1047 pr.done()
1048 }
1049}
1050
1051// project reads one project's ready changes, and returns the jobs that
1052// need a batch: the ready changes', or else the follow run's. It returns
1053// an error only when a read of origin failed. When it has read the
1054// project whole, it forgets the project's failures it did not meet, and
1055// stops the project's batches whose evidence would serve no landing. When
1056// it lists check requests a batch may build, it returns how to read them
1057// too, for the scan to call once no project has higher-class work.
1058func (w *worker) project(g git, name string) (projectRead, error) {
1059 list, _, err := sources(g, listing{repo: name}, w.stderr)
1060 if err != nil {
1061 return projectRead{}, failure(fmt.Sprintf("%s: %v; the pass stops here", name, err))
1062 }
1063 repos := readSources(list, newVerifier())
1064 r := repos[0]
1065 if r.err != nil {
1066 return projectRead{}, failure(fmt.Sprintf("%s: %v; the pass stops here", name, r.err))
1067 }
1068 view := r.pendingView(handles(repos))
1069 for _, c := range view.Changes {
1070 w.ready[versionName(name, c.ChangeID, c.Versions[c.Active-1].N)] = true
1071 }
1072 listed, pending, err := w.requests(r)
1073 if err != nil {
1074 return projectRead{}, err
1075 }
1076 met := map[string]bool{} // the failures this scan met, by key
1077 idle := len(view.Changes) == 0 && len(pending) == 0 && !w.requesting(name)
1078 if idle && r.snap.tip == "" {
1079 w.prune(name, met, len(listed) > 0)
1080 return projectRead{}, nil
1081 }
1082 if idle && (w.gating() || w.quiet.holds(name, r.snap.tip, w.failures)) {
1083 // Main is not read now, so its follow run's failure, if any, is
1084 // kept.
1085 return projectRead{}, nil
1086 }
1087 if r.snap.tip == "" {
1088 if w.noteAs(name, name+": origin has no main to read the policy at, so nothing is built") {
1089 w.troubles++
1090 }
1091 return projectRead{}, nil
1092 }
1093 instance, project, done, err := policyLayers(r.g, r.snap.tip)
1094 held := false // whether the requests' reader holds the layers, and removes them
1095 defer func() {
1096 if !held {
1097 done()
1098 }
1099 }()
1100 if err != nil {
1101 if w.noteAs(name, fmt.Sprintf("%s: the policy at main did not read, so nothing is built: %v", name, err)) {
1102 w.troubles++
1103 }
1104 return projectRead{}, nil
1105 }
1106 delete(w.said, name)
1107 whole := true
1108 var jobs []*job
1109 for _, c := range view.Changes {
1110 // A scan reads one change after another, which can take a while,
1111 // so a batch that ended meanwhile is handled between them.
1112 if err := w.reap(); err != nil {
1113 return projectRead{}, err
1114 }
1115 j, read, err := w.change(r, instance, project, c, met)
1116 if err != nil {
1117 return projectRead{}, err
1118 }
1119 whole = whole && read
1120 if j != nil {
1121 jobs = append(jobs, j)
1122 }
1123 }
1124 // A project read only for its check requests reads main only when a
1125 // pass would read it with none: when main is not quiet.
1126 quiet := len(view.Changes) == 0 && w.quiet.holds(name, r.snap.tip, w.failures)
1127 if len(jobs) == 0 && !w.gating() && !quiet {
1128 j, read, err := w.follows(r, instance, project, handles(repos), met)
1129 if err != nil {
1130 return projectRead{}, err
1131 }
1132 whole = whole && read
1133 if j != nil {
1134 jobs = append(jobs, j)
1135 }
1136 } else {
1137 // Main is not read now, so its follow run's failure, if any, is
1138 // kept.
1139 for _, key := range []string{w.mains[name], w.quiet.Projects[name].Wait} {
1140 if key != "" {
1141 met[key] = true
1142 }
1143 }
1144 }
1145 if whole {
1146 // A check request's push failure is met only when the requests
1147 // are read, so while the project lists any it is kept here, and
1148 // the request phase prunes it.
1149 w.prune(name, met, len(listed) > 0)
1150 w.stopSuperseded(name, view.Changes, listed)
1151 }
1152 pr := projectRead{jobs: jobs}
1153 if len(pending) > 0 {
1154 held = true
1155 pr.done = done
1156 pr.requests = func() ([]*job, error) {
1157 defer done()
1158 jobs, err := w.readRequests(r, instance, project, pending, met)
1159 if err == nil && whole {
1160 w.prune(name, met, false)
1161 }
1162 return jobs, err
1163 }
1164 }
1165 return pr, nil
1166}
1167
1168// readRequests fetches the commits a project's pending check requests
1169// name, and reads each request, as a scan reads them once no project has
1170// a ready change or follow run to build. It returns an error only when a
1171// read of origin failed.
1172func (w *worker) readRequests(r listed, instance, project string, pending []checkRequest, met map[string]bool) ([]*job, error) {
1173 var heads []string
1174 for _, q := range pending {
1175 heads = append(heads, q.head)
1176 }
1177 if err := fetch(r.g, heads...); err != nil {
1178 return nil, failure(fmt.Sprintf("%s: could not fetch the commits its check requests name; the pass stops here", r.name))
1179 }
1180 var jobs []*job
1181 for _, q := range pending {
1182 if err := w.reap(); err != nil {
1183 return nil, err
1184 }
1185 j, err := w.request(r, instance, project, q, met)
1186 if err != nil {
1187 return nil, err
1188 }
1189 if j != nil {
1190 jobs = append(jobs, j)
1191 }
1192 }
1193 return jobs, nil
1194}
1195
1196// checkRequest is one check request a listing found: its ref, and the
1197// commit it names.
1198type checkRequest struct{ ref, head string }
1199
1200// requests lists the project's check requests on origin, and forgets the
1201// marker of each request whose ref the listing finds gone or naming
1202// another commit. It returns every request listed, as its ref to the
1203// commit it names, and the ones a batch may build, sorted by name: those
1204// with no marker. A ref under the prefix that is not a request's is said
1205// and skipped. It returns an error only when a read of origin failed.
1206func (w *worker) requests(r listed) (listed map[string]string, pending []checkRequest, err error) {
1207 o, err := listOrigin(r.g, change.CheckRequestPrefix+"*")
1208 if err != nil {
1209 return nil, nil, failure(fmt.Sprintf("%s: could not list its check requests: %v; the pass stops here", r.name, err))
1210 }
1211 listed, pending = w.listRequests(r, o.refs)
1212 return listed, pending, nil
1213}
1214
1215// listRequests is what requests makes of a listing of origin's refs,
1216// which ls-remote matched by their ends: the refs under the prefix alone
1217// are read.
1218func (w *worker) listRequests(r listed, all map[string]string) (listed map[string]string, pending []checkRequest) {
1219 var refs []string
1220 for ref := range all {
1221 if strings.HasPrefix(ref, change.CheckRequestPrefix) {
1222 refs = append(refs, ref)
1223 }
1224 }
1225 sort.Strings(refs)
1226 listed = map[string]string{}
1227 for _, ref := range refs {
1228 head := all[ref]
1229 key := checkRequestName(r.name, ref, head)
1230 w.ready[key] = true
1231 if _, ok := w.seen[key]; !ok {
1232 w.seen[key] = w.scans
1233 }
1234 if _, _, _, ok := change.ParseCheckRequestRef(ref); !ok {
1235 w.noteAs(key, fmt.Sprintf("%s: %s is not a check request; one is %s<principal>/<worktree>/<attempt>. Skipped.", r.name, ref, change.CheckRequestPrefix))
1236 continue
1237 }
1238 listed[ref] = head
1239 }
1240 w.failures.keepRequests(r.name, listed)
1241 for _, ref := range refs {
1242 head, ok := listed[ref]
1243 if !ok {
1244 continue
1245 }
1246 if w.marked(&job{r: r, v: jsonVersion{Head: head}, req: ref}) {
1247 continue
1248 }
1249 pending = append(pending, checkRequest{ref, head})
1250 }
1251 return listed, pending
1252}
1253
1254// marked reports whether a check request is marked as not to be built
1255// again while its ref names the commit it names now, and says so once.
1256func (w *worker) marked(j *job) bool {
1257 if w.failures.Requests[j.r.name][j.req] != j.v.Head {
1258 return false
1259 }
1260 w.note(j, "an earlier batch for it did not end in evidence, so it is not built again until its ref moves or goes")
1261 return true
1262}
1263
1264// unbuildable records that a check request cannot be built for what its
1265// commit holds: it is said once, marked as a request whose batch failed,
1266// and not read again until its ref moves or goes.
1267func (w *worker) unbuildable(j *job, reason string) {
1268 w.say(j, "%s, so it is not built until its ref moves or goes", reason)
1269 w.spent(j, reason)
1270 w.troubles++
1271 w.waits++
1272}
1273
1274// request reads one check request, and returns its job when it needs a
1275// batch. Its checks are derived as a ready head's are, over its merge
1276// base with main, under both policy layers at main's tip, never from the
1277// commit. A request whose commit shares no history with main, or whose
1278// checks do not derive, is unbuildable.
1279func (w *worker) request(r listed, instance, project string, q checkRequest, met map[string]bool) (*job, error) {
1280 j := &job{r: r, v: jsonVersion{Head: q.head}, req: q.ref, seen: w.seen[checkRequestName(r.name, q.ref, q.head)]}
1281 if w.marked(j) {
1282 return nil, nil
1283 }
1284 base, err := r.g.output(true, "merge-base", r.snap.tip, q.head)
1285 if err != nil {
1286 w.unbuildable(j, "it shares no history with main")
1287 return nil, nil
1288 }
1289 doc, err := derivedChecks(r.g, "", instance, project, base, q.head)
1290 if err != nil {
1291 w.unbuildable(j, fmt.Sprintf("its checks did not derive: %v", err))
1292 return nil, nil
1293 }
1294 for _, c := range doc.Required {
1295 if c.Runner == "nix" {
1296 j.asked = append(j.asked, nixCheck{c.Name, c.Attribute})
1297 }
1298 }
1299 if len(j.asked) == 0 {
1300 w.note(j, "requires no nix check")
1301 return nil, nil
1302 }
1303 needed, _, err := w.assess(j, met)
1304 if err != nil || !needed {
1305 return nil, err
1306 }
1307 return j, nil
1308}
1309
1310// gating reports whether a batch for a ready change runs.
1311func (w *worker) gating() bool { return w.runningAbove(classFollow) }
1312
1313// runningAbove reports whether a batch of a class before class runs.
1314func (w *worker) runningAbove(class int) bool {
1315 for _, b := range w.running {
1316 if b.job.class() < class {
1317 return true
1318 }
1319 }
1320 return false
1321}
1322
1323// requesting reports whether a batch for one of the project's check
1324// requests runs.
1325func (w *worker) requesting(project string) bool {
1326 for _, b := range w.running {
1327 if b.job.r.name == project && b.job.class() == classRequest {
1328 return true
1329 }
1330 }
1331 return false
1332}
1333
1334// follows reads which follow checks are due on the project's main tip
1335// (mainstate.go), and returns the follow run that builds them when it
1336// needs a batch, as change does for a ready change. A walk that did not
1337// read is noted, and builds nothing. h names the landings a run covers.
1338func (w *worker) follows(r listed, instance, project string, h handleMap, met map[string]bool) (j *job, read bool, err error) {
1339 j = &job{r: r, v: jsonVersion{Head: r.snap.tip}, seen: w.scans, main: true}
1340 walk, err := followsUnder(r.g, r.snap.tip, instance, project, w.stderr)
1341 if err != nil {
1342 if w.note(j, "its follow checks did not read, so none is built: %v", err) {
1343 w.troubles++
1344 }
1345 return nil, false, nil
1346 }
1347 for _, q := range walk.checks {
1348 if q.due {
1349 j.asked = append(j.asked, q.nixCheck)
1350 }
1351 }
1352 j.covers = walk.landings(h, r.name)
1353 return w.followRun(j, met)
1354}
1355
1356// followRun assesses the follow run on main's tip, j.v.Head, for the
1357// checks due there, and returns it when it needs a batch, and whether it
1358// read the tip's evidence. It records the tip as quiet when it read it and
1359// found no follow run to start, so later passes read neither the policy
1360// nor main there; a tip whose evidence did not read is read again.
1361func (w *worker) followRun(j *job, met map[string]bool) (*job, bool, error) {
1362 r := j.r
1363 needed := false
1364 if len(j.asked) > 0 {
1365 var read bool
1366 var err error
1367 if needed, read, err = w.assess(j, met); err != nil || !read {
1368 return nil, read, err
1369 }
1370 if w.mains == nil {
1371 w.mains = map[string]string{}
1372 }
1373 w.mains[r.name] = j.key
1374 }
1375 // A pass that finds this tip again finds no follow run to start
1376 // either, unless one runs now: it may fail.
1377 quiet := quietMain{}
1378 if _, running := w.running[j.dest()]; !needed && (len(j.missing) == 0 || !running) {
1379 quiet = quietMain{Tip: j.v.Head, Wait: j.key}
1380 }
1381 if err := w.quiet.set(r.name, quiet); err != nil {
1382 fmt.Fprintf(w.stderr, "valley: could not write %s: %v\n", w.quiet.path, err)
1383 w.troubles++
1384 }
1385 if !needed {
1386 return nil, true, nil
1387 }
1388 return j, true, nil
1389}
1390
1391// stopSuperseded stops each of the project's running batches whose
1392// version is no longer its change's active version, and each whose check
1393// request's ref is gone or names another commit, when no ready version
1394// the scan assessed holds its tree. changes are the project's ready
1395// changes, as the scan read them whole, and listed its check requests, by
1396// ref, as the scan listed them. Each batch is stopped once; its end is
1397// handled when attest has ended (complete).
1398func (w *worker) stopSuperseded(project string, changes []jsonChange, listed map[string]string) {
1399 active := map[string]int{}
1400 for _, c := range changes {
1401 active[c.ChangeID] = c.Versions[c.Active-1].N
1402 }
1403 for dest, b := range w.running {
1404 j := b.job
1405 if j.r.name != project || w.wanted[dest] || b.stop == nil || b.stopped != "" {
1406 continue
1407 }
1408 switch j.class() {
1409 case classReady:
1410 n, ready := active[j.c.ChangeID]
1411 if !ready || n == j.v.N {
1412 continue
1413 }
1414 b.stopped = fmt.Sprintf("v%d supersedes it, and no ready change's active version holds its tree", n)
1415 case classRequest:
1416 head, ok := listed[j.req]
1417 switch {
1418 case head == j.v.Head:
1419 continue
1420 case ok:
1421 b.stopped = fmt.Sprintf("its ref names %s now, and no ready change's active version holds its tree", short(head))
1422 default:
1423 b.stopped = "its ref is gone, and no ready change's active version holds its tree"
1424 }
1425 default:
1426 continue
1427 }
1428 w.say(j, "stopping the batch: %s", b.stopped)
1429 b.stop()
1430 }
1431}
1432
1433// prune forgets the project's failures that a scan which read the project
1434// whole did not meet. It never forgets the key of a batch still running,
1435// nor a failure recorded since the scan began, which the scan's reads may
1436// have come too early to meet, nor, given pushes, any failed push, which
1437// the scan has yet to meet.
1438func (w *worker) prune(project string, met map[string]bool, pushes bool) {
1439 keep := map[string]bool{}
1440 for key := range met {
1441 keep[key] = true
1442 }
1443 for _, b := range w.running {
1444 if b.job.r.name == project {
1445 keep[b.job.key] = true
1446 }
1447 }
1448 for key := range w.fresh[project] {
1449 keep[key] = true
1450 }
1451 for key := range w.failures.Projects[project] {
1452 if pushes && strings.HasPrefix(key, "push ") {
1453 keep[key] = true
1454 }
1455 }
1456 w.failures.keep(project, keep)
1457}
1458
1459// failed records a failure, and that it was recorded during this scan.
1460func (w *worker) failed(project, key string, at time.Time, first time.Duration) backoff {
1461 if w.fresh != nil {
1462 if w.fresh[project] == nil {
1463 w.fresh[project] = map[string]bool{}
1464 }
1465 w.fresh[project][key] = true
1466 }
1467 return w.failures.failed(project, key, at, first)
1468}
1469
1470// reap handles every batch that has ended and not been handled, and then
1471// starts what the queue holds in the slots they freed. It returns an
1472// error only when a read of origin failed.
1473func (w *worker) reap() error {
1474 ended := false
1475 for {
1476 select {
1477 case c := <-w.done:
1478 w.complete(c)
1479 ended = true
1480 continue
1481 default:
1482 }
1483 break
1484 }
1485 if !ended {
1486 return nil
1487 }
1488 return w.admit(false)
1489}
1490
1491// change reads one ready change, and returns its job when it needs a
1492// batch. read says whether it read the change through: derived its
1493// checks, and read the evidence origin holds for them.
1494func (w *worker) change(r listed, instance, project string, c jsonChange, met map[string]bool) (j *job, read bool, err error) {
1495 v := c.Versions[c.Active-1]
1496 j = &job{r: r, c: c, v: v}
1497 first, ok := w.seen[j.version()]
1498 if !ok {
1499 first = w.scans
1500 w.seen[j.version()] = first
1501 }
1502 j.seen = first
1503 w.tel.reading(r.name, c, v, !ok)
1504 base, err := r.g.output(true, "merge-base", r.snap.tip, v.Head)
1505 if err != nil {
1506 if w.note(j, "shares no history with main, so nothing is built") {
1507 w.troubles++
1508 }
1509 return nil, false, nil
1510 }
1511 doc, err := derivedChecks(r.g, "", instance, project, base, v.Head)
1512 if err != nil {
1513 if w.note(j, "its checks did not derive, so nothing is built: %v", err) {
1514 w.troubles++
1515 }
1516 return nil, false, nil
1517 }
1518 for _, q := range doc.Required {
1519 if q.Runner == "nix" {
1520 j.asked = append(j.asked, nixCheck{q.Name, q.Attribute})
1521 }
1522 }
1523 if len(j.asked) == 0 {
1524 w.note(j, "requires no nix check")
1525 return nil, true, nil
1526 }
1527 needed, read, err := w.assess(j, met)
1528 if err != nil || !needed {
1529 return nil, read, err
1530 }
1531 return j, true, nil
1532}
1533
1534// assess reads the evidence origin holds for a job's head, and reports
1535// whether the job needs a batch now, and whether it read the head's
1536// evidence at all. It needs none when origin covers every check, when a
1537// batch for its destination runs, when its batch is waiting out a
1538// failure, or when a batch stored the ref here and origin lacks it, which
1539// it publishes first. Nor does a check request that is marked, which it
1540// checks again here, since a batch for it can end while the scan reads.
1541// When origin holds this worker's ref for the tree, the batch builds the
1542// checks the ref lacks and adds their notes to it (additive). met, when
1543// given, gets the failure keys it meets, and the scan reading a ready
1544// change or a follow run counts its destination as wanted, so a batch
1545// building that tree is not stopped; a request keeps no batch from being
1546// stopped. A reassessment of a queued job gives no met: its version may
1547// since have been superseded. An error reading the head's evidence that
1548// is not a failed read of origin is the head's own: it is said, the head
1549// is not read, and a request is unbuildable. It returns an error only
1550// when a read of origin failed.
1551func (w *worker) assess(j *job, met map[string]bool) (needed, read bool, err error) {
1552 if j.class() == classRequest && w.marked(j) {
1553 return false, true, nil
1554 }
1555 e, err := w.cover(j)
1556 var origin originFailure
1557 switch {
1558 case errors.As(err, &origin):
1559 return false, false, failure(fmt.Sprintf("%s: %v; the pass stops here", j.line(), err))
1560 case err != nil && j.class() == classRequest:
1561 w.unbuildable(j, fmt.Sprintf("its evidence could not be read: %v", err))
1562 return false, true, nil
1563 case err != nil:
1564 if w.note(j, "its evidence could not be read, so nothing is built: %v", err) {
1565 w.troubles++
1566 }
1567 return false, false, nil
1568 }
1569 j.digest, j.missing, j.additive = e.digest, nil, false
1570 j.ref = attestationRefs + e.digest + "/" + w.keyhash
1571 if met != nil && j.class() != classRequest {
1572 w.wanted[j.dest()] = true
1573 }
1574 for _, q := range j.asked {
1575 if _, ok := e.covered[q.name]; !ok {
1576 j.missing = append(j.missing, q)
1577 }
1578 }
1579 if len(j.missing) == 0 {
1580 w.note(j, "origin holds evidence for every nix check it requires")
1581 return false, true, nil
1582 }
1583 if b, ok := w.running[j.dest()]; ok {
1584 if b.job.version() != j.version() {
1585 w.note(j, "the batch for %s builds the same tree", b.job.label())
1586 }
1587 return false, true, nil
1588 }
1589 object, published := e.listed[j.ref]
1590 if !published && !j.main {
1591 if stored, found, err := j.r.g.ref(j.ref); err == nil && found {
1592 w.note(j, "an earlier pass stored %s, and origin does not hold it", j.ref)
1593 w.publish(j, stored, met)
1594 return false, true, nil
1595 }
1596 }
1597 if published {
1598 // A signer's ref holds one note for each check, and origin takes
1599 // it only with every note kept, so a check it holds a note for
1600 // that does not count cannot be built again under this signer.
1601 held, err := j.r.g.output(true, "ls-tree", "--name-only", object)
1602 if err != nil {
1603 if w.note(j, "%s on origin could not be read, so nothing is built: %v", j.ref, err) {
1604 w.troubles++
1605 }
1606 return false, false, nil
1607 }
1608 has := map[string]bool{}
1609 for _, name := range strings.Fields(held) {
1610 has[name] = true
1611 }
1612 var add, kept []nixCheck
1613 for _, q := range j.missing {
1614 if has[q.name] {
1615 kept = append(kept, q)
1616 } else {
1617 add = append(add, q)
1618 }
1619 }
1620 if len(kept) > 0 {
1621 var names []string
1622 for _, q := range kept {
1623 names = append(names, q.name)
1624 }
1625 w.note(j, "origin holds %s, this worker's evidence for its tree, with a note for %s that does not count, "+
1626 "and a worker adds notes to its ref but replaces none, so approve --build-here builds it (bd-7b7d58f)", j.ref, strings.Join(names, ", "))
1627 }
1628 if len(add) == 0 {
1629 if j.class() == classRequest {
1630 w.spent(j, fmt.Sprintf("origin holds %s, this worker's evidence for its tree, and it holds a note that does not count for every check the request lacks", j.ref))
1631 }
1632 return false, true, nil
1633 }
1634 j.missing, j.additive = add, true
1635 }
1636 names := strings.Join(j.names(), ", ")
1637 j.key = "build " + e.digest + " " + strings.Join(j.names(), ",")
1638 if met != nil {
1639 met[j.key] = true
1640 }
1641 if f, waiting := w.failures.waiting(j.r.name, j.key, clock()); waiting {
1642 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))
1643 return false, true, nil
1644 }
1645 return true, true, nil
1646}
1647
1648// admit starts the queue's jobs in order while fewer than w.batches run.
1649// It assesses each job again right before it starts it, so evidence that
1650// arrived since the scan is not built again. A job whose destination a
1651// batch holds, or that finds no slot, stays queued for the next scan to
1652// find again. So does a check request's, unless scanned says a scan has
1653// just found nothing of a higher class to build, and no batch of a higher
1654// class runs. It returns an error only when a read of origin failed.
1655func (w *worker) admit(scanned bool) error {
1656 var left []*job
1657 for i, j := range w.queue {
1658 if len(w.running) >= w.batches {
1659 left = append(left, w.queue[i:]...)
1660 break
1661 }
1662 if _, held := w.running[j.dest()]; held {
1663 left = append(left, j)
1664 continue
1665 }
1666 if j.class() == classRequest && (!scanned || w.runningAbove(classRequest)) {
1667 left = append(left, j)
1668 continue
1669 }
1670 needed, err := w.recheck(j)
1671 if err != nil {
1672 w.queue = nil
1673 return err
1674 }
1675 if needed {
1676 w.start(j)
1677 }
1678 }
1679 w.queue = left
1680 return nil
1681}
1682
1683// start runs a job's batch: it holds the job's destination, starts attest
1684// run, and leaves a goroutine to wait for it. The goroutine reads what
1685// attest stored and recorded, and hands it to the loop; it changes
1686// nothing the loop owns.
1687//
1688// attest is handed the lock file as well, and holds it until it ends, and
1689// the wake directory's lock with it. The flock belongs to the open file,
1690// so the lock stays held while attest runs, and while anything it started
1691// that inherited the file runs, even when this pass is killed. A later
1692// pass waits for all of it, and then finds the ref attest stored.
1693//
1694// The batch's evaluation is estimated from its project's record of peaks.
1695// An estimate larger than the whole budget cannot fit beside anything, so
1696// the evaluation runs alone, and the pass says so, once for the batch, in
1697// its output and as a capacity record. A pass that found no budget hands
1698// attest a budget equal to the estimate, so each evaluation runs alone,
1699// and said so once when it began.
1700func (w *worker) start(j *job) {
1701 b := &batch{job: j, run: telemetry.NewRunID(), mark: w.tel.streamEnd()}
1702 w.say(j, "building %s", strings.Join(j.names(), ", "))
1703 data := map[string]any{"attest_run": b.run}
1704 if j.main {
1705 data["covers"] = j.covers
1706 }
1707 if w.evals != nil {
1708 b.estimate = w.evals.estimate(j.r.name)
1709 b.budget = w.evals.handed(b.estimate)
1710 data["eval_estimate_bytes"], data["eval_budget_bytes"] = b.estimate, b.budget
1711 if w.evals.budget > 0 && b.estimate > w.evals.budget {
1712 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",
1713 bytesText(b.estimate), bytesText(w.evals.budget), w.evals.source)
1714 w.tel.capacity(j.identity(), b.estimate, w.evals.budget, w.evals.source)
1715 }
1716 }
1717 b.attempt = w.tel.begin("build", classNames[j.class()], j.identity(), j.names(), b.run, data)
1718 w.running[j.dest()] = b
1719 w.launch(b)
1720}
1721
1722// attest starts a batch's attest run, and a goroutine that waits for it
1723// and hands the loop its completion.
1724func (w *worker) attest(b *batch) {
1725 j := b.job
1726 repo := j.r.g.dir
1727 if repo == "" {
1728 repo = "."
1729 }
1730 args := []string{"run", "--repo", repo, "--rev", j.v.Head, "--key", w.key}
1731 if w.name != "" {
1732 args = append(args, "--name", w.name)
1733 }
1734 if w.slots > 0 {
1735 args = append(args, "--slots", strconv.Itoa(w.slots))
1736 }
1737 if w.roots != "" {
1738 args = append(args, "--gc-roots", w.roots)
1739 }
1740 peak := ""
1741 if w.evals != nil {
1742 peak = filepath.Join(w.evals.dir, b.run+".peak")
1743 args = append(args, "--eval-reservations", w.evals.dir, "--eval-estimate", strconv.FormatInt(b.estimate, 10),
1744 "--eval-budget", strconv.FormatInt(b.budget, 10), "--eval-peak", peak)
1745 }
1746 for _, q := range j.missing {
1747 args = append(args, "--check", q.name+"="+q.attribute)
1748 }
1749 if j.main || j.additive {
1750 // The batch adds its notes to this worker's ref for the tree on
1751 // origin, keeping every note the ref holds, as origin requires: a
1752 // follow run's, beside a gate batch's, and any batch's whose tree
1753 // origin holds this worker's evidence for already.
1754 args = append(args, "--push", "origin", "--ref-only")
1755 }
1756 stream := ""
1757 if w.tel != nil {
1758 stream = w.tel.stream()
1759 args = append(args, "--telemetry", stream, "--telemetry-run", b.run, "--project", j.r.name, "--capacity", w.capacity)
1760 if j.class() == classReady {
1761 args = append(args, "--change", j.c.ChangeID, "--change-version", strconv.Itoa(j.v.N))
1762 }
1763 }
1764 // attest writes to the pass's own output files, not through a pipe the
1765 // pass reads: an attest that outlives a killed pass must still be able
1766 // to write, and store its ref.
1767 cmd := exec.Command("attest", args...)
1768 cmd.Env = j.r.g.env
1769 cmd.Dir = j.r.g.dir
1770 cmd.Stdout, cmd.Stderr = w.out, w.errs
1771 cmd.ExtraFiles = []*os.File{w.lock}
1772 if w.wake != nil && w.wake.lock != nil {
1773 cmd.ExtraFiles = append(cmd.ExtraFiles, w.wake.lock)
1774 }
1775 if err := cmd.Start(); err != nil {
1776 go func() { w.done <- completion{b: b, err: err, ended: clock()} }()
1777 return
1778 }
1779 // A stop kills attest alone, never its process group: its nix
1780 // processes die with it (attest's dieWithParent), and a git storing
1781 // the ref finishes its one update.
1782 b.stop = func() { _ = cmd.Process.Kill() }
1783 g, ref, run, mark := j.r.g, j.ref, b.run, b.mark
1784 go func() {
1785 err := cmd.Wait()
1786 c := completion{b: b, err: err, ended: clock()}
1787 if peak != "" {
1788 if text, rerr := os.ReadFile(peak); rerr == nil {
1789 c.peak, c.outcome = readPeak(string(text))
1790 }
1791 os.Remove(peak)
1792 }
1793 if err != nil {
1794 c.failed = failedChecks(stream, run, mark)
1795 } else if stored, found, rerr := g.ref(ref); rerr == nil && found {
1796 c.stored = stored
1797 }
1798 w.done <- c
1799 }()
1800}
1801
1802// complete handles what one batch did: it records a failure at once, with
1803// its wait measured from when the batch ended, or publishes what the batch
1804// stored. The batch's destination is held until its push has been tried.
1805// A batch the loop stopped that did not pass is recorded as cancelled,
1806// with why it was stopped, and nothing else: it backs nothing off, and
1807// publishes nothing. One that passed before its stop took effect is
1808// handled as any other.
1809func (w *worker) complete(c completion) {
1810 b, j := c.b, c.b.job
1811 defer func() {
1812 delete(w.running, j.dest())
1813 w.tel.settle()
1814 }()
1815 cancelled := b.stopped != "" && c.err != nil
1816 outcome := c.outcome
1817 if outcome == "" && endedBySignal(c.err) && !cancelled {
1818 // attest was killed before it said how its evaluation ended,
1819 // which may have been during the evaluation. The loop's own stop
1820 // says nothing of the evaluation's memory.
1821 outcome = "killed"
1822 }
1823 if outcome != "" && w.evals != nil {
1824 if err := w.evals.record(j.r.name, c.peak, outcome); err != nil {
1825 fmt.Fprintf(w.stderr, "valley: could not record the evaluation's peak memory in %s: %v\n", w.evals.path, err)
1826 }
1827 }
1828 if cancelled {
1829 w.tel.end(b.attempt, "cancelled", b.stopped, j.key, nil)
1830 w.say(j, "the batch stopped; nothing is published")
1831 return
1832 }
1833 if c.err != nil {
1834 reason := fmt.Sprintf("attest run %s: %v", b.run, c.err)
1835 if len(c.failed) > 0 {
1836 reason += "; " + strings.Join(c.failed, ", ")
1837 }
1838 if j.class() == classRequest {
1839 w.tel.end(b.attempt, "failed", reason, j.key, nil)
1840 w.say(j, "the batch did not pass (%v); it is not built again until its ref moves or goes", c.err)
1841 w.spent(j, reason)
1842 w.troubles++
1843 w.waits++
1844 return
1845 }
1846 f := w.failed(j.r.name, j.key, c.ended, firstBuildWait)
1847 w.tel.end(b.attempt, "failed", reason, j.key, &f)
1848 w.say(j, "the batch did not pass (%v); it is not built again before %s", c.err, f.Retry.Format(time.RFC3339))
1849 w.troubles++
1850 w.waits++
1851 w.save()
1852 return
1853 }
1854 w.failures.passed(j.r.name, j.key)
1855 w.tel.end(b.attempt, "passed", "", j.key, nil)
1856 w.save()
1857 if j.main || j.additive {
1858 w.say(j, "added %s to %s on origin", strings.Join(j.names(), ", "), j.ref)
1859 return
1860 }
1861 if c.stored == "" {
1862 w.say(j, "attest stored no %s, so nothing is published", j.ref)
1863 w.troubles++
1864 return
1865 }
1866 w.publish(j, c.stored, nil)
1867}
1868
1869// publish pushes a job's attestation ref to origin, and nothing else. The
1870// hook verifies the notes against the tree and the signer whoever pushes
1871// them. A push that fails leaves the ref stored here, and the same object
1872// is not pushed again until its wait is over: by any pass, and for any
1873// change whose tree it is about. met, when given, gets the push's key.
1874func (w *worker) publish(j *job, object string, met map[string]bool) {
1875 key := "push " + object
1876 if met != nil {
1877 met[key] = true
1878 }
1879 if f, waiting := w.failures.waiting(j.r.name, key, clock()); waiting {
1880 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))
1881 return
1882 }
1883 a := w.tel.begin("push", classNames[j.class()], j.identity(), nil, "", map[string]any{"ref": j.ref, "object": object})
1884 if err := w.push(j, object); err != nil {
1885 f := w.failed(j.r.name, key, clock(), firstPushWait)
1886 w.tel.end(a, "failed", fmt.Sprintf("pushing %s to origin: %v", j.ref, err), key, &f)
1887 w.say(j, "could not publish %s; it is not pushed again before %s", j.ref, f.Retry.Format(time.RFC3339))
1888 w.troubles++
1889 w.waits++
1890 w.save()
1891 return
1892 }
1893 w.failures.passed(j.r.name, key)
1894 w.tel.end(a, "passed", "", key, nil)
1895 w.say(j, "published %s", j.ref)
1896}
1897
1898// push pushes object to the job's ref on origin. A host refuses every
1899// push while valley-init converges on its configuration, which takes
1900// seconds. A push refused for that is tried again every pausedPushRetry,
1901// for up to firstPushWait, before it fails and waits as any failed push
1902// does. The loop waits meanwhile; another batch's push would be refused
1903// too.
1904func (w *worker) push(j *job, object string) error {
1905 g := j.r.g
1906 var said bytes.Buffer
1907 g.stderr = &said
1908 if j.r.g.stderr != nil {
1909 g.stderr = io.MultiWriter(j.r.g.stderr, &said)
1910 }
1911 for began := time.Now(); ; time.Sleep(pausedPushRetry) {
1912 said.Reset()
1913 _, err := g.output(false, "push", "--quiet", "origin", object+":"+j.ref)
1914 if err == nil || !strings.Contains(said.String(), pausedPushes) || time.Since(began) >= firstPushWait {
1915 return err
1916 }
1917 w.note(j, "origin paused pushes while it converges, so publishing %s is tried again", j.ref)
1918 }
1919}
1920
1921// say prints a line about what the pass did with a version. The version's
1922// notes may be said again after it.
1923func (w *worker) say(j *job, format string, args ...any) {
1924 delete(w.said, j.version())
1925 fmt.Fprintf(w.stdout, "%s: %s\n", j.line(), fmt.Sprintf(format, args...))
1926}
1927
1928// note prints a line about how a version stands, unless the pass has said
1929// that line of it since it last did something with it, so a scan that
1930// finds things as they were says nothing new. It reports whether it
1931// printed.
1932func (w *worker) note(j *job, format string, args ...any) bool {
1933 return w.noteAs(j.version(), j.line()+": "+fmt.Sprintf(format, args...))
1934}
1935
1936func (w *worker) noteAs(about, line string) bool {
1937 if w.said[about][line] {
1938 return false
1939 }
1940 if w.said[about] == nil {
1941 w.said[about] = map[string]bool{}
1942 }
1943 w.said[about][line] = true
1944 fmt.Fprintln(w.stdout, line)
1945 return true
1946}
1947
1948// spent records that a check request's batch failed, or that no batch
1949// can build what it lacks: a marker of its ref and the commit it names,
1950// which keeps it from being built again until a listing finds its ref
1951// moved or gone, and a backoff record that says why. The record is
1952// written at once.
1953func (w *worker) spent(j *job, reason string) {
1954 w.failures.spend(j.r.name, j.req, j.v.Head)
1955 w.tel.spent(j.identity(), j.req, reason)
1956 w.save()
1957}
1958
1959// save writes the failure record, and counts a write that fails as
1960// something that went wrong.
1961func (w *worker) save() {
1962 if err := w.failures.save(); err != nil {
1963 fmt.Fprintf(w.stderr, "valley: could not write %s: %v\n", w.failures.path, err)
1964 w.troubles++
1965 }
1966}
1967
1968// policyLayers resolves the two policy layers a project's changes are
1969// derived under, as approve resolves them, and returns what
1970// removes them. Both are read at main's tip on origin.
1971func policyLayers(g git, tip string) (instance, project string, done func(), err error) {
1972 src, done, err := resolveLayers(g, tip, "", "")
1973 return src.instance, src.project, done, err
1974}
1975
1976// layerSource is where the two policy layers were read from: the
1977// directories, and what a reader needs to say where each came from.
1978type layerSource struct {
1979 instance, project string // directories of *.cue
1980
1981 ownValley bool // the tip carries its own floor
1982 valley string // the owning valley's URL, when the tip carries no floor
1983 noProject bool // the tip carries no project layer, so the floor alone applies
1984}
1985
1986// resolveLayers resolves the two policy layers at tip, and returns what
1987// removes them. A layer named, instance or project, is read as given, and
1988// nothing is fetched or read at the tip for it. The floor is the tip's own
1989// policy/instance when it carries one, and otherwise policy/instance at
1990// the tip of main in the owning valley that policy/valley names. A tip
1991// with no policy/project is derived under the floor alone. A layer that
1992// cannot be read is refused, and never read as one that is not there.
1993func resolveLayers(g git, tip, instance, project string) (src layerSource, done func(), err error) {
1994 ctx := context.Background()
1995 var ends []func()
1996 done = func() {
1997 for _, end := range ends {
1998 end()
1999 }
2000 }
2001 repo := g.dir
2002 if repo == "" {
2003 repo = "."
2004 }
2005 src.instance, src.project = instance, project
2006 if instance == "" {
2007 var end func()
2008 src.instance, end, err = composed.Floor{Repo: repo, Ref: tip, Dir: instanceLayer}.Open(ctx, "valley-work-floor")
2009 ends = append(ends, end)
2010 src.ownValley = err == nil
2011 if errors.Is(err, composed.ErrNoFloor) {
2012 var floor composed.Floor
2013 floor, src.valley, end, err = owningFloor(g, tip)
2014 ends = append(ends, end)
2015 if err != nil {
2016 return src, done, err
2017 }
2018 src.instance, end, err = floor.Open(ctx, "valley-work-floor")
2019 ends = append(ends, end)
2020 }
2021 if err != nil {
2022 return src, done, err
2023 }
2024 }
2025 if project == "" {
2026 var end func()
2027 var absent string
2028 src.project, absent, end, err = composed.Project(ctx, repo, tip, projectLayer, "valley-work-project")
2029 ends = append(ends, end)
2030 src.noProject = absent != ""
2031 }
2032 return src, done, err
2033}
2034
2035// owningFloor is where the floor of a tip that carries none of its own is
2036// read: policy/instance at the tip of main in the owning valley that
2037// policy/valley names, fetched into a scratch repository that end removes,
2038// and the URL the pointer names.
2039func owningFloor(g git, tip string) (floor composed.Floor, url string, end func(), err error) {
2040 end = func() {}
2041 pointer, err := g.output(true, "cat-file", "blob", tip+":"+valleyPointer)
2042 if err != nil {
2043 return floor, url, end, fmt.Errorf("main names no owning valley at %s", valleyPointer)
2044 }
2045 url = pointerURL(pointer)
2046 if url == "" {
2047 return floor, url, end, fmt.Errorf("%s on main names no repository", valleyPointer)
2048 }
2049 if err := checkURL(url); err != nil {
2050 return floor, url, end, err
2051 }
2052 scratch, err := os.MkdirTemp("", "valley-work-valley-")
2053 if err != nil {
2054 return floor, url, end, err
2055 }
2056 end = func() { _ = os.RemoveAll(scratch) }
2057 v := git{env: cacheEnvironment(g.env), stderr: g.stderr, dir: scratch}
2058 if _, err := v.output(true, "init", "--quiet", "--bare"); err != nil {
2059 return floor, url, end, errors.New("no scratch repository to fetch the floor into")
2060 }
2061 // The valley's main is read by its exact name, and fetched by the
2062 // object it names: given a ref name the valley lacks, fetch takes
2063 // another ref whose name ends in it, such as
2064 // refs/heads/refs/heads/main.
2065 at, err := remoteRef(v, url, "refs/heads/main")
2066 if err != nil {
2067 return floor, url, end, fmt.Errorf("could not fetch the owning valley %s", url)
2068 } else if at == "" {
2069 return floor, url, end, fmt.Errorf("the owning valley %s has no refs/heads/main", url)
2070 }
2071 if _, err := v.output(true, "fetch", "--quiet", "--depth", "1", "--no-tags", "--end-of-options", url, at); err != nil {
2072 return floor, url, end, fmt.Errorf("could not fetch the owning valley %s", url)
2073 }
2074 return composed.Floor{Repo: scratch, Ref: at, Dir: instanceLayer}, url, end, nil
2075}
2076
2077// followsUnder is mainFollows under the two policy layers named.
2078func followsUnder(g git, tip, instance, project string, stderr io.Writer) (mainWalk, error) {
2079 schema, err := schemaFile(g, "")
2080 if err != nil {
2081 return mainWalk{}, err
2082 }
2083 model, err := policyModel(schema, instance, project, false)
2084 if err != nil {
2085 return mainWalk{}, err
2086 }
2087 keys := hostKeys{use: assessEvidence}
2088 defer keys.done()
2089 return mainFollows(g, tip, model, &keys, nil, stderr)
2090}
2091
2092// failureRecord is the worker's record of what failed, project by
2093// project: each batch, keyed "build <tree digest> <check>,<check>", and
2094// each push, keyed "push <object ID>". For each it holds how many times in
2095// a row it failed, and the time before which it is not tried again. Apart
2096// from those, it marks each check request whose batch failed, or which no
2097// batch can build, by its ref, with the commit the ref named: a marked
2098// request waits for no time, but for its ref to move or go. It is kept as
2099// JSON at path.
2100type failureRecord struct {
2101 path string
2102 Projects map[string]map[string]backoff `json:"projects"`
2103 Requests map[string]map[string]string `json:"requests,omitempty"`
2104}
2105
2106type backoff struct {
2107 Failures int `json:"failures"`
2108 Retry time.Time `json:"retry"`
2109}
2110
2111// readFailures reads the record at path. A record that is not there is
2112// empty. One that does not read is said, and started again empty: the
2113// worst it costs is one more try of each thing it held.
2114func readFailures(path string, stderr io.Writer) *failureRecord {
2115 r := &failureRecord{path: path}
2116 data, err := os.ReadFile(path)
2117 if err == nil {
2118 err = json.Unmarshal(data, r)
2119 }
2120 if err != nil && !errors.Is(err, os.ErrNotExist) {
2121 fmt.Fprintf(stderr, "valley: %s does not read, so everything it held is tried again\n", path)
2122 r.Projects, r.Requests = nil, nil
2123 }
2124 if r.Projects == nil {
2125 r.Projects = map[string]map[string]backoff{}
2126 }
2127 if r.Requests == nil {
2128 r.Requests = map[string]map[string]string{}
2129 }
2130 return r
2131}
2132
2133// spend marks the project's check request at ref as not to be built again
2134// while it names head.
2135func (r *failureRecord) spend(project, ref, head string) {
2136 if r.Requests[project] == nil {
2137 r.Requests[project] = map[string]string{}
2138 }
2139 r.Requests[project][ref] = head
2140}
2141
2142// keepRequests forgets the marker of each of the project's check requests
2143// that listed, a whole listing of them, finds gone or naming another
2144// commit.
2145func (r *failureRecord) keepRequests(project string, listed map[string]string) {
2146 for ref, head := range r.Requests[project] {
2147 if listed[ref] != head {
2148 delete(r.Requests[project], ref)
2149 }
2150 }
2151 if len(r.Requests[project]) == 0 {
2152 delete(r.Requests, project)
2153 }
2154}
2155
2156// waiting reports whether something failed and its wait is not over.
2157func (r *failureRecord) waiting(project, key string, now time.Time) (backoff, bool) {
2158 f, ok := r.Projects[project][key]
2159 return f, ok && now.Before(f.Retry)
2160}
2161
2162// failed records one more failure in a row, and the time it may be tried
2163// again: first after the first failure, doubled for each one after it, and
2164// never more than longestWait.
2165func (r *failureRecord) failed(project, key string, now time.Time, first time.Duration) backoff {
2166 if r.Projects[project] == nil {
2167 r.Projects[project] = map[string]backoff{}
2168 }
2169 f := r.Projects[project][key]
2170 f.Failures++
2171 wait := first
2172 for i := 1; i < f.Failures && wait < longestWait; i++ {
2173 wait *= 2
2174 }
2175 f.Retry = now.Add(min(wait, longestWait))
2176 r.Projects[project][key] = f
2177 return f
2178}
2179
2180func (r *failureRecord) passed(project, key string) { delete(r.Projects[project], key) }
2181
2182// keep forgets every failure of the project that is not in met. Other
2183// projects' failures are kept.
2184func (r *failureRecord) keep(project string, met map[string]bool) {
2185 for key := range r.Projects[project] {
2186 if !met[key] {
2187 delete(r.Projects[project], key)
2188 }
2189 }
2190 if len(r.Projects[project]) == 0 {
2191 delete(r.Projects, project)
2192 }
2193}
2194
2195// quietMains is the worker's record, project by project, of the main tip
2196// on which a pass found no follow run to start: no follow check was due,
2197// origin held a pass for each one due, or the follow run was waiting out
2198// a failure, whose key it keeps. A later pass that finds the same tip,
2199// and that failure still waiting, would find the same, so it reads
2200// neither the policy nor main for a project with no ready change. Once
2201// the wait is over, or main moves, a pass reads main again. It is kept as
2202// JSON at path; deleting it costs one read of each project's main.
2203//
2204// The record holds main's tip alone, so a floor or known signers that
2205// change in the owning valley while main stays put are read at main's
2206// next landing.
2207type quietMains struct {
2208 path string
2209 Projects map[string]quietMain `json:"projects"`
2210}
2211
2212type quietMain struct {
2213 Tip string `json:"tip"`
2214 Wait string `json:"wait,omitempty"` // the failure key of the follow run waiting out its backoff
2215}
2216
2217// readQuiet reads the record at path. One that is not there, or does not
2218// read, is empty.
2219func readQuiet(path string, stderr io.Writer) *quietMains {
2220 q := &quietMains{path: path}
2221 data, err := os.ReadFile(path)
2222 if err == nil {
2223 err = json.Unmarshal(data, q)
2224 }
2225 if err != nil && !errors.Is(err, os.ErrNotExist) {
2226 fmt.Fprintf(stderr, "valley: %s does not read, so each project's main is read again\n", path)
2227 q.Projects = nil
2228 }
2229 if q.Projects == nil {
2230 q.Projects = map[string]quietMain{}
2231 }
2232 return q
2233}
2234
2235// holds reports whether the project's main is quiet at tip: a pass found
2236// no follow run to start there, and the failure it waited on, if any, is
2237// still waiting.
2238func (q *quietMains) holds(project, tip string, failures *failureRecord) bool {
2239 m, ok := q.Projects[project]
2240 if !ok || m.Tip != tip {
2241 return false
2242 }
2243 if m.Wait == "" {
2244 return true
2245 }
2246 _, waiting := failures.waiting(project, m.Wait, clock())
2247 return waiting
2248}
2249
2250// set records the project's main as m, or forgets it when m.Tip is "",
2251// and writes the record when that changed it.
2252func (q *quietMains) set(project string, m quietMain) error {
2253 if old, ok := q.Projects[project]; ok == (m.Tip != "") && old == m {
2254 return nil
2255 }
2256 if m.Tip == "" {
2257 delete(q.Projects, project)
2258 } else {
2259 q.Projects[project] = m
2260 }
2261 if len(q.Projects) == 0 {
2262 if err := os.Remove(q.path); err != nil && !errors.Is(err, os.ErrNotExist) {
2263 return err
2264 }
2265 return nil
2266 }
2267 return writeState(q.path, q)
2268}
2269
2270// save writes the record whole, through a file renamed into place, so a
2271// pass that is killed leaves the last record or the new one. An empty
2272// record is no file.
2273func (r *failureRecord) save() error {
2274 for project, failures := range r.Projects {
2275 if len(failures) == 0 {
2276 delete(r.Projects, project)
2277 }
2278 }
2279 if len(r.Projects) == 0 && len(r.Requests) == 0 {
2280 if err := os.Remove(r.path); err != nil && !errors.Is(err, os.ErrNotExist) {
2281 return err
2282 }
2283 return nil
2284 }
2285 return writeState(r.path, r)
2286}
2287
2288// writeState writes v as JSON at path, in key order, through a file
2289// renamed into place.
2290func writeState(path string, v any) error {
2291 data, err := json.MarshalIndent(v, "", " ")
2292 if err != nil {
2293 return err
2294 }
2295 tmp, err := os.CreateTemp(filepath.Dir(path), ".record-*")
2296 if err != nil {
2297 return err
2298 }
2299 _, err = tmp.Write(append(data, '\n'))
2300 if cerr := tmp.Close(); err == nil {
2301 err = cerr
2302 }
2303 if err == nil {
2304 err = os.Rename(tmp.Name(), path)
2305 }
2306 if err != nil {
2307 os.Remove(tmp.Name())
2308 }
2309 return err
2310}