gunk-dev/the-valley

checkcost.go

source1dfbf0f24992main's published tip history
13.9 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.
101type checkBuild struct {
102 time, run string
103 project, change string
104 version int
105 tree, check string
106 result string
107 buildMS, evalMS int64
108 cached bool
109 capacity string
110}
111
112// costs reads the worker's telemetry of each host a listing serves, once
113// a host, in the background.
114type costs struct {
115 mu sync.Mutex
116 reads map[string]*costRead // by destination identity
117 said map[string]bool // the reasons already said on stderr
118}
119
120type costRead struct {
121 done chan struct{}
122 builds []checkBuild // newest first
123 why string // why there are none, when the read failed
124}
125
126func newCosts() *costs {
127 return &costs{reads: map[string]*costRead{}, said: map[string]bool{}}
128}
129
130// start begins the read of the host g's telemetry remote names
131// (telemetryRemote), unless it has begun.
132func (c *costs) start(g git) *costRead {
133 dest, err := telemetryRemote(g, "")
134 c.mu.Lock()
135 defer c.mu.Unlock()
136 if err != nil {
137 r := &costRead{done: make(chan struct{}), why: err.Error()}
138 close(r.done)
139 return r
140 }
141 if r := c.reads[dest.identity()]; r != nil {
142 return r
143 }
144 r := &costRead{done: make(chan struct{})}
145 c.reads[dest.identity()] = r
146 go func() {
147 defer close(r.done)
148 r.builds, r.why = readBuilds(dest)
149 }()
150 return r
151}
152
153// wait is what a read found, once it has ended, and whether it read. The
154// reason a read failed is said on stderr the first time it is met.
155func (c *costs) wait(r *costRead, warn func(format string, args ...any)) ([]checkBuild, bool) {
156 <-r.done
157 if r.why == "" {
158 return r.builds, true
159 }
160 c.mu.Lock()
161 said := c.said[r.why]
162 c.said[r.why] = true
163 c.mu.Unlock()
164 if !said {
165 warn("no check lists its build times: %s", r.why)
166 }
167 return nil, false
168}
169
170// readBuilds reads up to costRecords of the newest records of the worker
171// source at dest, and returns the check builds among them, newest first.
172func readBuilds(dest sshDest) ([]checkBuild, string) {
173 first, err := readPage(dest, "")
174 if err != nil {
175 return nil, err.Error()
176 }
177 pages := []workerPage{first}
178 var mu sync.Mutex
179 var wg sync.WaitGroup
180 for p := 1; p*telemetry.MaxReadLimit < costRecords; p++ {
181 // Page p holds, for each stream, the records up to p pages
182 // before the newest one the first page read.
183 var parts []string
184 for name, pos := range first.cursor {
185 if after := pos.Seq - int64((p+1)*telemetry.MaxReadLimit); after+telemetry.MaxReadLimit > 0 {
186 parts = append(parts, fmt.Sprintf("%s=%s:%d", name, pos.Epoch, max(after, 0)))
187 }
188 }
189 if len(parts) == 0 {
190 break
191 }
192 sort.Strings(parts)
193 wg.Add(1)
194 go func() {
195 defer wg.Done()
196 // An older page that cannot be read leaves the baselines
197 // shorter, and nothing else.
198 if page, err := readPage(dest, strings.Join(parts, ",")); err == nil {
199 mu.Lock()
200 pages = append(pages, page)
201 mu.Unlock()
202 }
203 }()
204 }
205 wg.Wait()
206 seen := map[string]bool{}
207 var builds []checkBuild
208 for _, page := range pages {
209 for _, b := range page.builds {
210 if key := b.key; !seen[key] {
211 seen[key] = true
212 builds = append(builds, b.checkBuild)
213 }
214 }
215 }
216 sort.SliceStable(builds, func(i, j int) bool { return builds[i].time > builds[j].time })
217 return builds, ""
218}
219
220// workerPage is one answer to a read of the worker source.
221type workerPage struct {
222 cursor telemetry.Cursor
223 builds []keyedBuild
224}
225
226type keyedBuild struct {
227 checkBuild
228 key string // the record's stream and number
229}
230
231// readPage reads one page of the worker source: the records after the
232// cursor, or the newest without one.
233func readPage(dest sshDest, cursor string) (workerPage, error) {
234 req := telemetry.Request{V: 1, Op: telemetry.OpRead, Source: workerSource, Cursor: cursor, Limit: telemetry.MaxReadLimit}
235 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
236 defer cancel()
237 ssh := sshCommand(ctx, dest, req.Command())
238 out, err := ssh.StdoutPipe()
239 if err != nil {
240 return workerPage{}, err
241 }
242 var sshErr strings.Builder
243 ssh.Stderr = &sshErr
244 if err := ssh.Start(); err != nil {
245 return workerPage{}, fmt.Errorf("could not run ssh: %v", err)
246 }
247 page, refused, err := parsePage(out)
248 io.Copy(io.Discard, out)
249 waitErr := ssh.Wait()
250 switch {
251 case refused != "":
252 return workerPage{}, fmt.Errorf("%s refused to read the worker's telemetry: %s", dest.host, refused)
253 case err == nil:
254 return page, nil
255 }
256 if why := strings.TrimSpace(telemetry.Sanitize(sshErr.String())); why != "" {
257 err = fmt.Errorf("%v: %s", err, why)
258 } else if waitErr != nil {
259 err = fmt.Errorf("%v: %v", err, waitErr)
260 }
261 return workerPage{}, fmt.Errorf("the worker's telemetry on %s did not read: %v", dest.host, err)
262}
263
264// parsePage reads one answer, which must end, or says why the host
265// refused it.
266func parsePage(r io.Reader) (page workerPage, refused string, err error) {
267 sc := bufio.NewScanner(r)
268 sc.Buffer(make([]byte, 64<<10), telemetry.MaxResponseBytes)
269 for sc.Scan() {
270 var m struct {
271 Kind string `json:"kind"`
272 Stream string `json:"stream"`
273 Seq int64 `json:"seq"`
274 Type string `json:"type"`
275 Time string `json:"time"`
276 Run string `json:"run"`
277 Project string `json:"project"`
278 Change string `json:"change"`
279 Version int `json:"version"`
280 Tree string `json:"tree"`
281 Check string `json:"check"`
282 Data map[string]any `json:"data"`
283 Error string `json:"error"`
284 What string `json:"what"`
285 Cursor string `json:"cursor"`
286 }
287 if json.Unmarshal(sc.Bytes(), &m) != nil {
288 return workerPage{}, "", fmt.Errorf("an answer line is not JSON")
289 }
290 switch m.Kind {
291 case "error":
292 return workerPage{}, telemetry.Sanitize(m.Error), nil
293 case "unavailable":
294 // The journal says nothing a build time needs. A stream the
295 // host could not read may be missing records, so the page is
296 // not complete.
297 if m.What == "journal" {
298 continue
299 }
300 return workerPage{}, "", fmt.Errorf("the host could not read %s: %s", telemetry.Sanitize(m.What), telemetry.Sanitize(m.Error))
301 case "end":
302 cur, err := telemetry.ParseCursor(m.Cursor)
303 if err != nil {
304 return workerPage{}, "", err
305 }
306 page.cursor = cur
307 return page, "", nil
308 case "record":
309 if m.Type != "check.result" {
310 continue
311 }
312 build, ok := m.Data["build_ms"].(float64)
313 if !ok {
314 continue // a check that did not evaluate built nothing
315 }
316 b := checkBuild{time: m.Time, run: m.Run, project: m.Project, change: m.Change, version: m.Version,
317 tree: m.Tree, check: m.Check, buildMS: int64(build)}
318 b.result, _ = m.Data["result"].(string)
319 if eval, ok := m.Data["eval_ms"].(float64); ok {
320 b.evalMS = int64(eval)
321 }
322 b.capacity, _ = m.Data["capacity"].(string)
323 if cached, ok := m.Data["cached"].(bool); ok {
324 b.cached = cached
325 } else {
326 logged, _ := m.Data["log_bytes"].(float64)
327 b.cached = logged == 0
328 }
329 page.builds = append(page.builds, keyedBuild{b, fmt.Sprintf("%s#%d", m.Stream, m.Seq)})
330 }
331 }
332 return workerPage{}, "", fmt.Errorf("the answer did not end")
333}
334
335// addCosts gives a version's nix checks what they cost to build, from
336// builds, newest first: the version's own, and the recent builds of each
337// check in its project.
338func addCosts(out *jsonVersionChecks, required []jsonRequired, project, changeID string, n int, builds []checkBuild) {
339 runner := map[string]string{}
340 for _, q := range required {
341 runner[q.Name] = q.Runner
342 }
343 var total int64
344 evals := map[string]int64{} // each attest run's evaluation
345 found := false
346 for i := range out.Required {
347 s := &out.Required[i]
348 if runner[s.Name] != "nix" {
349 continue
350 }
351 var own *checkBuild
352 for j := range builds {
353 b := &builds[j]
354 if b.project == project && b.check == s.Name && b.change == changeID && b.version == n && (b.tree == "" || b.tree == out.Tree) {
355 own = b
356 break
357 }
358 }
359 var recent []int64
360 other := false
361 for j := range builds {
362 b := &builds[j]
363 if b.project != project || b.check != s.Name {
364 continue
365 }
366 if b.change == changeID || b.cached || b.result != checkPassed {
367 continue
368 }
369 if own != nil && b.capacity != own.capacity {
370 other = true
371 } else if len(recent) < baselineBuilds {
372 recent = append(recent, b.buildMS)
373 }
374 }
375 if own != nil {
376 found = true
377 build, cached := own.buildMS, own.cached
378 s.BuildMS, s.Cached = &build, &cached
379 total += build
380 evals[own.run] = max(evals[own.run], own.evalMS)
381 }
382 if len(recent) == 0 {
383 s.New, s.OtherCapacity = true, other
384 continue
385 }
386 base := median(recent)
387 s.BaselineMS = &base
388 s.Grown = own != nil && !own.cached && grew(own.buildMS, base)
389 }
390 if !found {
391 return
392 }
393 var eval int64
394 for _, ms := range evals {
395 eval += ms
396 }
397 out.BuildMS, out.EvalMS = &total, &eval
398}
399
400// costLine is what checksLine adds about a version's build times: its
401// total and its evaluation, then each check that grew against its
402// baseline, most first, and each new check: " in 9m10s (eval 24s);
403// worker-e2e 431s, +68s against its recent 363s; web-unit 135s, new".
404func costLine(c *jsonVersionChecks) string {
405 if c.BuildMS == nil {
406 return ""
407 }
408 line := fmt.Sprintf(" in %s (eval %s)", duration(*c.BuildMS), duration(*c.EvalMS))
409 var grown, fresh []jsonCheckState
410 for _, q := range c.Required {
411 switch {
412 case q.Grown:
413 grown = append(grown, q)
414 case q.New && q.BuildMS != nil:
415 fresh = append(fresh, q)
416 }
417 }
418 sort.SliceStable(grown, func(i, j int) bool {
419 return *grown[i].BuildMS-*grown[i].BaselineMS > *grown[j].BuildMS-*grown[j].BaselineMS
420 })
421 sort.SliceStable(fresh, func(i, j int) bool { return *fresh[i].BuildMS > *fresh[j].BuildMS })
422 for _, q := range grown {
423 line += fmt.Sprintf("; %s %s, +%s against its recent %s", q.Name, seconds(*q.BuildMS), seconds(*q.BuildMS-*q.BaselineMS), seconds(*q.BaselineMS))
424 }
425 for _, q := range fresh {
426 note := "new"
427 if q.OtherCapacity {
428 note = "new on this capacity"
429 }
430 line += fmt.Sprintf("; %s %s, %s", q.Name, seconds(*q.BuildMS), note)
431 }
432 return line
433}
434
435// duration is ms as 9m10s, to the second.
436func duration(ms int64) string {
437 return (time.Duration(ms) * time.Millisecond).Round(time.Second).String()
438}
439
440// seconds is ms as 431s, to the second.
441func seconds(ms int64) string {
442 return fmt.Sprintf("%ds", (ms+500)/1000)
443}