Skip to content

Commit faaafa0

Browse files
authored
Merge pull request #1245 from xgtcode/fix/sidecar-pipe-fd-leak
fix(harness): 修复 Sidecar 停止时管道 FD 泄漏及 atexit 引用残留
2 parents ea78f82 + e5a6384 commit faaafa0

2 files changed

Lines changed: 129 additions & 21 deletions

File tree

‎tests/extensions/harness/sidecar_runtime/test_sidecar.py‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,16 @@
1414

1515
from __future__ import annotations
1616

17+
import gc
1718
import json
1819
import stat
20+
import subprocess
1921
import sys
2022
import textwrap
2123
import threading
2224
import time
2325
import urllib.request
26+
import weakref
2427
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
2528
from pathlib import Path
2629
from secrets import token_urlsafe
@@ -29,6 +32,7 @@
2932

3033
from veadk.extensions.harness.sidecar_runtime.sidecar import (
3134
_configure_structured_mcp_upstreams,
35+
_terminate_process,
3236
HarnessSidecarError,
3337
HarnessSidecarRuntimeUnavailable,
3438
doctor_harness_sidecar,
@@ -745,3 +749,73 @@ def test_discovery_v2_reports_product_activation_state() -> None:
745749
"model_proxy",
746750
]
747751
assert spec.plan_hash == "sha256:test"
752+
753+
754+
def test_stop_closes_process_streams_and_releases_binding_references(
755+
fake_runtime: Path,
756+
) -> None:
757+
binding = start_harness_sidecar(_config(fake_runtime))
758+
process = binding.process
759+
assert process is not None
760+
binding_ref = weakref.ref(binding)
761+
process_ref = weakref.ref(process)
762+
763+
binding.stop()
764+
765+
assert process.stdout is not None and process.stderr is not None
766+
assert process.stdout.closed
767+
assert process.stderr.closed
768+
assert binding.process is None
769+
# Stopping twice must stay an idempotent no-op.
770+
binding.stop()
771+
772+
del binding
773+
del process
774+
gc.collect()
775+
# The atexit callback must not keep the binding, Popen, or pipes alive.
776+
assert binding_ref() is None
777+
assert process_ref() is None
778+
779+
780+
@pytest.mark.skipif(
781+
not sys.platform.startswith("linux"),
782+
reason="/proc/self/fd is Linux-specific",
783+
)
784+
def test_repeated_start_stop_returns_file_descriptors_to_baseline(
785+
fake_runtime: Path,
786+
) -> None:
787+
fd_directory = Path("/proc/self/fd")
788+
789+
def open_fd_count() -> int:
790+
return len(list(fd_directory.iterdir()))
791+
792+
baseline = open_fd_count()
793+
for _ in range(3):
794+
binding = start_harness_sidecar(_config(fake_runtime))
795+
binding.stop()
796+
gc.collect()
797+
798+
assert open_fd_count() == baseline
799+
800+
801+
def test_terminate_process_closes_streams_for_running_and_exited_children() -> None:
802+
cases = (
803+
[sys.executable, "-c", "import time; time.sleep(30)"],
804+
[sys.executable, "-c", "pass"],
805+
)
806+
for command in cases:
807+
process = subprocess.Popen(
808+
command,
809+
stdin=subprocess.DEVNULL,
810+
stdout=subprocess.PIPE,
811+
stderr=subprocess.PIPE,
812+
text=True,
813+
)
814+
if command[-1] == "pass":
815+
process.wait(timeout=5)
816+
817+
_terminate_process(process)
818+
819+
assert process.stdout is not None and process.stderr is not None
820+
assert process.stdout.closed
821+
assert process.stderr.closed

‎veadk/extensions/harness/sidecar_runtime/sidecar.py‎

Lines changed: 55 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -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

639673
def _read_startup_line(process: subprocess.Popen[str], timeout: float) -> str:

0 commit comments

Comments
 (0)