Skip to content

armgit / ax

Public Imported from GitHub
0

Agent Executor (AX) is Google's open agentic orchestration runtime

Go

feat: add support for terminating existing orphan processes before starting the Python sidecar

Jaana Dogana0bfb5fb74df
diff --git a/cmd/ax/harness.go b/cmd/ax/harness.go
index 6ecf3ac..493951b 100644
--- a/cmd/ax/harness.go
+++ b/cmd/ax/harness.go
@@ -111,6 +111,7 @@ func runAntigravityHarness(cmd *cobra.Command) error {
return fmt.Errorf("failed to resolve antigravity state dir: %w", err)
}
+ addr := net.JoinHostPort("127.0.0.1", strconv.Itoa(harnessPort))
cfg := pythonsidecar.Config{
Module: "python.antigravity.harness_server",
Args: []string{
@@ -118,9 +119,11 @@ func runAntigravityHarness(cmd *cobra.Command) error {
"--port", strconv.Itoa(harnessPort),
"--state-dir", stateDir,
},
- Stdout: os.Stdout,
- Stderr: os.Stderr,
- ReadyFunc: pythonsidecar.TCPReady(net.JoinHostPort("127.0.0.1", strconv.Itoa(harnessPort))),
+ Stdout: os.Stdout,
+ Stderr: os.Stderr,
+ ReadyFunc: pythonsidecar.TCPReady(addr),
+ KillOrphans: true,
+ Address: addr,
}
sidecar := pythonsidecar.New(cfg)
diff --git a/internal/harness/antigravity/antigravity.go b/internal/harness/antigravity/antigravity.go
index 0183937..db69ed9 100644
--- a/internal/harness/antigravity/antigravity.go
+++ b/internal/harness/antigravity/antigravity.go
@@ -84,9 +84,11 @@ func New(ctx context.Context, address, stateDir string, autoStart bool) (*Antigr
args = append(args, "--state-dir", stateDir)
}
cfg := pythonsidecar.Config{
- Module: "python.antigravity.harness_server",
- Args: args,
- ReadyFunc: pythonsidecar.TCPReady(address),
+ Module: "python.antigravity.harness_server",
+ Args: args,
+ ReadyFunc: pythonsidecar.TCPReady(address),
+ KillOrphans: true,
+ Address: address,
}
sidecar := pythonsidecar.New(cfg)
path, err := pythonsidecar.Setup(ctx, pythonsidecar.SetupOptions{
@@ -111,6 +113,14 @@ func New(ctx context.Context, address, stateDir string, autoStart bool) (*Antigr
return h, nil
}
+// Stop terminates the underlying Python sidecar process if it was started by this harness.
+func (h *AntigravityHarness) Stop() error {
+ if h.sidecar != nil {
+ return h.sidecar.Stop()
+ }
+ return nil
+}
+
// Start implements Harness.Start.
func (h *AntigravityHarness) Start(ctx context.Context, conversationID string, harnessConfig []byte) (harness.Execution, error) {
return &antigravityExecution{
diff --git a/internal/pythonsidecar/sidecar.go b/internal/pythonsidecar/sidecar.go
index 9c8f6fe..6b25c25 100644
--- a/internal/pythonsidecar/sidecar.go
+++ b/internal/pythonsidecar/sidecar.go
@@ -23,6 +23,7 @@ import (
"net"
"os"
"os/exec"
+ "strconv"
"strings"
"sync"
"syscall"
@@ -42,6 +43,11 @@ type Config struct {
// ReadyFunc is an optional function to check if the server is ready to accept requests.
// When provided, Start will poll ReadyFunc until it returns nil or the context expires. (Optional)
ReadyFunc func(ctx context.Context) error
+ // KillOrphans when true will attempt to terminate any pre-existing orphan process
+ // listening on Address before starting the sidecar. (Optional)
+ KillOrphans bool
+ // Address is the network host:port address used for orphan process cleanup. (Optional)
+ Address string
}
// TODO: Use /var/ax_agy_harness_service for communication instead of TCP.
@@ -82,8 +88,13 @@ func (s *Sidecar) Start(ctx context.Context, pythonPath string) error {
if s.cfg.ReadyFunc != nil {
if err := s.cfg.ReadyFunc(ctx); err == nil {
- s.mu.Unlock()
- return fmt.Errorf("cannot start sidecar: endpoint is already in use by another process")
+ if s.cfg.KillOrphans && s.cfg.Address != "" {
+ _ = killOrphanProcessOnAddr(ctx, s.cfg.Address)
+ }
+ if err := s.cfg.ReadyFunc(ctx); err == nil {
+ s.mu.Unlock()
+ return fmt.Errorf("cannot start sidecar: endpoint %s is already in use by another process", s.cfg.Address)
+ }
}
}
@@ -274,3 +285,59 @@ func TCPReady(addr string) func(ctx context.Context) error {
return nil
}
}
+
+// killOrphanProcessOnAddr attempts to terminate pre-existing processes listening on addr.
+func killOrphanProcessOnAddr(ctx context.Context, addr string) error {
+ _, portStr, err := net.SplitHostPort(addr)
+ if err != nil {
+ return err
+ }
+ port, err := strconv.Atoi(portStr)
+ if err != nil || port <= 0 {
+ return fmt.Errorf("invalid port %q", portStr)
+ }
+
+ out, err := exec.CommandContext(ctx, "lsof", "-ti", fmt.Sprintf("tcp:%d", port)).Output()
+ if err != nil || len(out) == 0 {
+ return nil
+ }
+
+ pidStrs := strings.Fields(string(out))
+ myPid := os.Getpid()
+ for _, pStr := range pidStrs {
+ pid, err := strconv.Atoi(pStr)
+ if err != nil || pid <= 0 || pid == myPid {
+ continue
+ }
+ proc, err := os.FindProcess(pid)
+ if err != nil {
+ continue
+ }
+ _ = proc.Signal(syscall.SIGTERM)
+ }
+
+ deadline := time.Now().Add(1 * time.Second)
+ for time.Now().Before(deadline) {
+ var d net.Dialer
+ conn, err := d.DialContext(ctx, "tcp", addr)
+ if err != nil {
+ return nil
+ }
+ _ = conn.Close()
+ time.Sleep(50 * time.Millisecond)
+ }
+
+ for _, pStr := range pidStrs {
+ pid, err := strconv.Atoi(pStr)
+ if err != nil || pid <= 0 || pid == myPid {
+ continue
+ }
+ proc, err := os.FindProcess(pid)
+ if err != nil {
+ continue
+ }
+ _ = proc.Kill()
+ }
+
+ return nil
+}
diff --git a/internal/pythonsidecar/sidecar_test.go b/internal/pythonsidecar/sidecar_test.go
index b594257..6e469bb 100644
--- a/internal/pythonsidecar/sidecar_test.go
+++ b/internal/pythonsidecar/sidecar_test.go
@@ -183,3 +183,40 @@ func TestSidecar_EndpointAlreadyInUse(t *testing.T) {
t.Fatalf("expected 'already in use' in error, got: %v", err)
}
}
+
+func TestSidecar_KillOrphans(t *testing.T) {
+ port := getFreePort(t)
+ addr := fmt.Sprintf("127.0.0.1:%d", port)
+
+ // Start a dummy sidecar listening on `port`
+ dummyCfg := pythonsidecar.Config{
+ Module: "http.server",
+ Args: []string{strconv.Itoa(port), "--bind", "127.0.0.1"},
+ ReadyFunc: pythonsidecar.TCPReady(addr),
+ }
+ dummySidecar := pythonsidecar.New(dummyCfg)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ if err := dummySidecar.Start(ctx, ""); err != nil {
+ t.Fatalf("failed to start dummy sidecar: %v", err)
+ }
+
+ // Now start a new sidecar with KillOrphans: true on the same addr
+ newCfg := pythonsidecar.Config{
+ Module: "http.server",
+ Args: []string{strconv.Itoa(port), "--bind", "127.0.0.1"},
+ ReadyFunc: pythonsidecar.TCPReady(addr),
+ KillOrphans: true,
+ Address: addr,
+ }
+ newSidecar := pythonsidecar.New(newCfg)
+ if err := newSidecar.Start(ctx, ""); err != nil {
+ t.Fatalf("Start() with KillOrphans failed: %v", err)
+ }
+ defer newSidecar.Stop()
+
+ if !newSidecar.IsRunning() {
+ t.Fatalf("expected new sidecar to be running")
+ }
+}