gunk-dev/the-valley

checkcost.go

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