gunk-dev/the-valley

checkcost.go

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