"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(session): one run per session, honest terminal states (#676)
tyj147454413-cmd5353a1844579
diff --git a/agent/src/api/sessions_routes.py b/agent/src/api/sessions_routes.pyindex a779f20cc..4f33230d9 100644--- a/agent/src/api/sessions_routes.py+++ b/agent/src/api/sessions_routes.py@@ -16,6 +16,8 @@ from fastapi import Depends, FastAPI, HTTPException, Query, Request, statusfrom fastapi.responses import StreamingResponsefrom pydantic import BaseModel, Field+from src.session.service import SessionBusyError+logger = logging.getLogger(__name__)@@ -693,6 +695,10 @@ def register_sessions_routes(app: FastAPI) -> None:include_shell_tools=_host_shell_tools_enabled_for_request(http_request),)return result+ except SessionBusyError as exc:+ # Must precede ValueError-style handling and stay distinct from 404:+ # the session exists, it is simply already running.+ raise HTTPException(status_code=409, detail=str(exc)) from excexcept ValueError as exc:raise HTTPException(status_code=404, detail=str(exc))diff --git a/agent/src/channels/runtime.py b/agent/src/channels/runtime.pyindex 337f8c52c..ede1f7d79 100644--- a/agent/src/channels/runtime.py+++ b/agent/src/channels/runtime.py@@ -18,6 +18,7 @@ from src.channels.manager import ChannelManagerfrom src.channels.pairing import PAIRING_COMMAND_META_KEY, handle_pairing_commandfrom src.config.paths import get_data_dirfrom src.session.models import Message, Session+from src.session.service import SessionBusyErrorlogger = logging.getLogger(__name__)@@ -193,6 +194,21 @@ class ChannelRuntime:)except asyncio.CancelledError:raise+ except SessionBusyError:+ # A chat maps to one persistent session, so a second message sent+ # while the first is still running is ordinary user behaviour, not+ # a fault. Say so plainly instead of surfacing an exception name.+ await self.bus.publish_outbound(+ OutboundMessage(+ channel=msg.channel,+ chat_id=msg.chat_id,+ content=(+ "Still working on your previous message — send this again "+ "once I reply, or use the reset command to start over."+ ),+ metadata={"_channel_runtime": True, "busy": True},+ )+ )except Exception as exc: # noqa: BLE001 - channel errors must surface to userslogger.exception("Channel runtime failed for %s:%s", msg.channel, msg.chat_id)await self.bus.publish_outbound(diff --git a/agent/src/session/models.py b/agent/src/session/models.pyindex a6327c4a5..c87b10650 100644--- a/agent/src/session/models.py+++ b/agent/src/session/models.py@@ -207,3 +207,19 @@ class Attempt:self.status = AttemptStatus.FAILEDself.completed_at = _utc_now_iso()self.error = error++ def mark_cancelled(self, reason: str = "") -> None:+ """Mark the attempt as user-cancelled.++ Cancelled is a distinct terminal status from FAILED so the UI does+ not misreport a cooperative cancel as an outage. ``AttemptStatus.CANCELLED``+ was previously dead code: ``SessionService._run_attempt`` lumped the+ result in with the failure branch and overwrote the status with FAILED.++ Args:+ reason: Optional free-text reason (usually ``"cancelled by user"``).+ """+ self.status = AttemptStatus.CANCELLED+ self.completed_at = _utc_now_iso()+ if reason:+ self.error = reasondiff --git a/agent/src/session/service.py b/agent/src/session/service.pyindex abe6087db..8cdd8d2ab 100644--- a/agent/src/session/service.py+++ b/agent/src/session/service.py@@ -7,6 +7,7 @@ from __future__ import annotationsimport asyncioimport concurrent.futures+import threadingimport timefrom datetime import datetimefrom pathlib import Path@@ -26,6 +27,25 @@ from src.session.search import get_shared_indexfrom src.session.store import SessionStore+#: Terminal attempt status -> SSE event name. Cancellation is its own event so+#: the UI can distinguish a user stop from a failure, both live and on reload.+_TERMINAL_EVENTS = {+ "completed": "attempt.completed",+ "cancelled": "attempt.cancelled",+ "failed": "attempt.failed",+}+++class SessionBusyError(RuntimeError):+ """Raised when a session already has an in-flight run.++ One AgentLoop per session: a second concurrent send is rejected rather+ than queued, because two loops writing the same session would interleave+ their messages and attempts. Callers surface this as HTTP 409 so the user+ can wait for the running attempt or cancel it first.+ """++class SessionService:"""Session lifecycle service.@@ -51,9 +71,40 @@ class SessionService:self.store = storeself.event_bus = event_busself.runs_dir = runs_dir+ # _active_loops is the cancellation handle only. It is populated after+ # the registry is built, which is far too late to serve as the+ # concurrency gate, so in-flight sessions are tracked separately and+ # reserved synchronously in send_message.self._active_loops: Dict[str, "AgentLoop"] = {}+ self._inflight: set[str] = set()+ self._inflight_lock = threading.Lock()self._search_index = get_shared_index()+ def _reserve_session(self, session_id: str) -> None:+ """Claim a session for one in-flight run.++ Args:+ session_id: Session to claim.++ Raises:+ SessionBusyError: If the session is already claimed.+ """+ with self._inflight_lock:+ if session_id in self._inflight:+ raise SessionBusyError(+ f"Session {session_id} already has a run in progress"+ )+ self._inflight.add(session_id)++ def _release_session(self, session_id: str) -> None:+ """Release a session claim. Safe to call when no claim is held.++ Args:+ session_id: Session to release.+ """+ with self._inflight_lock:+ self._inflight.discard(session_id)+def create_session(self, title: str = "", config: Optional[Dict[str, Any]] = None) -> Session:"""Create a new session.@@ -101,29 +152,49 @@ class SessionService:Returns:Dictionary containing message_id and attempt_id.++ Raises:+ ValueError: If the session does not exist.+ SessionBusyError: If the session already has a run in progress.+ Callers surface this as HTTP 409; the user can wait for the+ running attempt or cancel it first."""session = self.store.get_session(session_id)if not session:raise ValueError(f"Session {session_id} not found")- message = Message(session_id=session_id, role=role, content=content)- self.store.append_message(message)- self._search_index.index_message(session_id, role, content)- self.event_bus.emit(session_id, "message.received", {"message_id": message.message_id, "role": role, "content": content})-- if role != "user":- return {"message_id": message.message_id}-- attempt = Attempt(session_id=session_id, parent_attempt_id=session.last_attempt_id, prompt=content)- self.store.create_attempt(attempt)- session.config["include_shell_tools"] = include_shell_tools- session.last_attempt_id = attempt.attempt_id- session.updated_at = datetime.now().isoformat()- self.store.update_session(session)- self.event_bus.emit(session_id, "attempt.created", {"attempt_id": attempt.attempt_id, "prompt": content})+ # Claim the session before persisting anything. Reserving after the+ # user message is appended (or relying on _active_loops, which is only+ # populated once the registry is built) lets two concurrent sends both+ # store a message and create an attempt.+ if role == "user":+ self._reserve_session(session_id)+ handed_off = False- asyncio.create_task(self._run_attempt(session, attempt, include_shell_tools=include_shell_tools))- return {"message_id": message.message_id, "attempt_id": attempt.attempt_id}+ try:+ message = Message(session_id=session_id, role=role, content=content)+ self.store.append_message(message)+ self._search_index.index_message(session_id, role, content)+ self.event_bus.emit(session_id, "message.received", {"message_id": message.message_id, "role": role, "content": content})++ if role != "user":+ return {"message_id": message.message_id}++ attempt = Attempt(session_id=session_id, parent_attempt_id=session.last_attempt_id, prompt=content)+ self.store.create_attempt(attempt)+ session.config["include_shell_tools"] = include_shell_tools+ session.last_attempt_id = attempt.attempt_id+ session.updated_at = datetime.now().isoformat()+ self.store.update_session(session)+ self.event_bus.emit(session_id, "attempt.created", {"attempt_id": attempt.attempt_id, "prompt": content})++ asyncio.create_task(self._run_attempt(session, attempt, include_shell_tools=include_shell_tools))+ # _run_attempt now owns the claim and releases it in its finally.+ handed_off = True+ return {"message_id": message.message_id, "attempt_id": attempt.attempt_id}+ finally:+ if role == "user" and not handed_off:+ self._release_session(session_id)def get_messages(self, session_id: str, limit: int = 100) -> list[Message]:"""Return the message history."""@@ -158,11 +229,21 @@ class SessionService:include_shell_tools=include_shell_tools,session_config=dict(session.config),)- if result.get("status") == "success":+ status = result.get("status")+ if status == "success":attempt.mark_completed(summary=result.get("content", ""))+ elif status == "cancelled":+ # A cooperative cancel is not an outage; AttemptStatus.CANCELLED+ # existed but was dead because every non-success landed in the+ # failure branch.+ attempt.mark_cancelled(reason=result.get("reason", "cancelled by user"))else:attempt.mark_failed(error=result.get("reason", "unknown"))attempt.run_dir = result.get("run_dir")+ if result.get("metrics"):+ # Metrics were loaded from the run directory but never reached+ # the attempt, so the reply metadata below was always empty.+ attempt.metrics = result["metrics"]self.store.update_attempt(attempt)reply_metadata = {}@@ -187,7 +268,7 @@ class SessionService:self._search_index.index_message(session.session_id, "assistant", reply.content)self.event_bus.emit(session.session_id,- "attempt.completed" if attempt.status == AttemptStatus.COMPLETED else "attempt.failed",+ _TERMINAL_EVENTS.get(attempt.status.value, "attempt.failed"),{"attempt_id": attempt.attempt_id, "status": attempt.status.value,"summary": attempt.summary, "error": attempt.error, "run_dir": attempt.run_dir},)@@ -196,6 +277,9 @@ class SessionService:attempt.mark_failed(error=str(exc))self.store.update_attempt(attempt)self.event_bus.emit(session.session_id, "attempt.failed", {"attempt_id": attempt.attempt_id, "error": str(exc)})+ finally:+ # The only release path for the claim taken in send_message.+ self._release_session(session.session_id)async def _run_with_agent(self,@@ -404,11 +488,18 @@ class SessionService:total_chars = 0trimmed: list = []for msg in reversed(history):- msg_len = len(msg.get("content", ""))- if total_chars + msg_len > MAX_HISTORY_CHARS:- break- trimmed.append(msg)- total_chars += msg_len+ content = msg.get("content", "")+ remaining = MAX_HISTORY_CHARS - total_chars+ if len(content) <= remaining:+ trimmed.append(msg)+ total_chars += len(content)+ continue+ # A single oversized message must not wipe the whole window: when+ # nothing has been kept yet, the newest turn survives truncated+ # rather than the agent starting with no history at all.+ if not trimmed:+ trimmed.append({**msg, "content": content[:remaining] + "\n[... truncated]"})+ breakreturn list(reversed(trimmed))@staticmethod@@ -429,7 +520,23 @@ class SessionService:@staticmethoddef _format_result_message(attempt: Attempt) -> str:- """Format the final execution result message."""+ """Format the final execution result message.++ Args:+ attempt: The terminal attempt.++ Returns:+ The reply text shown in the transcript.+ """if attempt.status == AttemptStatus.COMPLETED:- return attempt.summary or "Strategy execution completed."+ if attempt.summary:+ return attempt.summary+ # Do not dress an empty answer up as a finished strategy run: say+ # that nothing came back so the user knows to retry or rephrase.+ return (+ "The run finished without producing any text output. "+ "Check the run artifacts, or rephrase the request and try again."+ )+ if attempt.status == AttemptStatus.CANCELLED:+ return "Run cancelled."return f"Execution failed: {attempt.error or 'unknown error'}"diff --git a/agent/tests/test_session_service_lifecycle.py b/agent/tests/test_session_service_lifecycle.pynew file mode 100644index 000000000..361a13e18--- /dev/null+++ b/agent/tests/test_session_service_lifecycle.py@@ -0,0 +1,248 @@+"""Session lifecycle invariants: one run per session, honest terminal states."""++from __future__ import annotations++import asyncio+from pathlib import Path++import pytest++from src.session.events import EventBus+from src.session.models import Attempt, AttemptStatus+from src.session.service import SessionBusyError, SessionService+from src.session.store import SessionStore+++class _DummyIndex:+ def index_session(self, session_id: str, title: str) -> None:+ del session_id, title++ def index_message(self, session_id: str, role: str, content: str) -> None:+ del session_id, role, content+++def _service(tmp_path: Path, monkeypatch) -> SessionService:+ monkeypatch.setattr("src.session.service.get_shared_index", lambda: _DummyIndex())+ return SessionService(+ store=SessionStore(tmp_path / "sessions"),+ event_bus=EventBus(),+ runs_dir=tmp_path / "runs",+ )+++def _stub_agent(service: SessionService, monkeypatch, result: dict, *, gate=None):+ """Replace _run_with_agent with a stub returning ``result``.++ Args:+ service: Service under test.+ monkeypatch: pytest monkeypatch fixture.+ result: Result dict the fake agent returns.+ gate: Optional asyncio.Event the fake agent waits on before returning,+ used to hold a run in flight while a second send is attempted.+ """++ async def _fake(attempt, messages=None, **kwargs):+ del attempt, messages, kwargs+ if gate is not None:+ await gate.wait()+ return dict(result)++ monkeypatch.setattr(service, "_run_with_agent", _fake)+++# ---------------------------------------------------------------------------+# Concurrency+# ---------------------------------------------------------------------------+++def test_second_send_is_refused_while_the_first_run_is_in_flight(tmp_path, monkeypatch):+ """The claim is taken synchronously, so no second attempt is ever created."""++ async def scenario() -> None:+ service = _service(tmp_path, monkeypatch)+ session = service.create_session(title="busy")+ gate = asyncio.Event()+ _stub_agent(service, monkeypatch, {"status": "success", "content": "ok"}, gate=gate)++ first = await service.send_message(session.session_id, "one")+ assert first["attempt_id"]++ with pytest.raises(SessionBusyError):+ await service.send_message(session.session_id, "two")++ # The refused send must not have persisted a message or an attempt.+ assert [m.content for m in service.store.get_messages(session.session_id)] == ["one"]+ stored = service.store.get_session(session.session_id)+ assert stored.last_attempt_id == first["attempt_id"]++ gate.set()+ for _ in range(100):+ await asyncio.sleep(0.01)+ if session.session_id not in service._inflight:+ break+ assert session.session_id not in service._inflight++ asyncio.run(scenario())+++def test_claim_is_released_after_the_run_finishes(tmp_path, monkeypatch):+ """A sequential second send succeeds once the first run reaches a terminal state."""++ async def scenario() -> None:+ service = _service(tmp_path, monkeypatch)+ session = service.create_session(title="sequential")+ _stub_agent(service, monkeypatch, {"status": "success", "content": "ok"})++ await service.send_message(session.session_id, "one")+ for _ in range(100):+ await asyncio.sleep(0.01)+ if session.session_id not in service._inflight:+ break+ assert session.session_id not in service._inflight++ second = await service.send_message(session.session_id, "two")+ assert second["attempt_id"]++ asyncio.run(scenario())+++def test_claim_is_released_when_the_agent_raises(tmp_path, monkeypatch):+ """An exception inside the run must not strand the session as busy."""++ async def scenario() -> None:+ service = _service(tmp_path, monkeypatch)+ session = service.create_session(title="boom")++ async def _explode(attempt, messages=None, **kwargs):+ del attempt, messages, kwargs+ raise RuntimeError("agent exploded")++ monkeypatch.setattr(service, "_run_with_agent", _explode)++ await service.send_message(session.session_id, "one")+ for _ in range(100):+ await asyncio.sleep(0.01)+ if session.session_id not in service._inflight:+ break+ assert session.session_id not in service._inflight+ stored = service.store.get_session(session.session_id)+ attempt = service.store.get_attempt(session.session_id, stored.last_attempt_id)+ assert attempt.status == AttemptStatus.FAILED++ asyncio.run(scenario())+++def test_non_user_roles_never_claim_the_session(tmp_path, monkeypatch):+ """System/assistant messages create no attempt, so they must not block sends."""++ async def scenario() -> None:+ service = _service(tmp_path, monkeypatch)+ session = service.create_session(title="notes")+ _stub_agent(service, monkeypatch, {"status": "success", "content": "ok"})++ await service.send_message(session.session_id, "note", role="system")+ assert session.session_id not in service._inflight+ assert await service.send_message(session.session_id, "real")++ asyncio.run(scenario())+++# ---------------------------------------------------------------------------+# Terminal states+# ---------------------------------------------------------------------------+++def test_cancelled_run_is_cancelled_not_failed(tmp_path, monkeypatch):+ """A cooperative cancel gets its own status, event and reply text."""++ async def scenario() -> None:+ service = _service(tmp_path, monkeypatch)+ session = service.create_session(title="cancel")+ seen: list[str] = []+ service.event_bus.emit = lambda sid, event, data: seen.append(event) # type: ignore[assignment]+ _stub_agent(+ service,+ monkeypatch,+ {"status": "cancelled", "reason": "cancelled by user"},+ )++ await service.send_message(session.session_id, "go")+ for _ in range(100):+ await asyncio.sleep(0.01)+ if session.session_id not in service._inflight:+ break++ stored = service.store.get_session(session.session_id)+ attempt = service.store.get_attempt(session.session_id, stored.last_attempt_id)+ assert attempt.status == AttemptStatus.CANCELLED+ assert "attempt.cancelled" in seen+ assert "attempt.failed" not in seen+ reply = service.store.get_messages(session.session_id)[-1]+ assert reply.content == "Run cancelled."++ asyncio.run(scenario())+++def test_metrics_reach_the_attempt_and_the_reply(tmp_path, monkeypatch):+ """Loaded metrics were dropped on the floor before reaching the reply."""++ async def scenario() -> None:+ service = _service(tmp_path, monkeypatch)+ session = service.create_session(title="metrics")+ _stub_agent(+ service,+ monkeypatch,+ {"status": "success", "content": "done", "metrics": {"sharpe": 1.25}},+ )++ await service.send_message(session.session_id, "backtest")+ for _ in range(100):+ await asyncio.sleep(0.01)+ if session.session_id not in service._inflight:+ break++ stored = service.store.get_session(session.session_id)+ attempt = service.store.get_attempt(session.session_id, stored.last_attempt_id)+ assert attempt.metrics == {"sharpe": 1.25}+ reply = service.store.get_messages(session.session_id)[-1]+ assert reply.metadata["metrics"] == {"sharpe": 1.25}++ asyncio.run(scenario())+++def test_empty_successful_answer_says_so():+ """An empty answer must not be dressed up as a finished strategy run."""+ attempt = Attempt(session_id="s" * 12, prompt="p")+ attempt.mark_completed(summary="")+ message = SessionService._format_result_message(attempt)+ assert "without producing any text output" in message+ assert "Strategy execution completed" not in message+++# ---------------------------------------------------------------------------+# History window+# ---------------------------------------------------------------------------+++def test_one_oversized_message_does_not_empty_the_history_window():+ """The newest turn survives truncated instead of the window collapsing."""+ messages = [+ type("M", (), {"role": "user", "content": "older turn"})(),+ type("M", (), {"role": "assistant", "content": "x" * 20000})(),+ type("M", (), {"role": "user", "content": "current turn is dropped"})(),+ ]+ history = SessionService._convert_messages_to_history(messages)+ assert history, "an oversized newest message wiped the entire window"+ assert history[-1]["content"].endswith("[... truncated]")+ assert len(history[-1]["content"]) <= 12000 + len("\n[... truncated]")+++def test_normal_history_is_untouched():+ """Messages inside the budget are passed through unchanged."""+ messages = [+ type("M", (), {"role": "user", "content": "first"})(),+ type("M", (), {"role": "assistant", "content": "second"})(),+ type("M", (), {"role": "user", "content": "current turn is dropped"})(),+ ]+ history = SessionService._convert_messages_to_history(messages)+ assert [m["content"] for m in history] == ["first", "second"]diff --git a/frontend/src/hooks/useSSE.ts b/frontend/src/hooks/useSSE.tsindex 031869449..721f05e36 100644--- a/frontend/src/hooks/useSSE.ts+++ b/frontend/src/hooks/useSSE.ts@@ -88,6 +88,7 @@ export function useSSE(config?: SSEConfig) {"tool_heartbeat", "tool_progress", "llm_usage","swarm.started", "swarm.event","attempt.created", "attempt.started", "attempt.completed", "attempt.failed",+ "attempt.cancelled","message.received", "session.created","goal.created", "goal.evidence", "goal.updated","mandate.proposal", "mandate.committed", "live.halted", "live.resumed", "live.action",diff --git a/frontend/src/pages/Agent.tsx b/frontend/src/pages/Agent.tsxindex 306eb8b00..6b30af330 100644--- a/frontend/src/pages/Agent.tsx+++ b/frontend/src/pages/Agent.tsx@@ -500,7 +500,11 @@ export function Agent() {fallbackTimestamp: ts,idPrefix: `${m.message_id}_`,attemptId: m.linked_attempt_id || `${m.message_id}_attempt`,- state: meta?.status === "failed" ? "failed" : "done",+ state: meta?.status === "failed"+ ? "failed"+ : meta?.status === "cancelled"+ ? "stopped"+ : "done",endedAt: ts,}): [];@@ -924,6 +928,42 @@ export function Agent() {scrollToBottom();},+ // A user stop is its own terminal event now, so it no longer arrives as+ // attempt.failed and no longer needs the pre-marked "stopped" workaround+ // to avoid showing an error bubble.+ "attempt.cancelled": (d) => {+ touch();+ const attemptId = String(d.attempt_id || "");+ if (act().sessionId !== sid) {+ act().clearStreamingSession(sid);+ return;+ }+ const archived = act().messages.find(+ (message) => message.meta?.activity?.attemptId === attemptId,+ )?.meta?.activity;+ if (archived && archived.state !== "stopped") {+ useAgentStore.setState((state) => ({+ messages: state.messages.map((message) => (+ message.meta?.activity?.attemptId === attemptId+ ? {+ ...message,+ meta: {+ ...message.meta,+ activity: { ...archived, state: "stopped", endedAt: Date.now() },+ },+ }+ : message+ )),+ }));+ } else if (!archived) {+ if (!act().activity) act().startActivity(attemptId || `cancelled-${Date.now()}`);+ archiveActivity("stopped");+ }+ clearStreamingView();+ act().setStatus("idle");+ scrollToBottom();+ },+"goal.created": () => {touch();loadGoalSnapshot(sid);