Debian Codegraph @

scripts/update_benchmarks.go

raw
1 package main
2
3 // Refreshes the numbers in the README benchmark tables. Each ```text table
4 // starts with the `go test` command that produced it, so the table is its own
5 // recipe: re-run that command, replace the values of the rows it reports, and
6 // rewrite the Environment: header above it with the machine that ran.
7
8 import (
9 "bytes"
10 "context"
11 "fmt"
12 "io"
13 "os"
14 "os/exec"
15 "path/filepath"
16 "runtime"
17 "slices"
18 "strconv"
19 "strings"
20 )
21
22 var envKeys = []string{"goos", "goarch", "pkg", "cpu"}
23
24 // machineKeys are the header lines a run describes. pkg is not one of them: it
25 // names the package the table documents and is what pick() disambiguates on, so
26 // taking it from the output would let one run decide the next run's rows.
27 var machineKeys = []string{"goos", "goarch", "cpu"}
28
29 // benchBlock is one ```text table plus the Environment: header above it.
30 type benchBlock struct {
31 env map[string]int // envKeys -> line index
32 pkg string
33 goos string
34 goarch string
35 cmd []string // the "// go test ..." line inside the table
36 open int // the ```text line
37 end int // the closing ``` line
38 }
39
40 // benchResult is one benchmark line of `go test -benchmem` output.
41 type benchResult struct {
42 pkg string
43 fields []string // name (with its -N suffix) followed by the measured columns
44 ns float64
45 }
46
47 func updateBenchmarks(ctx context.Context, path string, only int) error {
48 lines, err := readLines(path)
49 if err != nil {
50 return err
51 }
52
53 blocks, err := parseBlocks(lines)
54 if err != nil {
55 return err
56 }
57 if only > len(blocks) {
58 return fmt.Errorf("-block %d: %s has %d benchmark tables", only, path, len(blocks))
59 }
60
61 known := knownRows(lines, blocks)
62 dir := filepath.Dir(path)
63 ran := 0
64 for i, b := range blocks {
65 num := i + 1
66 switch {
67 case only > 0 && only != num:
68 continue
69 // -block picks a table, not the architecture: the rows the command does not
70 // measure would keep the other machine's numbers under this machine's header.
71 case b.goarch != runtime.GOARCH:
72 logf("table %d (%s/%s): skipped, this machine is %s/%s\n", num, b.goos, b.goarch, runtime.GOOS, runtime.GOARCH)
73 continue
74 case len(b.cmd) == 0:
75 logf("table %d: skipped, no \"// go test ...\" line to re-run\n", num)
76 continue
77 }
78
79 logf("table %d (%s/%s): %s\n", num, b.goos, b.goarch, strings.Join(b.cmd, " "))
80 out, err := runBench(ctx, dir, b.cmd)
81 if err != nil {
82 return err
83 }
84 applyResults(lines, b, num, out, known)
85 ran++
86 }
87
88 if ran == 0 {
89 return fmt.Errorf("no benchmark table was refreshed on %s/%s, see the reasons above", runtime.GOOS, runtime.GOARCH)
90 }
91 return writeLines(path, lines)
92 }
93
94 // knownRows names every benchmark any table documents. Table 1's command is
95 // `go test ./...`, so it measures the rows of the other tables too, and only the
96 // whole set answers "this was measured but is written down nowhere".
97 func knownRows(lines []string, blocks []benchBlock) map[string]bool {
98 known := map[string]bool{}
99 for _, b := range blocks {
100 for i := b.open + 1; i < b.end; i++ {
101 if name, ok := rowName(lines[i]); ok {
102 known[stripProcs(name)] = true
103 }
104 }
105 }
106 return known
107 }
108
109 // rowName also matches rows benchFields rejects: those are documented all the same.
110 func rowName(line string) (string, bool) {
111 fields := strings.Fields(line)
112 if len(fields) == 0 || !strings.HasPrefix(fields[0], "Benchmark") {
113 return "", false
114 }
115 return fields[0], true
116 }
117
118 // applyResults rewrites the rows of one table and the Environment: header above it.
119 func applyResults(lines []string, b benchBlock, num int, out string, known map[string]bool) {
120 env, results, odd := parseBenchOutput(out)
121
122 updated := 0
123 var stale, mixed, unusable, narrower []string
124 for i := b.open + 1; i < b.end; i++ {
125 fields, ok := benchFields(lines[i])
126 if !ok {
127 if name, isRow := rowName(lines[i]); isRow {
128 unusable = append(unusable, name)
129 }
130 continue
131 }
132 name := stripProcs(fields[0])
133
134 runs, ok := pick(results[name], b.pkg)
135 if !ok {
136 mixed = append(mixed, name)
137 continue
138 }
139 best := median(runs)
140 if best == nil {
141 stale = append(stale, name)
142 continue
143 }
144 row := canonical(best.fields)
145 if len(row) < len(fields) {
146 // Fewer columns than the table documents, so the run measured less than
147 // it did last time. Replacing the row would drop what it no longer has.
148 narrower = append(narrower, name)
149 continue
150 }
151 lines[i] = strings.Join(row, " ")
152 updated++
153 }
154
155 var missing []string
156 for _, key := range machineKeys {
157 at, ok := b.env[key]
158 if !ok {
159 continue
160 }
161 if env[key] == "" {
162 // A header naming a machine that did not run is worse than one that says
163 // it does not know; arm64 Linux reports no cpu line at all.
164 lines[at] = key + ": unknown"
165 missing = append(missing, key)
166 continue
167 }
168 lines[at] = key + ": " + env[key]
169 }
170
171 var added []string
172 for name := range results {
173 if !known[name] {
174 added = append(added, name)
175 }
176 }
177
178 logf("table %d: %d rows refreshed\n", num, updated)
179 report(num, "not in the new output, left as they were", stale)
180 report(num, "measured but in none of the tables", added)
181 report(num, "in the table, but not in a shape this tool can refresh", unusable)
182 report(num, "measured with fewer columns than the table has, left as they were", narrower)
183 report(num, "measured by several packages and none of them is the table's, left as they were", mixed)
184 report(num, "measured in a shape the table cannot hold", odd)
185 report(num, "not reported by this run, the header says unknown", missing)
186 }
187
188 // pick narrows a name's runs down to one package. `go test ./...` spans packages
189 // and the same name can live in two of them, which a table row cannot tell apart,
190 // so the package named in the table's own header decides.
191 func pick(runs []benchResult, pkg string) ([]benchResult, bool) {
192 packages := map[string]bool{}
193 for _, r := range runs {
194 packages[r.pkg] = true
195 }
196 if len(packages) < 2 {
197 return runs, true
198 }
199 owned := slices.DeleteFunc(slices.Clone(runs), func(r benchResult) bool { return r.pkg != pkg })
200 return owned, len(owned) > 0
201 }
202
203 // canonical keeps the columns the tables are built from. `go test` adds an MB/s
204 // column for benchmarks that call b.SetBytes, and the tables are aligned by
205 // column index, so a wider row would misalign everything around it.
206 func canonical(fields []string) []string {
207 row := append([]string{}, fields[:2]...)
208 for i := 2; i+1 < len(fields); i += 2 {
209 switch fields[i+1] {
210 case "ns/op", "B/op", "allocs/op":
211 row = append(row, fields[i], fields[i+1])
212 }
213 }
214 return row
215 }
216
217 // benchFields returns the columns of a benchmark row, in `go test` output and in
218 // a README table alike. ns/op has to be the first metric, because the tables are
219 // aligned by column index.
220 func benchFields(line string) ([]string, bool) {
221 fields := strings.Fields(line)
222 if len(fields) < 4 || !strings.HasPrefix(fields[0], "Benchmark") || fields[3] != "ns/op" {
223 return nil, false
224 }
225 return fields, true
226 }
227
228 func report(num int, title string, names []string) {
229 if len(names) == 0 {
230 return
231 }
232 slices.Sort(names)
233 shown := names
234 if len(shown) > 10 {
235 shown = shown[:10]
236 }
237 logf(" table %d: %s (%d): %s\n", num, title, len(names), strings.Join(shown, ", "))
238 if len(names) > len(shown) {
239 logf(" ... and %d more\n", len(names)-len(shown))
240 }
241 }
242
243 // median returns the run in the middle by ns/op, the slower one of the two when
244 // -count is even, so a repeated measurement documents a representative run
245 // instead of the last one.
246 func median(runs []benchResult) *benchResult {
247 if len(runs) == 0 {
248 return nil
249 }
250 sorted := slices.Clone(runs)
251 slices.SortFunc(sorted, func(a, b benchResult) int {
252 switch {
253 case a.ns < b.ns:
254 return -1
255 case a.ns > b.ns:
256 return 1
257 default:
258 return 0
259 }
260 })
261 return &sorted[len(sorted)/2]
262 }
263
264 func parseBenchOutput(out string) (map[string]string, map[string][]benchResult, []string) {
265 env := map[string]string{}
266 results := map[string][]benchResult{}
267 var odd []string
268 pkg := ""
269
270 for line := range strings.Lines(out) {
271 line = strings.TrimSpace(line)
272 if key, value, ok := strings.Cut(line, ": "); ok && slices.Contains(envKeys, key) {
273 if key == "pkg" {
274 pkg = strings.TrimSpace(value)
275 }
276 if env[key] == "" {
277 env[key] = strings.TrimSpace(value)
278 }
279 continue
280 }
281 if !strings.HasPrefix(line, "Benchmark") {
282 continue
283 }
284
285 fields, ok := benchFields(line)
286 if !ok {
287 odd = append(odd, strings.Fields(line)[0])
288 continue
289 }
290 ns, err := strconv.ParseFloat(fields[2], 64)
291 if err != nil {
292 odd = append(odd, fields[0])
293 continue
294 }
295 name := stripProcs(fields[0])
296 results[name] = append(results[name], benchResult{pkg: pkg, fields: fields, ns: ns})
297 }
298 return env, results, odd
299 }
300
301 // stripProcs drops the -N GOMAXPROCS suffix so a table recorded on 12 cores
302 // matches the same benchmark measured on 4.
303 func stripProcs(name string) string {
304 if i := strings.LastIndexByte(name, '-'); i > 0 {
305 if _, err := strconv.Atoi(name[i+1:]); err == nil {
306 return name[:i]
307 }
308 }
309 return name
310 }
311
312 func parseBlocks(lines []string) ([]benchBlock, error) {
313 var blocks []benchBlock
314 for i, line := range lines {
315 if strings.TrimSpace(line) != "```text" {
316 continue
317 }
318
319 b := benchBlock{open: i, env: map[string]int{}}
320 for j := i + 1; j < len(lines); j++ {
321 text := strings.TrimSpace(lines[j])
322 if text == "```text" {
323 return nil, fmt.Errorf("line %d: ```text block opened at line %d is never closed", j+1, i+1)
324 }
325 if text == "```" {
326 b.end = j
327 break
328 }
329 if b.cmd == nil && strings.HasPrefix(text, "// go test") {
330 cmd, err := splitArgs(strings.TrimPrefix(text, "//"))
331 if err != nil {
332 return nil, fmt.Errorf("line %d: %w", j+1, err)
333 }
334 b.cmd = cmd
335 }
336 }
337 if b.end == 0 {
338 return nil, fmt.Errorf("line %d: ```text block is never closed", i+1)
339 }
340
341 readEnvHeader(lines, &b)
342 // A ```text block without a full Environment: header is sample output, not a
343 // benchmark table. Skipping it keeps -block numbering on the tables alone.
344 if len(b.env) == len(envKeys) {
345 blocks = append(blocks, b)
346 }
347 }
348 return blocks, nil
349 }
350
351 // readEnvHeader walks up from the fence over the "goos: ... cpu: ..." lines.
352 func readEnvHeader(lines []string, b *benchBlock) {
353 for j := b.open - 1; j >= 0; j-- {
354 text := strings.TrimSpace(lines[j])
355 switch text {
356 case "":
357 continue
358 case "Environment:":
359 return
360 }
361
362 key, value, ok := strings.Cut(text, ": ")
363 if !ok {
364 return
365 }
366 value = strings.TrimSpace(value)
367 switch key {
368 case "goos":
369 b.goos = value
370 case "goarch":
371 b.goarch = value
372 case "pkg":
373 b.pkg = value
374 case "cpu":
375 default:
376 return
377 }
378 b.env[key] = j
379 }
380 }
381
382 // splitArgs splits a command line on whitespace, honoring quotes so a
383 // -bench='^Benchmark_(A|B)$' survives. Nothing is expanded and the result is
384 // executed without a shell, so quoting is the only thing it has to get right.
385 func splitArgs(s string) ([]string, error) {
386 var args []string
387 var cur strings.Builder
388 quote := byte(0)
389 started := false
390
391 for i := 0; i < len(s); i++ {
392 c := s[i]
393 switch {
394 case quote != 0 && c == quote:
395 quote = 0
396 case quote == 0 && (c == '\'' || c == '"'):
397 quote = c
398 started = true
399 case quote == 0 && (c == ' ' || c == '\t'):
400 if started {
401 args = append(args, cur.String())
402 cur.Reset()
403 started = false
404 }
405 default:
406 cur.WriteByte(c)
407 started = true
408 }
409 }
410 if quote != 0 {
411 return nil, fmt.Errorf("unbalanced %c in %q", quote, strings.TrimSpace(s))
412 }
413 if started {
414 args = append(args, cur.String())
415 }
416
417 if len(args) < 2 || args[0] != "go" || args[1] != "test" {
418 return nil, fmt.Errorf("expected a `go test` command, got %q", strings.TrimSpace(s))
419 }
420 return args, nil
421 }
422
423 func runBench(ctx context.Context, dir string, args []string) (string, error) {
424 cmd := exec.CommandContext(ctx, args[0], args[1:]...) // #nosec G204 -- `go test` runs this repo's own code either way; no shell means the line cannot mean more than arguments
425 cmd.Dir = dir
426 var out bytes.Buffer
427 cmd.Stdout = io.MultiWriter(&out, os.Stderr)
428 cmd.Stderr = os.Stderr
429 if err := cmd.Run(); err != nil {
430 return "", fmt.Errorf("%s: %w", strings.Join(args, " "), err)
431 }
432 return out.String(), nil
433 }
434
435 func readLines(path string) ([]string, error) {
436 data, err := os.ReadFile(path) // #nosec G304
437 if err != nil {
438 return nil, err
439 }
440 return strings.Split(strings.TrimSuffix(string(data), "\n"), "\n"), nil
441 }
442
443 func writeLines(path string, lines []string) error {
444 return os.WriteFile(path, []byte(strings.Join(lines, "\n")+"\n"), 0o600) // #nosec G306
445 }
446
447 func logf(format string, args ...any) {
448 _, _ = fmt.Fprintf(os.Stderr, format, args...) //nolint:errcheck // progress reporting only
449 }