From e5a6384b0b7143274facf8ea7273d7deea0f65ad Mon Sep 17 00:00:00 2001 From: shanchunhua Date: Thu, 3 Dec 2026 17:18:10 +0800 Subject: [PATCH] fix(harness): close Sidecar pipes and drop atexit binding on stop stop() only terminated the child process while leaving its stdout/stderr pipes open and keeping the Popen on the binding; the registered atexit callback held the binding alive, so every Sidecar cycle leaked two pipe file descriptors until the process hit its open-file limit. - close stdin/stdout/stderr and clear the process in stop() and the startup-failure _terminate_process() path - join the stderr drain thread with a bounded timeout before closing - unregister the atexit callback so stopped bindings can be reclaimed - add regression tests for stream closure, reference reclamation, FD baseline across cycles, and failure-path cleanup Co-authored-by: TRAE CLI --- .../harness/sidecar_runtime/test_sidecar.py | 74 ++++++++++++++++++ .../harness/sidecar_runtime/sidecar.py | 76 ++++++++++++++----- 2 files changed, 129 insertions(+), 21 deletions(-) diff --git a/tests/extensions/harness/sidecar_runtime/test_sidecar.py b/tests/extensions/harness/sidecar_runtime/test_sidecar.py index 08975eda5..de5386693 100644 --- a/tests/extensions/harness/sidecar_runtime/test_sidecar.py +++ b/tests/extensions/harness/sidecar_runtime/test_sidecar.py @@ -14,13 +14,16 @@ from __future__ import annotations +import gc import json import stat +import subprocess import sys import textwrap import threading import time import urllib.request +import weakref from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from secrets import token_urlsafe @@ -29,6 +32,7 @@ from veadk.extensions.harness.sidecar_runtime.sidecar import ( _configure_structured_mcp_upstreams, + _terminate_process, HarnessSidecarError, HarnessSidecarRuntimeUnavailable, doctor_harness_sidecar, @@ -745,3 +749,73 @@ def test_discovery_v2_reports_product_activation_state() -> None: "model_proxy", ] assert spec.plan_hash == "sha256:test" + + +def test_stop_closes_process_streams_and_releases_binding_references( + fake_runtime: Path, +) -> None: + binding = start_harness_sidecar(_config(fake_runtime)) + process = binding.process + assert process is not None + binding_ref = weakref.ref(binding) + process_ref = weakref.ref(process) + + binding.stop() + + assert process.stdout is not None and process.stderr is not None + assert process.stdout.closed + assert process.stderr.closed + assert binding.process is None + # Stopping twice must stay an idempotent no-op. + binding.stop() + + del binding + del process + gc.collect() + # The atexit callback must not keep the binding, Popen, or pipes alive. + assert binding_ref() is None + assert process_ref() is None + + +@pytest.mark.skipif( + not sys.platform.startswith("linux"), + reason="/proc/self/fd is Linux-specific", +) +def test_repeated_start_stop_returns_file_descriptors_to_baseline( + fake_runtime: Path, +) -> None: + fd_directory = Path("/proc/self/fd") + + def open_fd_count() -> int: + return len(list(fd_directory.iterdir())) + + baseline = open_fd_count() + for _ in range(3): + binding = start_harness_sidecar(_config(fake_runtime)) + binding.stop() + gc.collect() + + assert open_fd_count() == baseline + + +def test_terminate_process_closes_streams_for_running_and_exited_children() -> None: + cases = ( + [sys.executable, "-c", "import time; time.sleep(30)"], + [sys.executable, "-c", "pass"], + ) + for command in cases: + process = subprocess.Popen( + command, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + if command[-1] == "pass": + process.wait(timeout=5) + + _terminate_process(process) + + assert process.stdout is not None and process.stderr is not None + assert process.stdout.closed + assert process.stderr.closed diff --git a/veadk/extensions/harness/sidecar_runtime/sidecar.py b/veadk/extensions/harness/sidecar_runtime/sidecar.py index a11df56cf..7491e03fe 100644 --- a/veadk/extensions/harness/sidecar_runtime/sidecar.py +++ b/veadk/extensions/harness/sidecar_runtime/sidecar.py @@ -90,6 +90,7 @@ class SidecarBinding: ) _state_lock: threading.RLock = field(default_factory=threading.RLock, repr=False) _monitor_thread: threading.Thread | None = field(default=None, repr=False) + _stderr_thread: threading.Thread | None = field(default=None, repr=False) _runtime_exit_code: int | None = field(default=None, init=False, repr=False) _stopped: bool = field(default=False, init=False, repr=False) @@ -113,13 +114,27 @@ def stop(self) -> None: if self._stopped: return self._stopped = True - if self.process is not None and self.process.poll() is None: - self.process.terminate() - try: - self.process.wait(timeout=5) - except subprocess.TimeoutExpired: - self.process.kill() - self.process.wait(timeout=5) + process = self.process + if process is not None: + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + stderr_thread = self._stderr_thread + if stderr_thread is not None and stderr_thread.is_alive(): + # The child has exited and closed its stderr write end; bound the + # join in case a grandchild inherited it and keeps the drainer + # blocked on read(). + stderr_thread.join(timeout=2) + _close_process_streams(process) + self.process = None + self._stderr_thread = None + # Drop the atexit ownership chain (callback -> binding -> Popen -> pipes) + # so stopped bindings and their file descriptors can be reclaimed. + atexit.unregister(self.stop) if self.config_path is not None: self.config_path.unlink(missing_ok=True) for relay in self._relays: @@ -324,6 +339,7 @@ def start_harness_sidecar( stderr_lines: list[str] = [] config_path: Path | None = None process: subprocess.Popen[str] | None = None + stderr_thread: threading.Thread | None = None binding: SidecarBinding | None = None try: command = _resolve_runtime_command(resolved, runtime_env) @@ -337,7 +353,7 @@ def start_harness_sidecar( env=runtime_env, bufsize=1, ) - _drain_stream(process.stderr, stderr_lines) + stderr_thread = _drain_stream(process.stderr, stderr_lines) line = _read_startup_line(process, resolved.startup_timeout_seconds) discovery = json.loads(line) if not isinstance(discovery, dict): @@ -355,6 +371,7 @@ def start_harness_sidecar( config_path=config_path, stderr_lines=stderr_lines, _upstream_relays=upstream_relays, + _stderr_thread=stderr_thread, ) binding._configure_failover_relays(runtime_env) if apply_env: @@ -369,7 +386,7 @@ def start_harness_sidecar( if config_path is not None: config_path.unlink(missing_ok=True) if process is not None: - _terminate_process(process) + _terminate_process(process, stderr_thread) for relay in upstream_relays: relay.close() if isinstance(error, HarnessSidecarError): @@ -611,29 +628,46 @@ def _write_runtime_config(config: HarnessSidecarConfig) -> Path: return path -def _drain_stream(stream, target: list[str]) -> None: +def _drain_stream(stream, target: list[str]) -> threading.Thread | None: if stream is None: - return + return None def drain() -> None: for line in stream: target.append(line.rstrip()) - threading.Thread(target=drain, name="harness-sidecar-stderr", daemon=True).start() + thread = threading.Thread(target=drain, name="harness-sidecar-stderr", daemon=True) + thread.start() + return thread -def _terminate_process(process: subprocess.Popen[str]) -> None: - if process.poll() is not None: - return - process.terminate() - try: - process.wait(timeout=3) - except subprocess.TimeoutExpired: - process.kill() +def _close_process_streams(process: subprocess.Popen[str]) -> None: + for stream in (process.stdin, process.stdout, process.stderr): + if stream is None: + continue + try: + stream.close() + except OSError: + pass + + +def _terminate_process( + process: subprocess.Popen[str], + drain_thread: threading.Thread | None = None, +) -> None: + if process.poll() is None: + process.terminate() try: process.wait(timeout=3) except subprocess.TimeoutExpired: - pass + process.kill() + try: + process.wait(timeout=3) + except subprocess.TimeoutExpired: + pass + if drain_thread is not None and drain_thread.is_alive(): + drain_thread.join(timeout=2) + _close_process_streams(process) def _read_startup_line(process: subprocess.Popen[str], timeout: float) -> str: