gunk-dev/the-valley

checkcost_test.go

sourceb40fcdedd01cmain's published tip history
12.1 KiB
1package main
2
3import (
4 "bufio"
5 "context"
6 "fmt"
7 "net"
8 "os"
9 "os/exec"
10 "path/filepath"
11 "strconv"
12 "strings"
13 "syscall"
14 "testing"
15 "time"
16
17 "the-valley/telemetry"
18)
19
20// A host or a proxy that says far more on ssh's stderr than a read keeps
21// costs it no more than sshSaidLimit bytes: the read's error carries the
22// last of what was said, which says why it failed.
23func TestAReadKeepsTheLastOfWhatSSHSaid(t *testing.T) {
24 dir := t.TempDir()
25 toolsOnPath(t, dir)
26 ssh := "#!/bin/sh\nhead -c 1048576 /dev/zero | tr '\\0' x >&2\necho ' the host went away' >&2\nexit 255\n"
27 if err := os.WriteFile(filepath.Join(dir, "bin", "ssh"), []byte(ssh), 0o755); err != nil {
28 t.Fatal(err)
29 }
30 _, err := readPage(context.Background(), sshDest{host: "valley-host"}, "")
31 if err == nil || !strings.HasSuffix(err.Error(), "x the host went away") || len(err.Error()) > sshSaidLimit+200 {
32 t.Errorf("the read said %d bytes, ending %q", len(fmt.Sprint(err)), fmt.Sprint(err)[max(len(fmt.Sprint(err))-60, 0):])
33 }
34}
35
36// One valley pending's history reads its older pages of the worker's
37// stream at once, and a host whose collector gives the principal
38// telemetry.BoundedSlots bounded slots admits every one: each page's
39// build is read, none refused. Each older page's read joins a barrier
40// and tells it whether it took a slot; an admitted one keeps its slot and
41// answers only once every older page has told, so the slots held when
42// the last one tells are held at once, and every one must be.
43func TestAHistoryReadFitsTheBoundedSlots(t *testing.T) {
44 dir, bin := t.TempDir(), t.TempDir()
45 if err := os.Symlink(os.Args[0], filepath.Join(bin, "ssh")); err != nil {
46 t.Fatal(err)
47 }
48 t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
49 t.Setenv("FAKE_SSH_POOL", dir)
50 barrier, err := net.Listen("unix", filepath.Join(dir, "barrier"))
51 if err != nil {
52 t.Fatal(err)
53 }
54 older := costRecords/telemetry.MaxReadLimit - 1
55 held := make(chan int, 1)
56 go func() {
57 var joined []net.Conn
58 defer func() {
59 for _, c := range joined {
60 c.Close()
61 }
62 }()
63 n := 0
64 for len(joined) < older {
65 c, err := barrier.Accept()
66 if err != nil {
67 held <- -1
68 return
69 }
70 joined = append(joined, c)
71 c.SetReadDeadline(time.Now().Add(time.Minute))
72 told, err := bufio.NewReader(c).ReadString('\n')
73 if err != nil {
74 held <- -1
75 return
76 }
77 if told == "held\n" {
78 n++
79 }
80 }
81 for _, c := range joined {
82 c.Write([]byte("go\n"))
83 }
84 held <- n
85 }()
86 builds, _, _, why := readBuilds(context.Background(), sshDest{host: "valley-host"})
87 barrier.Close()
88 if n := <-held; n != older {
89 t.Errorf("%d of the %d older pages' reads held a slot at once", n, older)
90 }
91 if pages := costRecords / telemetry.MaxReadLimit; why != "" || len(builds) != pages {
92 t.Errorf("the history read %d of %d pages' builds: %q", len(builds), pages, why)
93 }
94}
95
96// fakePooledSSH is a host whose collector admits telemetry.BoundedSlots
97// reads at once, as it does for one principal, and refuses any more. The
98// newest page answers at once. An older page's read joins the test's
99// barrier, tries for a slot and tells the barrier whether it holds one;
100// admitted, it answers once the barrier says go, and fails when the
101// barrier closes without saying it.
102func fakePooledSSH(dir string, args []string) int {
103 _, command, ok := sshDestCommand(args)
104 if !ok {
105 return 255
106 }
107 req, err := telemetry.ParseCommand(command)
108 if err != nil || req.Op != telemetry.OpRead {
109 return 1
110 }
111 answer := func(seq, end int64) {
112 fmt.Printf(`{"kind":"record","stream":"worker","seq":%d,"type":"check.result","project":"app","tree":"t1","check":"c-%d","data":{"result":"passed","build_ms":1000}}`+"\n", seq, seq)
113 fmt.Printf(`{"kind":"end","cursor":"worker=0123456789abcdef:%d"}`+"\n", end)
114 }
115 if req.Cursor == "" {
116 answer(costRecords, costRecords)
117 return 0
118 }
119 cursor, _ := telemetry.ParseCursor(req.Cursor)
120 after := cursor["worker"].Seq
121 barrier, err := net.Dial("unix", filepath.Join(dir, "barrier"))
122 if err != nil {
123 return 1
124 }
125 defer barrier.Close()
126 var slot *os.File
127 for i := range telemetry.BoundedSlots {
128 f, err := os.OpenFile(filepath.Join(dir, fmt.Sprintf("slot.%d", i)), os.O_CREATE|os.O_RDWR, 0o600)
129 if err == nil && syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) == nil {
130 slot = f
131 break
132 }
133 f.Close()
134 }
135 if slot == nil {
136 barrier.Write([]byte("refused\n"))
137 fmt.Printf(`{"kind":"error","error":%q}`+"\n", telemetry.SlotRefusal("operator", telemetry.BoundedSlots, "bounded"))
138 return 0
139 }
140 defer slot.Close()
141 if _, err := barrier.Write([]byte("held\n")); err != nil {
142 return 1
143 }
144 if said, _ := bufio.NewReader(barrier).ReadString('\n'); said != "go\n" {
145 return 1
146 }
147 answer(after+1, after+telemetry.MaxReadLimit)
148 return 0
149}
150
151// lastBytes keeps the last bytes written through it, however they come.
152func TestLastBytes(t *testing.T) {
153 l := &lastBytes{max: 4}
154 for _, w := range []string{"ab", "cde", "f", "ghijklm", "n"} {
155 l.Write([]byte(w))
156 }
157 if string(l.b) != "klmn" {
158 t.Errorf("kept %q, not the last four bytes", l.b)
159 }
160}
161
162// Closing the reads cancels one still running at once, even when a
163// process its ssh started, as a ProxyCommand is, holds ssh's output open:
164// close never waits for that output, which a wait for ssh would take up
165// to sshWaitDelay to give up on.
166func TestClosingAReadDoesNotWaitForOutputHeldOpen(t *testing.T) {
167 dir := t.TempDir()
168 toolsOnPath(t, dir, "git")
169 said := filepath.Join(dir, "ssh.pids")
170 if err := syscall.Mkfifo(said, 0o600); err != nil {
171 t.Fatal(err)
172 }
173 // ssh starts a process that holds its output, says both process IDs,
174 // and stalls.
175 ssh := fmt.Sprintf("#!/bin/sh\nsleep 86397 &\necho \"$! $$\" > '%s'\nexec sleep 86396\n", said)
176 if err := os.WriteFile(filepath.Join(dir, "bin", "ssh"), []byte(ssh), 0o755); err != nil {
177 t.Fatal(err)
178 }
179 repo := filepath.Join(dir, "repo")
180 for _, args := range [][]string{{"init", "--quiet", repo}, {"-C", repo, "config", "valley.telemetry.remote", "ssh://git@valley-host/app.git"}} {
181 if out, err := exec.Command("git", args...).CombinedOutput(); err != nil {
182 t.Fatalf("git %v: %v\n%s", args, err, out)
183 }
184 }
185
186 c := newCosts()
187 read := c.start(git{env: os.Environ(), dir: repo})
188 pids := make(chan []string, 1)
189 go func() {
190 data, _ := os.ReadFile(said)
191 pids <- strings.Fields(string(data))
192 }()
193 var held []string
194 select {
195 case held = <-pids:
196 case <-read.done:
197 unheard(said)
198 t.Fatalf("the read ended before ssh started: %s", read.why)
199 case <-time.After(time.Minute):
200 unheard(said)
201 t.Fatal("the read's ssh did not start in a minute")
202 }
203 for _, p := range held {
204 if n, err := strconv.Atoi(p); err == nil {
205 defer syscall.Kill(n, syscall.SIGKILL)
206 }
207 }
208 began := time.Now()
209 c.close()
210 if took := time.Since(began); took >= sshWaitDelay {
211 t.Errorf("closing the read took %s, waiting for the output a process its ssh started held open", took)
212 }
213}
214
215// A build has grown only when it is slower than its baseline by more than
216// both 20% and 30 s.
217func TestGrew(t *testing.T) {
218 for _, c := range []struct {
219 build, baseline int64
220 grown bool
221 }{
222 {100_000, 60_000, true}, // +40 s, +67%
223 {500_000, 400_000, true}, // +100 s, +25%
224 {431_000, 363_000, false}, // +68 s, but +18.7%
225 {80_000, 60_000, false}, // +20 s, +33%
226 {1_230_000, 1_200_000 - 1, false}, // +30 s, +2.5%
227 {400_000, 400_000, false},
228 {10_000, 400_000, false}, // faster
229 } {
230 if got := grew(c.build, c.baseline); got != c.grown {
231 t.Errorf("grew(%d, %d) = %v, want %v", c.build, c.baseline, got, c.grown)
232 }
233 }
234}
235
236func TestMedian(t *testing.T) {
237 for _, c := range []struct {
238 ms []int64
239 want int64
240 }{
241 {[]int64{5}, 5},
242 {[]int64{9, 1, 5}, 5},
243 {[]int64{4, 1, 3, 2}, 2},
244 {[]int64{10, 20}, 15},
245 } {
246 if got := median(c.ms); got != c.want {
247 t.Errorf("median(%v) = %d, want %d", c.ms, got, c.want)
248 }
249 }
250}
251
252// The baseline is the median of a check's newest 20 uncached, passing
253// builds in the project, with every version of the change left out.
254func TestAddCosts(t *testing.T) {
255 me := strings.Repeat("k", 32)
256 other := func(i int) string { return fmt.Sprintf("%s%02d", strings.Repeat("m", 30), i) }
257 var builds []checkBuild // newest first
258 add := func(b checkBuild) {
259 if b.project == "" {
260 b.project = "app"
261 }
262 if b.result == "" {
263 b.result = checkPassed
264 }
265 builds = append(builds, b)
266 }
267 // This version's own builds, in one run.
268 add(checkBuild{run: "r2", change: me, version: 2, tree: "t2", check: "slow", buildMS: 200_000, evalMS: 24_000})
269 add(checkBuild{run: "r2", change: me, version: 2, tree: "t2", check: "fast", buildMS: 120, evalMS: 24_000, cached: true})
270 add(checkBuild{run: "r2", change: me, version: 2, tree: "t2", check: "fresh", buildMS: 9_000, evalMS: 23_000})
271 // The change's earlier version, never counted.
272 add(checkBuild{run: "r1", change: me, version: 1, tree: "t1", check: "slow", buildMS: 1})
273 // Other changes: a cached build, a failed one and another project's
274 // are left out, then 25 builds of which the newest 20 count.
275 add(checkBuild{change: other(98), check: "slow", buildMS: 2, cached: true})
276 add(checkBuild{change: other(99), check: "slow", buildMS: 3, result: "failed"})
277 add(checkBuild{project: "site", change: other(97), check: "slow", buildMS: 4})
278 for i := 0; i < 25; i++ {
279 ms := int64(100_000 + i*1_000) // the newest 20: 100 s to 119 s
280 if i >= 20 {
281 ms = 900_000
282 }
283 add(checkBuild{change: other(i), check: "slow", buildMS: ms})
284 add(checkBuild{change: other(i), check: "fast", buildMS: 5_000})
285 }
286 out := &jsonVersionChecks{Tree: "t2", Required: []jsonCheckState{{Name: "slow"}, {Name: "fast"}, {Name: "fresh"}, {Name: "manual"}}}
287 required := []jsonRequired{{Name: "slow", Runner: "nix"}, {Name: "fast", Runner: "nix"}, {Name: "fresh", Runner: "nix"}, {Name: "manual", Runner: "command"}}
288 addCosts(out, required, "app", me, 2, builds)
289
290 slow, fast, fresh, manual := out.Required[0], out.Required[1], out.Required[2], out.Required[3]
291 if slow.BuildMS == nil || *slow.BuildMS != 200_000 || *slow.Cached || slow.BaselineMS == nil || *slow.BaselineMS != 109_500 || !slow.Grown || slow.New {
292 t.Errorf("slow: %+v", slow)
293 }
294 if fast.BuildMS == nil || *fast.BuildMS != 120 || !*fast.Cached || *fast.BaselineMS != 5_000 || fast.Grown {
295 t.Errorf("fast: %+v", fast)
296 }
297 if fresh.BuildMS == nil || *fresh.BuildMS != 9_000 || fresh.BaselineMS != nil || !fresh.New || fresh.Grown {
298 t.Errorf("fresh: %+v", fresh)
299 }
300 if manual.BuildMS != nil || manual.New || manual.BaselineMS != nil {
301 t.Errorf("manual: %+v", manual)
302 }
303 if out.BuildMS == nil || *out.BuildMS != 209_120 || *out.EvalMS != 24_000 {
304 t.Errorf("totals: build %v, eval %v", out.BuildMS, out.EvalMS)
305 }
306 out.State = checkPassed
307 for i := range out.Required {
308 out.Required[i].State = checkPassed
309 }
310 want := "checks: 4 passed in 3m29s (eval 24s); slow 200s, +91s against its recent 110s"
311 if got := checksLine(out); got != want {
312 t.Errorf("checksLine:\n got %s\nwant %s", got, want)
313 }
314}
315
316// A build is compared only with builds on its own capacity. A check whose
317// builds so far ran on another is new, and is not grown.
318func TestAddCostsCapacity(t *testing.T) {
319 builds := []checkBuild{ // newest first
320 {run: "r", change: "me", version: 1, check: "same", buildMS: 200_000, capacity: "big"},
321 {run: "r", change: "me", version: 1, check: "resized", buildMS: 200_000, capacity: "big"},
322 {change: "o1", check: "same", buildMS: 100_000, capacity: "big"},
323 {change: "o1", check: "resized", buildMS: 10_000, capacity: "small"},
324 }
325 var states []jsonCheckState
326 var required []jsonRequired
327 for _, name := range []string{"same", "resized"} {
328 builds[len(states)].project, builds[len(states)+2].project = "app", "app"
329 builds[len(states)].result, builds[len(states)+2].result = checkPassed, checkPassed
330 states = append(states, jsonCheckState{Name: name, State: checkPassed})
331 required = append(required, jsonRequired{Name: name, Runner: "nix"})
332 }
333 out := &jsonVersionChecks{State: checkPassed, Required: states}
334 addCosts(out, required, "app", "me", 1, builds)
335 if same := out.Required[0]; !same.Grown || same.New || *same.BaselineMS != 100_000 {
336 t.Errorf("same: %+v", same)
337 }
338 if resized := out.Required[1]; !resized.New || !resized.OtherCapacity || resized.Grown || resized.BaselineMS != nil {
339 t.Errorf("resized: %+v", resized)
340 }
341}