gunk-dev/the-valley

timing_test.go

sourcebabe14e6c71cmain's published tip history
13.7 KiB
1package main
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "os"
9 "os/exec"
10 "path/filepath"
11 "reflect"
12 "sort"
13 "strings"
14 "syscall"
15 "testing"
16 "time"
17)
18
19// The timing log is a file other tools will read line by line, so its
20// lines are pinned here: one JSON object per check, with exactly these
21// fields, appended to whatever the file already holds.
22func TestTimingLogAppendsOneLinePerCheck(t *testing.T) {
23 path := filepath.Join(t.TempDir(), "state", "valley", "timings.jsonl")
24 var warned bytes.Buffer
25 log := &timingLog{path: path, warn: &warned}
26 log.append(checkTiming{
27 Time: "2026-10-20T12:00:00.000Z", Repository: "ssh://git@host/project.git",
28 Change: "kqxmkqxmkqxmkqxmkqxmkqxmkqxmkqxm", Version: 2, Head: strings.Repeat("a", 40),
29 Check: "prose-format", Runner: "nix", Cost: "quick", Result: "passed", Satisfied: satisfiedCached,
30 DurationMS: 1234,
31 })
32 // A plain branch has no change ID or version.
33 log.append(checkTiming{
34 Time: "2026-10-20T12:00:01.234Z", Repository: "/srv/project", Head: strings.Repeat("b", 40),
35 Check: "tree-ok", Runner: "command", Result: "failed", Satisfied: satisfiedRan,
36 })
37 if warned.Len() != 0 {
38 t.Fatalf("a writable log warned: %s", warned.String())
39 }
40 // Only its owner can read it.
41 for p, want := range map[string]os.FileMode{path: 0o600, filepath.Dir(path): 0o700} {
42 if info, err := os.Stat(p); err != nil || info.Mode().Perm() != want {
43 t.Errorf("%s was created %v, want %v", p, info.Mode().Perm(), want)
44 }
45 }
46
47 data, err := os.ReadFile(path)
48 if err != nil {
49 t.Fatal(err)
50 }
51 lines := strings.Split(strings.TrimSuffix(string(data), "\n"), "\n")
52 if len(lines) != 2 {
53 t.Fatalf("the log holds %d lines, want 2:\n%s", len(lines), data)
54 }
55 want := [][]string{
56 {"change", "check", "cost", "duration_ms", "head", "repository", "result", "runner", "satisfied", "time", "version"},
57 {"check", "duration_ms", "head", "repository", "result", "runner", "satisfied", "time"},
58 }
59 for i, line := range lines {
60 var fields map[string]any
61 if err := json.Unmarshal([]byte(line), &fields); err != nil {
62 t.Fatalf("line %d is not JSON: %v: %s", i+1, err, line)
63 }
64 var keys []string
65 for k := range fields {
66 keys = append(keys, k)
67 }
68 sort.Strings(keys)
69 if !reflect.DeepEqual(keys, want[i]) {
70 t.Errorf("line %d has the fields %v, want %v", i+1, keys, want[i])
71 }
72 }
73 var first checkTiming
74 if err := json.Unmarshal([]byte(lines[0]), &first); err != nil {
75 t.Fatal(err)
76 }
77 if first.DurationMS != 1234 || first.Version != 2 || first.Satisfied != "cached" {
78 t.Errorf("the first line reads back as %+v", first)
79 }
80}
81
82// A log others can read, such as one an earlier attest created, is made
83// readable by its owner alone before a line is added, and keeps the lines
84// it held.
85func TestATimingLogOthersCanReadIsMadePrivate(t *testing.T) {
86 path := filepath.Join(t.TempDir(), "timings.jsonl")
87 if err := os.WriteFile(path, []byte("{\"check\":\"earlier\"}\n"), 0o644); err != nil {
88 t.Fatal(err)
89 }
90 if err := os.Chmod(path, 0o644); err != nil {
91 t.Fatal(err)
92 }
93 var warned bytes.Buffer
94 log := &timingLog{path: path, warn: &warned}
95 log.append(checkTiming{Check: "later", Result: "passed"})
96 if warned.Len() != 0 {
97 t.Fatalf("a log others can read warned: %s", warned.String())
98 }
99 if info, err := os.Stat(path); err != nil || info.Mode().Perm() != 0o600 {
100 t.Errorf("a log others could read is now %v, want %v", info.Mode().Perm(), os.FileMode(0o600))
101 }
102 data, err := os.ReadFile(path)
103 if err != nil {
104 t.Fatal(err)
105 }
106 if lines := strings.Split(strings.TrimSuffix(string(data), "\n"), "\n"); len(lines) != 2 ||
107 !strings.Contains(lines[0], "earlier") || !strings.Contains(lines[1], "later") {
108 t.Errorf("the log holds:\n%s", data)
109 }
110}
111
112// A log that cannot be written says so once and goes on: the run it
113// belongs to is not failed by it, and is not made to repeat the warning
114// for every check after the first.
115func TestAnUnwritableTimingLogOnlyWarns(t *testing.T) {
116 // A directory that is a regular file cannot be written under, whoever
117 // runs the test.
118 blocker := filepath.Join(t.TempDir(), "state")
119 if err := os.WriteFile(blocker, []byte("not a directory\n"), 0o644); err != nil {
120 t.Fatal(err)
121 }
122 var warned bytes.Buffer
123 log := &timingLog{path: filepath.Join(blocker, "valley", "timings.jsonl"), warn: &warned}
124 for _, check := range []string{"one", "two", "three"} {
125 log.append(checkTiming{Check: check, Result: "passed"})
126 }
127 lines := strings.Split(strings.TrimSuffix(warned.String(), "\n"), "\n")
128 if len(lines) != 1 || !strings.HasPrefix(lines[0], "attest: warning: timings not logged: ") {
129 t.Fatalf("an unwritable log warned %q, want one warning line", warned.String())
130 }
131}
132
133// The log is a regular file. Anything else at its path is refused at once,
134// with one warning, and is written nothing. A FIFO nobody reads would hold
135// the open forever, and one somebody reads would hand them the log.
136func TestATimingLogThatIsNotARegularFileIsRefused(t *testing.T) {
137 for _, reading := range []bool{false, true} {
138 path := filepath.Join(t.TempDir(), "timings.jsonl")
139 if err := syscall.Mkfifo(path, 0o600); err != nil {
140 t.Fatal(err)
141 }
142 var reader *os.File
143 if reading {
144 fd, err := syscall.Open(path, syscall.O_RDONLY|syscall.O_NONBLOCK, 0)
145 if err != nil {
146 t.Fatal(err)
147 }
148 reader = os.NewFile(uintptr(fd), path)
149 defer reader.Close()
150 }
151 var warned bytes.Buffer
152 log := &timingLog{path: path, warn: &warned}
153 began := time.Now()
154 for _, check := range []string{"one", "two"} {
155 log.append(checkTiming{Check: check, Result: "passed"})
156 }
157 if took := time.Since(began); took >= timingDeadline {
158 t.Errorf("a FIFO at the log's path (read: %v) held the run for %v", reading, took)
159 }
160 if lines := strings.Split(strings.TrimSuffix(warned.String(), "\n"), "\n"); len(lines) != 1 ||
161 !strings.HasSuffix(lines[0], path+" is not a regular file") {
162 t.Errorf("a FIFO at the log's path (read: %v) warned %q, want one warning", reading, warned.String())
163 }
164 if reading {
165 if n, _ := reader.Read(make([]byte, 1)); n != 0 {
166 t.Errorf("a FIFO at the log's path was written to")
167 }
168 }
169 }
170}
171
172// Timing output to a standard stream nobody reads is dropped, and is never
173// what ends a run or holds it up. Go ends a process whose write to its own
174// standard output fails because nobody reads it, so each case runs in a
175// child: this test again, with both standard streams one pipe. In one, the
176// pipe's reader has gone. In the other, the pipe is full and its reader
177// never reads.
178func TestTimingOutputNobodyReadsIsDropped(t *testing.T) {
179 const survived = 3
180 if os.Getenv("ATTEST_TIMING_CHILD") != "" {
181 fmt.Fprintln(timingStdout(), "time one passed 1ms (ran)")
182 fmt.Fprintln(timingStderr(), "attest: warning: timings not logged: a test")
183 fmt.Fprintln(timingStdout(), "time two passed 1ms (ran)")
184 os.Exit(survived)
185 }
186 for _, full := range []bool{false, true} {
187 r, w, err := os.Pipe()
188 if err != nil {
189 t.Fatal(err)
190 }
191 if full {
192 // The write end is non-blocking until the child is given it,
193 // so it fills until a write would wait.
194 w.SetWriteDeadline(time.Now().Add(100 * time.Millisecond))
195 for err == nil {
196 _, err = w.Write(make([]byte, 1<<16))
197 }
198 w.SetWriteDeadline(time.Time{})
199 } else {
200 r.Close()
201 }
202 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
203 cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestTimingOutputNobodyReadsIsDropped$")
204 cmd.Env = append(os.Environ(), "ATTEST_TIMING_CHILD=1")
205 cmd.Stdout, cmd.Stderr = w, w
206 began := time.Now()
207 cmd.Run()
208 took := time.Since(began)
209 cancel()
210 w.Close()
211 r.Close()
212 if code := cmd.ProcessState.ExitCode(); code != survived {
213 t.Errorf("timing output to a pipe nobody reads (full: %v) ended the run: %v", full, cmd.ProcessState)
214 }
215 // Three writes: the first to each stream waits out its deadline,
216 // and the second to stdout is dropped at once.
217 if took > 2*timingDeadline+5*time.Second {
218 t.Errorf("timing output to a pipe nobody reads (full: %v) held the run for %v", full, took)
219 }
220 }
221}
222
223// A run without --timings asks the nix store nothing beyond what its
224// statements need. A run with it asks whether each output is already
225// there; a store that does not answer in time makes the answer "unknown",
226// and the check is built all the same. nix and nix-store are stand-ins
227// that log what they are asked.
228func TestOnlyATimedRunAsksTheStoreAboutOutputs(t *testing.T) {
229 dir := t.TempDir()
230 calls := filepath.Join(dir, "calls")
231 drv := filepath.Join(dir, "check.drv")
232 built := filepath.Join(dir, "out")
233 bin := filepath.Join(dir, "bin")
234 for path, content := range map[string]string{
235 drv: "Derive()",
236 filepath.Join(built, "passed"): "",
237 filepath.Join(bin, "nix"): `#!/bin/sh
238echo "nix $*" >> "$STUB_CALLS"
239case "$1" in
240eval) echo "$STUB_DRV" ;;
241build) echo "$STUB_OUT" ;;
242esac
243`,
244 filepath.Join(bin, "nix-store"): `#!/bin/sh
245echo "nix-store $*" >> "$STUB_CALLS"
246case "$1 $2" in
247"--query --references") echo /nix/store/00000000000000000000000000000000-input ;;
248"--query --outputs") [ -z "$STUB_HANG" ] || exec sleep 30; echo "$STUB_OUT" ;;
249esac
250`,
251 } {
252 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
253 t.Fatal(err)
254 }
255 if err := os.WriteFile(path, []byte(content), 0o755); err != nil {
256 t.Fatal(err)
257 }
258 }
259 t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
260 t.Setenv("STUB_CALLS", calls)
261 t.Setenv("STUB_DRV", drv)
262 t.Setenv("STUB_OUT", built)
263 deadline := probeDeadline
264 probeDeadline = 200 * time.Millisecond
265 t.Cleanup(func() { probeDeadline = deadline })
266
267 run := func(probe bool) (checkOutcome, string) {
268 t.Helper()
269 os.Remove(calls)
270 out, err := runPure(dir, "x86_64-linux", checkSpec{name: "tree-ok", attribute: "tree-ok"}, probe)
271 if err != nil {
272 t.Fatal(err)
273 }
274 if !out.passed {
275 t.Fatalf("the check did not pass: %s", out.log)
276 }
277 asked, err := os.ReadFile(calls)
278 if err != nil {
279 t.Fatal(err)
280 }
281 return out, string(asked)
282 }
283 probed := func(asked string) bool {
284 return strings.Contains(asked, "--outputs") || strings.Contains(asked, "--check-validity")
285 }
286
287 if out, asked := run(false); probed(asked) || out.satisfied != "" {
288 t.Errorf("a run without --timings asked about outputs (satisfied %q):\n%s", out.satisfied, asked)
289 }
290 if out, asked := run(true); !probed(asked) || out.satisfied != satisfiedCached {
291 t.Errorf("a run with --timings did not find its output cached (satisfied %q):\n%s", out.satisfied, asked)
292 }
293 t.Setenv("STUB_HANG", "1")
294 began := time.Now()
295 if out, asked := run(true); !strings.Contains(asked, "nix build") || out.satisfied != satisfiedUnknown {
296 t.Errorf("a store that does not answer left satisfied %q:\n%s", out.satisfied, asked)
297 }
298 if took := time.Since(began); took > 10*time.Second {
299 t.Errorf("a store that does not answer held the check for %v", took)
300 }
301}
302
303func TestTimingsPathFollowsXDGStateHome(t *testing.T) {
304 home := t.TempDir()
305 t.Setenv("HOME", home)
306 fallback := filepath.Join(home, ".local", "state", "valley", "timings.jsonl")
307 for _, c := range []struct{ state, want string }{
308 {"/var/lib/someone/state", "/var/lib/someone/state/valley/timings.jsonl"},
309 {"", fallback},
310 // The specification ignores a relative path.
311 {"relative/state", fallback},
312 } {
313 t.Setenv("XDG_STATE_HOME", c.state)
314 got, err := timingsPath()
315 if err != nil {
316 t.Fatal(err)
317 }
318 if got != c.want {
319 t.Errorf("XDG_STATE_HOME=%q: %s, want %s", c.state, got, c.want)
320 }
321 }
322}
323
324// A remote can carry a token, in its user name, its password, its query or
325// its fragment, and the log is not the place for any of them. What names
326// the repository is kept, and a remote that cannot be read as one of the
327// forms git takes is withheld.
328func TestTheRepositoryNameCarriesNoCredentials(t *testing.T) {
329 for remote, want := range map[string]string{
330 "https://someone:ghp_token@forge.example/project.git": "https://forge.example/project.git",
331 "https://forge.example/project.git?access_token=SECRET": "https://forge.example/project.git",
332 "https://forge.example/project.git#SECRET": "https://forge.example/project.git",
333 "https://someone:SECRET@forge.example/project.git?token=SECRET#SECRET": "https://forge.example/project.git",
334 "ssh://git@valley.example:2222/project.git": "ssh://valley.example:2222/project.git",
335 "file:///srv/git/project.git": "file:///srv/git/project.git",
336 "git@valley.example:project.git": "valley.example:project.git",
337 "/srv/git/project.git": "/srv/git/project.git",
338 "../project.git": "../project.git",
339 "someone:SECRET@valley.example:project.git": "",
340 "valley.example:project.git?token=SECRET": "",
341 "https://forge.example:SECRET/project.git": "",
342 "persistent-https::https://someone:SECRET@forge.example/project.git": "",
343 "ext::ssh -i SECRET valley.example %S project.git": "",
344 } {
345 if got := remoteIdentifier(remote); got != want {
346 t.Errorf("%s: %q, want %q", remote, got, want)
347 }
348 }
349
350 // A withheld origin names the repository by its main working tree.
351 repo := t.TempDir()
352 for _, args := range [][]string{
353 {"init", "--quiet", repo},
354 {"-C", repo, "remote", "add", "origin", "someone:SECRET@valley.example:project.git"},
355 } {
356 if out, err := exec.Command("git", args...).CombinedOutput(); err != nil {
357 t.Fatalf("git %v: %v: %s", args, err, out)
358 }
359 }
360 want, err := filepath.EvalSymlinks(repo)
361 if err != nil {
362 t.Fatal(err)
363 }
364 if got := repositoryName(repo); got != want {
365 t.Errorf("a repository whose origin is withheld is named %q, want %q", got, want)
366 }
367}