Skip to content

Secure, Fast, and Extensible Sandbox runtime for AI agents.

fix(execd): stop signalling the PTY shell once it is reaped

Maohao05335ee4272a
diff --git a/components/execd/pkg/runtime/pty_session.go b/components/execd/pkg/runtime/pty_session.go
index adfc413e7..db9334c13 100644
--- a/components/execd/pkg/runtime/pty_session.go
+++ b/components/execd/pkg/runtime/pty_session.go
@@ -467,6 +467,15 @@ const ptyDrainTimeout = 2 * time.Second
func (s *ptySession) waitAndExit(mp *managedProcess, ptmx *os.File, outputDone <-chan struct{}) {
_ = mp.Wait()
+ // The shell is reaped and its PID may be reused, so stop signalling it
+ // before waiting for its output below.
+ s.mu.Lock()
+ exitCode := mp.ExitCode()
+ s.lastExitCode = exitCode
+ s.pid = 0
+ doneCh := s.doneCh
+ s.mu.Unlock()
+
// Output the shell wrote before exiting can still be buffered in the
// master, and closing it discards that output. The broadcast goroutine
// stops once it has read everything (the master then returns EIO), so
@@ -478,13 +487,6 @@ func (s *ptySession) waitAndExit(mp *managedProcess, ptmx *os.File, outputDone <
}
_ = ptmx.Close()
- s.mu.Lock()
- exitCode := mp.ExitCode()
- s.lastExitCode = exitCode
- s.pid = 0
- doneCh := s.doneCh
- s.mu.Unlock()
-
close(doneCh)
}
diff --git a/components/execd/pkg/runtime/pty_session_test.go b/components/execd/pkg/runtime/pty_session_test.go
index 706e548d7..26c7b1e16 100644
--- a/components/execd/pkg/runtime/pty_session_test.go
+++ b/components/execd/pkg/runtime/pty_session_test.go
@@ -475,3 +475,19 @@ func TestPTYSession_EndsWhileClientStopsReading(t *testing.T) {
t.Fatal("session did not end after the shell exited")
}
}
+
+// The shell is reaped before its output is drained, so its PID may be reused
+// meanwhile: the session must stop signalling it right away.
+func TestPTYSession_StopsSignallingOnceShellIsReaped(t *testing.T) {
+ requireBash(t)
+
+ s := newPTYSession(uuidString(), "", "echo started")
+ require.NoError(t, s.StartPTY())
+ t.Cleanup(func() { s.close() })
+ _, _, detach := s.AttachOutput()
+ defer detach()
+
+ require.Eventually(t, func() bool { return !s.IsRunning() },
+ ptyDrainTimeout/2, 10*time.Millisecond,
+ "session still signalable while its output drains")
+}