|
| 1 | +//go:build unix |
| 2 | + |
| 3 | +package agent |
| 4 | + |
| 5 | +import ( |
| 6 | + "context" |
| 7 | + "log/slog" |
| 8 | + "os" |
| 9 | + "path/filepath" |
| 10 | + "strconv" |
| 11 | + "strings" |
| 12 | + "syscall" |
| 13 | + "testing" |
| 14 | + "time" |
| 15 | +) |
| 16 | + |
| 17 | +// opencodeCancelFakeScript returns a POSIX-sh script that impersonates a |
| 18 | +// long-running `opencode`: it spawns a background grandchild, records both its |
| 19 | +// own (process-group-leader) pid and the grandchild pid, then streams stdout in |
| 20 | +// a tight loop forever. This is the shape that orphans and spins on EPIPE when |
| 21 | +// the daemon closes stdout while the process is still alive. When ignoreTerm is |
| 22 | +// true the whole group ignores SIGTERM, forcing the SIGKILL escalation path. |
| 23 | +func opencodeCancelFakeScript(ignoreTerm bool) string { |
| 24 | + trap := "trap 'exit 0' TERM\n" |
| 25 | + if ignoreTerm { |
| 26 | + trap = "trap '' TERM\n" |
| 27 | + } |
| 28 | + return "#!/bin/sh\n" + trap + |
| 29 | + `# Background grandchild so the test can assert the *whole* group is |
| 30 | +# terminated on cancellation, not just the direct child. |
| 31 | +( sleep 300 ) & |
| 32 | +child=$! |
| 33 | +if [ -n "$OPENCODE_PID_FILE" ]; then |
| 34 | + printf '%s %s\n' "$$" "$child" > "$OPENCODE_PID_FILE" |
| 35 | +fi |
| 36 | +printf '{"type":"step_start","timestamp":1,"sessionID":"ses_fake","part":{"type":"step-start"}}\n' |
| 37 | +while true; do |
| 38 | + printf '{"type":"text","timestamp":2,"sessionID":"ses_fake","part":{"type":"text","text":"tick"}}\n' |
| 39 | + sleep 0.1 |
| 40 | +done |
| 41 | +` |
| 42 | +} |
| 43 | + |
| 44 | +// TestOpencodeCancellationTerminatesProcessGroupGraceful verifies that |
| 45 | +// cancelling a run terminates a SIGTERM-respecting opencode and its whole |
| 46 | +// process group, returns an "aborted" result without hanging, and leaves no |
| 47 | +// orphaned descendant. |
| 48 | +func TestOpencodeCancellationTerminatesProcessGroupGraceful(t *testing.T) { |
| 49 | + runOpencodeCancellationTest(t, opencodeCancelFakeScript(false)) |
| 50 | +} |
| 51 | + |
| 52 | +// TestOpencodeCancellationEscalatesToSIGKILL verifies the worst case from |
| 53 | +// #4533: opencode (and its children) ignore SIGTERM and keep writing to stdout. |
| 54 | +// Cancellation must escalate to a group SIGKILL, still return promptly, and |
| 55 | +// still reap the whole group — without deadlocking on the stdout scanner or |
| 56 | +// closing the pipe under a live writer. |
| 57 | +func TestOpencodeCancellationEscalatesToSIGKILL(t *testing.T) { |
| 58 | + opencodeTerminateGraceNanos.Store(int64(300 * time.Millisecond)) |
| 59 | + t.Cleanup(func() { opencodeTerminateGraceNanos.Store(0) }) |
| 60 | + runOpencodeCancellationTest(t, opencodeCancelFakeScript(true)) |
| 61 | +} |
| 62 | + |
| 63 | +func runOpencodeCancellationTest(t *testing.T, script string) { |
| 64 | + t.Helper() |
| 65 | + |
| 66 | + tempDir := t.TempDir() |
| 67 | + pidFile := filepath.Join(tempDir, "pids") |
| 68 | + fakePath := filepath.Join(tempDir, "opencode") |
| 69 | + writeTestExecutable(t, fakePath, []byte(script)) |
| 70 | + |
| 71 | + backend, err := New("opencode", Config{ |
| 72 | + ExecutablePath: fakePath, |
| 73 | + Logger: slog.Default(), |
| 74 | + Env: map[string]string{"OPENCODE_PID_FILE": pidFile}, |
| 75 | + }) |
| 76 | + if err != nil { |
| 77 | + t.Fatalf("new opencode backend: %v", err) |
| 78 | + } |
| 79 | + |
| 80 | + ctx, cancel := context.WithCancel(context.Background()) |
| 81 | + defer cancel() |
| 82 | + |
| 83 | + session, err := backend.Execute(ctx, "prompt-ignored", ExecOptions{Cwd: tempDir}) |
| 84 | + if err != nil { |
| 85 | + t.Fatalf("execute: %v", err) |
| 86 | + } |
| 87 | + |
| 88 | + // Drain streamed messages so processEvents never blocks on a full channel. |
| 89 | + go func() { |
| 90 | + for range session.Messages { |
| 91 | + } |
| 92 | + }() |
| 93 | + |
| 94 | + pids := waitForPids(t, pidFile) |
| 95 | + |
| 96 | + cancel() // user cancels the task |
| 97 | + |
| 98 | + select { |
| 99 | + case res := <-session.Result: |
| 100 | + if res.Status != "aborted" { |
| 101 | + t.Errorf("status = %q, want aborted", res.Status) |
| 102 | + } |
| 103 | + case <-time.After(10 * time.Second): |
| 104 | + t.Fatal("Execute did not return after cancellation (possible scanner deadlock or unkilled process)") |
| 105 | + } |
| 106 | + |
| 107 | + // The leader and the grandchild must both be gone — cancellation reaped the |
| 108 | + // whole group, leaving no orphan spinning. |
| 109 | + for _, pid := range pids { |
| 110 | + waitProcessGone(t, pid) |
| 111 | + } |
| 112 | +} |
| 113 | + |
| 114 | +// waitForPids polls pidFile until it contains the space-separated pids the fake |
| 115 | +// recorded, then returns them. |
| 116 | +func waitForPids(t *testing.T, pidFile string) []int { |
| 117 | + t.Helper() |
| 118 | + deadline := time.Now().Add(5 * time.Second) |
| 119 | + for time.Now().Before(deadline) { |
| 120 | + raw, err := os.ReadFile(pidFile) |
| 121 | + if err == nil { |
| 122 | + fields := strings.Fields(string(raw)) |
| 123 | + if len(fields) >= 2 { |
| 124 | + pids := make([]int, 0, len(fields)) |
| 125 | + ok := true |
| 126 | + for _, f := range fields { |
| 127 | + n, perr := strconv.Atoi(f) |
| 128 | + if perr != nil || n <= 0 { |
| 129 | + ok = false |
| 130 | + break |
| 131 | + } |
| 132 | + pids = append(pids, n) |
| 133 | + } |
| 134 | + if ok { |
| 135 | + return pids |
| 136 | + } |
| 137 | + } |
| 138 | + } |
| 139 | + time.Sleep(20 * time.Millisecond) |
| 140 | + } |
| 141 | + t.Fatalf("fake opencode never recorded its pids in %s", pidFile) |
| 142 | + return nil |
| 143 | +} |
| 144 | + |
| 145 | +// waitProcessGone polls until signal 0 to pid reports the process no longer |
| 146 | +// exists (ESRCH), failing if it is still alive after the deadline. |
| 147 | +func waitProcessGone(t *testing.T, pid int) { |
| 148 | + t.Helper() |
| 149 | + deadline := time.Now().Add(5 * time.Second) |
| 150 | + for time.Now().Before(deadline) { |
| 151 | + if err := syscall.Kill(pid, 0); err == syscall.ESRCH { |
| 152 | + return |
| 153 | + } |
| 154 | + time.Sleep(20 * time.Millisecond) |
| 155 | + } |
| 156 | + t.Errorf("process %d still alive after cancellation — orphaned/leaked", pid) |
| 157 | +} |
0 commit comments