"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(session): keep deletion retryable when search purge fails
Haozhe Wu4ae04fc0dbfc
diff --git a/agent/src/api/sessions_routes.py b/agent/src/api/sessions_routes.pyindex 7b1a521d2..a1657d377 100644--- a/agent/src/api/sessions_routes.py+++ b/agent/src/api/sessions_routes.py@@ -660,7 +660,10 @@ def register_sessions_routes(app: FastAPI) -> None:svc = _host_get_session_service()if not svc:raise HTTPException(status_code=501, detail="Session runtime not enabled")- deleted = svc.delete_session(session_id)+ try:+ deleted = svc.delete_session(session_id)+ except SessionBusyError as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from excif not deleted:raise HTTPException(status_code=404, detail=f"Session {session_id} not found")_get_goal_store().delete_session_goals(session_id)diff --git a/agent/src/session/search.py b/agent/src/session/search.pyindex aae272f08..a5b803a18 100644--- a/agent/src/session/search.py+++ b/agent/src/session/search.py@@ -312,12 +312,9 @@ class SessionSearchIndex:session_id: Session ID."""conn = self._get_conn()- try:+ with conn:conn.execute("DELETE FROM messages WHERE session_id = ?", (session_id,))conn.execute("DELETE FROM sessions WHERE id = ?", (session_id,))- conn.commit()- except sqlite3.OperationalError as exc:- logger.debug("remove_session failed for %s: %s", session_id, exc)@staticmethoddef _sanitize_fts_query(query: str) -> str:diff --git a/agent/src/session/service.py b/agent/src/session/service.pyindex 983b938d1..061856ffe 100644--- a/agent/src/session/service.py+++ b/agent/src/session/service.py@@ -242,21 +242,28 @@ class SessionService:return self.store.list_sessions(limit)def delete_session(self, session_id: str) -> bool:- """Delete a session."""- self.event_bus.clear(session_id)- deleted = self.store.delete_session(session_id)- if deleted:- # The search index is always on, so leftover rows would keep the- # deleted conversation's title and text searchable.- try:- self._search_index.remove_session(session_id)- except Exception: # noqa: BLE001- logger.debug(- "Search index remove_session failed for %s",- session_id,- exc_info=True,- )- return deleted+ """Delete an idle session after purging its searchable text.++ Args:+ session_id: Session to delete.++ Returns:+ Whether the on-disk session existed and was deleted.++ Raises:+ SessionBusyError: If a run could recreate the deleted content.+ Exception: If the search purge fails; the on-disk session remains+ available so the user can retry instead of receiving false success.+ """+ with self._inflight_lock:+ if session_id in self._inflight:+ raise SessionBusyError("Stop the active run before deleting its session")+ # Purge even when the directory is absent: a retry can clear stale+ # index rows left by an older version or an interrupted deletion.+ self._search_index.remove_session(session_id)+ deleted = self.store.delete_session(session_id)+ self.event_bus.clear(session_id)+ return deletedasync def send_message(self,diff --git a/agent/tests/test_session_delete_clears_search_index.py b/agent/tests/test_session_delete_clears_search_index.pyindex 4fdf466b3..9508f5870 100644--- a/agent/tests/test_session_delete_clears_search_index.py+++ b/agent/tests/test_session_delete_clears_search_index.py@@ -3,12 +3,13 @@from __future__ import annotationsimport json+import sqlite3import pytestfrom src.session.events import EventBusfrom src.session.models import Messagefrom src.session.search import SessionSearchIndex-from src.session.service import SessionService+from src.session.service import SessionBusyError, SessionServicefrom src.session.store import SessionStorefrom src.tools.session_search_tool import SessionSearchTool@@ -97,10 +98,10 @@ def test_delete_leaves_an_unrelated_session_fully_indexed(owned_delete_index):)-def test_delete_succeeds_when_the_search_index_is_unavailable(+def test_delete_keeps_the_session_for_retry_when_search_is_unavailable(owned_delete_index, monkeypatch):- """An index failure must not turn a successful on-disk delete into a failure."""+ """A failed purge must not claim that the private text was deleted."""service, index, doomed, _sibling = owned_delete_indexdef _boom(session_id: str) -> None:@@ -108,5 +109,44 @@ def test_delete_succeeds_when_the_search_index_is_unavailable(monkeypatch.setattr(index, "remove_session", _boom, raising=False)+ with pytest.raises(RuntimeError, match="index offline"):+ service.delete_session(doomed.session_id)+ assert service.store.get_session(doomed.session_id) is not None+++def test_purge_transaction_rolls_back_and_a_retry_succeeds(owned_delete_index):+ service, index, doomed, _ = owned_delete_index+ conn = index._get_conn()+ conn.execute("CREATE TRIGGER block_delete BEFORE DELETE ON sessions "+ "BEGIN SELECT RAISE(ABORT, 'purge failed'); END")+ conn.commit()+ with pytest.raises(sqlite3.IntegrityError, match="purge failed"):+ service.delete_session(doomed.session_id)+ assert service.store.get_session(doomed.session_id) is not None+ assert _index_rows(index, doomed.session_id) == (1, 1)+ assert _fts_hits(index, DELETED_TERM) == 1+ conn.execute("DROP TRIGGER block_delete")+ conn.commit()+ assert service.delete_session(doomed.session_id) is True+ assert _fts_hits(index, DELETED_TERM) == 0+++def test_missing_directory_still_clears_orphaned_index_rows(owned_delete_index):+ service, index, doomed, _ = owned_delete_index+ service.store.delete_session(doomed.session_id)+ assert service.delete_session(doomed.session_id) is False+ assert _index_rows(index, doomed.session_id) == (0, 0)+ assert _fts_hits(index, DELETED_TERM) == 0+++def test_active_run_cannot_recreate_deleted_content(owned_delete_index):+ service, index, doomed, _ = owned_delete_index+ service._reserve_session(doomed.session_id)+ try:+ with pytest.raises(SessionBusyError):+ service.delete_session(doomed.session_id)+ assert service.store.get_session(doomed.session_id) is not None+ assert _fts_hits(index, DELETED_TERM) == 1+ finally:+ service._release_session(doomed.session_id)assert service.delete_session(doomed.session_id) is True- assert service.store.get_session(doomed.session_id) is None