"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(session): recover interrupted replies after restart
huanghua01884c08e1e24c
diff --git a/README.md b/README.mdindex a305d57b3..501e3044c 100644--- a/README.md+++ b/README.md@@ -799,7 +799,7 @@ Docker publishes the backend on `127.0.0.1:8899` by default and runs the app as> [!NOTE]> **Using Ollama with Docker:** the container reaches a host-side Ollama via `host.docker.internal`, not `localhost` (inside the container `localhost` is the container itself). `docker-compose.yml` defaults `OLLAMA_BASE_URL` to `http://host.docker.internal:11434`; export `OLLAMA_BASE_URL` (or set it in a top-level `.env`) to point elsewhere. This relies on the `host-gateway` mapping in `extra_hosts`, which requires **Docker Engine ≥ 20.10 / Compose v2** (provided automatically on Docker Desktop).-Your data survives updates: persistent memory, the cross-session search index, user-created skills, shadow accounts, broker connector config, web sessions, backtest runs, swarm history, and uploads all live in named Docker volumes, so `git pull && docker compose up --build` keeps them. They are deleted only by `docker compose down -v`.+Your data survives updates: persistent memory, the cross-session search index, user-created skills, shadow accounts, broker connector config, web sessions, backtest runs, swarm history, and uploads all live in named Docker volumes, so `git pull && docker compose up --build` keeps them. In-progress Web replies are checkpointed too, so a restart restores the partial response and marks the attempt interrupted instead of silently dropping it. Data is deleted only by `docker compose down -v`.### Path B: Local installdiff --git a/agent/src/session/checkpoint.py b/agent/src/session/checkpoint.pynew file mode 100644index 000000000..6c4e704b3--- /dev/null+++ b/agent/src/session/checkpoint.py@@ -0,0 +1,90 @@+"""Durable checkpoints for an assistant response that is still streaming."""++from __future__ import annotations++import threading+import time+from typing import Any, Dict++from src.session.models import Attempt+from src.session.store import SessionStore+++class ResponseCheckpoint:+ """Persist a bounded-frequency snapshot of streamed assistant text.++ The first text chunk is written immediately. Later chunks are coalesced to+ avoid an fsync for every provider token, and :meth:`flush` captures the+ remaining buffer when the run leaves the streaming loop.+ """++ def __init__(+ self,+ store: SessionStore,+ attempt: Attempt,+ *,+ min_interval_seconds: float = 0.25,+ ) -> None:+ """Create a response checkpoint.++ Args:+ store: Session persistence store.+ attempt: Attempt whose response is being streamed.+ min_interval_seconds: Minimum time between snapshot writes.+ """+ self._store = store+ self._session_id = attempt.session_id+ self._attempt_id = attempt.attempt_id+ self._min_interval_seconds = max(0.0, min_interval_seconds)+ self._text = ""+ self._dirty = False+ self._last_flush = 0.0+ self._lock = threading.Lock()++ def handle_event(self, event_type: str, data: Dict[str, Any]) -> None:+ """Apply an AgentLoop stream event to the durable snapshot.++ Args:+ event_type: Agent event name.+ data: Event payload.+ """+ if event_type not in {"text_delta", "stream_reset"}:+ return++ with self._lock:+ if event_type == "stream_reset":+ self._text = ""+ self._dirty = True+ self._flush_locked()+ # The replacement stream's first chunk should be durable+ # immediately, just like the original stream's first chunk.+ self._last_flush = 0.0+ return++ delta = data.get("delta")+ if not isinstance(delta, str) or not delta:+ return+ self._text += delta+ self._dirty = True+ now = time.monotonic()+ if (+ self._last_flush == 0.0+ or now - self._last_flush >= self._min_interval_seconds+ ):+ self._flush_locked(now)++ def flush(self) -> None:+ """Persist any text accumulated since the last snapshot."""+ with self._lock:+ self._flush_locked()++ def _flush_locked(self, now: float | None = None) -> None:+ if not self._dirty:+ return+ self._store.save_partial_response(+ self._session_id,+ self._attempt_id,+ self._text,+ )+ self._dirty = False+ self._last_flush = time.monotonic() if now is None else nowdiff --git a/agent/src/session/models.py b/agent/src/session/models.pyindex 7e07736e1..df5e61c3a 100644--- a/agent/src/session/models.py+++ b/agent/src/session/models.py@@ -135,6 +135,7 @@ class AttemptStatus(str, Enum):COMPLETED = "completed"FAILED = "failed"CANCELLED = "cancelled"+ INTERRUPTED = "interrupted"@dataclass@@ -339,3 +340,14 @@ class Attempt:self.completed_at = _utc_now_iso()if reason:self.error = reason++ def mark_interrupted(self, reason: str = "") -> None:+ """Mark the attempt as interrupted by process lifecycle.++ Args:+ reason: Optional explanation of the interruption.+ """+ self.status = AttemptStatus.INTERRUPTED+ self.completed_at = _utc_now_iso()+ if reason:+ self.error = reasondiff --git a/agent/src/session/service.py b/agent/src/session/service.pyindex b8fc24642..6bf6aede9 100644--- a/agent/src/session/service.py+++ b/agent/src/session/service.py@@ -7,12 +7,14 @@ from __future__ import annotationsimport asyncioimport concurrent.futures+import loggingimport threadingimport timefrom datetime import datetimefrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Dict, Optional+from src.session.checkpoint import ResponseCheckpointfrom src.session.events import EventBusfrom src.session.models import (Attempt,@@ -29,6 +31,7 @@ if TYPE_CHECKING:# Dedicated thread pool limited to four concurrent agents to avoid exhausting the default executor._AGENT_EXECUTOR = concurrent.futures.ThreadPoolExecutor(max_workers=4, thread_name_prefix="agent")+logger = logging.getLogger(__name__)#: Terminal attempt status -> SSE event name. Cancellation is its own event so@@ -86,9 +89,92 @@ class SessionService:# only cancellation route: a hung discovery would otherwise hold the# claim forever and lock the session behind 409.self._active_tasks: Dict[str, "asyncio.Task"] = {}+ # Only task cancellation requested through cancel_current is a user+ # cancellation. Event-loop shutdown also raises CancelledError, but+ # that attempt must remain recoverable on the next process start.+ self._user_cancel_requests: set[str] = set()self._inflight: set[str] = set()self._inflight_lock = threading.Lock()self._search_index = get_shared_index()+ self._recover_interrupted_attempts()++ def _recover_interrupted_attempts(self) -> None:+ """Finalize attempts that could not outlive the previous process.++ A newly constructed service has no live AgentLoop instances. Any+ attempt still marked pending or running therefore belongs to the+ previous process. Convert it to an explicit terminal state and expose+ the most recent durable response snapshot in conversation history.+ """+ recoverable = {AttemptStatus.PENDING, AttemptStatus.RUNNING}+ for attempt in self.store.list_attempts():+ if attempt.status not in recoverable:+ continue+ partial = self.store.get_partial_response(+ attempt.session_id, attempt.attempt_id+ )+ has_partial = bool(partial)+ existing_reply = self.store.get_message_for_attempt(+ attempt.session_id, attempt.attempt_id+ )+ if existing_reply is None:+ reply = Message(+ session_id=attempt.session_id,+ role="assistant",+ content=self._format_interrupted_message(partial),+ linked_attempt_id=attempt.attempt_id,+ metadata={+ "status": AttemptStatus.INTERRUPTED.value,+ "partial": has_partial,+ "recovery_reason": "service_restart",+ },+ )+ self.store.append_message(reply)+ self._search_index.index_message(+ attempt.session_id, "assistant", reply.content+ )+ attempt.mark_interrupted("service restarted before attempt completed")+ else:+ # The append-only reply is committed before attempt.json. If a+ # process exits between those writes, finish the second half+ # from the reply's terminal metadata instead of mislabelling a+ # complete response as interrupted.+ reply_status = existing_reply.metadata.get("status")+ if reply_status == AttemptStatus.COMPLETED.value:+ attempt.mark_completed(summary=existing_reply.content)+ elif reply_status == AttemptStatus.CANCELLED.value:+ attempt.mark_cancelled(reason="cancelled by user")+ elif reply_status == AttemptStatus.FAILED.value:+ attempt.mark_failed(error="execution failed")+ else:+ attempt.mark_interrupted(+ "service restarted before attempt completed"+ )+ self.store.update_attempt(attempt)+ self.store.delete_partial_response(attempt.session_id, attempt.attempt_id)++ @staticmethod+ def _format_interrupted_message(partial: Optional[str]) -> str:+ """Build the transcript message for a recovered attempt.++ Args:+ partial: Durable assistant text captured before restart.++ Returns:+ User-facing interruption notice, including partial text when any.+ """+ if partial:+ return (+ "Vibe Trading restarted before this response finished. "+ "The partial response recovered below may be incomplete:\n\n"+ f"{partial}\n\n"+ "Review it before sending a follow-up or retrying the request."+ )+ return (+ "Vibe Trading restarted before this response finished, so no "+ "complete assistant response was saved. Review any completed tool "+ "actions before retrying the request."+ )def _reserve_session(self, session_id: str) -> None:"""Claim a session for one in-flight run.@@ -241,6 +327,7 @@ class SessionService:# itself so the claim is released instead of stranding the session.task = self._active_tasks.get(session_id)if task is not None and not task.done():+ self._user_cancel_requests.add(session_id)task.cancel()return Truereturn False@@ -281,7 +368,6 @@ class SessionService:# the attempt, so the reply metadata below was always empty.attempt.metrics = result["metrics"]- self.store.update_attempt(attempt)reply_metadata = {}if attempt.run_dir:reply_metadata["run_id"] = Path(attempt.run_dir).name@@ -313,6 +399,11 @@ class SessionService:),)self.store.append_message(reply)+ # The append-only transcript is the user-visible source of truth.+ # Commit it before attempt.json so startup recovery can finish a+ # process interrupted between the two writes.+ self.store.update_attempt(attempt)+ self.store.delete_partial_response(session.session_id, attempt.attempt_id)self._search_index.index_message(session.session_id, "assistant", reply.content)self.event_bus.emit(session.session_id,@@ -323,24 +414,35 @@ class SessionService:)except asyncio.CancelledError:- # cancel_current() cancels this task when the run has not reached- # its AgentLoop yet. CancelledError is a BaseException, so it would- # slip past the handler below and leave the attempt stuck RUNNING.- attempt.mark_cancelled(reason="cancelled by user")- self.store.update_attempt(attempt)- self.event_bus.emit(- session.session_id,- "attempt.cancelled",- {"attempt_id": attempt.attempt_id, "status": attempt.status.value},- )+ if session.session_id in self._user_cancel_requests:+ # cancel_current() cancels this task when the run has not+ # reached its AgentLoop yet. Keep that explicit user action+ # distinct from event-loop cancellation during server shutdown.+ attempt.mark_cancelled(reason="cancelled by user")+ self.store.update_attempt(attempt)+ self.store.delete_partial_response(+ session.session_id, attempt.attempt_id+ )+ self.event_bus.emit(+ session.session_id,+ "attempt.cancelled",+ {"attempt_id": attempt.attempt_id, "status": attempt.status.value},+ )+ else:+ logger.info(+ "Leaving attempt %s recoverable after service task cancellation",+ attempt.attempt_id,+ )raiseexcept Exception as exc:attempt.mark_failed(error=str(exc))self.store.update_attempt(attempt)+ 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:# 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)self._release_session(session.session_id)async def _run_with_agent(@@ -378,12 +480,23 @@ class SessionService:attempt_id = attempt.attempt_idloop = asyncio.get_running_loop()tool_trail: list[Dict[str, Any]] = []+ checkpoint = ResponseCheckpoint(self.store, attempt)safe_overrides = sanitize_session_overrides(session_config) if session_config else session_configagent_config = load_runtime_agent_config(overrides=safe_overrides)def event_callback(event_type: str, data: Dict[str, Any]) -> None:"""Forward AgentLoop events to the SSE event bus."""+ try:+ checkpoint.handle_event(event_type, data)+ except OSError as exc:+ # A checkpoint failure must not hide the live response or stop+ # the agent. The terminal attempt write still gets a chance.+ logger.warning(+ "Could not checkpoint response for attempt %s: %s",+ attempt_id,+ exc,+ )if event_type in {"tool_call", "tool_result"}:self._record_tool_trail_event(tool_trail, event_type, data)data["attempt_id"] = attempt_id@@ -428,6 +541,14 @@ class SessionService:)finally:self._active_loops.pop(session_id, None)+ try:+ checkpoint.flush()+ except OSError as exc:+ logger.warning(+ "Could not flush response checkpoint for attempt %s: %s",+ attempt_id,+ exc,+ )result["tool_trail"] = tool_traildiff --git a/agent/src/session/store.py b/agent/src/session/store.pyindex 0d8ec6bdc..d29a160de 100644--- a/agent/src/session/store.py+++ b/agent/src/session/store.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport jsonimport loggingimport os+import tempfilefrom pathlib import Pathfrom typing import Any, Dict, List, Optional@@ -54,6 +55,9 @@ class SessionStore:def _attempt_file(self, session_id: str, attempt_id: str) -> Path:return self._attempt_dir(session_id, attempt_id) / "attempt.json"+ def _partial_response_file(self, session_id: str, attempt_id: str) -> Path:+ return self._attempt_dir(session_id, attempt_id) / "partial_response.json"+# ---- Session CRUD ----def create_session(self, session: Session) -> Session:@@ -238,15 +242,102 @@ class SessionStore:attempt.to_dict(),)+ def list_attempts(self) -> List[Attempt]:+ """Read every valid persisted attempt.++ Returns:+ Attempts found below the session storage root.+ """+ attempts: List[Attempt] = []+ for path in self.base_dir.glob("*/attempts/*/attempt.json"):+ data = self._read_json(path)+ if not isinstance(data, dict):+ continue+ try:+ attempts.append(Attempt.from_dict(data))+ except (TypeError, ValueError, KeyError) as exc:+ logger.warning("Skipping corrupt attempt file %s: %s", path, exc)+ return attempts++ def get_message_for_attempt(+ self, session_id: str, attempt_id: str+ ) -> Optional[Message]:+ """Return the persisted assistant message linked to an attempt.++ Args:+ session_id: Session ID.+ attempt_id: Attempt ID.++ Returns:+ The linked message, or None when the reply is not in the log.+ """+ for message in reversed(self.get_messages(session_id, limit=1_000_000)):+ if message.linked_attempt_id == attempt_id:+ return message+ return None++ # ---- Streaming Response Checkpoints ----++ def save_partial_response(+ self, session_id: str, attempt_id: str, content: str+ ) -> None:+ """Atomically persist the current streamed assistant text.++ Args:+ session_id: Session ID.+ attempt_id: Attempt ID.+ content: Assistant text accumulated so far.+ """+ self._write_json(+ self._partial_response_file(session_id, attempt_id),+ {"content": content},+ )++ def get_partial_response(self, session_id: str, attempt_id: str) -> Optional[str]:+ """Read a streamed assistant response checkpoint.++ Args:+ session_id: Session ID.+ attempt_id: Attempt ID.++ Returns:+ Saved response text, or None when no checkpoint exists.+ """+ data = self._read_json(self._partial_response_file(session_id, attempt_id))+ if not isinstance(data, dict):+ return None+ content = data.get("content")+ return content if isinstance(content, str) else None++ def delete_partial_response(self, session_id: str, attempt_id: str) -> None:+ """Remove a response checkpoint after the attempt becomes terminal.++ Args:+ session_id: Session ID.+ attempt_id: Attempt ID.+ """+ self._partial_response_file(session_id, attempt_id).unlink(missing_ok=True)+# ---- IO Helpers ----@staticmethoddef _write_json(path: Path, data: Dict[str, Any]) -> None:path.parent.mkdir(parents=True, exist_ok=True)- path.write_text(- json.dumps(data, ensure_ascii=False, indent=2),- encoding="utf-8",+ encoded = json.dumps(data, ensure_ascii=False, indent=2).encode("utf-8")+ fd, temporary_name = tempfile.mkstemp(+ dir=path.parent,+ prefix=f".{path.name}.",+ suffix=".tmp",)+ temporary_path = Path(temporary_name)+ try:+ with os.fdopen(fd, "wb") as temporary_file:+ temporary_file.write(encoded)+ temporary_file.flush()+ os.fsync(temporary_file.fileno())+ os.replace(temporary_path, path)+ finally:+ temporary_path.unlink(missing_ok=True)@staticmethoddef _read_json(path: Path) -> Optional[Dict[str, Any]]:diff --git a/agent/tests/test_session_restart_recovery.py b/agent/tests/test_session_restart_recovery.pynew file mode 100644index 000000000..e0e8774f4--- /dev/null+++ b/agent/tests/test_session_restart_recovery.py@@ -0,0 +1,177 @@+"""Recovery regressions for assistant replies interrupted by a restart."""++from __future__ import annotations++import asyncio+from pathlib import Path++import pytest++from src.session.checkpoint import ResponseCheckpoint+from src.session.events import EventBus+from src.session.models import Attempt, AttemptStatus, Message, Session+from src.session.service import 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(store: SessionStore, runs_dir: Path, monkeypatch) -> SessionService:+ monkeypatch.setattr("src.session.service.get_shared_index", lambda: _DummyIndex())+ return SessionService(store=store, event_bus=EventBus(), runs_dir=runs_dir)+++def test_stream_checkpoint_tracks_deltas_and_resets(tmp_path: Path) -> None:+ store = SessionStore(tmp_path / "sessions")+ session = Session(title="checkpoint")+ store.create_session(session)+ attempt = Attempt(session_id=session.session_id, prompt="hello")+ store.create_attempt(attempt)+ checkpoint = ResponseCheckpoint(store, attempt, min_interval_seconds=60)++ checkpoint.handle_event("text_delta", {"delta": "first"})+ checkpoint.handle_event("text_delta", {"delta": " second"})+ assert store.get_partial_response(session.session_id, attempt.attempt_id) == "first"++ checkpoint.flush()+ assert (+ store.get_partial_response(session.session_id, attempt.attempt_id)+ == "first second"+ )++ checkpoint.handle_event("stream_reset", {})+ assert store.get_partial_response(session.session_id, attempt.attempt_id) == ""++ checkpoint.handle_event("text_delta", {"delta": "replacement"})+ assert (+ store.get_partial_response(session.session_id, attempt.attempt_id)+ == "replacement"+ )+++def test_service_restart_recovers_partial_reply_once(+ tmp_path: Path, monkeypatch+) -> None:+ store = SessionStore(tmp_path / "sessions")+ session = Session(title="restart")+ store.create_session(session)+ attempt = Attempt(session_id=session.session_id, prompt="analyze")+ attempt.mark_running()+ store.create_attempt(attempt)+ store.save_partial_response(+ session.session_id, attempt.attempt_id, "Partial answer"+ )++ _service(store, tmp_path / "runs", monkeypatch)++ recovered = store.get_attempt(session.session_id, attempt.attempt_id)+ assert recovered is not None+ assert recovered.status == AttemptStatus.INTERRUPTED+ assert recovered.completed_at is not None+ replies = [+ message+ for message in store.get_messages(session.session_id)+ if message.linked_attempt_id == attempt.attempt_id+ ]+ assert len(replies) == 1+ assert "Partial answer" in replies[0].content+ assert replies[0].metadata == {+ "status": "interrupted",+ "partial": True,+ "recovery_reason": "service_restart",+ }+ assert store.get_partial_response(session.session_id, attempt.attempt_id) is None++ # Startup reconciliation must be safe to run repeatedly.+ _service(store, tmp_path / "runs", monkeypatch)+ replies = [+ message+ for message in store.get_messages(session.session_id)+ if message.linked_attempt_id == attempt.attempt_id+ ]+ assert len(replies) == 1+++def test_service_restart_recovers_pending_attempt_without_partial(+ tmp_path: Path, monkeypatch+) -> None:+ store = SessionStore(tmp_path / "sessions")+ session = Session(title="pending")+ store.create_session(session)+ attempt = Attempt(session_id=session.session_id, prompt="queued")+ store.create_attempt(attempt)++ _service(store, tmp_path / "runs", monkeypatch)++ recovered = store.get_attempt(session.session_id, attempt.attempt_id)+ assert recovered is not None+ assert recovered.status == AttemptStatus.INTERRUPTED+ reply = store.get_messages(session.session_id)[-1]+ assert "no complete assistant response was saved" in reply.content+ assert reply.metadata["partial"] is False+++def test_restart_finishes_attempt_when_terminal_reply_was_already_appended(+ tmp_path: Path, monkeypatch+) -> None:+ store = SessionStore(tmp_path / "sessions")+ session = Session(title="commit ordering")+ store.create_session(session)+ attempt = Attempt(session_id=session.session_id, prompt="answer")+ attempt.mark_running()+ store.create_attempt(attempt)+ store.append_message(+ Message(+ session_id=session.session_id,+ role="assistant",+ content="Complete answer",+ linked_attempt_id=attempt.attempt_id,+ metadata={"status": "completed"},+ )+ )++ _service(store, tmp_path / "runs", monkeypatch)++ recovered = store.get_attempt(session.session_id, attempt.attempt_id)+ assert recovered is not None+ assert recovered.status == AttemptStatus.COMPLETED+ assert recovered.summary == "Complete answer"+ assert len(store.get_messages(session.session_id)) == 1+++def test_event_loop_shutdown_remains_recoverable(tmp_path: Path, monkeypatch) -> None:+ async def scenario() -> None:+ store = SessionStore(tmp_path / "sessions")+ service = _service(store, tmp_path / "runs", monkeypatch)+ session = service.create_session(title="shutdown")+ gate = asyncio.Event()++ async def wait_forever(attempt, messages=None, **kwargs):+ del attempt, messages, kwargs+ await gate.wait()+ return {"status": "success", "content": "too late"}++ monkeypatch.setattr(service, "_run_with_agent", wait_forever)+ sent = await service.send_message(session.session_id, "keep this")+ await asyncio.sleep(0)+ task = service._active_tasks[session.session_id]+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task++ attempt = store.get_attempt(session.session_id, sent["attempt_id"])+ assert attempt is not None+ assert attempt.status == AttemptStatus.RUNNING++ _service(store, tmp_path / "runs", monkeypatch)+ recovered = store.get_attempt(session.session_id, sent["attempt_id"])+ assert recovered is not None+ assert recovered.status == AttemptStatus.INTERRUPTED++ asyncio.run(scenario())diff --git a/agent/tests/test_session_store_atomic_json.py b/agent/tests/test_session_store_atomic_json.pynew file mode 100644index 000000000..dacc76fa6--- /dev/null+++ b/agent/tests/test_session_store_atomic_json.py@@ -0,0 +1,37 @@+"""Atomic JSON durability checks for filesystem-backed sessions."""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from src.session.store import SessionStore+++def test_atomic_json_write_roundtrips_unicode(tmp_path: Path) -> None:+ target = tmp_path / "attempt.json"+ SessionStore._write_json(target, {"summary": "恢复中的回复"})+ assert json.loads(target.read_text(encoding="utf-8")) == {+ "summary": "恢复中的回复"+ }+ assert list(tmp_path.glob(".attempt.json.*.tmp")) == []+++def test_failed_atomic_replace_preserves_previous_json(+ tmp_path: Path, monkeypatch+) -> None:+ target = tmp_path / "session.json"+ SessionStore._write_json(target, {"status": "old"})++ def fail_replace(source, destination) -> None:+ del source, destination+ raise OSError("simulated replace failure")++ monkeypatch.setattr("src.session.store.os.replace", fail_replace)+ with pytest.raises(OSError, match="replace failure"):+ SessionStore._write_json(target, {"status": "new"})++ assert json.loads(target.read_text(encoding="utf-8")) == {"status": "old"}+ assert list(tmp_path.glob(".session.json.*.tmp")) == []