Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6118: fix(agent): own Codex process trees with a Job Object on Windows (#6897)

Bohan Jiange7e01638ad87
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 08b0c5b680..b8f37f0dee 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -359,12 +359,15 @@ jobs:
# in the log instead of passing as "ok".
run: go test ./pkg/agent -v -run '^TestOpencodeExecuteOversizedPromptStartsOnWindows$' -count=1 -timeout=5m
- - name: Test bounded Codex cleanup with inherited stdout descendant
+ - name: Test Windows agent process-tree ownership
working-directory: server
- # Windows cannot prove whole-tree termination without a Job Object,
- # but a descendant holding inherited stdout must never keep Result
- # blocked forever. -v makes RUN/PASS evidence explicit in CI logs.
- run: go test ./pkg/agent -v -run '^TestCodexWindowsInheritedStdoutDescendantCleanupIsBounded$' -count=1 -timeout=5m
+ # A Job Object is the only way to prove whole-tree termination on
+ # Windows, and only a real Windows runner can exercise it: that a
+ # grandchild dies with the tree that owns it, that an unowned process
+ # still reports cleanup as unconfirmed, and that a descendant holding
+ # inherited stdout neither keeps Result blocked nor survives cleanup.
+ # -v makes RUN/PASS evidence explicit in CI logs.
+ run: go test ./pkg/agent -v -run '^(TestStartOwnedProcessTreeCapturesImmediateDescendants|TestStartOwnedProcessTreeLeavesNoSuspendedChild|TestWaitProcessGroupGoneWithoutOwnershipReportsUnconfirmed|TestCodexInitializeRetrySupportedWithOwnedProcessTree|TestCodexWindowsDescendantsDieWithTheOwnedProcessTree)$' -count=1 -timeout=5m
- name: Test Windows OpenClaw npm shim interpreter resolution
working-directory: server
diff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.go
index 2d8bc390ca..9d59d9b998 100644
--- a/server/pkg/agent/claude.go
+++ b/server/pkg/agent/claude.go
@@ -200,7 +200,7 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
}
closeStdin()
if cmd.Process != nil {
- signalProcessGroup(cmd.Process, syscall.SIGTERM)
+ signalProcessGroup(cmd, syscall.SIGTERM)
// Escalate to a group SIGKILL unless the WHOLE process group has
// exited within the grace window. This must key off the process
// group, not procDone: procDone only means cmd.Wait() returned
@@ -209,8 +209,8 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
// and skip the SIGKILL — leaking exactly the orphan this fix
// targets. waitProcessGroupGone returns as soon as the group is
// empty, so the graceful case adds no latency.
- if !waitProcessGroupGone(cmd.Process, claudeTerminateGrace()) {
- signalProcessGroup(cmd.Process, syscall.SIGKILL)
+ if !waitProcessGroupGone(cmd, claudeTerminateGrace()) {
+ signalProcessGroup(cmd, syscall.SIGKILL)
}
}
_ = stdout.Close()
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.go
index d965a765d0..3f97065050 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -994,7 +994,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
// still backstops cmd.Wait() if the kill leaves an open pipe.
cmd.Cancel = func() error {
if cmd.Process != nil {
- signalProcessGroup(cmd.Process, syscall.SIGKILL)
+ signalProcessGroup(cmd, syscall.SIGKILL)
}
return nil
}
@@ -1023,7 +1023,14 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
stderrBuf := newStderrTail(io.Discard, codexStderrTailBytes)
cmd.Stderr = stderrBuf
- if err := cmd.Start(); err != nil {
+ // Start and take ownership of the process tree in one step. On Windows the
+ // child is created suspended and placed in a Job Object before it runs, so
+ // the cleanup below reaches the Node wrapper, the native app-server, and the
+ // sandbox helpers underneath them rather than just the direct child. On Unix
+ // the process group configured above already covers that and this is a plain
+ // Start. Ownership that cannot be taken is logged, not fatal; a child that
+ // cannot be resumed is killed and reported here.
+ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {
cancel()
return nil, fmt.Errorf("start codex: %w", err)
}
@@ -1256,7 +1263,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
// Wait returning with a ProcessState is the os/exec reap boundary.
// On Unix, ProcessState.Exited reports false for a process terminated
// by SIGKILL even though Wait successfully reaped it.
- cleanupConfirmed = waitReturned && cmd.ProcessState != nil && waitProcessGroupGone(cmd.Process, grace)
+ cleanupConfirmed = waitReturned && cmd.ProcessState != nil && waitProcessGroupGone(cmd, grace)
if codexCleanupConfirmationOverride.Load() < 0 {
cleanupConfirmed = false
}
@@ -1274,6 +1281,12 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
"stderr_bytes", stderrBuf.TotalBytes(),
"stderr_truncated", stderrBuf.TotalBytes() > codexStderrTailBytes,
)
+ // The tree has been reaped and observed; drop ownership. This is
+ // the only safe point to do so on Windows, where releasing kills
+ // whatever is still inside the job — which is precisely what should
+ // happen to anything that outlived the reap above. waitOnce makes it
+ // exactly-once per launch attempt.
+ releaseProcessGroup(cmd)
})
}
@@ -1313,7 +1326,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
// A timed-out initialize may still complete after the host gives up.
// Kill the whole process group before waiting so a leader that exits
// on stdin EOF cannot leave detached-stdio descendants behind.
- signalProcessGroup(cmd.Process, syscall.SIGKILL)
+ signalProcessGroup(cmd, syscall.SIGKILL)
}
drainAndWait() // flush os/exec stderr goroutine before sampling Tail
finalStatus = "failed"
@@ -1352,7 +1365,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
// A timed-out thread/start has an uncertain provider outcome. Kill
// the whole process group before waiting so a leader that exits on
// EOF cannot leave detached-stdio descendants behind.
- signalProcessGroup(cmd.Process, syscall.SIGKILL)
+ signalProcessGroup(cmd, syscall.SIGKILL)
}
drainAndWait() // flush os/exec stderr goroutine before sampling Tail
finalStatus = "failed"
diff --git a/server/pkg/agent/deveco.go b/server/pkg/agent/deveco.go
index d259a57b91..433b30d7da 100644
--- a/server/pkg/agent/deveco.go
+++ b/server/pkg/agent/deveco.go
@@ -182,11 +182,11 @@ func (b *devecoBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
case <-runCtx.Done():
}
if cmd.Process != nil {
- signalProcessGroup(cmd.Process, syscall.SIGTERM)
+ signalProcessGroup(cmd, syscall.SIGTERM)
select {
case <-procDone: // exited within the grace window
case <-time.After(devecoTerminateGrace()):
- signalProcessGroup(cmd.Process, syscall.SIGKILL)
+ signalProcessGroup(cmd, syscall.SIGKILL)
}
}
_ = stdout.Close()
diff --git a/server/pkg/agent/opencode.go b/server/pkg/agent/opencode.go
index a711a469d2..d6aad25db4 100644
--- a/server/pkg/agent/opencode.go
+++ b/server/pkg/agent/opencode.go
@@ -232,11 +232,11 @@ func (b *opencodeBackend) Execute(ctx context.Context, prompt string, opts ExecO
// strand that goroutine for the lifetime of the daemon.
closeStdin()
if cmd.Process != nil {
- signalProcessGroup(cmd.Process, syscall.SIGTERM)
+ signalProcessGroup(cmd, syscall.SIGTERM)
select {
case <-procDone: // exited within the grace window
case <-time.After(opencodeTerminateGrace()):
- signalProcessGroup(cmd.Process, syscall.SIGKILL)
+ signalProcessGroup(cmd, syscall.SIGKILL)
}
}
_ = stdout.Close()
diff --git a/server/pkg/agent/proc_other.go b/server/pkg/agent/proc_other.go
index d99eb77dda..659b39c1ee 100644
--- a/server/pkg/agent/proc_other.go
+++ b/server/pkg/agent/proc_other.go
@@ -4,7 +4,7 @@ package agent
import (
"errors"
- "os"
+ "log/slog"
"os/exec"
"syscall"
"time"
@@ -26,28 +26,38 @@ func configureProcessGroup(cmd *exec.Cmd) {
cmd.SysProcAttr.Setpgid = true
}
+// startOwnedProcessTree is a plain Start on non-Windows platforms:
+// configureProcessGroup already put the child in its own process group before
+// it existed, so there is nothing left to claim once it is running. The logger
+// is unused here; Windows needs it to report degraded ownership.
+func startOwnedProcessTree(cmd *exec.Cmd, _ *slog.Logger) error { return cmd.Start() }
+
+// releaseProcessGroup is a no-op on non-Windows platforms: a process group needs
+// no handle and is gone once its members are.
+func releaseProcessGroup(cmd *exec.Cmd) {}
+
func codexInitializeRetrySupported() bool { return true }
-// signalProcessGroup sends sig to the whole process group led by p (when the
-// command was started with configureProcessGroup), falling back to the single
+// signalProcessGroup sends sig to the whole process group led by the command
+// (when it was started with configureProcessGroup), falling back to the single
// process if the group send fails. Targeting the group (negative pid) reaches
// the descendants the agent spawned, not just the leader.
-func signalProcessGroup(p *os.Process, sig syscall.Signal) {
- if p == nil {
+func signalProcessGroup(cmd *exec.Cmd, sig syscall.Signal) {
+ if cmd == nil || cmd.Process == nil {
return
}
- if err := syscall.Kill(-p.Pid, sig); err != nil {
- _ = p.Signal(sig)
+ if err := syscall.Kill(-cmd.Process.Pid, sig); err != nil {
+ _ = cmd.Process.Signal(sig)
}
}
-func waitProcessGroupGone(p *os.Process, timeout time.Duration) bool {
- if p == nil {
+func waitProcessGroupGone(cmd *exec.Cmd, timeout time.Duration) bool {
+ if cmd == nil || cmd.Process == nil {
return false
}
deadline := time.Now().Add(timeout)
for {
- err := syscall.Kill(-p.Pid, 0)
+ err := syscall.Kill(-cmd.Process.Pid, 0)
if errors.Is(err, syscall.ESRCH) {
return true
}
diff --git a/server/pkg/agent/proc_windows.go b/server/pkg/agent/proc_windows.go
index 94c6b54587..dcad4d42c2 100644
--- a/server/pkg/agent/proc_windows.go
+++ b/server/pkg/agent/proc_windows.go
@@ -3,10 +3,15 @@
package agent
import (
- "os"
+ "fmt"
+ "log/slog"
"os/exec"
+ "sync"
"syscall"
"time"
+ "unsafe"
+
+ "golang.org/x/sys/windows"
)
// createNewConsole allocates a fresh console for the child process. Combined
@@ -21,6 +26,10 @@ import (
// pass CREATE_NO_WINDOW — the exact popup storm reported in #1521.
const createNewConsole = 0x00000010
+// createSuspended starts the child with its initial thread suspended, so it can
+// be placed in a Job Object before it executes a single instruction.
+const createSuspended = 0x00000004
+
// hideAgentWindow configures cmd to suppress the console window on Windows
// while still giving descendant processes a hidden console to inherit.
// Stdio pipes set via cmd.StdoutPipe/StdinPipe keep working because
@@ -33,24 +42,246 @@ func hideAgentWindow(cmd *exec.Cmd) {
cmd.SysProcAttr.CreationFlags |= createNewConsole
}
-// configureProcessGroup is a no-op on Windows: there is no Setpgid/process-group
-// signalling. Descendant cleanup relies on the hidden console group set up by
-// hideAgentWindow plus exec.CommandContext / WaitDelay terminating the child.
+// configureProcessGroup is a no-op on Windows: there is no Setpgid equivalent,
+// and job membership cannot be requested before the process exists. Ownership
+// is taken by startOwnedProcessTree instead, which a backend opts into by
+// calling it in place of cmd.Start.
func configureProcessGroup(cmd *exec.Cmd) {}
-// codexInitializeRetrySupported remains false until Codex children are owned
-// by a Job Object and descendant termination can be positively confirmed.
-func codexInitializeRetrySupported() bool { return false }
+// ownedProcessTree is the Windows equivalent of a Unix process group: a Job
+// Object the agent belongs to, which every process it goes on to create
+// inherits membership of.
+type ownedProcessTree struct {
+ job windows.Handle
+}
+
+// ownedProcessTrees is keyed by the *exec.Cmd of one launch, never by pid. A pid
+// is only unique while its process is alive, so a launch that outlived its
+// process could otherwise look up — and terminate — an unrelated task that
+// happened to inherit the number.
+var (
+ ownedProcessTreesMu sync.Mutex
+ ownedProcessTrees = map[*exec.Cmd]ownedProcessTree{}
+)
+
+// jobObjectBasicAccountingInformation mirrors JOBOBJECT_BASIC_ACCOUNTING_INFORMATION.
+// x/sys/windows exports the info class but not the struct.
+type jobObjectBasicAccountingInformation struct {
+ TotalUserTime int64
+ TotalKernelTime int64
+ ThisPeriodTotalUserTime int64
+ ThisPeriodTotalKernelTime int64
+ TotalPageFaultCount uint32
+ TotalProcesses uint32
+ ActiveProcesses uint32
+ TotalTerminatedProcesses uint32
+}
+
+// startOwnedProcessTree starts cmd and takes ownership of every process it goes
+// on to create. Backends that need whole-tree cleanup call this instead of
+// cmd.Start.
+//
+// The child is created suspended and assigned to a Job Object before it runs.
+// That ordering is the whole point: Windows grants membership only to processes
+// created *after* the assignment, and never retroactively. Assigning after a
+// plain Start leaves a window in which the direct child — usually a cmd.exe
+// wrapping a .cmd shim — has already spawned the real agent outside the job.
+// That is worse than owning nothing, because the job would then hold only a
+// wrapper that exits immediately: accounting would report the tree empty while
+// the escaped app-server is still running, and cleanup would be reported as
+// confirmed when it is not.
+//
+// The child is never left suspended. If ownership cannot be taken it is resumed
+// anyway and runs unowned, exactly as it did before Job Objects, with the reason
+// logged. Only a failure to resume is unrecoverable: that child is killed and
+// the error returned, so the caller fails the launch instead of waiting forever
+// on a process that will never run.
+func startOwnedProcessTree(cmd *exec.Cmd, logger *slog.Logger) error {
+ if cmd.SysProcAttr == nil {
+ cmd.SysProcAttr = &syscall.SysProcAttr{}
+ }
+ cmd.SysProcAttr.CreationFlags |= createSuspended
+
+ if err := cmd.Start(); err != nil {
+ return err
+ }
+
+ if err := ownProcessTree(cmd); err != nil && logger != nil {
+ logger.Warn("could not take ownership of the agent process tree; descendant cleanup will be best-effort",
+ "error", err, "pid", cmd.Process.Pid)
+ }
+
+ if err := resumeProcess(cmd.Process.Pid); err != nil {
+ // The child cannot run, so nothing downstream can succeed. Drop
+ // ownership first: closing the job terminates the suspended child, and
+ // Kill covers the case where ownership was never taken.
+ releaseProcessGroup(cmd)
+ _ = cmd.Process.Kill()
+ _ = cmd.Wait()
+ return fmt.Errorf("resume suspended child: %w", err)
+ }
+ return nil
+}
-// signalProcessGroup terminates the process on Windows. Windows has no
-// SIGTERM/SIGKILL distinction or process-group signalling, so the signal is
-// ignored and the process is killed directly (TerminateProcess via Kill). The
-// caller's grace window still applies before this is invoked with SIGKILL.
-func signalProcessGroup(p *os.Process, _ syscall.Signal) {
- if p == nil {
+// ownProcessTree creates the Job Object and assigns the (still suspended) child
+// to it. The process handle is only needed for the assignment and is closed
+// straight after: termination and accounting both go through the job.
+func ownProcessTree(cmd *exec.Cmd) error {
+ job, err := windows.CreateJobObject(nil, nil)
+ if err != nil {
+ return fmt.Errorf("create job object: %w", err)
+ }
+ // KILL_ON_JOB_CLOSE makes the tree die with the last handle, so a daemon
+ // crash cannot strand agent descendants. It also means releaseProcessGroup
+ // must only run once the tree is finished with.
+ info := windows.JOBOBJECT_EXTENDED_LIMIT_INFORMATION{}
+ info.BasicLimitInformation.LimitFlags = windows.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
+ if _, err := windows.SetInformationJobObject(
+ job,
+ windows.JobObjectExtendedLimitInformation,
+ uintptr(unsafe.Pointer(&info)),
+ uint32(unsafe.Sizeof(info)),
+ ); err != nil {
+ _ = windows.CloseHandle(job)
+ return fmt.Errorf("set KILL_ON_JOB_CLOSE: %w", err)
+ }
+ process, err := windows.OpenProcess(
+ windows.PROCESS_SET_QUOTA|windows.PROCESS_TERMINATE,
+ false,
+ uint32(cmd.Process.Pid),
+ )
+ if err != nil {
+ _ = windows.CloseHandle(job)
+ return fmt.Errorf("open process: %w", err)
+ }
+ defer windows.CloseHandle(process)
+ if err := windows.AssignProcessToJobObject(job, process); err != nil {
+ _ = windows.CloseHandle(job)
+ return fmt.Errorf("assign process to job object: %w", err)
+ }
+
+ ownedProcessTreesMu.Lock()
+ defer ownedProcessTreesMu.Unlock()
+ ownedProcessTrees[cmd] = ownedProcessTree{job: job}
+ return nil
+}
+
+// resumeProcess releases the initial thread of a CREATE_SUSPENDED child. A
+// freshly created process has exactly one thread; the snapshot is filtered by
+// owning pid so a concurrent enumeration cannot resume somebody else's.
+func resumeProcess(pid int) error {
+ snapshot, err := windows.CreateToolhelp32Snapshot(windows.TH32CS_SNAPTHREAD, 0)
+ if err != nil {
+ return fmt.Errorf("snapshot threads: %w", err)
+ }
+ defer windows.CloseHandle(snapshot)
+
+ var entry windows.ThreadEntry32
+ entry.Size = uint32(unsafe.Sizeof(entry))
+ resumed := 0
+ for err = windows.Thread32First(snapshot, &entry); err == nil; err = windows.Thread32Next(snapshot, &entry) {
+ if entry.OwnerProcessID != uint32(pid) {
+ continue
+ }
+ thread, openErr := windows.OpenThread(windows.THREAD_SUSPEND_RESUME, false, entry.ThreadID)
+ if openErr != nil {
+ return fmt.Errorf("open thread %d: %w", entry.ThreadID, openErr)
+ }
+ _, resumeErr := windows.ResumeThread(thread)
+ _ = windows.CloseHandle(thread)
+ if resumeErr != nil {
+ return fmt.Errorf("resume thread %d: %w", entry.ThreadID, resumeErr)
+ }
+ resumed++
+ }
+ if resumed == 0 {
+ return fmt.Errorf("no threads found for pid %d", pid)
+ }
+ return nil
+}
+
+// releaseProcessGroup drops ownership of a finished tree. Closing the job handle
+// is what kills anything still inside it, so this must run only after the caller
+// has reaped the process — never on a path that could still be serving a live
+// agent.
+func releaseProcessGroup(cmd *exec.Cmd) {
+ ownedProcessTreesMu.Lock()
+ tree, ok := ownedProcessTrees[cmd]
+ delete(ownedProcessTrees, cmd)
+ ownedProcessTreesMu.Unlock()
+ if ok {
+ _ = windows.CloseHandle(tree.job)
+ }
+}
+
+func lookupProcessTree(cmd *exec.Cmd) (ownedProcessTree, bool) {
+ ownedProcessTreesMu.Lock()
+ defer ownedProcessTreesMu.Unlock()
+ tree, ok := ownedProcessTrees[cmd]
+ return tree, ok
+}
+
+func (t ownedProcessTree) activeProcesses() (uint32, error) {
+ var info jobObjectBasicAccountingInformation
+ if err := windows.QueryInformationJobObject(
+ t.job,
+ windows.JobObjectBasicAccountingInformation,
+ uintptr(unsafe.Pointer(&info)),
+ uint32(unsafe.Sizeof(info)),
+ nil,
+ ); err != nil {
+ return 0, fmt.Errorf("query job object members: %w", err)
+ }
+ return info.ActiveProcesses, nil
+}
+
+// codexInitializeRetrySupported reports whether descendant termination can be
+// positively confirmed. Owning the tree in a Job Object is what makes that
+// possible; when ownership was not taken, waitProcessGroupGone returns false and
+// the caller's cleanup_confirmed gate suppresses the retry anyway.
+func codexInitializeRetrySupported() bool { return true }
+
+// signalProcessGroup terminates the whole owned process tree. Windows has no
+// SIGTERM/SIGKILL distinction and no process-group signalling, so the signal is
+// ignored and the Job Object is terminated; the caller's grace window still
+// applies before this is invoked with SIGKILL. Without an owned tree this falls
+// back to killing the direct child alone.
+func signalProcessGroup(cmd *exec.Cmd, _ syscall.Signal) {
+ if cmd == nil || cmd.Process == nil {
return
}
- _ = p.Kill()
+ if tree, ok := lookupProcessTree(cmd); ok {
+ if err := windows.TerminateJobObject(tree.job, 1); err == nil {
+ return
+ }
+ }
+ _ = cmd.Process.Kill()
}
-func waitProcessGroupGone(_ *os.Process, _ time.Duration) bool { return false }
+// waitProcessGroupGone reports whether every process in the owned tree is gone,
+// polling the job's accounting information until the timeout. Without an owned
+// tree there is nothing to observe, so it reports false — callers treat that as
+// "cleanup could not be confirmed" rather than as success.
+func waitProcessGroupGone(cmd *exec.Cmd, timeout time.Duration) bool {
+ if cmd == nil || cmd.Process == nil {
+ return false
+ }
+ tree, ok := lookupProcessTree(cmd)
+ if !ok {
+ return false
+ }
+ deadline := time.Now().Add(timeout)
+ for {
+ active, err := tree.activeProcesses()
+ if err != nil {
+ return false
+ }
+ if active == 0 {
+ return true
+ }
+ if time.Now().After(deadline) {
+ return false
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+}
diff --git a/server/pkg/agent/proc_windows_test.go b/server/pkg/agent/proc_windows_test.go
index 1b01147a13..391d188e46 100644
--- a/server/pkg/agent/proc_windows_test.go
+++ b/server/pkg/agent/proc_windows_test.go
@@ -5,6 +5,7 @@ package agent
import (
"bytes"
"context"
+ "io"
"log/slog"
"os"
"os/exec"
@@ -14,6 +15,9 @@ import (
"syscall"
"testing"
"time"
+ "unsafe"
+
+ "golang.org/x/sys/windows"
)
// TestHideAgentWindowSetsCreateNewConsole guards against a regression where
@@ -72,13 +76,194 @@ func TestHideAgentWindowPreservesExistingSysProcAttr(t *testing.T) {
}
}
-func TestCodexInitializeRetrySuppressedWithoutConfirmedTreeCleanup(t *testing.T) {
- if codexInitializeRetrySupported() {
- t.Fatal("Codex initialize retry must remain disabled until Windows descendant cleanup is positively confirmed")
+// TestCodexInitializeRetrySupportedWithOwnedProcessTree pins the inverse of the
+// invariant this file used to hold. Now that a launched Codex is assigned to a
+// Job Object, descendant termination is observable, so the retry is no longer
+// categorically suppressed on Windows. The cleanup_confirmed gate at the call
+// site still suppresses it whenever ownership could not be taken, so a host
+// where the assignment fails behaves exactly as it did before.
+func TestCodexInitializeRetrySupportedWithOwnedProcessTree(t *testing.T) {
+ if !codexInitializeRetrySupported() {
+ t.Fatal("Codex initialize retry should be available once the process tree is owned by a Job Object")
+ }
+}
+
+// TestStartOwnedProcessTreeCapturesImmediateDescendants is the pre-attach
+// window: Windows grants job membership only to processes created after the
+// assignment and never retroactively, so a child that spawns its real work
+// immediately could escape a job it joined after Start. The helper here spawns
+// its grandchild as the very first thing it does, and the assertion is direct —
+// the job's own accounting must have seen both processes, not just the wrapper.
+//
+// That distinction matters more than it looks: a job holding only a wrapper that
+// exits reports the tree empty while the escaped process is still running, which
+// would make cleanup look confirmed when it is not.
+func TestStartOwnedProcessTreeCapturesImmediateDescendants(t *testing.T) {
+ exePath, pidPath := buildDescendantSpawner(t)
+
+ cmd := exec.Command(exePath, "spawn")
+ cmd.Env = append(os.Environ(), "DESCENDANT_PID_FILE="+pidPath)
+ hideAgentWindow(cmd)
+ if err := startOwnedProcessTree(cmd, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil {
+ t.Fatalf("startOwnedProcessTree: %v", err)
+ }
+ t.Cleanup(func() { releaseProcessGroup(cmd) })
+
+ descendantPid := waitForDescendantPid(t, pidPath)
+ if !processStillRunning(descendantPid) {
+ t.Fatalf("descendant %d was not running; the test cannot prove anything", descendantPid)
+ }
+ if total := jobTotalProcesses(t, cmd); total < 2 {
+ t.Fatalf("job accounted for %d processes, want the child and its descendant; the descendant escaped the job", total)
+ }
+
+ signalProcessGroup(cmd, syscall.SIGKILL)
+ if !waitProcessGroupGone(cmd, 10*time.Second) {
+ t.Fatal("waitProcessGroupGone reported the tree still active after terminating the job")
+ }
+ _ = cmd.Wait()
+ if processStillRunning(descendantPid) {
+ t.Fatalf("descendant %d survived termination of its owning process tree", descendantPid)
+ }
+}
+
+// TestWaitProcessGroupGoneWithoutOwnershipReportsUnconfirmed covers the
+// degraded path: a command started with a plain Start owns no job, so there is
+// nothing to observe, and callers must read that as "cleanup unconfirmed"
+// rather than as success.
+func TestWaitProcessGroupGoneWithoutOwnershipReportsUnconfirmed(t *testing.T) {
+ cmd := exec.Command("cmd.exe", "/c", "exit", "0")
+ hideAgentWindow(cmd)
+ if err := cmd.Start(); err != nil {
+ t.Fatal(err)
+ }
+ _ = cmd.Wait()
+ if waitProcessGroupGone(cmd, 50*time.Millisecond) {
+ t.Fatal("waitProcessGroupGone must not confirm cleanup for an unowned process")
+ }
+}
+
+// TestStartOwnedProcessTreeLeavesNoSuspendedChild guards the CREATE_SUSPENDED
+// path: a child that is never resumed would hang the launch forever, so a
+// successful return has to mean the process is actually running.
+func TestStartOwnedProcessTreeLeavesNoSuspendedChild(t *testing.T) {
+ marker := filepath.Join(t.TempDir(), "ran.txt")
+ cmd := exec.Command("cmd.exe", "/c", "echo ran > "+marker)
+ hideAgentWindow(cmd)
+ if err := startOwnedProcessTree(cmd, slog.New(slog.NewTextHandler(io.Discard, nil))); err != nil {
+ t.Fatalf("startOwnedProcessTree: %v", err)
+ }
+ t.Cleanup(func() { releaseProcessGroup(cmd) })
+
+ done := make(chan error, 1)
+ go func() { done <- cmd.Wait() }()
+ select {
+ case err := <-done:
+ if err != nil {
+ t.Fatalf("child exited with error: %v", err)
+ }
+ case <-time.After(30 * time.Second):
+ t.Fatal("child never exited; it was most likely left suspended")
}
+ if _, err := os.ReadFile(marker); err != nil {
+ t.Fatalf("child produced no output, so it never ran: %v", err)
+ }
+}
+
+// jobTotalProcesses reports how many processes the command's job has ever
+// accounted for, which is what proves membership regardless of whether a
+// descendant has already exited.
+func jobTotalProcesses(t *testing.T, cmd *exec.Cmd) uint32 {
+ t.Helper()
+ tree, ok := lookupProcessTree(cmd)
+ if !ok {
+ t.Fatal("command owns no process tree")
+ }
+ var info jobObjectBasicAccountingInformation
+ if err := windows.QueryInformationJobObject(
+ tree.job,
+ windows.JobObjectBasicAccountingInformation,
+ uintptr(unsafe.Pointer(&info)),
+ uint32(unsafe.Sizeof(info)),
+ nil,
+ ); err != nil {
+ t.Fatalf("query job accounting: %v", err)
+ }
+ return info.TotalProcesses
}
-func TestCodexWindowsInheritedStdoutDescendantCleanupIsBounded(t *testing.T) {
+// buildDescendantSpawner compiles a helper that starts a long-lived grandchild
+// and records its pid, then blocks. It is the smallest shape that distinguishes
+// "killed the child" from "killed the tree".
+func buildDescendantSpawner(t *testing.T) (exePath, pidPath string) {
+ t.Helper()
+ tempDir := t.TempDir()
+ sourcePath := filepath.Join(tempDir, "spawner.go")
+ exePath = filepath.Join(tempDir, "spawner.exe")
+ pidPath = filepath.Join(tempDir, "descendant.pid")
+ const source = `package main
+import (
+ "fmt"
+ "os"
+ "os/exec"
+ "time"
+)
+func main() {
+ if len(os.Args) > 1 && os.Args[1] == "descendant" { time.Sleep(10*time.Minute); return }
+ child := exec.Command(os.Args[0], "descendant")
+ if err := child.Start(); err != nil { panic(err) }
+ if err := os.WriteFile(os.Getenv("DESCENDANT_PID_FILE"), []byte(fmt.Sprint(child.Process.Pid)), 0600); err != nil { panic(err) }
+ time.Sleep(10*time.Minute)
+}`
+ if err := os.WriteFile(sourcePath, []byte(source), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ build := exec.Command("go", "build", "-o", exePath, sourcePath)
+ if output, err := build.CombinedOutput(); err != nil {
+ t.Fatalf("build descendant spawner: %v: %s", err, output)
+ }
+ return exePath, pidPath
+}
+
+func waitForDescendantPid(t *testing.T, pidPath string) int {
+ t.Helper()
+ deadline := time.Now().Add(30 * time.Second)
+ for time.Now().Before(deadline) {
+ raw, err := os.ReadFile(pidPath)
+ if err == nil {
+ if pid, err := strconv.Atoi(strings.TrimSpace(string(raw))); err == nil && pid > 0 {
+ t.Cleanup(func() {
+ if process, err := os.FindProcess(pid); err == nil {
+ _ = process.Kill()
+ }
+ })
+ return pid
+ }
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ t.Fatalf("descendant pid never appeared at %s", pidPath)
+ return 0
+}
+
+// processStillRunning reports whether pid names a live process. An exited
+// process can still be openable while a handle to it is held, so the exit code
+// is what decides.
+func processStillRunning(pid int) bool {
+ handle, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid))
+ if err != nil {
+ return false
+ }
+ defer windows.CloseHandle(handle)
+ var code uint32
+ if err := windows.GetExitCodeProcess(handle, &code); err != nil {
+ return false
+ }
+ const stillActive = 259
+ return code == stillActive
+}
+
+func TestCodexWindowsDescendantsDieWithTheOwnedProcessTree(t *testing.T) {
tempDir := t.TempDir()
sourcePath := filepath.Join(tempDir, "fake_codex.go")
exePath := filepath.Join(tempDir, "fake_codex.exe")
@@ -158,12 +343,26 @@ func main() {
}
entries := parseJSONLogEntries(t, logs.String())
failure := findCodexLifecyclePhase(t, entries, "thread_start_failure")
- if failure["cleanup_confirmed"] != false || failure["reaped"] != false {
- t.Fatalf("Windows tree cleanup must remain unconfirmed: %v", failure)
+ if failure["cleanup_confirmed"] != true || failure["reaped"] != true {
+ t.Fatalf("Windows tree cleanup should be confirmed once the tree is owned: %v", failure)
}
if phaseCount(entries, "thread_start_response") != 0 {
t.Fatalf("unexpected thread_start_response: %v", entries)
}
+
+ // The descendant inherited its stdout from the app-server and outlives a
+ // plain child kill; it must not outlive the tree.
+ raw, err := os.ReadFile(pidPath)
+ if err != nil {
+ t.Fatalf("descendant pid was never recorded: %v", err)
+ }
+ descendantPid, err := strconv.Atoi(strings.TrimSpace(string(raw)))
+ if err != nil {
+ t.Fatalf("parse descendant pid %q: %v", raw, err)
+ }
+ if processStillRunning(descendantPid) {
+ t.Fatalf("descendant %d survived codex cleanup", descendantPid)
+ }
}
func phaseCount(entries []map[string]any, phase string) int {