gunk-dev/the-valley

timing_test.go

sourceb88442951ad7main's published tip history
12.6 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 that cannot be written says so once and goes on: the run it
83// belongs to is not failed by it, and is not made to repeat the warning
84// for every check after the first.
85func TestAnUnwritableTimingLogOnlyWarns(t *testing.T) {
86 // A directory that is a regular file cannot be written under, whoever
87 // runs the test.
88 blocker := filepath.Join(t.TempDir(), "state")
89 if err := os.WriteFile(blocker, []byte("not a directory\n"), 0o644); err != nil {
90 t.Fatal(err)
91 }
92 var warned bytes.Buffer
93 log := &timingLog{path: filepath.Join(blocker, "valley", "timings.jsonl"), warn: &warned}
94 for _, check := range []string{"one", "two", "three"} {
95 log.append(checkTiming{Check: check, Result: "passed"})
96 }
97 lines := strings.Split(strings.TrimSuffix(warned.String(), "\n"), "\n")
98 if len(lines) != 1 || !strings.HasPrefix(lines[0], "attest: warning: timings not logged: ") {
99 t.Fatalf("an unwritable log warned %q, want one warning line", warned.String())
100 }
101}
102
103// The log is a regular file. Anything else at its path is refused at once,
104// with one warning, and is written nothing. A FIFO nobody reads would hold
105// the open forever, and one somebody reads would hand them the log.
106func TestATimingLogThatIsNotARegularFileIsRefused(t *testing.T) {
107 for _, reading := range []bool{false, true} {
108 path := filepath.Join(t.TempDir(), "timings.jsonl")
109 if err := syscall.Mkfifo(path, 0o600); err != nil {
110 t.Fatal(err)
111 }
112 var reader *os.File
113 if reading {
114 fd, err := syscall.Open(path, syscall.O_RDONLY|syscall.O_NONBLOCK, 0)
115 if err != nil {
116 t.Fatal(err)
117 }
118 reader = os.NewFile(uintptr(fd), path)
119 defer reader.Close()
120 }
121 var warned bytes.Buffer
122 log := &timingLog{path: path, warn: &warned}
123 began := time.Now()
124 for _, check := range []string{"one", "two"} {
125 log.append(checkTiming{Check: check, Result: "passed"})
126 }
127 if took := time.Since(began); took >= timingDeadline {
128 t.Errorf("a FIFO at the log's path (read: %v) held the run for %v", reading, took)
129 }
130 if lines := strings.Split(strings.TrimSuffix(warned.String(), "\n"), "\n"); len(lines) != 1 ||
131 !strings.HasSuffix(lines[0], path+" is not a regular file") {
132 t.Errorf("a FIFO at the log's path (read: %v) warned %q, want one warning", reading, warned.String())
133 }
134 if reading {
135 if n, _ := reader.Read(make([]byte, 1)); n != 0 {
136 t.Errorf("a FIFO at the log's path was written to")
137 }
138 }
139 }
140}
141
142// Timing output to a standard stream nobody reads is dropped, and is never
143// what ends a run or holds it up. Go ends a process whose write to its own
144// standard output fails because nobody reads it, so each case runs in a
145// child: this test again, with both standard streams one pipe. In one, the
146// pipe's reader has gone. In the other, the pipe is full and its reader
147// never reads.
148func TestTimingOutputNobodyReadsIsDropped(t *testing.T) {
149 const survived = 3
150 if os.Getenv("ATTEST_TIMING_CHILD") != "" {
151 fmt.Fprintln(timingStdout(), "time one passed 1ms (ran)")
152 fmt.Fprintln(timingStderr(), "attest: warning: timings not logged: a test")
153 fmt.Fprintln(timingStdout(), "time two passed 1ms (ran)")
154 os.Exit(survived)
155 }
156 for _, full := range []bool{false, true} {
157 r, w, err := os.Pipe()
158 if err != nil {
159 t.Fatal(err)
160 }
161 if full {
162 // The write end is non-blocking until the child is given it,
163 // so it fills until a write would wait.
164 w.SetWriteDeadline(time.Now().Add(100 * time.Millisecond))
165 for err == nil {
166 _, err = w.Write(make([]byte, 1<<16))
167 }
168 w.SetWriteDeadline(time.Time{})
169 } else {
170 r.Close()
171 }
172 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
173 cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestTimingOutputNobodyReadsIsDropped$")
174 cmd.Env = append(os.Environ(), "ATTEST_TIMING_CHILD=1")
175 cmd.Stdout, cmd.Stderr = w, w
176 began := time.Now()
177 cmd.Run()
178 took := time.Since(began)
179 cancel()
180 w.Close()
181 r.Close()
182 if code := cmd.ProcessState.ExitCode(); code != survived {
183 t.Errorf("timing output to a pipe nobody reads (full: %v) ended the run: %v", full, cmd.ProcessState)
184 }
185 // Three writes: the first to each stream waits out its deadline,
186 // and the second to stdout is dropped at once.
187 if took > 2*timingDeadline+5*time.Second {
188 t.Errorf("timing output to a pipe nobody reads (full: %v) held the run for %v", full, took)
189 }
190 }
191}
192
193// A run without --timings asks the nix store nothing beyond what its
194// statements need. A run with it asks whether each output is already
195// there; a store that does not answer in time makes the answer "unknown",
196// and the check is built all the same. nix and nix-store are stand-ins
197// that log what they are asked.
198func TestOnlyATimedRunAsksTheStoreAboutOutputs(t *testing.T) {
199 dir := t.TempDir()
200 calls := filepath.Join(dir, "calls")
201 drv := filepath.Join(dir, "check.drv")
202 built := filepath.Join(dir, "out")
203 bin := filepath.Join(dir, "bin")
204 for path, content := range map[string]string{
205 drv: "Derive()",
206 filepath.Join(built, "passed"): "",
207 filepath.Join(bin, "nix"): `#!/bin/sh
208echo "nix $*" >> "$STUB_CALLS"
209case "$1" in
210eval) echo "$STUB_DRV" ;;
211build) echo "$STUB_OUT" ;;
212esac
213`,
214 filepath.Join(bin, "nix-store"): `#!/bin/sh
215echo "nix-store $*" >> "$STUB_CALLS"
216case "$1 $2" in
217"--query --references") echo /nix/store/00000000000000000000000000000000-input ;;
218"--query --outputs") [ -z "$STUB_HANG" ] || exec sleep 30; echo "$STUB_OUT" ;;
219esac
220`,
221 } {
222 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
223 t.Fatal(err)
224 }
225 if err := os.WriteFile(path, []byte(content), 0o755); err != nil {
226 t.Fatal(err)
227 }
228 }
229 t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
230 t.Setenv("STUB_CALLS", calls)
231 t.Setenv("STUB_DRV", drv)
232 t.Setenv("STUB_OUT", built)
233 deadline := probeDeadline
234 probeDeadline = 200 * time.Millisecond
235 t.Cleanup(func() { probeDeadline = deadline })
236
237 run := func(probe bool) (checkOutcome, string) {
238 t.Helper()
239 os.Remove(calls)
240 out, err := runPure(dir, "x86_64-linux", checkSpec{name: "tree-ok", attribute: "tree-ok"}, probe)
241 if err != nil {
242 t.Fatal(err)
243 }
244 if !out.passed {
245 t.Fatalf("the check did not pass: %s", out.log)
246 }
247 asked, err := os.ReadFile(calls)
248 if err != nil {
249 t.Fatal(err)
250 }
251 return out, string(asked)
252 }
253 probed := func(asked string) bool {
254 return strings.Contains(asked, "--outputs") || strings.Contains(asked, "--check-validity")
255 }
256
257 if out, asked := run(false); probed(asked) || out.satisfied != "" {
258 t.Errorf("a run without --timings asked about outputs (satisfied %q):\n%s", out.satisfied, asked)
259 }
260 if out, asked := run(true); !probed(asked) || out.satisfied != satisfiedCached {
261 t.Errorf("a run with --timings did not find its output cached (satisfied %q):\n%s", out.satisfied, asked)
262 }
263 t.Setenv("STUB_HANG", "1")
264 began := time.Now()
265 if out, asked := run(true); !strings.Contains(asked, "nix build") || out.satisfied != satisfiedUnknown {
266 t.Errorf("a store that does not answer left satisfied %q:\n%s", out.satisfied, asked)
267 }
268 if took := time.Since(began); took > 10*time.Second {
269 t.Errorf("a store that does not answer held the check for %v", took)
270 }
271}
272
273func TestTimingsPathFollowsXDGStateHome(t *testing.T) {
274 home := t.TempDir()
275 t.Setenv("HOME", home)
276 fallback := filepath.Join(home, ".local", "state", "valley", "timings.jsonl")
277 for _, c := range []struct{ state, want string }{
278 {"/var/lib/someone/state", "/var/lib/someone/state/valley/timings.jsonl"},
279 {"", fallback},
280 // The specification ignores a relative path.
281 {"relative/state", fallback},
282 } {
283 t.Setenv("XDG_STATE_HOME", c.state)
284 got, err := timingsPath()
285 if err != nil {
286 t.Fatal(err)
287 }
288 if got != c.want {
289 t.Errorf("XDG_STATE_HOME=%q: %s, want %s", c.state, got, c.want)
290 }
291 }
292}
293
294// A remote can carry a token, in its user name, its password, its query or
295// its fragment, and the log is not the place for any of them. What names
296// the repository is kept, and a remote that cannot be read as one of the
297// forms git takes is withheld.
298func TestTheRepositoryNameCarriesNoCredentials(t *testing.T) {
299 for remote, want := range map[string]string{
300 "https://someone:ghp_token@forge.example/project.git": "https://forge.example/project.git",
301 "https://forge.example/project.git?access_token=SECRET": "https://forge.example/project.git",
302 "https://forge.example/project.git#SECRET": "https://forge.example/project.git",
303 "https://someone:SECRET@forge.example/project.git?token=SECRET#SECRET": "https://forge.example/project.git",
304 "ssh://git@valley.example:2222/project.git": "ssh://valley.example:2222/project.git",
305 "file:///srv/git/project.git": "file:///srv/git/project.git",
306 "git@valley.example:project.git": "valley.example:project.git",
307 "/srv/git/project.git": "/srv/git/project.git",
308 "../project.git": "../project.git",
309 "someone:SECRET@valley.example:project.git": "",
310 "valley.example:project.git?token=SECRET": "",
311 "https://forge.example:SECRET/project.git": "",
312 "persistent-https::https://someone:SECRET@forge.example/project.git": "",
313 "ext::ssh -i SECRET valley.example %S project.git": "",
314 } {
315 if got := remoteIdentifier(remote); got != want {
316 t.Errorf("%s: %q, want %q", remote, got, want)
317 }
318 }
319
320 // A withheld origin names the repository by its main working tree.
321 repo := t.TempDir()
322 for _, args := range [][]string{
323 {"init", "--quiet", repo},
324 {"-C", repo, "remote", "add", "origin", "someone:SECRET@valley.example:project.git"},
325 } {
326 if out, err := exec.Command("git", args...).CombinedOutput(); err != nil {
327 t.Fatalf("git %v: %v: %s", args, err, out)
328 }
329 }
330 want, err := filepath.EvalSymlinks(repo)
331 if err != nil {
332 t.Fatal(err)
333 }
334 if got := repositoryName(repo); got != want {
335 t.Errorf("a repository whose origin is withheld is named %q, want %q", got, want)
336 }
337}