"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(background): stop timed-out process trees
xkam7arcd8acfc8148a
diff --git a/agent/src/tools/background_tools.py b/agent/src/tools/background_tools.pyindex 75dff6ffd..e19d35e4c 100644--- a/agent/src/tools/background_tools.py+++ b/agent/src/tools/background_tools.py@@ -3,6 +3,8 @@from __future__ import annotationsimport json+import os+import signalimport subprocessimport threadingimport uuid@@ -12,6 +14,77 @@ from typing import Any, Dict, List, Optionalfrom src.agent.tools import BaseToolWORKDIR = Path(__file__).resolve().parents[2]+_COMMAND_TIMEOUT_SECONDS = 300.0+_TERMINATION_GRACE_SECONDS = 2.0+_MAX_OUTPUT_CHARS = 50_000+++def _start_process(command: str) -> subprocess.Popen[str]:+ """Start a shell command in a process group that can be stopped as a unit."""+ kwargs: dict[str, Any] = {+ "shell": True,+ "cwd": WORKDIR,+ "stdout": subprocess.PIPE,+ "stderr": subprocess.PIPE,+ "text": True,+ "encoding": "utf-8",+ "errors": "replace",+ }+ if os.name == "nt":+ kwargs["creationflags"] = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)+ else:+ kwargs["start_new_session"] = True+ return subprocess.Popen(command, **kwargs)+++def _signal_posix_process_group(process: subprocess.Popen[str], sig: int) -> None:+ try:+ os.killpg(process.pid, sig)+ except ProcessLookupError:+ pass+++def _taskkill_windows_process_tree(process: subprocess.Popen[str]) -> None:+ """Ask Windows to stop the process and every descendant."""+ try:+ subprocess.run(+ ["taskkill", "/PID", str(process.pid), "/T", "/F"],+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ check=False,+ )+ except OSError:+ if process.poll() is None:+ process.kill()+++def _terminate_process_tree(process: subprocess.Popen[str]) -> tuple[str, str]:+ """Terminate a timed-out process tree, drain its pipes, and reap its root."""+ if os.name == "nt":+ _taskkill_windows_process_tree(process)+ try:+ return process.communicate(timeout=_TERMINATION_GRACE_SECONDS)+ except subprocess.TimeoutExpired:+ if process.poll() is None:+ process.kill()+ return process.communicate()++ _signal_posix_process_group(process, signal.SIGTERM)+ try:+ stdout, stderr = process.communicate(timeout=_TERMINATION_GRACE_SECONDS)+ except subprocess.TimeoutExpired:+ _signal_posix_process_group(process, signal.SIGKILL)+ return process.communicate()++ # The shell can exit before a descendant that ignored SIGTERM. The group+ # retains the shell's process-group id, so this final signal prevents an+ # orphan even when that descendant closed its inherited output pipes.+ _signal_posix_process_group(process, signal.SIGKILL)+ return stdout, stderr+++def _combined_output(stdout: str | None, stderr: str | None) -> str:+ return ((stdout or "") + (stderr or "")).strip()[:_MAX_OUTPUT_CHARS]class BackgroundManager:@@ -43,15 +116,25 @@ class BackgroundManager:def _execute(self, task_id: str, command: str) -> None:exit_code: int | None = None+ process: subprocess.Popen[str] | None = Nonetry:- r = subprocess.run(command, shell=True, cwd=WORKDIR,- capture_output=True, text=True, timeout=300,- encoding="utf-8", errors="replace")- output = (r.stdout + r.stderr).strip()[:50000]- exit_code = r.returncode- status = "completed" if exit_code == 0 else "error"- except subprocess.TimeoutExpired:- output, status = "Timeout (300s)", "timeout"+ process = _start_process(command)+ try:+ stdout, stderr = process.communicate(timeout=_COMMAND_TIMEOUT_SECONDS)+ output = _combined_output(stdout, stderr)+ exit_code = process.returncode+ status = "completed" if exit_code == 0 else "error"+ except subprocess.TimeoutExpired:+ stdout, stderr = _terminate_process_tree(process)+ partial_output = _combined_output(stdout, stderr)+ timeout_message = f"Timeout ({_COMMAND_TIMEOUT_SECONDS:g}s)"+ output = (+ f"{partial_output}\n{timeout_message}"+ if partial_output+ else timeout_message+ )+ output = output[:_MAX_OUTPUT_CHARS]+ status = "timeout"except Exception as e:output, status = str(e), "error"self.tasks[task_id]["status"] = statusdiff --git a/agent/tests/test_background_tools.py b/agent/tests/test_background_tools.pyindex 20ce59355..f92428a1e 100644--- a/agent/tests/test_background_tools.py+++ b/agent/tests/test_background_tools.py@@ -3,8 +3,15 @@from __future__ import annotationsimport json+import os+import shleximport sys+import time+from pathlib import Path+import pytest++from src.tools import background_toolsfrom src.tools.background_tools import BackgroundManager@@ -40,3 +47,39 @@ def test_nonzero_exit_is_reported_as_error() -> None:"exit_code": 7,}]++[email protected](os.name == "nt", reason="POSIX process-group regression")+def test_timeout_kills_descendant_and_reaps_shell(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ started_marker = tmp_path / "child-started"+ orphan_marker = tmp_path / "orphan-wrote-after-timeout"+ child_code = (+ "import time; from pathlib import Path; "+ f"Path({str(started_marker)!r}).write_text('started', encoding='utf-8'); "+ "time.sleep(1.5); "+ f"Path({str(orphan_marker)!r}).write_text('orphan', encoding='utf-8')"+ )+ command = f"{shlex.quote(sys.executable)} -c {shlex.quote(child_code)} & wait"+ processes: list[background_tools.subprocess.Popen[str]] = []+ real_popen = background_tools.subprocess.Popen++ def tracked_popen(*args, **kwargs):+ process = real_popen(*args, **kwargs)+ processes.append(process)+ return process++ monkeypatch.setattr(background_tools, "_COMMAND_TIMEOUT_SECONDS", 0.8)+ monkeypatch.setattr(background_tools, "_TERMINATION_GRACE_SECONDS", 0.2)+ monkeypatch.setattr(background_tools.subprocess, "Popen", tracked_popen)++ manager = BackgroundManager()+ task = _execute(manager, "timeout", command)++ assert started_marker.exists()+ assert task["status"] == "timeout"+ assert processes[0].poll() is not None+ time.sleep(1.0)+ assert not orphan_marker.exists()