Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions tests/extensions/harness/sidecar_runtime/test_sidecar.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -29,6 +32,7 @@

from veadk.extensions.harness.sidecar_runtime.sidecar import (
_configure_structured_mcp_upstreams,
_terminate_process,
HarnessSidecarError,
HarnessSidecarRuntimeUnavailable,
doctor_harness_sidecar,
Expand Down Expand Up @@ -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
76 changes: 55 additions & 21 deletions veadk/extensions/harness/sidecar_runtime/sidecar.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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:
Expand Down Expand Up @@ -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)
Expand All @@ -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):
Expand All @@ -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:
Expand All @@ -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):
Expand Down Expand Up @@ -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:
Expand Down
Loading