"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
Merge PR #2098: cancel owned processes on failure and keep shutdown off the event loop
Haozhe Wube8c0e50fa72
diff --cc agent/api_server.pyindex 261bee911,63446c981..b1583497f--- a/agent/api_server.py+++ b/agent/api_server.py@@@ -8,6 -8,6 +8,7 @@@ infrastructure lives in ``src.api.{secufrom __future__ import annotations++import asyncioimport loggingfrom contextlib import asynccontextmanagerfrom pathlib import Path@@@ -156,6 -156,14 +157,16 @@@ async def _lifespan(_: FastAPI) -> Asynyieldfinally:await _stop_scheduled_research_on_shutdown()+ # Reap background work this host owns before its runtime disappears.+ # Read the existing service rather than _get_session_service(): a+ # shutdown must not create the very object it is trying to release.+ import src.api.state as _api_state++ service = getattr(_api_state, "_session_service", None)+ if service is not None:- service.shutdown(timeout=5.0)++ pending = await asyncio.to_thread(service.shutdown, timeout=5.0)++ if pending:++ logger.warning("Background cleanup incomplete at shutdown: %s", pending)app = FastAPI(diff --cc agent/src/agent/loop.pyindex cae56ab31,1c2b9dc65..6de3467e5--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@@ -371,10 -375,10 +375,14 @@@ class AgentLoop(ToolCallLifecycle)Execution result dict."""token = bind_llm_session_id(session_id)++ result = Nonetry:-- return self._run_bound(user_message, history, session_id)++ result = self._run_bound(user_message, history, session_id)++ return resultfinally:reset_llm_session_id(token)++ if result is None or result.get("status") not in {"success", "waiting_user"}:++ self._background_manager.cancel_all()def _run_bound(self, user_message: str, history: Optional[List[Dict[str, Any]]] = None, session_id: str = "") -> Dict[str, Any]:"""Run the ReAct loop with the LLM session already bound.diff --cc agent/src/session/service.pyindex 34150fb22,32731aa27..0af58474e--- a/agent/src/session/service.py+++ b/agent/src/session/service.py@@@ -207,12 -209,50 +209,55 @@@ class SessionServiceSessionBusyError: If the session is already claimed."""with self._inflight_lock:++ if self._shutting_down:++ raise SessionBusyError("shutting down; no new runs are accepted")if session_id in self._inflight:raise SessionBusyError(f"Session {session_id} already has a run in progress")self._inflight.add(session_id)+ def _publish_background_completion(self, owner_id: str, payload: dict) -> None:+ """Route a background task's terminal state to its owning session.++ The AgentLoop that started the task may already have exited by the time+ the command finishes, so this cannot depend on a later iteration draining+ the queue. The payload keeps the attempt that started the task, which is+ the attempt the completion belongs to, not whichever one is current.+ """+ if not owner_id.startswith("session:"):+ return+ session_id = owner_id[len("session:"):]+ self.event_bus.emit(session_id, "background.completed", payload)++ def shutdown(self, *, timeout: float = 5.0) -> list[str]:+ """Stop accepting work, cancel owned background work, and wait for reaping.++ Does not tear down the event bus or thread pools this service may share+ with other hosts. Returns task ids still running after the wait, so an+ incomplete cleanup is reported instead of being called a success.+ """+ with self._inflight_lock:+ self._shutting_down = True+ with self._inflight_lock:+ tasks = [task for task in self._active_tasks.values() if not task.done()]++ for active_loop in list(self._active_loops.values()):++ active_loop.cancel()+ for task in tasks:- task.cancel()++ task.get_loop().call_soon_threadsafe(task.cancel)+ deadline = time.monotonic() + max(0.0, timeout)+ while any(not task.done() for task in tasks) and time.monotonic() < deadline:+ time.sleep(0.01)- pending = []++ pending = [f"attempt:{session_id}" for session_id, task in self._active_tasks.items()++ if not task.done()]+ for background in list(self._background_handles.values()):+ remaining = max(0.0, deadline - time.monotonic())+ # cancel_all, not shutdown: these handles sit over the process-wide+ # table, and closing it would stop unrelated hosts in this process.+ # New work is refused by the _shutting_down gate in send_message.+ pending.extend(background.cancel_all(timeout=remaining)["pending"])+ return pending+def _release_session(self, session_id: str) -> None:"""Release a session claim. Safe to call when no claim is held.@@@ -515,6 -563,6 +568,10 @@@self.store.delete_partial_response(session.session_id, attempt.attempt_id)self.event_bus.emit(session.session_id, "attempt.failed", {"attempt_id": attempt.attempt_id, "error": str(exc)})finally:++ if attempt.status != AttemptStatus.COMPLETED:++ background = self._background_handles.get(session.session_id)++ if background is not None:++ background.cancel_all()# The only release path for the claim taken in send_message.self._active_tasks.pop(session.session_id, None)self._user_cancel_requests.discard(session.session_id)@@@ -635,6 -687,6 +696,9 @@@session_id=session_id,),)++ except asyncio.CancelledError:++ agent.cancel()++ raisefinally:self._active_loops.pop(session_id, None)try:diff --cc agent/src/swarm/worker.pyindex 7df9628bd,860e1d8e7..162400683--- a/agent/src/swarm/worker.py+++ b/agent/src/swarm/worker.py@@@ -578,8 -578,8 +578,9 @@@ def run_workerWorkerResult with status, summary, artifacts, and iteration count."""llm = ChatLLM(model_name=agent_spec.model_name)++ result = Nonetry:-- return _run_worker_impl(++ result = _run_worker_impl(agent_spec=agent_spec,task=task,upstream_summaries=upstream_summaries,@@@ -592,10 -592,10 +593,22 @@@agent_config=agent_config,cancel_event=cancel_event,)++ return resultfinally:++ if result is None or result.status != "completed":++ _worker_background(run_dir, agent_spec.id, task.id).cancel_all()llm.close()++def _worker_background(run_dir: Path, agent_id: str, task_id: str):++ """Return the canonical background handle for a worker."""++ from src.tools.background_tools import BackgroundScope, get_background_manager++++ return get_background_manager().for_scope(BackgroundScope(++ owner_id=f"swarm:{Path(run_dir).resolve()}:{agent_id}:{task_id}", attempt_id=task_id,++ ))++++def _run_worker_impl(agent_spec: SwarmAgentSpec,task: SwarmTask,@@@ -665,13 -665,13 +678,8 @@@# Each worker owns its background tasks. Two workers running the same# preset concurrently must never read or cancel each other's commands, and# neither may see the tasks of the session that launched the swarm.-- from src.tools.background_tools import BackgroundScope, get_background_manager---- background_scope = BackgroundScope(- owner_id=f"swarm:{Path(run_dir).resolve()}:{agent_id}:{task_id}",- owner_id=f"swarm:{Path(run_dir).name}:{agent_id}:{task_id}",-- attempt_id=task_id,-- )-- background = get_background_manager().for_scope(background_scope)++ background = _worker_background(run_dir, agent_id, task_id)++ background_scope = background.scoperegistry = build_swarm_registry(agent_spec.tools,agent_config=agent_config,diff --cc agent/tests/test_background_host_lifecycle.pyindex 000000000,4d514045f..089781095mode 000000,100644..100644--- a/agent/tests/test_background_host_lifecycle.py+++ b/agent/tests/test_background_host_lifecycle.py@@@ -1,0 -1,233 +1,271 @@@+ """Real, harmless process fixtures for owner cancellation and host shutdown."""++ from __future__ import annotations++ import json+ import os+ import shlex+ import subprocess+ import sys+ import threading+ import time+ from pathlib import Path+ from types import SimpleNamespace++ import pytest++ from src.tools import background_tools as bg+++ def command(source: str) -> str:+ args = [sys.executable, "-c", source]+ return subprocess.list2cmdline(args) if os.name == "nt" else shlex.join(args)+++ def wait_until(predicate, timeout=8.0):+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if predicate():+ return+ time.sleep(0.01)+ raise AssertionError("process fixture did not reach the expected state")+++ @pytest.fixture+ def manager(tmp_path, monkeypatch):+ monkeypatch.setattr(bg, "WORKDIR", tmp_path)+ instance = bg.BackgroundManager(bg.BackgroundScope("host-a"))+ yield instance+ if hasattr(instance, "shutdown"):+ assert instance.shutdown(timeout=8.0) == []+ else:+ for task_id in list(instance.tasks):+ instance.cancel(task_id)+++ def launch(manager, ready: Path) -> str:+ task_id = json.loads(+ manager.run(command(f"from pathlib import Path; import time; Path({str(ready)!r}).touch(); time.sleep(60)"))+ )["task_id"]+ wait_until(ready.exists)+ return task_id+++ def test_cancel_all_reaps_only_its_owner(manager, tmp_path):+ sibling = manager.for_scope(bg.BackgroundScope("host-b"))+ mine = launch(manager, tmp_path / "a")+ theirs = launch(sibling, tmp_path / "b")+ outcome = manager.cancel_all(timeout=8.0)+ assert outcome == {"requested": 1, "pending": []}+ assert json.loads(manager.check(mine))["status"] == "cancelled"+ assert json.loads(sibling.check(theirs))["status"] == "running"+ assert manager.cancel_all(timeout=0) == {"requested": 0, "pending": []}+++ def test_shutdown_closes_all_handles_and_reaps(manager, tmp_path):+ sibling = manager.for_scope(bg.BackgroundScope("host-b"))+ launch(manager, tmp_path / "a")+ launch(sibling, tmp_path / "b")+ assert manager.shutdown(timeout=8.0) == []+ assert json.loads(sibling.run(command("print('must not run')")))["status"] == "error"+ assert all(t["status"] == "cancelled" and t["process"] is None for t in manager.tasks.values())+++ def test_cancellation_during_spawn_is_reaped(manager, monkeypatch):+ entered, release = threading.Event(), threading.Event()+ original = bg._start_process++ def delayed_start(cmd):+ entered.set()+ assert release.wait(5)+ return original(cmd)++ monkeypatch.setattr(bg, "_start_process", delayed_start)+ task_id = json.loads(manager.run(command("import time; time.sleep(60)")))["task_id"]+ try:+ assert entered.wait(5)+ assert manager.cancel_all(timeout=0)["pending"] == [task_id]+ assert json.loads(manager.check(task_id))["status"] == "cancelling"+ finally:+ release.set()+ assert manager.cancel_all(timeout=8)["pending"] == []+ assert json.loads(manager.check(task_id))["status"] == "cancelled"+++ def test_cancel_before_spawn_never_starts_command(manager, monkeypatch):+ class DeferredThread:+ def __init__(self, **kwargs):+ pass++ def start(self):+ pass++ monkeypatch.setattr(bg.threading, "Thread", DeferredThread)+ cmd = command("print('must not run')")+ task_id = json.loads(manager.run(cmd))["task_id"]+ manager.cancel(task_id)+ monkeypatch.setattr(bg, "_start_process", lambda _: pytest.fail("cancelled before spawn"))+ manager._execute(task_id, cmd)+ assert json.loads(manager.check(task_id))["status"] == "cancelled"+++ @pytest.mark.skipif(os.name == "nt", reason="POSIX process-group contract; Windows has native CI")+ def test_cancel_reaps_descendant_even_after_shell_exits(manager, tmp_path):+ ready = tmp_path / "child"+ child = f"import time; from pathlib import Path; Path({str(ready)!r}).touch(); time.sleep(60)"+ source = f"import subprocess, sys; subprocess.Popen([sys.executable, '-c', {child!r}])"+ task_id = json.loads(manager.run(command(source)))["task_id"]+ wait_until(ready.exists)+ wait_until(lambda: manager.tasks[task_id]["process"].poll() is not None)+ assert manager.cancel_all(timeout=8)["pending"] == []+ assert json.loads(manager.check(task_id))["status"] == "cancelled"+++ def test_session_cancel_reaps_background_tasks_before_its_turn_ends():+ from types import SimpleNamespace+ from src.session.service import SessionService++ calls = []+ service = SessionService.__new__(SessionService)+ manager = bg.BackgroundManager(bg.BackgroundScope("session:s1"))+ service._background_handles = {"s1": manager}+ service._active_tasks = {"s1": SimpleNamespace(done=lambda: False, cancel=lambda: calls.append("cancelled"))}+ service._active_loops = {}+ service._user_cancel_requests = set()+ service._inflight_lock = __import__("threading").Lock()+ service._inflight = set()+ service._shutting_down = False+ task_id = json.loads(manager.run(command("import time; time.sleep(60)")))["task_id"]+ assert service.cancel_current("s1") is True+ wait_until(lambda: json.loads(manager.check(task_id))["status"] == "cancelled")+ assert calls == ["cancelled"]+++ def test_session_shutdown_stops_new_work_and_reaps_tasks():+ import threading+ from src.session.service import SessionService++ service = SessionService.__new__(SessionService)+ service._background_handles = {"s1": bg.BackgroundManager(bg.BackgroundScope("session:s1"))}+ service._active_tasks = {}++ service._active_loops = {}+ service._inflight_lock = threading.Lock()+ service._inflight = set()+ service._shutting_down = False+ manager = service._background_handles["s1"]+ task_id = json.loads(manager.run(command("import time; time.sleep(60)")))["task_id"]+ assert service.shutdown(timeout=8.0) == []+ assert json.loads(manager.check(task_id))["status"] == "cancelled"+ # Refusal lives at the service gate: these handles share the process-wide+ # table, so closing that table would stop unrelated hosts in this process.+ service.store = SimpleNamespace(+ get_session=lambda session_id: SimpleNamespace(+ session_id=session_id,+ config={},+ last_attempt_id=None,+ )+ )+ service._search_index = SimpleNamespace(index_message=lambda *a, **k: None)+ service.event_bus = SimpleNamespace(emit=lambda *a, **k: None)+ with pytest.raises(RuntimeError, match="shutting down"):+ __import__("asyncio").run(service.send_message("s1", "hello"))+++ def test_session_attempt_registers_completion_with_its_owner():+ from src.session.service import SessionService++ emitted = []+ service = SessionService.__new__(SessionService)+ service.event_bus = SimpleNamespace(+ emit=lambda session_id, event_type, data: emitted.append((session_id, event_type, data)),+ )+ service._publish_background_completion(+ "session:s1",+ {+ "task_id": "task-1",+ "status": "completed",+ "attempt_id": "a1",+ "command": "echo done",+ "exit_code": 0,+ "result": "done",+ },+ )+ # A swarm worker's owner is not a session; it must not leak onto a bus.+ service._publish_background_completion("swarm:run:agent:task", {"task_id": "t"})+ assert emitted == [+ (+ "s1",+ "background.completed",+ {+ "task_id": "task-1",+ "status": "completed",+ "attempt_id": "a1",+ "command": "echo done",+ "exit_code": 0,+ "result": "done",+ },+ )+ ]+++ def test_agent_stop_reaps_tasks_it_started_or_carried():+ from src.agent.loop import AgentLoop++ registry = bg.BackgroundManager(bg.BackgroundScope("session:s1"))+ task_id = json.loads(registry.run(command("import time; time.sleep(60)")))["task_id"]+ loop = AgentLoop(+ registry=SimpleNamespace(get=lambda name: None, background=registry),+ llm=SimpleNamespace(),+ max_iterations=1,+ background_manager=registry,+ )+ loop.cancel()+ wait_until(lambda: json.loads(registry.check(task_id))["status"] == "cancelled")+++ def test_completion_callback_keeps_originating_attempt(manager):+ seen = []+ manager._on_completion = lambda owner, payload: seen.append((owner, payload))+ handle = manager.for_scope(bg.BackgroundScope("host-a", "attempt-1"))+ task_id = json.loads(handle.run(command("print('done')")))["task_id"]+ wait_until(lambda: bool(seen))+ assert seen[0][0] == "host-a"+ assert seen[0][1]["task_id"] == task_id+ assert seen[0][1]["attempt_id"] == "attempt-1"++++++++def test_shutdown_off_event_loop_cancels_real_async_attempt():++ import asyncio++ from src.session.service import SessionService++++ async def scenario():++ stopped = asyncio.Event()++ async def work():++ try:++ await asyncio.sleep(30)++ finally:++ stopped.set()++ task = asyncio.create_task(work())++ await asyncio.sleep(0)++ service = SessionService.__new__(SessionService)++ service._inflight_lock = threading.Lock()++ service._active_loops = {}++ service._active_tasks = {"s1": task}++ service._background_handles = {}++ assert await asyncio.to_thread(service.shutdown, timeout=2) == []++ assert stopped.is_set()++ assert task.cancelled()++ asyncio.run(scenario())++++[email protected]("status", ["success", "failed"])++def test_agent_terminal_status_only_cancels_background_on_failure(monkeypatch, status):++ from src.agent.loop import AgentLoop++ from unittest.mock import Mock++++ loop = AgentLoop.__new__(AgentLoop)++ loop._background_manager = Mock()++ monkeypatch.setattr(loop, "_run_bound", lambda *a: {"status": status})++ assert loop.run("test")["status"] == status++ assert loop._background_manager.cancel_all.call_count == (status == "failed")