oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package mac
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "slices"
11 "strconv"
12 "strings"
13 "sync"
14 "syscall"
15 "testing"
16 "time"
17)
18
19// fakeSRT stands in for srt on Linux: it needs --settings <file> -- and a
20// readable JSON file, runs the command through a shell as srt does,
21// sets its TMPDIR as srt 0.0.81 does (CLAUDE_CODE_TMPDIR, else
22// CLAUDE_TMPDIR, else /tmp/claude), and exits 0 when the command dies of
23// SIGTERM, as srt's cli does.
24const fakeSRT = `#!/bin/bash
25[ "$1" = --settings ] && [ "$3" = -- ] || exit 97
26python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$2" || exit 98
27cp "$2" "$FAKE_SRT_SEEN"
28shift 3
29export TMPDIR="${CLAUDE_CODE_TMPDIR:-${CLAUDE_TMPDIR:-/tmp/claude}}"
30"$@"
31s=$?
32[ "$s" = 143 ] && exit 0
33exit "$s"
34`
35
36func gateFixture(t *testing.T, sandboxed bool) (*Gate, string) {
37 t.Helper()
38 root := t.TempDir()
39 dir := filepath.Join(root, "tree")
40 if err := os.MkdirAll(dir, 0700); err != nil {
41 t.Fatal(err)
42 }
43 g := &Gate{Env: []string{"HOME=" + root, "PATH=/usr/bin:/bin", "CI=1", "FAKE_SRT_SEEN=" + filepath.Join(root, "seen.json")}, Grace: 300 * time.Millisecond, Settle: 5 * time.Second, Lines: 200, Sandbox: "none"}
44 if sandboxed {
45 srt := filepath.Join(root, "srt")
46 if err := os.WriteFile(srt, []byte(fakeSRT), 0700); err != nil {
47 t.Fatal(err)
48 }
49 g.SRT, g.Sandbox = srt, "seatbelt"
50 g.Settings = func(tree, attempt string) ([]byte, error) {
51 return json.Marshal(map[string]string{"tree": tree, "attempt": attempt})
52 }
53 }
54 return g, dir
55}
56
57func run(g *Gate, dir, attempt string, limit time.Duration, script string) (Result, string) {
58 var id string
59 res := g.Run(context.Background(), attempt, dir, []string{"/bin/bash", "-c", script}, limit, func(s string) error { id = s; return nil })
60 return res, id
61}
62
63// Pass and fail are srt's exit and the recorded status agreeing; the
64// profile is written beside the tree for that attempt and removed.
65func TestGateRunsUnderSRT(t *testing.T) {
66 g, dir := gateFixture(t, true)
67 res, id := run(g, dir, "checks-a-1", time.Minute, "echo hello; exit 0")
68 if res.Code != 0 || !res.Terminated || res.Reason != "" || res.Sandbox != "seatbelt" || res.Output != "hello" {
69 t.Fatalf("pass: %+v", res)
70 }
71 if !strings.HasPrefix(id, "pg:") || !strings.HasSuffix(id, ":checks-a-1") {
72 t.Fatalf("record %q", id)
73 }
74 var seen map[string]string
75 raw, _ := os.ReadFile(filepath.Join(filepath.Dir(dir), "seen.json"))
76 if json.Unmarshal(raw, &seen) != nil || seen["tree"] != dir || !strings.HasPrefix(seen["attempt"], filepath.Dir(dir)+"/attempt-") {
77 t.Fatalf("srt saw %s", raw)
78 }
79 left, _ := filepath.Glob(filepath.Join(filepath.Dir(dir), "srt-settings-*"))
80 scratch, _ := filepath.Glob(filepath.Join(filepath.Dir(dir), "attempt-*"))
81 if len(left) != 0 || len(scratch) != 0 {
82 t.Fatalf("left behind: %v %v", left, scratch)
83 }
84 if res, _ = run(g, dir, "checks-a-2", time.Minute, "echo no; exit 3"); res.Code != 3 || res.Sandbox != "seatbelt" {
85 t.Fatalf("fail: %+v", res)
86 }
87}
88
89// srt exits 0 when its command dies of SIGTERM. A gate that kills the
90// shell recording its status, or exits 143, is never a pass.
91func TestGateSIGTERMIsNotAPass(t *testing.T) {
92 g, dir := gateFixture(t, true)
93 if res, _ := run(g, dir, "checks-b-1", time.Minute, "kill -TERM $PPID; sleep 2"); res.Code == 0 {
94 t.Fatalf("killed status shell passed: %+v", res)
95 }
96 if res, _ := run(g, dir, "checks-b-2", time.Minute, "kill -TERM $$"); res.Code == 0 {
97 t.Fatalf("gate killed by SIGTERM passed: %+v", res)
98 }
99}
100
101// The gate's environment is the gate's alone: nothing of the runner's
102// own reaches it, and TMPDIR is the attempt's scratch.
103func TestGateEnvironmentFromScratch(t *testing.T) {
104 t.Setenv("EQUIPO_SECRET_SENTINEL", "leak")
105 g, dir := gateFixture(t, false)
106 res, _ := run(g, dir, "checks-c-1", time.Minute, "env | sort")
107 if res.Code != 0 || res.Sandbox != "none" {
108 t.Fatalf("%+v", res)
109 }
110 var names []string
111 for _, l := range strings.Split(res.Output, "\n") {
112 k, v, _ := strings.Cut(l, "=")
113 if k == "TMPDIR" && !strings.HasPrefix(v, filepath.Dir(dir)+"/attempt-") {
114 t.Fatalf("TMPDIR %s", v)
115 }
116 names = append(names, k)
117 }
118 for _, k := range names {
119 if !slices.Contains([]string{"HOME", "PATH", "CI", "FAKE_SRT_SEEN", "TMPDIR", "EQUIPO_ATTEMPT", "EQUIPO_GATE_STATUS", "PWD", "SHLVL", "_", "OLDPWD"}, k) {
120 t.Fatalf("unexpected variable %s in %s", k, res.Output)
121 }
122 }
123}
124
125// Under srt TMPDIR is still the attempt's own scratch, not srt's shared
126// /tmp/claude: what a check leaves there goes with the attempt, and no
127// other user's /tmp/claude decides whether it can write.
128func TestGateKeepsTMPDIRUnderSRT(t *testing.T) {
129 g, dir := gateFixture(t, true)
130 res, _ := run(g, dir, "checks-c-2", time.Minute, `echo "$TMPDIR"; echo "$XDG_CONFIG_HOME"`)
131 lines := strings.Split(res.Output, "\n")
132 if res.Code != 0 || len(lines) != 2 || !strings.HasPrefix(lines[0], filepath.Dir(dir)+"/attempt-") {
133 t.Fatalf("TMPDIR under srt: %+v", res)
134 }
135 // SwiftPM's ~/.swiftpm goes to the attempt's scratch too.
136 if lines[1] != lines[0]+"/config" {
137 t.Fatalf("XDG_CONFIG_HOME under srt: %+v", res)
138 }
139}
140
141// Cancel and timeout: SIGTERM to the group, SIGKILL after the grace, a
142// sweep of marked processes (a child that ignores SIGTERM and one that
143// left the group but kept its marker), and the proof: the group gone
144// and no marked process, so the attempt is terminated.
145func TestGateCancelAndTimeoutProveTheEnd(t *testing.T) {
146 g, dir := gateFixture(t, true)
147 stubborn := "trap '' TERM; (trap '' TERM; setsid sleep 60 & sleep 60) & sleep 60"
148 ctx, cancel := context.WithCancel(context.Background())
149 var res Result
150 done := make(chan struct{})
151 go func() {
152 res = g.Run(ctx, "checks-d-1", dir, []string{"/bin/bash", "-c", stubborn}, time.Minute, func(string) error { return nil })
153 close(done)
154 }()
155 time.Sleep(700 * time.Millisecond)
156 cancel()
157 <-done
158 if res.Reason != "cancelled" || !res.Terminated {
159 t.Fatalf("cancel: %+v", res)
160 }
161 if left, _ := Marked("checks-d-1"); len(left) != 0 {
162 t.Fatalf("marked processes left: %v", left)
163 }
164 res, _ = run(g, dir, "checks-d-2", 500*time.Millisecond, stubborn)
165 if res.Reason != "checks_timeout" || !res.Terminated {
166 t.Fatalf("timeout: %+v", res)
167 }
168 if left, _ := Marked("checks-d-2"); len(left) != 0 {
169 t.Fatalf("marked processes left: %v", left)
170 }
171}
172
173// The simulators an attempt booted are shut down after it; the ones that
174// were already up are left alone.
175func TestGateShutsDownWhatItBooted(t *testing.T) {
176 g, dir := gateFixture(t, false)
177 var mu sync.Mutex
178 booted, down := []string{"A"}, []string{}
179 g.Booted = func(context.Context) []string { mu.Lock(); defer mu.Unlock(); return slices.Clone(booted) }
180 g.Shutdown = func(_ context.Context, u string) { mu.Lock(); down = append(down, u); mu.Unlock() }
181 res := g.Run(context.Background(), "checks-e-1", dir, []string{"/bin/sh", "-c", "true"}, time.Minute, func(id string) error {
182 if !strings.HasPrefix(id, "pg:0:") {
183 mu.Lock()
184 booted = append(booted, "B")
185 mu.Unlock()
186 }
187 return nil
188 })
189 if res.Code != 0 || !slices.Equal(down, []string{"B"}) {
190 t.Fatalf("%+v shut down %v", res, down)
191 }
192}
193
194// After a restart a recorded attempt is settled: its marked processes
195// are killed. A group id since reused by an unmarked process is left
196// alone, and not taken as over while it lives.
197func TestGateVerifyAfterRestart(t *testing.T) {
198 g, _ := gateFixture(t, false)
199 marked := exec.Command("/bin/sleep", "60")
200 marked.Env = []string{"EQUIPO_ATTEMPT=checks-f-1"}
201 marked.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
202 other := exec.Command("/bin/sleep", "60")
203 other.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
204 for _, c := range []*exec.Cmd{marked, other} {
205 if err := c.Start(); err != nil {
206 t.Fatal(err)
207 }
208 defer func(c *exec.Cmd) { _ = c.Process.Kill(); _ = c.Wait() }(c)
209 }
210 waited := make(chan error, 1)
211 go func() { waited <- marked.Wait() }()
212 if !g.Verify(RecordID(marked.Process.Pid, "checks-f-1")) {
213 t.Fatal("marked attempt not settled")
214 }
215 select {
216 case <-waited:
217 case <-time.After(5 * time.Second):
218 t.Fatal("marked process still running")
219 }
220 g.Settle = 300 * time.Millisecond
221 if g.Verify(RecordID(other.Process.Pid, "checks-f-2")) {
222 t.Fatal("proven over while its recorded group is alive")
223 }
224 if syscall.Kill(other.Process.Pid, 0) != nil {
225 t.Fatal("an unmarked group with a reused id was killed")
226 }
227 if g.Verify("pg:1:x") || g.Verify("ns:abc") || g.Verify("pg:"+strconv.Itoa(other.Process.Pid)+":") {
228 t.Fatal("malformed record accepted")
229 }
230}
231
232// ps -E output: the marker must be a whole word of the environment.
233func TestParseMarked(t *testing.T) {
234 out := " 101 101 /bin/bash -c make ci HOME=/Users/e EQUIPO_ATTEMPT=checks/a-1 TMPDIR=/x\n" +
235 " 102 101 xcodebuild test EQUIPO_ATTEMPT=checks/a-10\n" +
236 " 103 103 sleep 9 EQUIPO_ATTEMPT=checks/a-1\n" +
237 " 104 104 grep EQUIPO_ATTEMPT=checks/a-1x\n" +
238 " 555 555 equipo-runner run EQUIPO_ATTEMPT=checks/a-1\n" +
239 "garbage\n"
240 got := ParseMarked(out, "checks/a-1", 555)
241 if !slices.Equal(got, []Proc{{PID: 101, PGID: 101}, {PID: 103, PGID: 103}}) {
242 t.Fatalf("%v", got)
243 }
244}
245
246func TestTailKeepsTheLastLines(t *testing.T) {
247 tl := &tail{max: 3}
248 for i := range 10 {
249 _, _ = tl.Write([]byte("line " + strconv.Itoa(i) + "\n"))
250 }
251 _, _ = tl.Write([]byte("partial"))
252 if tl.String() != "line 8\nline 9\npartial" {
253 t.Fatalf("%q", tl.String())
254 }
255}
256
257// The end is proven only when the group is gone AND nothing marked is
258// left: a marked process that cannot be killed keeps the attempt
259// unproven (no Retry), however the group fares.
260func TestGateUnprovenWhileMarkedRemain(t *testing.T) {
261 g, dir := gateFixture(t, false)
262 g.Settle = 500 * time.Millisecond
263 g.procs = withPhantom()
264 if res, _ := run(g, dir, "checks-g-1", time.Minute, "true"); res.Terminated {
265 t.Fatalf("proven with a marked process left: %+v", res)
266 }
267}
268
269// Retention is bounded on every write: a gate that prints without end,
270// with or without newlines, holds at most max lines of maxLineBytes.
271func TestTailIsBounded(t *testing.T) {
272 tl := &tail{max: 200}
273 chunk := []byte(strings.Repeat("x", 1<<20))
274 for range 64 {
275 _, _ = tl.Write(chunk)
276 }
277 if len(tl.partial) > maxLineBytes || len(tl.String()) > maxLineBytes {
278 t.Fatalf("a line without a newline held %d bytes", len(tl.partial))
279 }
280 line := []byte(strings.Repeat("y", 10<<10) + "\n")
281 for range 5000 {
282 _, _ = tl.Write(line)
283 }
284 held := 0
285 for _, l := range tl.lines {
286 held += len(l)
287 }
288 if len(tl.lines) > 200 || held > 200*maxLineBytes || cap(tl.lines) > 400 {
289 t.Fatalf("held %d lines, %d bytes, cap %d", len(tl.lines), held, cap(tl.lines))
290 }
291}
292
293// The record comes first: if the marker cannot be kept, nothing runs; if
294// the group cannot be, the group is killed at once and the end proven.
295func TestGateRecordsBeforeRunning(t *testing.T) {
296 g, dir := gateFixture(t, false)
297 ran := filepath.Join(filepath.Dir(dir), "ran")
298 script := "touch " + ran + "; sleep 60"
299 var ids []string
300 res := g.Run(context.Background(), "checks-h-1", dir, []string{"/bin/bash", "-c", script}, time.Minute, func(id string) error {
301 ids = append(ids, id)
302 return errors.New("disk full")
303 })
304 if _, err := os.Stat(ran); !os.IsNotExist(err) || res.Code == 0 || res.Reason != "checks_unavailable" || !slices.Equal(ids, []string{"pg:0:checks-h-1"}) {
305 t.Fatalf("ran without a record: %+v %v", res, ids)
306 }
307 ids = nil
308 start := time.Now()
309 res = g.Run(context.Background(), "checks-h-2", dir, []string{"/bin/bash", "-c", script}, time.Minute, func(id string) error {
310 ids = append(ids, id)
311 if len(ids) == 2 {
312 return errors.New("disk full")
313 }
314 return nil
315 })
316 if res.Reason != "checks_unavailable" || !res.Terminated || time.Since(start) > 20*time.Second || len(ids) != 2 || ids[0] != "pg:0:checks-h-2" || !strings.HasPrefix(ids[1], "pg:") {
317 t.Fatalf("group not stopped when its record failed: %+v %v", res, ids)
318 }
319 if left, _ := Marked("checks-h-2"); len(left) != 0 {
320 t.Fatalf("left %v", left)
321 }
322}
323
324// After a restart an attempt that recorded only its marker (no group) is
325// settled by the marker: its processes are killed, then it has ended.
326func TestGateVerifyByMarkerAlone(t *testing.T) {
327 g, _ := gateFixture(t, false)
328 c := exec.Command("/bin/sleep", "60")
329 c.Env = []string{"EQUIPO_ATTEMPT=checks-i-1"}
330 c.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
331 if err := c.Start(); err != nil {
332 t.Fatal(err)
333 }
334 waited := make(chan error, 1)
335 go func() { waited <- c.Wait() }()
336 // Start returns once the child has begun its exec, and the kernel shows
337 // the new environment a moment later. On a loaded machine Verify could
338 // look in between, see no marked process and settle: wait for the marker.
339 for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(5 * time.Millisecond) {
340 if marked, _ := Marked("checks-i-1"); len(marked) != 0 {
341 break
342 }
343 if time.Now().After(deadline) {
344 t.Fatal("the marked process never showed its marker")
345 }
346 }
347 if !g.Verify(RecordID(0, "checks-i-1")) {
348 t.Fatal("marker-only record not settled")
349 }
350 select {
351 case <-waited:
352 case <-time.After(5 * time.Second):
353 t.Fatal("marked process survived")
354 }
355 if g.Verify("") || g.Verify("pg:-1:x") {
356 t.Fatal("an empty or malformed record taken as ended")
357 }
358}
359