package mac import ( "context" "encoding/json" "errors" "os" "os/exec" "path/filepath" "slices" "strconv" "strings" "sync" "syscall" "testing" "time" ) // fakeSRT stands in for srt on Linux: it needs --settings -- and a // readable JSON file, runs the command through a shell as srt does, // sets its TMPDIR as srt 0.0.81 does (CLAUDE_CODE_TMPDIR, else // CLAUDE_TMPDIR, else /tmp/claude), and exits 0 when the command dies of // SIGTERM, as srt's cli does. const fakeSRT = `#!/bin/bash [ "$1" = --settings ] && [ "$3" = -- ] || exit 97 python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$2" || exit 98 cp "$2" "$FAKE_SRT_SEEN" shift 3 export TMPDIR="${CLAUDE_CODE_TMPDIR:-${CLAUDE_TMPDIR:-/tmp/claude}}" "$@" s=$? [ "$s" = 143 ] && exit 0 exit "$s" ` func gateFixture(t *testing.T, sandboxed bool) (*Gate, string) { t.Helper() root := t.TempDir() dir := filepath.Join(root, "tree") if err := os.MkdirAll(dir, 0700); err != nil { t.Fatal(err) } 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"} if sandboxed { srt := filepath.Join(root, "srt") if err := os.WriteFile(srt, []byte(fakeSRT), 0700); err != nil { t.Fatal(err) } g.SRT, g.Sandbox = srt, "seatbelt" g.Settings = func(tree, attempt string) ([]byte, error) { return json.Marshal(map[string]string{"tree": tree, "attempt": attempt}) } } return g, dir } func run(g *Gate, dir, attempt string, limit time.Duration, script string) (Result, string) { var id string res := g.Run(context.Background(), attempt, dir, []string{"/bin/bash", "-c", script}, limit, func(s string) error { id = s; return nil }) return res, id } // Pass and fail are srt's exit and the recorded status agreeing; the // profile is written beside the tree for that attempt and removed. func TestGateRunsUnderSRT(t *testing.T) { g, dir := gateFixture(t, true) res, id := run(g, dir, "checks-a-1", time.Minute, "echo hello; exit 0") if res.Code != 0 || !res.Terminated || res.Reason != "" || res.Sandbox != "seatbelt" || res.Output != "hello" { t.Fatalf("pass: %+v", res) } if !strings.HasPrefix(id, "pg:") || !strings.HasSuffix(id, ":checks-a-1") { t.Fatalf("record %q", id) } var seen map[string]string raw, _ := os.ReadFile(filepath.Join(filepath.Dir(dir), "seen.json")) if json.Unmarshal(raw, &seen) != nil || seen["tree"] != dir || !strings.HasPrefix(seen["attempt"], filepath.Dir(dir)+"/attempt-") { t.Fatalf("srt saw %s", raw) } left, _ := filepath.Glob(filepath.Join(filepath.Dir(dir), "srt-settings-*")) scratch, _ := filepath.Glob(filepath.Join(filepath.Dir(dir), "attempt-*")) if len(left) != 0 || len(scratch) != 0 { t.Fatalf("left behind: %v %v", left, scratch) } if res, _ = run(g, dir, "checks-a-2", time.Minute, "echo no; exit 3"); res.Code != 3 || res.Sandbox != "seatbelt" { t.Fatalf("fail: %+v", res) } } // srt exits 0 when its command dies of SIGTERM. A gate that kills the // shell recording its status, or exits 143, is never a pass. func TestGateSIGTERMIsNotAPass(t *testing.T) { g, dir := gateFixture(t, true) if res, _ := run(g, dir, "checks-b-1", time.Minute, "kill -TERM $PPID; sleep 2"); res.Code == 0 { t.Fatalf("killed status shell passed: %+v", res) } if res, _ := run(g, dir, "checks-b-2", time.Minute, "kill -TERM $$"); res.Code == 0 { t.Fatalf("gate killed by SIGTERM passed: %+v", res) } } // The gate's environment is the gate's alone: nothing of the runner's // own reaches it, and TMPDIR is the attempt's scratch. func TestGateEnvironmentFromScratch(t *testing.T) { t.Setenv("EQUIPO_SECRET_SENTINEL", "leak") g, dir := gateFixture(t, false) res, _ := run(g, dir, "checks-c-1", time.Minute, "env | sort") if res.Code != 0 || res.Sandbox != "none" { t.Fatalf("%+v", res) } var names []string for _, l := range strings.Split(res.Output, "\n") { k, v, _ := strings.Cut(l, "=") if k == "TMPDIR" && !strings.HasPrefix(v, filepath.Dir(dir)+"/attempt-") { t.Fatalf("TMPDIR %s", v) } names = append(names, k) } for _, k := range names { if !slices.Contains([]string{"HOME", "PATH", "CI", "FAKE_SRT_SEEN", "TMPDIR", "EQUIPO_ATTEMPT", "EQUIPO_GATE_STATUS", "PWD", "SHLVL", "_", "OLDPWD"}, k) { t.Fatalf("unexpected variable %s in %s", k, res.Output) } } } // Under srt TMPDIR is still the attempt's own scratch, not srt's shared // /tmp/claude: what a check leaves there goes with the attempt, and no // other user's /tmp/claude decides whether it can write. func TestGateKeepsTMPDIRUnderSRT(t *testing.T) { g, dir := gateFixture(t, true) res, _ := run(g, dir, "checks-c-2", time.Minute, `echo "$TMPDIR"; echo "$XDG_CONFIG_HOME"`) lines := strings.Split(res.Output, "\n") if res.Code != 0 || len(lines) != 2 || !strings.HasPrefix(lines[0], filepath.Dir(dir)+"/attempt-") { t.Fatalf("TMPDIR under srt: %+v", res) } // SwiftPM's ~/.swiftpm goes to the attempt's scratch too. if lines[1] != lines[0]+"/config" { t.Fatalf("XDG_CONFIG_HOME under srt: %+v", res) } } // Cancel and timeout: SIGTERM to the group, SIGKILL after the grace, a // sweep of marked processes (a child that ignores SIGTERM and one that // left the group but kept its marker), and the proof: the group gone // and no marked process, so the attempt is terminated. func TestGateCancelAndTimeoutProveTheEnd(t *testing.T) { g, dir := gateFixture(t, true) stubborn := "trap '' TERM; (trap '' TERM; setsid sleep 60 & sleep 60) & sleep 60" ctx, cancel := context.WithCancel(context.Background()) var res Result done := make(chan struct{}) go func() { res = g.Run(ctx, "checks-d-1", dir, []string{"/bin/bash", "-c", stubborn}, time.Minute, func(string) error { return nil }) close(done) }() time.Sleep(700 * time.Millisecond) cancel() <-done if res.Reason != "cancelled" || !res.Terminated { t.Fatalf("cancel: %+v", res) } if left, _ := Marked("checks-d-1"); len(left) != 0 { t.Fatalf("marked processes left: %v", left) } res, _ = run(g, dir, "checks-d-2", 500*time.Millisecond, stubborn) if res.Reason != "checks_timeout" || !res.Terminated { t.Fatalf("timeout: %+v", res) } if left, _ := Marked("checks-d-2"); len(left) != 0 { t.Fatalf("marked processes left: %v", left) } } // The simulators an attempt booted are shut down after it; the ones that // were already up are left alone. func TestGateShutsDownWhatItBooted(t *testing.T) { g, dir := gateFixture(t, false) var mu sync.Mutex booted, down := []string{"A"}, []string{} g.Booted = func(context.Context) []string { mu.Lock(); defer mu.Unlock(); return slices.Clone(booted) } g.Shutdown = func(_ context.Context, u string) { mu.Lock(); down = append(down, u); mu.Unlock() } res := g.Run(context.Background(), "checks-e-1", dir, []string{"/bin/sh", "-c", "true"}, time.Minute, func(id string) error { if !strings.HasPrefix(id, "pg:0:") { mu.Lock() booted = append(booted, "B") mu.Unlock() } return nil }) if res.Code != 0 || !slices.Equal(down, []string{"B"}) { t.Fatalf("%+v shut down %v", res, down) } } // After a restart a recorded attempt is settled: its marked processes // are killed. A group id since reused by an unmarked process is left // alone, and not taken as over while it lives. func TestGateVerifyAfterRestart(t *testing.T) { g, _ := gateFixture(t, false) marked := exec.Command("/bin/sleep", "60") marked.Env = []string{"EQUIPO_ATTEMPT=checks-f-1"} marked.SysProcAttr = &syscall.SysProcAttr{Setsid: true} other := exec.Command("/bin/sleep", "60") other.SysProcAttr = &syscall.SysProcAttr{Setsid: true} for _, c := range []*exec.Cmd{marked, other} { if err := c.Start(); err != nil { t.Fatal(err) } defer func(c *exec.Cmd) { _ = c.Process.Kill(); _ = c.Wait() }(c) } waited := make(chan error, 1) go func() { waited <- marked.Wait() }() if !g.Verify(RecordID(marked.Process.Pid, "checks-f-1")) { t.Fatal("marked attempt not settled") } select { case <-waited: case <-time.After(5 * time.Second): t.Fatal("marked process still running") } g.Settle = 300 * time.Millisecond if g.Verify(RecordID(other.Process.Pid, "checks-f-2")) { t.Fatal("proven over while its recorded group is alive") } if syscall.Kill(other.Process.Pid, 0) != nil { t.Fatal("an unmarked group with a reused id was killed") } if g.Verify("pg:1:x") || g.Verify("ns:abc") || g.Verify("pg:"+strconv.Itoa(other.Process.Pid)+":") { t.Fatal("malformed record accepted") } } // ps -E output: the marker must be a whole word of the environment. func TestParseMarked(t *testing.T) { out := " 101 101 /bin/bash -c make ci HOME=/Users/e EQUIPO_ATTEMPT=checks/a-1 TMPDIR=/x\n" + " 102 101 xcodebuild test EQUIPO_ATTEMPT=checks/a-10\n" + " 103 103 sleep 9 EQUIPO_ATTEMPT=checks/a-1\n" + " 104 104 grep EQUIPO_ATTEMPT=checks/a-1x\n" + " 555 555 equipo-runner run EQUIPO_ATTEMPT=checks/a-1\n" + "garbage\n" got := ParseMarked(out, "checks/a-1", 555) if !slices.Equal(got, []Proc{{PID: 101, PGID: 101}, {PID: 103, PGID: 103}}) { t.Fatalf("%v", got) } } func TestTailKeepsTheLastLines(t *testing.T) { tl := &tail{max: 3} for i := range 10 { _, _ = tl.Write([]byte("line " + strconv.Itoa(i) + "\n")) } _, _ = tl.Write([]byte("partial")) if tl.String() != "line 8\nline 9\npartial" { t.Fatalf("%q", tl.String()) } } // The end is proven only when the group is gone AND nothing marked is // left: a marked process that cannot be killed keeps the attempt // unproven (no Retry), however the group fares. func TestGateUnprovenWhileMarkedRemain(t *testing.T) { g, dir := gateFixture(t, false) g.Settle = 500 * time.Millisecond g.procs = withPhantom() if res, _ := run(g, dir, "checks-g-1", time.Minute, "true"); res.Terminated { t.Fatalf("proven with a marked process left: %+v", res) } } // Retention is bounded on every write: a gate that prints without end, // with or without newlines, holds at most max lines of maxLineBytes. func TestTailIsBounded(t *testing.T) { tl := &tail{max: 200} chunk := []byte(strings.Repeat("x", 1<<20)) for range 64 { _, _ = tl.Write(chunk) } if len(tl.partial) > maxLineBytes || len(tl.String()) > maxLineBytes { t.Fatalf("a line without a newline held %d bytes", len(tl.partial)) } line := []byte(strings.Repeat("y", 10<<10) + "\n") for range 5000 { _, _ = tl.Write(line) } held := 0 for _, l := range tl.lines { held += len(l) } if len(tl.lines) > 200 || held > 200*maxLineBytes || cap(tl.lines) > 400 { t.Fatalf("held %d lines, %d bytes, cap %d", len(tl.lines), held, cap(tl.lines)) } } // The record comes first: if the marker cannot be kept, nothing runs; if // the group cannot be, the group is killed at once and the end proven. func TestGateRecordsBeforeRunning(t *testing.T) { g, dir := gateFixture(t, false) ran := filepath.Join(filepath.Dir(dir), "ran") script := "touch " + ran + "; sleep 60" var ids []string res := g.Run(context.Background(), "checks-h-1", dir, []string{"/bin/bash", "-c", script}, time.Minute, func(id string) error { ids = append(ids, id) return errors.New("disk full") }) if _, err := os.Stat(ran); !os.IsNotExist(err) || res.Code == 0 || res.Reason != "checks_unavailable" || !slices.Equal(ids, []string{"pg:0:checks-h-1"}) { t.Fatalf("ran without a record: %+v %v", res, ids) } ids = nil start := time.Now() res = g.Run(context.Background(), "checks-h-2", dir, []string{"/bin/bash", "-c", script}, time.Minute, func(id string) error { ids = append(ids, id) if len(ids) == 2 { return errors.New("disk full") } return nil }) 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:") { t.Fatalf("group not stopped when its record failed: %+v %v", res, ids) } if left, _ := Marked("checks-h-2"); len(left) != 0 { t.Fatalf("left %v", left) } } // After a restart an attempt that recorded only its marker (no group) is // settled by the marker: its processes are killed, then it has ended. func TestGateVerifyByMarkerAlone(t *testing.T) { g, _ := gateFixture(t, false) c := exec.Command("/bin/sleep", "60") c.Env = []string{"EQUIPO_ATTEMPT=checks-i-1"} c.SysProcAttr = &syscall.SysProcAttr{Setsid: true} if err := c.Start(); err != nil { t.Fatal(err) } waited := make(chan error, 1) go func() { waited <- c.Wait() }() // Start returns once the child has begun its exec, and the kernel shows // the new environment a moment later. On a loaded machine Verify could // look in between, see no marked process and settle: wait for the marker. for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(5 * time.Millisecond) { if marked, _ := Marked("checks-i-1"); len(marked) != 0 { break } if time.Now().After(deadline) { t.Fatal("the marked process never showed its marker") } } if !g.Verify(RecordID(0, "checks-i-1")) { t.Fatal("marker-only record not settled") } select { case <-waited: case <-time.After(5 * time.Second): t.Fatal("marked process survived") } if g.Verify("") || g.Verify("pg:-1:x") { t.Fatal("an empty or malformed record taken as ended") } }