gunk-dev/the-valley

timing_test.go

sourcec8dae721b943main's published tip history
13.9 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 $2" in
240"eval --json") printf '{"tree-ok":"%s"}\n' "$STUB_DRV" ;;
241"eval "*) echo "$STUB_DRV" ;;
242"build "*) echo "$STUB_OUT" ;;
243esac
244`,
245 filepath.Join(bin, "nix-store"): `#!/bin/sh
246echo "nix-store $*" >> "$STUB_CALLS"
247case "$1 $2" in
248"--query --references") echo /nix/store/00000000000000000000000000000000-input ;;
249"--query --outputs") [ -z "$STUB_HANG" ] || exec sleep 30; echo "$STUB_OUT" ;;
250esac
251`,
252 } {
253 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
254 t.Fatal(err)
255 }
256 if err := os.WriteFile(path, []byte(content), 0o755); err != nil {
257 t.Fatal(err)
258 }
259 }
260 t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
261 t.Setenv("STUB_CALLS", calls)
262 t.Setenv("STUB_DRV", drv)
263 t.Setenv("STUB_OUT", built)
264 deadline := probeDeadline
265 probeDeadline = 200 * time.Millisecond
266 t.Cleanup(func() { probeDeadline = deadline })
267
268 run := func(probe bool) (checkOutcome, string) {
269 t.Helper()
270 os.Remove(calls)
271 runs := runPure(dir, "x86_64-linux", []checkSpec{{name: "tree-ok", attribute: "tree-ok"}}, probe, nil)
272 if len(runs) != 1 {
273 t.Fatalf("one check ran %d times", len(runs))
274 }
275 out, err := runs[0].out, runs[0].err
276 if err != nil {
277 t.Fatal(err)
278 }
279 if !out.passed {
280 t.Fatalf("the check did not pass: %s", out.log)
281 }
282 asked, err := os.ReadFile(calls)
283 if err != nil {
284 t.Fatal(err)
285 }
286 return out, string(asked)
287 }
288 probed := func(asked string) bool {
289 return strings.Contains(asked, "--outputs") || strings.Contains(asked, "--check-validity")
290 }
291
292 if out, asked := run(false); probed(asked) || out.satisfied != "" {
293 t.Errorf("a run without --timings asked about outputs (satisfied %q):\n%s", out.satisfied, asked)
294 }
295 if out, asked := run(true); !probed(asked) || out.satisfied != satisfiedCached {
296 t.Errorf("a run with --timings did not find its output cached (satisfied %q):\n%s", out.satisfied, asked)
297 }
298 t.Setenv("STUB_HANG", "1")
299 began := time.Now()
300 if out, asked := run(true); !strings.Contains(asked, "nix build") || out.satisfied != satisfiedUnknown {
301 t.Errorf("a store that does not answer left satisfied %q:\n%s", out.satisfied, asked)
302 }
303 if took := time.Since(began); took > 10*time.Second {
304 t.Errorf("a store that does not answer held the check for %v", took)
305 }
306}
307
308func TestTimingsPathFollowsXDGStateHome(t *testing.T) {
309 home := t.TempDir()
310 t.Setenv("HOME", home)
311 fallback := filepath.Join(home, ".local", "state", "valley", "timings.jsonl")
312 for _, c := range []struct{ state, want string }{
313 {"/var/lib/someone/state", "/var/lib/someone/state/valley/timings.jsonl"},
314 {"", fallback},
315 // The specification ignores a relative path.
316 {"relative/state", fallback},
317 } {
318 t.Setenv("XDG_STATE_HOME", c.state)
319 got, err := timingsPath()
320 if err != nil {
321 t.Fatal(err)
322 }
323 if got != c.want {
324 t.Errorf("XDG_STATE_HOME=%q: %s, want %s", c.state, got, c.want)
325 }
326 }
327}
328
329// A remote can carry a token, in its user name, its password, its query or
330// its fragment, and the log is not the place for any of them. What names
331// the repository is kept, and a remote that cannot be read as one of the
332// forms git takes is withheld.
333func TestTheRepositoryNameCarriesNoCredentials(t *testing.T) {
334 for remote, want := range map[string]string{
335 "https://someone:ghp_token@forge.example/project.git": "https://forge.example/project.git",
336 "https://forge.example/project.git?access_token=SECRET": "https://forge.example/project.git",
337 "https://forge.example/project.git#SECRET": "https://forge.example/project.git",
338 "https://someone:SECRET@forge.example/project.git?token=SECRET#SECRET": "https://forge.example/project.git",
339 "ssh://git@valley.example:2222/project.git": "ssh://valley.example:2222/project.git",
340 "file:///srv/git/project.git": "file:///srv/git/project.git",
341 "git@valley.example:project.git": "valley.example:project.git",
342 "/srv/git/project.git": "/srv/git/project.git",
343 "../project.git": "../project.git",
344 "someone:SECRET@valley.example:project.git": "",
345 "valley.example:project.git?token=SECRET": "",
346 "https://forge.example:SECRET/project.git": "",
347 "persistent-https::https://someone:SECRET@forge.example/project.git": "",
348 "ext::ssh -i SECRET valley.example %S project.git": "",
349 } {
350 if got := remoteIdentifier(remote); got != want {
351 t.Errorf("%s: %q, want %q", remote, got, want)
352 }
353 }
354
355 // A withheld origin names the repository by its main working tree.
356 repo := t.TempDir()
357 for _, args := range [][]string{
358 {"init", "--quiet", repo},
359 {"-C", repo, "remote", "add", "origin", "someone:SECRET@valley.example:project.git"},
360 } {
361 if out, err := exec.Command("git", args...).CombinedOutput(); err != nil {
362 t.Fatalf("git %v: %v: %s", args, err, out)
363 }
364 }
365 want, err := filepath.EvalSymlinks(repo)
366 if err != nil {
367 t.Fatal(err)
368 }
369 if got := repositoryName(repo); got != want {
370 t.Errorf("a repository whose origin is withheld is named %q, want %q", got, want)
371 }
372}