Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

proc: a command's context ending on Windows kills what it started too (#2341)

yetone68a96b67b890
diff --git a/internal/proc/killtree_windows.go b/internal/proc/killtree_windows.go
new file mode 100644
index 000000000..27e591ade
--- /dev/null
+++ b/internal/proc/killtree_windows.go
@@ -0,0 +1,91 @@
+package proc
+
+import (
+ "os/exec"
+ "unsafe"
+
+ "golang.org/x/sys/windows"
+)
+
+// cancelTree has a command's context ending kill what the command started
+// as well as the command. Output starts a command out of a job's reach (a
+// job is joined only once it has started), so the descendants are found by
+// their parent at the kill. The Store's WSL runs System32's wsl.exe, which
+// starts Program Files' wsl.exe and waits on it: a listing that hung past
+// its timeout had the first killed and the second left waiting on the
+// service, one more for every retry, dozens a day (#2341).
+func cancelTree(cmd *exec.Cmd) {
+ cmd.Cancel = func() error {
+ killDescendants(cmd.Process.Pid)
+ return cmd.Process.Kill()
+ }
+}
+
+// killDescendants ends every process started under pid, at any depth. A
+// pid Windows has given again to a later process is told apart by its
+// start: a child starts after its parent.
+func killDescendants(pid int) {
+ for _, d := range descendants(uint32(pid)) {
+ h, err := windows.OpenProcess(windows.PROCESS_TERMINATE, false, d)
+ if err != nil {
+ continue
+ }
+ _ = windows.TerminateProcess(h, 1)
+ _ = windows.CloseHandle(h)
+ }
+}
+
+// descendants lists the processes under pid, nearest first.
+func descendants(pid uint32) []uint32 {
+ snap, err := windows.CreateToolhelp32Snapshot(windows.TH32CS_SNAPPROCESS, 0)
+ if err != nil {
+ return nil
+ }
+ defer windows.CloseHandle(snap)
+ kids := map[uint32][]uint32{}
+ var e windows.ProcessEntry32
+ e.Size = uint32(unsafe.Sizeof(e))
+ for err = windows.Process32First(snap, &e); err == nil; err = windows.Process32Next(snap, &e) {
+ if e.ProcessID != e.ParentProcessID {
+ kids[e.ParentProcessID] = append(kids[e.ParentProcessID], e.ProcessID)
+ }
+ }
+ var out []uint32
+ seen := map[uint32]bool{pid: true}
+ queue := []uint32{pid}
+ for len(queue) > 0 {
+ p := queue[0]
+ queue = queue[1:]
+ born, ok := started(p)
+ if !ok {
+ continue
+ }
+ for _, k := range kids[p] {
+ if seen[k] {
+ continue
+ }
+ if t, ok := started(k); !ok || t < born {
+ // the parent's pid is another, older process's
+ continue
+ }
+ seen[k] = true
+ out = append(out, k)
+ queue = append(queue, k)
+ }
+ }
+ return out
+}
+
+// started is when pid started, in 100ns since 1601.
+func started(pid uint32) (int64, bool) {
+ h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, pid)
+ if err != nil {
+ return 0, false
+ }
+ defer windows.CloseHandle(h)
+ var c, x, k, u windows.Filetime
+ if err := windows.GetProcessTimes(h, &c, &x, &k, &u); err != nil {
+ return 0, false
+ }
+ return int64(c.HighDateTime)<<32 | int64(c.LowDateTime), true
+}
diff --git a/internal/proc/killtree_windows_test.go b/internal/proc/killtree_windows_test.go
new file mode 100644
index 000000000..d0273ad16
--- /dev/null
+++ b/internal/proc/killtree_windows_test.go
@@ -0,0 +1,76 @@
+package proc
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "golang.org/x/sys/windows"
+)
+
+// alive says pid is a process still running.
+func alive(pid uint32) bool {
+ h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, pid)
+ if err != nil {
+ return false
+ }
+ defer windows.CloseHandle(h)
+ var code uint32
+ return windows.GetExitCodeProcess(h, &code) == nil && code == 259 // STILL_ACTIVE
+}
+
+// The Store's WSL runs System32's wsl.exe, which starts Program Files'
+// wsl.exe and waits on it. A listing past its timeout had only the first
+// killed, and the second, waiting on a hung service, was left: dozens a day
+// (#2341). A command's context ending kills what it started too. cmd.exe
+// running ping stands in for the two wsl.exe.
+func TestContextEndKillsWhatTheCommandStarted(t *testing.T) {
+ for _, name := range []string{"CommandContext", "ProbeContext"} {
+ t.Run(name, func(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ mk := CommandContext
+ if name == "ProbeContext" {
+ mk = ProbeContext
+ }
+ cmd := mk(ctx, "cmd.exe", "/c", "ping -n 60 127.0.0.1 >NUL")
+ if err := cmd.Start(); err != nil {
+ t.Fatal(err)
+ }
+ done := make(chan struct{})
+ go func() { cmd.Wait(); close(done) }()
+ var kids []uint32
+ for range 100 {
+ if kids = descendants(uint32(cmd.Process.Pid)); len(kids) > 0 {
+ break
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+ if len(kids) == 0 {
+ t.Fatal("cmd.exe started no ping")
+ }
+ t.Cleanup(func() {
+ for _, k := range kids {
+ if h, err := windows.OpenProcess(windows.PROCESS_TERMINATE, false, k); err == nil {
+ windows.TerminateProcess(h, 1)
+ windows.CloseHandle(h)
+ }
+ }
+ })
+ cancel()
+ select {
+ case <-done:
+ case <-time.After(10 * time.Second):
+ t.Fatal("cmd.exe not ended 10s after its context")
+ }
+ for _, k := range kids {
+ for i := 0; alive(k) && i < 40; i++ {
+ time.Sleep(50 * time.Millisecond)
+ }
+ if alive(k) {
+ t.Errorf("process %d that cmd.exe started still runs after its context ended", k)
+ }
+ }
+ })
+ }
+}
diff --git a/internal/proc/probe_windows.go b/internal/proc/probe_windows.go
index 2ad745959..51a5dd45b 100644
--- a/internal/proc/probe_windows.go
+++ b/internal/proc/probe_windows.go
@@ -5,14 +5,15 @@ import (
"time"
)
-// probeGroup kills the probe alone, as CommandContext does: a job, as
-// StartTree gives a command, is joined only once it has started, and Output
-// starts it out of reach. EndProbes ends it the same way when magpie exits,
-// so what a shim started (npm's .cmd running node) is still left running.
+// probeGroup kills the probe and what it started, as CommandContext does:
+// a job, as StartTree gives a command, is joined only once it has started,
+// and Output starts it out of reach, so they are found by their parent at
+// the kill. EndProbes ends it the same way when magpie exits.
func probeGroup(cmd *exec.Cmd, p *probe) {
cmd.Cancel = func() error {
p.kill()
defer p.end()
+ killDescendants(cmd.Process.Pid)
return cmd.Process.Kill()
}
}
diff --git a/internal/proc/proc.go b/internal/proc/proc.go
index ec6ec2744..fa5273f80 100644
--- a/internal/proc/proc.go
+++ b/internal/proc/proc.go
@@ -37,6 +37,8 @@ func CommandContext(ctx context.Context, name string, args ...string) *exec.Cmd
// Output waited for it however long it took (#123) — its pipes are
// closed a moment after instead
cmd.WaitDelay = waitDelay
+ // on Windows what it started is killed with it (#2341)
+ cancelTree(cmd)
batch(cmd)
hide(cmd)
return cmd
diff --git a/internal/proc/proc_other.go b/internal/proc/proc_other.go
index 702dd3963..782f92102 100644
--- a/internal/proc/proc_other.go
+++ b/internal/proc/proc_other.go
@@ -9,3 +9,7 @@ func hide(*exec.Cmd) {}
// batch has nothing to do: only Windows runs a script through cmd.exe.
func batch(*exec.Cmd) {}
+
+// cancelTree has nothing to do: a Unix command that should take what it
+// started with it is a probe, which leads a group of its own.
+func cancelTree(*exec.Cmd) {}
diff --git a/internal/wslrun/wslrun.go b/internal/wslrun/wslrun.go
index 221c6d0c1..84cb1a89a 100644
--- a/internal/wslrun/wslrun.go
+++ b/internal/wslrun/wslrun.go
@@ -299,9 +299,12 @@ func (t Tool) cancelable(cmd *exec.Cmd) *exec.Cmd {
mark = v
}
}
+ // then proc's own kill: wsl.exe with what it started on Windows (the
+ // Store's second wsl.exe), and a probe's group (#2341)
+ kill := cmd.Cancel
cmd.Cancel = func() error {
t.Stop(mark)
- return cmd.Process.Kill()
+ return kill()
}
return cmd
}