Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(cursor): own Windows background shells by launch Job membership (MUL-7417) (#8638)
Bohan Jiangf41fae6b08fb
diff --git a/server/pkg/agent/cursor_background_late_child_test.go b/server/pkg/agent/cursor_background_late_child_test.goindex 32639237b6..586eaff266 100644--- a/server/pkg/agent/cursor_background_late_child_test.go+++ b/server/pkg/agent/cursor_background_late_child_test.go@@ -1,14 +1,14 @@-//go:build linux || darwin+//go:build linux || darwin || windows-// Windows is excluded deliberately, not by omission: this test was flaky there-// and nowhere else. Over 40 main pushes it never failed on the ubuntu runner,-// while the Windows arm failed twice in 43 -- once as `Access is denied.` and-// once as `not an owned descendant`, both from the same capture call. Those are-// two faces of one race: cursorWindowsProcessParents snapshots every PID->PPID-// pair on the machine, Windows keeps a child's recorded PPID after the parent-// exits, and the PID is then free to be reused, so the walk can reach a PID now-// owned by someone else. Restoring `windows` here without fixing that race-// restores the flake; MUL-7417 tracks the fix.+// Windows was excluded here for a while: over 40 main pushes this test never+// failed on the ubuntu runner, while the Windows arm failed twice in 43 -- once+// as `Access is denied.` and once as `not an owned descendant`, both from the+// same capture call. Those were two faces of one race: the capture walked a+// machine-wide PID->PPID snapshot, Windows keeps a child's recorded PPID after+// the parent exits, and the PID is then free to be reused, so the walk could+// reach a PID owned by someone else. The Windows capture now takes its+// candidates from the launch's own Job Object instead (MUL-7417), so a foreign+// PID is never opened and Windows is back in the build.package agentdiff --git a/server/pkg/agent/cursor_background_process_windows.go b/server/pkg/agent/cursor_background_process_windows.goindex 407274eb3c..bee81ece08 100644--- a/server/pkg/agent/cursor_background_process_windows.go+++ b/server/pkg/agent/cursor_background_process_windows.go@@ -31,6 +31,69 @@ func cursorProcessCreated(process windows.Handle) (uint64, error) {return uint64(created.HighDateTime)<<32 | uint64(created.LowDateTime), err}+// jobObjectBasicProcessIDList mirrors JOBOBJECT_BASIC_PROCESS_ID_LIST. The+// kernel writes as many PIDs as fit after the two counts; ProcessIdList is the+// first slot of that trailing array, and callers size the buffer behind it.+type jobObjectBasicProcessIDList struct {+ NumberOfAssignedProcesses uint32+ NumberOfProcessIdsInList uint32+ ProcessIdList [1]uintptr+}++// cursorJobProcessIDListCapacity is the PID capacity of the first buffer handed+// to QueryInformationJobObject. Tests shrink it so a small tree exercises the+// grow-and-retry path.+var cursorJobProcessIDListCapacity = 256++// cursorOpenProcess is OpenProcess, replaceable in tests to make a live launch+// member unopenable.+var cursorOpenProcess = windows.OpenProcess++// cursorJobProcessIDs lists the processes currently assigned to job. Every+// descendant of a launch inherits its Job at creation and cannot leave it, so+// this is the authoritative record of what belongs to the launch — unlike the+// machine-wide parent-PID snapshot, which keeps a child's recorded parent after+// that parent exits and lets a reused PID point at a process owned by someone+// else (MUL-7417).+//+// The kernel writes as many PIDs as fit and reports the full count separately;+// a short list can come back with ERROR_MORE_DATA or with success, and either+// way it is not the membership. The query is retried with a larger buffer until+// the two counts agree, and fails explicitly if they never do.+func cursorJobProcessIDs(job windows.Handle) (map[uint32]struct{}, error) {+ const word = int(unsafe.Sizeof(uintptr(0)))+ const header = int(unsafe.Sizeof(jobObjectBasicProcessIDList{})) - word+ capacity := cursorJobProcessIDListCapacity+ if capacity < 1 {+ capacity = 1+ }+ for attempt := 0; attempt < 8; attempt++ {+ // A []uintptr backing array keeps the header pointer-aligned.+ words := make([]uintptr, (header+word-1)/word+capacity)+ size := uint32(len(words) * word)+ err := windows.QueryInformationJobObject(job, windows.JobObjectBasicProcessIdList, uintptr(unsafe.Pointer(&words[0])), size, nil)+ if err != nil && !errors.Is(err, windows.ERROR_MORE_DATA) {+ return nil, fmt.Errorf("query job process ids: %w", err)+ }+ list := (*jobObjectBasicProcessIDList)(unsafe.Pointer(&words[0]))+ assigned, listed := int(list.NumberOfAssignedProcesses), int(list.NumberOfProcessIdsInList)+ if listed > capacity {+ listed = capacity+ }+ if err != nil || listed < assigned {+ capacity = max(assigned+64, capacity*2)+ continue+ }+ ids := unsafe.Slice(&list.ProcessIdList[0], capacity)[:listed]+ members := make(map[uint32]struct{}, listed)+ for _, id := range ids {+ members[uint32(id)] = struct{}{}+ }+ return members, nil+ }+ return nil, errors.New("query job process ids: member list did not settle")+}+func captureCursorBackgroundProcess(cmd *exec.Cmd, pid int) (*cursorBackgroundProcess, error) {if cmd == nil || cmd.Process == nil || pid <= 0 || uint64(pid) > uint64(^uint32(0)) || pid == cmd.Process.Pid {return nil, errCursorBackgroundProcessInvalid@@ -39,10 +102,6 @@ func captureCursorBackgroundProcess(cmd *exec.Cmd, pid int) (*cursorBackgroundPrif !ok {return nil, errCursorBackgroundProcessInvalid}- parents, err := cursorWindowsProcessParents()- if err != nil {- return nil, err- }type heldProcess struct {pid uint32handle windows.Handle@@ -54,40 +113,74 @@ func captureCursorBackgroundProcess(cmd *exec.Cmd, pid int) (*cursorBackgroundPr_ = windows.CloseHandle(p.handle)}}()+ // open is only ever asked for a PID the launch Job listed. Membership is+ // re-checked on the handle so a PID reused between the listing and the open+ // is refused rather than claimed; that case is reported as+ // errCursorBackgroundProcessInvalid, every other failure verbatim.open := func(pid uint32) (heldProcess, error) {- h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION|windows.PROCESS_SET_QUOTA|windows.PROCESS_TERMINATE, false, pid)+ h, err := cursorOpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION|windows.PROCESS_SET_QUOTA|windows.PROCESS_TERMINATE, false, pid)if err != nil {return heldProcess{}, err}created, err := cursorProcessCreated(h)- member, memberErr := cursorProcessInJob(h, root.job)- if err != nil || memberErr != nil || !member {+ if err == nil {+ var member bool+ if member, err = cursorProcessInJob(h, root.job); err == nil && !member {+ err = errCursorBackgroundProcessInvalid+ }+ }+ if err != nil {_ = windows.CloseHandle(h)- return heldProcess{}, errCursorBackgroundProcessInvalid+ return heldProcess{}, err}p := heldProcess{pid, h, created}held = append(held, p)return p, nil}- target, err := open(uint32(pid))+ // openMember opens a listed member for the child walk. skip reports a PID+ // proven to carry no launch member any more: the process behind it is+ // outside the launch Job, or the Job no longer lists it. A live member+ // this process cannot open — a DACL that denies PROCESS_SET_QUOTA or+ // PROCESS_TERMINATE, say — is an error instead: left out of the tool Job+ // it would outlive the tool's completion, so the capture fails and the+ // caller takes its watchdog fallback.+ openMember := func(pid uint32) (p heldProcess, skip bool, err error) {+ for attempt := 0; ; attempt++ {+ p, err = open(pid)+ if err == nil {+ return p, false, nil+ }+ if errors.Is(err, errCursorBackgroundProcessInvalid) {+ return heldProcess{}, true, nil+ }+ current, listErr := cursorJobProcessIDs(root.job)+ if listErr != nil {+ return heldProcess{}, false, listErr+ }+ if _, listed := current[pid]; !listed {+ return heldProcess{}, true, nil+ }+ // Still listed: either alive and unopenable, or exited and reused+ // by another launch member in the meantime. One more open settles it.+ if attempt == 1 {+ return heldProcess{}, false, fmt.Errorf("open launch member %d: %w", pid, err)+ }+ }+ }+ // Membership of this launch's Job is the ownership proof: only processes+ // descended from cmd can be in it, and a payload cannot name another+ // task's process. No walk up the parent chain is needed, and none is+ // attempted — that walk is what a reused PID could derail.+ members, err := cursorJobProcessIDs(root.job)if err != nil {return nil, err}- // Held handles and creation ordering reject reused parent PIDs. Membership- // of this launch's Job also prevents a payload from claiming another task.- child := target- seen := map[uint32]bool{}- for child.pid != uint32(cmd.Process.Pid) {- parentPID := parents[child.pid]- if parentPID == 0 || seen[parentPID] {- return nil, errCursorBackgroundProcessInvalid- }- seen[parentPID] = true- parent, err := open(parentPID)- if err != nil || parent.created > child.created {- return nil, errCursorBackgroundProcessInvalid- }- child = parent+ if _, ok := members[uint32(pid)]; !ok {+ return nil, errCursorBackgroundProcessInvalid+ }+ target, err := open(uint32(pid))+ if err != nil {+ return nil, err}job, err := windows.CreateJobObject(nil, nil)if err != nil {@@ -104,25 +197,38 @@ func captureCursorBackgroundProcess(cmd *exec.Cmd, pid int) (*cursorBackgroundPr}// Assign each parent BEFORE enumerating its immediate children. New children// now inherit the Job, and pre-existing children are attached breadth first.+ // Candidates come from the launch Job, so a stale parent PID in the snapshot+ // can at worst point at another launch member, never at a foreign process;+ // creation order then tells a real child from one that only points at this+ // PID because its own parent exited and the PID was reused.queue := []heldProcess{target}+ claimed := map[uint32]bool{target.pid: true}for len(queue) > 0 {parent := queue[0]queue = queue[1:]+ members, err := cursorJobProcessIDs(root.job)+ if err != nil {+ return nil, err+ }parents, err := cursorWindowsProcessParents()if err != nil {return nil, err}- for childPID, parentPID := range parents {- if parentPID != parent.pid {+ for childPID := range members {+ if claimed[childPID] || parents[childPID] != parent.pid {continue}- child, err := open(childPID)+ child, skip, err := openMember(childPID)if err != nil {return nil, err}+ if skip {+ continue+ }if child.created < parent.created {- return nil, errCursorBackgroundProcessIdentity+ continue}+ claimed[childPID] = truemember, err := cursorProcessInJob(child.handle, job)if err != nil {return nil, errdiff --git a/server/pkg/agent/cursor_background_process_windows_test.go b/server/pkg/agent/cursor_background_process_windows_test.gonew file mode 100644index 0000000000..1ad4399b7d--- /dev/null+++ b/server/pkg/agent/cursor_background_process_windows_test.go@@ -0,0 +1,122 @@+//go:build windows++package agent++import (+ "encoding/json"+ "log/slog"+ "os"+ "os/exec"+ "path/filepath"+ "syscall"+ "testing"+ "time"++ "golang.org/x/sys/windows"+)++// spawnCursorTestTree starts the fake cursor-agent in its default mode, which+// launches one background shell that launches one leaf and publishes+// [shell, leaf] to <dir>/0.json. All three live in the launch's Job.+func spawnCursorTestTree(t *testing.T) (root *exec.Cmd, shell, leaf int) {+ t.Helper()+ dir := t.TempDir()+ root = exec.Command(os.Args[0])+ root.Env = append(os.Environ(), cursorFakeModeEnv+"=natural", "CURSOR_FAKE_DIR="+dir, "CURSOR_FAKE_DURATION=30s")+ hideAgentWindow(root)+ if err := startOwnedProcessTree(root, slog.Default()); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { signalProcessGroup(root, syscall.SIGKILL); _ = root.Wait(); releaseProcessGroup(root) })+ deadline := time.Now().Add(5 * time.Second)+ for time.Now().Before(deadline) {+ var pids []int+ data, _ := os.ReadFile(filepath.Join(dir, "0.json"))+ if json.Unmarshal(data, &pids) == nil && len(pids) == 2 {+ return root, pids[0], pids[1]+ }+ time.Sleep(5 * time.Millisecond)+ }+ t.Fatal("fixture did not publish shell and leaf PIDs")+ return nil, 0, 0+}++func assertCursorTestProcessAlive(t *testing.T, pid int) {+ t.Helper()+ handle, err := windows.OpenProcess(windows.SYNCHRONIZE, false, uint32(pid))+ if err != nil {+ t.Fatalf("process %d is gone: %v", pid, err)+ }+ defer windows.CloseHandle(handle)+ status, err := windows.WaitForSingleObject(handle, 0)+ if err != nil || status != uint32(windows.WAIT_TIMEOUT) {+ t.Fatalf("process %d exited: status=%d err=%v", pid, status, err)+ }+}++// A short PID list is not the membership. With the first buffer sized below+// the tree, the query must grow until the two counts agree and return every+// member, whether the kernel signals the shortfall with ERROR_MORE_DATA or+// only through the counts.+func TestCaptureCursorBackgroundJobListGrowsPastInitialCapacity(t *testing.T) {+ root, shell, leaf := spawnCursorTestTree(t)+ tree, ok := lookupProcessTree(root)+ if !ok {+ t.Fatal("launch is not owned")+ }+ saved := cursorJobProcessIDListCapacity+ t.Cleanup(func() { cursorJobProcessIDListCapacity = saved })+ for _, capacity := range []int{1, 2, 3} {+ cursorJobProcessIDListCapacity = capacity+ members, err := cursorJobProcessIDs(tree.job)+ if err != nil {+ t.Fatalf("capacity %d: %v", capacity, err)+ }+ for _, pid := range []int{root.Process.Pid, shell, leaf} {+ if _, ok := members[uint32(pid)]; !ok {+ t.Fatalf("capacity %d: member %d missing from %v", capacity, pid, members)+ }+ }+ }+}++// A launch member that is alive but cannot be opened must fail the capture,+// not be skipped: skipped, it would sit outside the tool Job and outlive the+// tool's completion. The failed capture must also leave the healthy shell and+// its child running, exactly as before the attempt.+func TestCaptureCursorBackgroundProcessFailsWhenLiveMemberCannotBeOpened(t *testing.T) {+ root, shell, leaf := spawnCursorTestTree(t)+ saved := cursorOpenProcess+ t.Cleanup(func() { cursorOpenProcess = saved })+ cursorOpenProcess = func(access uint32, inherit bool, pid uint32) (windows.Handle, error) {+ if pid == uint32(leaf) {+ return 0, windows.ERROR_ACCESS_DENIED+ }+ return saved(access, inherit, pid)+ }+ if p, err := captureCursorBackgroundProcess(root, shell); err == nil {+ p.Close()+ t.Fatal("capture succeeded while a live launch member could not be opened")+ }+ assertCursorTestProcessAlive(t, shell)+ assertCursorTestProcessAlive(t, leaf)+}++// Sanity for the same tree with nothing in the way: the shell and its+// pre-existing child are both claimed and both die with the tool Job.+func TestCaptureCursorBackgroundProcessClaimsExistingChild(t *testing.T) {+ root, shell, leaf := spawnCursorTestTree(t)+ owned, err := captureCursorBackgroundProcess(root, shell)+ if err != nil {+ t.Fatal(err)+ }+ if err := owned.Terminate(); err != nil {+ t.Fatalf("terminate: %v", err)+ }+ assertCursorTestProcessGone(t, shell)+ assertCursorTestProcessGone(t, leaf)+ if alive, err := owned.Alive(); alive || err != nil {+ t.Fatalf("tool job still alive: alive=%v err=%v", alive, err)+ }+ owned.Close()+}