@@ -90,6 +90,7 @@ class SidecarBinding:
9090 )
9191 _state_lock : threading .RLock = field (default_factory = threading .RLock , repr = False )
9292 _monitor_thread : threading .Thread | None = field (default = None , repr = False )
93+ _stderr_thread : threading .Thread | None = field (default = None , repr = False )
9394 _runtime_exit_code : int | None = field (default = None , init = False , repr = False )
9495 _stopped : bool = field (default = False , init = False , repr = False )
9596
@@ -113,13 +114,27 @@ def stop(self) -> None:
113114 if self ._stopped :
114115 return
115116 self ._stopped = True
116- if self .process is not None and self .process .poll () is None :
117- self .process .terminate ()
118- try :
119- self .process .wait (timeout = 5 )
120- except subprocess .TimeoutExpired :
121- self .process .kill ()
122- self .process .wait (timeout = 5 )
117+ process = self .process
118+ if process is not None :
119+ if process .poll () is None :
120+ process .terminate ()
121+ try :
122+ process .wait (timeout = 5 )
123+ except subprocess .TimeoutExpired :
124+ process .kill ()
125+ process .wait (timeout = 5 )
126+ stderr_thread = self ._stderr_thread
127+ if stderr_thread is not None and stderr_thread .is_alive ():
128+ # The child has exited and closed its stderr write end; bound the
129+ # join in case a grandchild inherited it and keeps the drainer
130+ # blocked on read().
131+ stderr_thread .join (timeout = 2 )
132+ _close_process_streams (process )
133+ self .process = None
134+ self ._stderr_thread = None
135+ # Drop the atexit ownership chain (callback -> binding -> Popen -> pipes)
136+ # so stopped bindings and their file descriptors can be reclaimed.
137+ atexit .unregister (self .stop )
123138 if self .config_path is not None :
124139 self .config_path .unlink (missing_ok = True )
125140 for relay in self ._relays :
@@ -324,6 +339,7 @@ def start_harness_sidecar(
324339 stderr_lines : list [str ] = []
325340 config_path : Path | None = None
326341 process : subprocess .Popen [str ] | None = None
342+ stderr_thread : threading .Thread | None = None
327343 binding : SidecarBinding | None = None
328344 try :
329345 command = _resolve_runtime_command (resolved , runtime_env )
@@ -337,7 +353,7 @@ def start_harness_sidecar(
337353 env = runtime_env ,
338354 bufsize = 1 ,
339355 )
340- _drain_stream (process .stderr , stderr_lines )
356+ stderr_thread = _drain_stream (process .stderr , stderr_lines )
341357 line = _read_startup_line (process , resolved .startup_timeout_seconds )
342358 discovery = json .loads (line )
343359 if not isinstance (discovery , dict ):
@@ -355,6 +371,7 @@ def start_harness_sidecar(
355371 config_path = config_path ,
356372 stderr_lines = stderr_lines ,
357373 _upstream_relays = upstream_relays ,
374+ _stderr_thread = stderr_thread ,
358375 )
359376 binding ._configure_failover_relays (runtime_env )
360377 if apply_env :
@@ -369,7 +386,7 @@ def start_harness_sidecar(
369386 if config_path is not None :
370387 config_path .unlink (missing_ok = True )
371388 if process is not None :
372- _terminate_process (process )
389+ _terminate_process (process , stderr_thread )
373390 for relay in upstream_relays :
374391 relay .close ()
375392 if isinstance (error , HarnessSidecarError ):
@@ -611,29 +628,46 @@ def _write_runtime_config(config: HarnessSidecarConfig) -> Path:
611628 return path
612629
613630
614- def _drain_stream (stream , target : list [str ]) -> None :
631+ def _drain_stream (stream , target : list [str ]) -> threading . Thread | None :
615632 if stream is None :
616- return
633+ return None
617634
618635 def drain () -> None :
619636 for line in stream :
620637 target .append (line .rstrip ())
621638
622- threading .Thread (target = drain , name = "harness-sidecar-stderr" , daemon = True ).start ()
639+ thread = threading .Thread (target = drain , name = "harness-sidecar-stderr" , daemon = True )
640+ thread .start ()
641+ return thread
623642
624643
625- def _terminate_process (process : subprocess .Popen [str ]) -> None :
626- if process .poll () is not None :
627- return
628- process .terminate ()
629- try :
630- process .wait (timeout = 3 )
631- except subprocess .TimeoutExpired :
632- process .kill ()
644+ def _close_process_streams (process : subprocess .Popen [str ]) -> None :
645+ for stream in (process .stdin , process .stdout , process .stderr ):
646+ if stream is None :
647+ continue
648+ try :
649+ stream .close ()
650+ except OSError :
651+ pass
652+
653+
654+ def _terminate_process (
655+ process : subprocess .Popen [str ],
656+ drain_thread : threading .Thread | None = None ,
657+ ) -> None :
658+ if process .poll () is None :
659+ process .terminate ()
633660 try :
634661 process .wait (timeout = 3 )
635662 except subprocess .TimeoutExpired :
636- pass
663+ process .kill ()
664+ try :
665+ process .wait (timeout = 3 )
666+ except subprocess .TimeoutExpired :
667+ pass
668+ if drain_thread is not None and drain_thread .is_alive ():
669+ drain_thread .join (timeout = 2 )
670+ _close_process_streams (process )
637671
638672
639673def _read_startup_line (process : subprocess .Popen [str ], timeout : float ) -> str :
0 commit comments