diff --git a/internal/tools/builtin/shell.go b/internal/tools/builtin/shell.go index 15c6a96fe..8eabcf669 100644 --- a/internal/tools/builtin/shell.go +++ b/internal/tools/builtin/shell.go @@ -4,6 +4,13 @@ // Mutations from upstream: // - package renamed tools -> builtin (archie-core already has an // internal/tools package holding the registry these are registered into). +// - the command runs in its own process group and cancellation signals +// the whole group. Upstream relies on exec.CommandContext's default, +// which kills only the direct shell, so `go test ./...` left its test +// binary running and `nohup x &` survived outright. archie's /stop +// cancels the turn context, so without this the command it was aimed +// at would keep going. tau applies the same treatment to spawned +// agents in agent.go; this extends it to the shell tool. // // Refresh by diffing against that path at a newer tau commit. Do not // edit without recording the change above. @@ -20,12 +27,17 @@ import ( "regexp" "runtime" "strings" + "syscall" "time" ) const ( defaultShellTimeout = 120 * time.Second maxShellTimeout = 10 * time.Minute + + // shellWaitDelay bounds how long Wait keeps reading from inherited + // pipes after the process group has been signalled. + shellWaitDelay = 2 * time.Second ) // ShellParams are the parameters for the shell tool. @@ -114,6 +126,23 @@ func makeShellExecutor(cwd string, mq *MutationQueue) Executor { cmd.Dir = cwd } + // Run the command as its own process group and, on cancellation, + // signal the group rather than the shell alone. + // + // exec.CommandContext's default kills only the process it started. + // A shell's real work is almost always a child of that shell, so + // the default leaves the actual command running: cancelling + // `go test ./...` reaps the shell and lets the test binary carry + // on, and anything backgrounded with & or nohup is never touched. + // /stop cancels this context, so that gap is the difference + // between stopping a command and only appearing to. + setProcessGroup(cmd) + cmd.Cancel = func() error { return signalProcessGroup(cmd, syscall.SIGKILL) } + // Stop waiting on inherited pipes shortly after the kill. A + // grandchild holding stdout open would otherwise keep Wait + // blocked long after the group was signalled. + cmd.WaitDelay = shellWaitDelay + var stdout, stderr bytes.Buffer bw := &bridgeWriter{bridge: bridge} cmd.Stdout = io.MultiWriter(&stdout, bw) diff --git a/internal/tools/builtin/shell_procgroup_unix_test.go b/internal/tools/builtin/shell_procgroup_unix_test.go new file mode 100644 index 000000000..3f1fbba7c --- /dev/null +++ b/internal/tools/builtin/shell_procgroup_unix_test.go @@ -0,0 +1,90 @@ +//go:build !windows + +package builtin + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "strconv" + "strings" + "syscall" + "testing" + "time" +) + +// TestShellCancellationKillsGrandchildren is the guarantee /stop depends on. +// +// exec.CommandContext's default cancellation kills only the shell it +// started. A shell's real work is a child of that shell, so without an +// explicit process group the command survives its own cancellation: the +// turn unwinds, the user is told it stopped, and `go test ./...` keeps +// running. This drives the case directly -- a backgrounded grandchild that +// outlives its parent shell -- and asserts it is gone. +func TestShellCancellationKillsGrandchildren(t *testing.T) { + dir := t.TempDir() + pidFile := filepath.Join(dir, "child.pid") + + // Background a long sleep, record its pid, then keep the parent shell + // alive. Only a group-wide signal reaps the sleep. + command := "sleep 300 & echo $! > " + pidFile + "; sleep 300" + params, err := json.Marshal(ShellParams{Command: command, Timeout: 60}) + if err != nil { + t.Fatal(err) + } + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + defer close(done) + _, _ = makeShellExecutor(dir, nil)(ctx, params, NonInteractiveBridge{}) + }() + + pid := waitForPID(t, pidFile) + if !processAlive(pid) { + t.Fatalf("grandchild %d was not running before cancellation", pid) + } + + cancel() + select { + case <-done: + case <-time.After(30 * time.Second): + t.Fatal("the shell tool did not return after cancellation") + } + + deadline := time.Now().Add(10 * time.Second) + for time.Now().Before(deadline) { + if !processAlive(pid) { + return + } + time.Sleep(20 * time.Millisecond) + } + + // Do not leave a stray sleep behind if the assertion fails. + _ = syscall.Kill(pid, syscall.SIGKILL) + t.Fatalf("grandchild %d survived cancellation; /stop would not have stopped it", pid) +} + +// waitForPID blocks until the shell has recorded its background child's pid. +func waitForPID(t *testing.T, path string) int { + t.Helper() + deadline := time.Now().Add(20 * time.Second) + for time.Now().Before(deadline) { + raw, err := os.ReadFile(path) + if err == nil { + if pid, convErr := strconv.Atoi(strings.TrimSpace(string(raw))); convErr == nil && pid > 0 { + return pid + } + } + time.Sleep(20 * time.Millisecond) + } + t.Fatal("the shell never recorded a background child pid") + return 0 +} + +// processAlive reports whether pid still exists. Signal 0 performs the +// permission and existence checks without delivering anything. +func processAlive(pid int) bool { + return syscall.Kill(pid, 0) == nil +}