gunk-dev/the-valley

checkcost.go

source69d7baef1f04main's published tip history
18.7 KiB
1package main
2
3// What each check of a version cost the host to build, against what the
4// same check recently cost, and whether the host's newest build of it
5// failed, for valley changes --checks, valley pending --checks and valley
6// review.
7//
8// The numbers are the host's check worker's own: each attest run a pass
9// starts records a check.result for each check it builds, in the worker's
10// telemetry stream (workertelemetry.go), naming the project, change,
11// version and tree. Its result is passed, failed, or error when attest
12// could not decide the check, as when it did not evaluate. Its build_ms is
13// how long the check's nix build took, and its eval_ms how long the run's
14// shared evaluation took. A check that did not evaluate records no
15// build_ms, and no cost counts it. The worker records the end of each batch
16// too, with its result and its attest run. These are diagnostics, never
17// evidence: nothing here is signed, and neither approve, the integrator,
18// nor a check's or a version's state reads them.
19//
20// A listing reads the worker source once for each host it lists, with the
21// same command valley telemetry read runs (telemetry.go). The newest page
22// is read first, and then the older pages up to costRecords records, at
23// once, each from a cursor made from the newest page's. The reads run
24// while the listing reads the policy, so they add little to its time. A
25// host that does not answer, or refuses, leaves every version it serves
26// without build times, and stderr says why, once.
27//
28// For each required nix check of a version:
29//
30// - build_ms is the newest build of the check for this version, and
31// cached says whether its output was already in the host's store;
32// - baseline_ms is the median build time of the check's newest
33// baselineBuilds uncached, passing builds in the same project and on
34// the same capacity as the version's own build, the
35// builds of every version of this change left out;
36// - new says no such build is among the records read, and
37// other_capacity says there are builds, but only on other capacity:
38// the host was resized, so the check starts afresh and is not grown;
39// - grown says the build took longer than its baseline by more than
40// both grownShare of it and grownBy (grew).
41//
42// A build's capacity is the line the worker gave attest (capacity.go).
43// Records with none compare only with each other.
44//
45// A record from an attest that does not say whether the output was
46// cached counts as cached when its build wrote no log: nix writes the
47// builder's output to the log, and building nothing writes none.
48//
49// attest publishes nothing when any check of its batch fails, so a check
50// the worker built and that failed has no note, and its state is pending.
51// The worker's report tells it from a check not built yet:
52//
53// - a check whose state is not passed carries worker, the result, time
54// and attest run of the newest build of the check for the version's
55// tree, when that build did not pass. The build may be any change's
56// or version's with the same tree, since a check is about a tree. A
57// record from an attest that names no tree counts only for its own
58// change and version;
59// - when a check is pending, the version carries worker, the time and
60// attest run of the newest batch for its tree, when that batch failed
61// and no check.result names its attest run: it failed before any
62// check ran, as when the evaluation or attest itself failed.
63
64import (
65 "bufio"
66 "context"
67 "encoding/json"
68 "fmt"
69 "io"
70 "sort"
71 "strings"
72 "sync"
73 "time"
74
75 "the-valley/telemetry"
76)
77
78// workerSource is the telemetry source the host module gives the check
79// worker.
80const workerSource = "worker"
81
82// costRecords bounds how many of the worker's newest records a listing
83// reads from one host: five of the collector's largest pages. Each batch
84// of checks writes about five records a check, so this holds the last
85// few hundred check builds.
86const costRecords = 5 * telemetry.MaxReadLimit
87
88// baselineBuilds is how many of a check's recent builds its baseline is
89// the median of.
90const baselineBuilds = 20
91
92// A check has grown when its build took longer than its baseline by more
93// than both of these. Batches build side by side on one host, so a build
94// can take a few seconds longer, or a few percent, for reasons of the
95// host's and not the change's. Only growth past both is shown.
96const (
97 grownShare = 0.20
98 grownBy = 30 * time.Second
99)
100
101// grew reports whether a build of build ms has grown against a baseline
102// of baseline ms.
103func grew(build, baseline int64) bool {
104 d := build - baseline
105 return d > grownBy.Milliseconds() && float64(d) > grownShare*float64(baseline)
106}
107
108// median is the median of ms, which must not be empty.
109func median(ms []int64) int64 {
110 s := append([]int64(nil), ms...)
111 sort.Slice(s, func(i, j int) bool { return s[i] < s[j] })
112 n := len(s)
113 if n%2 == 1 {
114 return s[n/2]
115 }
116 return (s[n/2-1] + s[n/2]) / 2
117}
118
119// checkBuild is one check.result record of the worker's: one check built
120// for one version or main's tip, or one that did not evaluate.
121type checkBuild struct {
122 time, run string
123 project, change string
124 version int
125 tree, check string
126 result string
127 unevaluated bool // the check did not evaluate, so nothing was built
128 buildMS, evalMS int64
129 cached bool
130 capacity string
131}
132
133// forTree reports whether b built a check for tree, or, when its record
134// names no tree, for version n of the change changeID.
135func (b *checkBuild) forTree(tree, changeID string, n int) bool {
136 return b.tree == tree || b.tree == "" && b.change == changeID && b.version == n
137}
138
139// batchEnd is the end of a batch the worker ran for a change's version:
140// when it ended, its attest run, the project and tree it was for, and its
141// result, passed, failed or cancelled.
142type batchEnd struct {
143 time, run string
144 project, tree string
145 result string
146}
147
148// costs reads the worker's telemetry of each host a listing serves, once
149// a host, in the background.
150type costs struct {
151 mu sync.Mutex
152 reads map[string]*costRead // by destination identity
153 said map[string]bool // the reasons already said on stderr
154}
155
156type costRead struct {
157 done chan struct{}
158 builds []checkBuild // newest first
159 mains []mainRun // the batches run on main tips (mainstate.go)
160 batches []batchEnd // the ends of the batches run for changes, newest first
161 why string // why there are none, when the read failed
162}
163
164func newCosts() *costs {
165 return &costs{reads: map[string]*costRead{}, said: map[string]bool{}}
166}
167
168// start begins the read of the host g's telemetry remote names
169// (telemetryRemote), unless it has begun.
170func (c *costs) start(g git) *costRead {
171 dest, err := telemetryRemote(g, "")
172 c.mu.Lock()
173 defer c.mu.Unlock()
174 if err != nil {
175 r := &costRead{done: make(chan struct{}), why: err.Error()}
176 close(r.done)
177 return r
178 }
179 if r := c.reads[dest.identity()]; r != nil {
180 return r
181 }
182 r := &costRead{done: make(chan struct{})}
183 c.reads[dest.identity()] = r
184 go func() {
185 defer close(r.done)
186 r.builds, r.mains, r.batches, r.why = readBuilds(dest)
187 }()
188 return r
189}
190
191// wait waits for a read to end, and reports whether it read. The reason a
192// read failed is said on stderr the first time it is met.
193func (c *costs) wait(r *costRead, warn func(format string, args ...any)) bool {
194 <-r.done
195 if r.why == "" {
196 return true
197 }
198 c.mu.Lock()
199 said := c.said[r.why]
200 c.said[r.why] = true
201 c.mu.Unlock()
202 if !said {
203 warn("no check lists its build times: %s", r.why)
204 }
205 return false
206}
207
208// readBuilds reads up to costRecords of the newest records of the worker
209// source at dest, and returns the check builds among them, newest first,
210// the starts and ends of the batches run on main tips, and the ends of the
211// batches run for changes, newest first.
212func readBuilds(dest sshDest) ([]checkBuild, []mainRun, []batchEnd, string) {
213 first, err := readPage(dest, "")
214 if err != nil {
215 return nil, nil, nil, err.Error()
216 }
217 pages := []workerPage{first}
218 var mu sync.Mutex
219 var wg sync.WaitGroup
220 for p := 1; p*telemetry.MaxReadLimit < costRecords; p++ {
221 // Page p holds, for each stream, the records up to p pages
222 // before the newest one the first page read.
223 var parts []string
224 for name, pos := range first.cursor {
225 if after := pos.Seq - int64((p+1)*telemetry.MaxReadLimit); after+telemetry.MaxReadLimit > 0 {
226 parts = append(parts, fmt.Sprintf("%s=%s:%d", name, pos.Epoch, max(after, 0)))
227 }
228 }
229 if len(parts) == 0 {
230 break
231 }
232 sort.Strings(parts)
233 wg.Add(1)
234 go func() {
235 defer wg.Done()
236 // An older page that cannot be read leaves the baselines
237 // shorter, and nothing else.
238 if page, err := readPage(dest, strings.Join(parts, ",")); err == nil {
239 mu.Lock()
240 pages = append(pages, page)
241 mu.Unlock()
242 }
243 }()
244 }
245 wg.Wait()
246 seen := map[string]bool{}
247 var builds []checkBuild
248 var mains []mainRun
249 var batches []batchEnd
250 for _, page := range pages {
251 mains = append(mains, page.mains...)
252 for _, b := range page.builds {
253 if key := b.key; !seen[key] {
254 seen[key] = true
255 builds = append(builds, b.checkBuild)
256 }
257 }
258 for _, e := range page.batches {
259 if key := e.key; !seen[key] {
260 seen[key] = true
261 batches = append(batches, e.batchEnd)
262 }
263 }
264 }
265 sort.SliceStable(builds, func(i, j int) bool { return builds[i].time > builds[j].time })
266 sort.SliceStable(batches, func(i, j int) bool { return batches[i].time > batches[j].time })
267 return builds, mains, batches, ""
268}
269
270// workerPage is one answer to a read of the worker source.
271type workerPage struct {
272 cursor telemetry.Cursor
273 builds []keyedBuild
274 mains []mainRun
275 batches []keyedBatch
276}
277
278type keyedBatch struct {
279 batchEnd
280 key string // the record's stream and number
281}
282
283type keyedBuild struct {
284 checkBuild
285 key string // the record's stream and number
286}
287
288// readPage reads one page of the worker source: the records after the
289// cursor, or the newest without one.
290func readPage(dest sshDest, cursor string) (workerPage, error) {
291 req := telemetry.Request{V: 1, Op: telemetry.OpRead, Source: workerSource, Cursor: cursor, Limit: telemetry.MaxReadLimit}
292 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
293 defer cancel()
294 ssh := sshCommand(ctx, dest, req.Command())
295 out, err := ssh.StdoutPipe()
296 if err != nil {
297 return workerPage{}, err
298 }
299 var sshErr strings.Builder
300 ssh.Stderr = &sshErr
301 if err := ssh.Start(); err != nil {
302 return workerPage{}, fmt.Errorf("could not run ssh: %v", err)
303 }
304 page, refused, err := parsePage(out)
305 io.Copy(io.Discard, out)
306 waitErr := ssh.Wait()
307 switch {
308 case refused != "":
309 return workerPage{}, fmt.Errorf("%s refused to read the worker's telemetry: %s", dest.host, refused)
310 case err == nil:
311 return page, nil
312 }
313 if why := strings.TrimSpace(telemetry.Sanitize(sshErr.String())); why != "" {
314 err = fmt.Errorf("%v: %s", err, why)
315 } else if waitErr != nil {
316 err = fmt.Errorf("%v: %v", err, waitErr)
317 }
318 return workerPage{}, fmt.Errorf("the worker's telemetry on %s did not read: %v", dest.host, err)
319}
320
321// parsePage reads one answer, which must end, or says why the host
322// refused it.
323func parsePage(r io.Reader) (page workerPage, refused string, err error) {
324 sc := bufio.NewScanner(r)
325 sc.Buffer(make([]byte, 64<<10), telemetry.MaxResponseBytes)
326 for sc.Scan() {
327 var m struct {
328 Kind string `json:"kind"`
329 Stream string `json:"stream"`
330 Seq int64 `json:"seq"`
331 Type string `json:"type"`
332 Time string `json:"time"`
333 Run string `json:"run"`
334 Project string `json:"project"`
335 Change string `json:"change"`
336 Version int `json:"version"`
337 Tree string `json:"tree"`
338 Check string `json:"check"`
339 Data map[string]any `json:"data"`
340 Error string `json:"error"`
341 What string `json:"what"`
342 Cursor string `json:"cursor"`
343 }
344 if json.Unmarshal(sc.Bytes(), &m) != nil {
345 return workerPage{}, "", fmt.Errorf("an answer line is not JSON")
346 }
347 switch m.Kind {
348 case "error":
349 return workerPage{}, telemetry.Sanitize(m.Error), nil
350 case "unavailable":
351 // The journal says nothing a build time needs. A stream the
352 // host could not read may be missing records, so the page is
353 // not complete.
354 if m.What == "journal" {
355 continue
356 }
357 return workerPage{}, "", fmt.Errorf("the host could not read %s: %s", telemetry.Sanitize(m.What), telemetry.Sanitize(m.Error))
358 case "end":
359 cur, err := telemetry.ParseCursor(m.Cursor)
360 if err != nil {
361 return workerPage{}, "", err
362 }
363 page.cursor = cur
364 return page, "", nil
365 case "record":
366 if m.Change == "" && (m.Type == "batch.start" || m.Type == "batch.end") {
367 // A follow run or a request; its class tells which
368 // (mainstate.go).
369 run := mainRun{project: m.Project, tree: m.Tree, ended: m.Type == "batch.end"}
370 run.class, _ = m.Data["class"].(string)
371 run.run, _ = m.Data["attest_run"].(string)
372 checks, _ := m.Data["checks"].([]any)
373 for _, c := range checks {
374 if name, ok := c.(string); ok {
375 run.checks = append(run.checks, name)
376 }
377 }
378 page.mains = append(page.mains, run)
379 continue
380 }
381 if m.Type == "batch.end" {
382 e := batchEnd{time: m.Time, project: m.Project, tree: m.Tree}
383 e.run, _ = m.Data["attest_run"].(string)
384 e.result, _ = m.Data["result"].(string)
385 page.batches = append(page.batches, keyedBatch{e, fmt.Sprintf("%s#%d", m.Stream, m.Seq)})
386 continue
387 }
388 if m.Type != "check.result" {
389 continue
390 }
391 // A check that did not evaluate is kept as a run that failed,
392 // which main's state and a version's worker report read. It
393 // built nothing, so no cost counts it.
394 build, built := m.Data["build_ms"].(float64)
395 b := checkBuild{time: m.Time, run: m.Run, project: m.Project, change: m.Change, version: m.Version,
396 tree: m.Tree, check: m.Check, unevaluated: !built, buildMS: int64(build)}
397 b.result, _ = m.Data["result"].(string)
398 if eval, ok := m.Data["eval_ms"].(float64); ok {
399 b.evalMS = int64(eval)
400 }
401 b.capacity, _ = m.Data["capacity"].(string)
402 if cached, ok := m.Data["cached"].(bool); ok {
403 b.cached = cached
404 } else {
405 logged, _ := m.Data["log_bytes"].(float64)
406 b.cached = logged == 0
407 }
408 page.builds = append(page.builds, keyedBuild{b, fmt.Sprintf("%s#%d", m.Stream, m.Seq)})
409 }
410 }
411 return workerPage{}, "", fmt.Errorf("the answer did not end")
412}
413
414// addCosts gives a version's nix checks what they cost to build, from
415// builds, newest first: the version's own, and the recent builds of each
416// check in its project.
417func addCosts(out *jsonVersionChecks, required []jsonRequired, project, changeID string, n int, builds []checkBuild) {
418 runner := map[string]string{}
419 for _, q := range required {
420 runner[q.Name] = q.Runner
421 }
422 var total int64
423 evals := map[string]int64{} // each attest run's evaluation
424 found := false
425 for i := range out.Required {
426 s := &out.Required[i]
427 if runner[s.Name] != "nix" {
428 continue
429 }
430 var own *checkBuild
431 for j := range builds {
432 b := &builds[j]
433 if !b.unevaluated && b.project == project && b.check == s.Name && b.change == changeID && b.version == n && (b.tree == "" || b.tree == out.Tree) {
434 own = b
435 break
436 }
437 }
438 var recent []int64
439 other := false
440 for j := range builds {
441 b := &builds[j]
442 if b.unevaluated || b.project != project || b.check != s.Name {
443 continue
444 }
445 if b.change == changeID || b.cached || b.result != checkPassed {
446 continue
447 }
448 if own != nil && b.capacity != own.capacity {
449 other = true
450 } else if len(recent) < baselineBuilds {
451 recent = append(recent, b.buildMS)
452 }
453 }
454 if own != nil {
455 found = true
456 build, cached := own.buildMS, own.cached
457 s.BuildMS, s.Cached = &build, &cached
458 total += build
459 evals[own.run] = max(evals[own.run], own.evalMS)
460 }
461 if len(recent) == 0 {
462 s.New, s.OtherCapacity = true, other
463 continue
464 }
465 base := median(recent)
466 s.BaselineMS = &base
467 s.Grown = own != nil && !own.cached && grew(own.buildMS, base)
468 }
469 if !found {
470 return
471 }
472 var eval int64
473 for _, ms := range evals {
474 eval += ms
475 }
476 out.BuildMS, out.EvalMS = &total, &eval
477}
478
479// addWorkerReports gives each nix check of a version that no note makes
480// passed the worker's report of its newest build for the version's tree,
481// when that build failed, whatever change or version it was built for.
482// When a nix check is pending, the version also gets the report of the
483// worker's newest batch for its tree, when that batch failed and recorded
484// no check's result: it failed before any check ran. builds and batches
485// are newest first.
486func addWorkerReports(out *jsonVersionChecks, required []jsonRequired, project, changeID string, n int, builds []checkBuild, batches []batchEnd) {
487 runner := map[string]string{}
488 for _, q := range required {
489 runner[q.Name] = q.Runner
490 }
491 ran := map[string]bool{} // the attest runs that recorded a check's result
492 for i := range builds {
493 ran[builds[i].run] = true
494 }
495 pending := false
496 for i := range out.Required {
497 s := &out.Required[i]
498 if runner[s.Name] != "nix" || s.State == checkPassed {
499 continue
500 }
501 pending = pending || s.State == checkPending
502 for j := range builds {
503 b := &builds[j]
504 if b.project != project || b.check != s.Name || !b.forTree(out.Tree, changeID, n) {
505 continue
506 }
507 if b.result != checkPassed {
508 s.Worker = &jsonWorkerReport{Result: b.result, Time: b.time, Run: b.run}
509 }
510 break
511 }
512 }
513 if !pending {
514 return
515 }
516 for _, e := range batches {
517 if e.project != project || e.tree != out.Tree {
518 continue
519 }
520 if e.result == checkFailed && e.run != "" && !ran[e.run] {
521 out.Worker = &jsonWorkerReport{Result: e.result, Time: e.time, Run: e.run}
522 }
523 break
524 }
525}
526
527// costLine is what checksLine adds about a version's build times: its
528// total and its evaluation, then each check that grew against its
529// baseline, most first: " in 9m10s (eval 24s); worker-e2e 431s, +68s
530// against its recent 363s". A check with no baseline is no news, and is
531// left out.
532func costLine(c *jsonVersionChecks) string {
533 if c.BuildMS == nil {
534 return ""
535 }
536 line := fmt.Sprintf(" in %s (eval %s)", duration(*c.BuildMS), duration(*c.EvalMS))
537 var grown []jsonCheckState
538 for _, q := range c.Required {
539 if q.Grown {
540 grown = append(grown, q)
541 }
542 }
543 sort.SliceStable(grown, func(i, j int) bool {
544 return *grown[i].BuildMS-*grown[i].BaselineMS > *grown[j].BuildMS-*grown[j].BaselineMS
545 })
546 for _, q := range grown {
547 line += fmt.Sprintf("; %s %s, +%s against its recent %s", q.Name, seconds(*q.BuildMS), seconds(*q.BuildMS-*q.BaselineMS), seconds(*q.BaselineMS))
548 }
549 return line
550}
551
552// duration is ms as 9m10s, to the second.
553func duration(ms int64) string {
554 return (time.Duration(ms) * time.Millisecond).Round(time.Second).String()
555}
556
557// seconds is ms as 431s, to the second.
558func seconds(ms int64) string {
559 return fmt.Sprintf("%ds", (ms+500)/1000)
560}