"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(session): serialize shared search connection operations
Rudy Celeklic94b9218180b
diff --git a/agent/src/session/search.py b/agent/src/session/search.pyindex b1ca0e457..0798ae63b 100644--- a/agent/src/session/search.py+++ b/agent/src/session/search.py@@ -16,10 +16,12 @@ import reimport sqlite3import threading as _threadingimport time+from collections.abc import Callablefrom dataclasses import dataclassfrom datetime import datetime+from functools import wrapsfrom pathlib import Path-from typing import List, Optional+from typing import Anyfrom src.config.paths import get_runtime_root@@ -41,7 +43,11 @@ def _prepare_search_text(text: str) -> str:def _search_snippet(content: str, query: str) -> str:"""Highlight query terms in the original text, never in expanded tokens."""terms = sorted(set(_QUERY_TERM.findall(query)), key=len, reverse=True)- pattern = re.compile("|".join(re.escape(term) for term in terms), re.IGNORECASE) if terms else None+ pattern = (+ re.compile("|".join(re.escape(term) for term in terms), re.IGNORECASE)+ if terms+ else None+ )first = pattern.search(content) if pattern else Nonestart = max(0, first.start() - 100) if first else 0end = min(len(content), start + 400)@@ -82,6 +88,17 @@ class SearchMatch:}+def _serialized_operation(fn: Callable[..., Any]) -> Callable[..., Any]:+ """Keep each shared-connection operation and its cursor consumption together."""++ @wraps(fn)+ def wrapped(self: SessionSearchIndex, *args: Any, **kwargs: Any) -> Any:+ with self._operation_lock:+ return fn(self, *args, **kwargs)++ return wrapped++class SessionSearchIndex:"""SQLite FTS5 index for cross-session search.@@ -97,9 +114,10 @@ class SessionSearchIndex:Args:db_path: Path to SQLite database file."""+ self._operation_lock = _threading.RLock()self.db_path = db_pathself.db_path.parent.mkdir(parents=True, exist_ok=True)- self._conn: Optional[sqlite3.Connection] = None+ self._conn: sqlite3.Connection | None = Noneself._init_db()def _get_conn(self) -> sqlite3.Connection:@@ -135,7 +153,9 @@ class SessionSearchIndex:""")# Serialize upgrade across processes. Keep original messages for readable# snippets; rebuild the derived index once, including historical rows.- conn.create_function("prepare_session_text", 1, _prepare_search_text, deterministic=True)+ conn.create_function(+ "prepare_session_text", 1, _prepare_search_text, deterministic=True+ )with conn:conn.execute("BEGIN IMMEDIATE")columns = {row[1] for row in conn.execute("PRAGMA table_info(messages)")}@@ -143,28 +163,39 @@ class SessionSearchIndex:if migrating:for name in ("messages_ai", "messages_ad", "messages_au"):conn.execute(f"DROP TRIGGER IF EXISTS {name}")- conn.execute("ALTER TABLE messages ADD COLUMN search_content TEXT NOT NULL DEFAULT ''")- conn.execute("UPDATE messages SET search_content = prepare_session_text(content)")+ conn.execute(+ "ALTER TABLE messages ADD COLUMN search_content TEXT NOT NULL DEFAULT ''"+ )+ conn.execute(+ "UPDATE messages SET search_content = prepare_session_text(content)"+ )conn.execute("DROP TABLE IF EXISTS messages_fts")conn.execute("""CREATE VIRTUAL TABLE IF NOT EXISTS messages_ftsUSING fts5(search_content, content=messages, content_rowid=id)""")- conn.execute("""CREATE TRIGGER IF NOT EXISTS messages_ai AFTER INSERT ON messages BEGIN+ conn.execute(+ """CREATE TRIGGER IF NOT EXISTS messages_ai AFTER INSERT ON messages BEGININSERT INTO messages_fts(rowid, search_content) VALUES (new.id, new.search_content);- END""")- conn.execute("""CREATE TRIGGER IF NOT EXISTS messages_ad AFTER DELETE ON messages BEGIN+ END"""+ )+ conn.execute(+ """CREATE TRIGGER IF NOT EXISTS messages_ad AFTER DELETE ON messages BEGININSERT INTO messages_fts(messages_fts, rowid, search_content)VALUES ('delete', old.id, old.search_content);- END""")+ END"""+ )if migrating:- conn.execute("INSERT INTO messages_fts(messages_fts) VALUES ('rebuild')")+ conn.execute(+ "INSERT INTO messages_fts(messages_fts) VALUES ('rebuild')"+ )+ @_serialized_operationdef index_session(self,session_id: str,title: str = "",- ts: Optional[float] = None,+ ts: float | None = None,) -> None:"""Upsert a session record.@@ -193,8 +224,10 @@ class SessionSearchIndex:)conn.commit()- def index_message(self, session_id: str, role: str, content: str,- tool_name: Optional[str] = None) -> None:+ @_serialized_operation+ def index_message(+ self, session_id: str, role: str, content: str, tool_name: str | None = None+ ) -> None:"""Index a single message.Args:@@ -234,10 +267,13 @@ class SessionSearchIndex:Returns:FTS5-safe MATCH expression."""- tokens = [_prepare_search_text(term).strip() for term in _QUERY_TERM.findall(query)]+ tokens = [+ _prepare_search_text(term).strip() for term in _QUERY_TERM.findall(query)+ ]return " OR ".join(f'"{token}"' for token in tokens) if tokens else '""'- def search(self, query: str, max_sessions: int = 3) -> List[SearchMatch]:+ @_serialized_operation+ def search(self, query: str, max_sessions: int = 3) -> list[SearchMatch]:"""Full-text search across all sessions.Args:@@ -302,14 +338,18 @@ class SessionSearchIndex:if not store_base_dir.exists():return 0- conn = self._get_conn()- conn.execute("DELETE FROM messages")- conn.execute("DELETE FROM sessions")- try:- conn.execute("INSERT INTO messages_fts(messages_fts) VALUES ('rebuild')")- except sqlite3.OperationalError:- pass- conn.commit()+ # Only SQLite work is serialized; source-file reads remain outside.+ with self._operation_lock:+ conn = self._get_conn()+ conn.execute("DELETE FROM messages")+ conn.execute("DELETE FROM sessions")+ try:+ conn.execute(+ "INSERT INTO messages_fts(messages_fts) VALUES ('rebuild')"+ )+ except sqlite3.OperationalError:+ pass+ conn.commit()count = 0for session_dir in store_base_dir.iterdir():@@ -328,14 +368,18 @@ class SessionSearchIndex:title = session_data.get("title", "")try:- ts = datetime.fromisoformat(session_data.get("created_at", "")).timestamp()+ ts = datetime.fromisoformat(+ session_data.get("created_at", "")+ ).timestamp()except (ValueError, TypeError):ts = time.time()self.index_session(sid, title, ts=ts)if messages_file.exists():- for line in messages_file.read_text(encoding="utf-8").strip().splitlines():+ for line in (+ messages_file.read_text(encoding="utf-8").strip().splitlines()+ ):if not line.strip():continuetry:@@ -347,7 +391,8 @@ class SessionSearchIndex:count += 1except json.JSONDecodeError:continue- except Exception as exc:+ # One corrupt session must not abort the remaining reindex.+ except Exception as exc: # noqa: BLE001logger.warning("Failed to index session %s: %s", session_dir.name, exc)return count@@ -360,6 +405,7 @@ class SessionSearchIndex:except (OSError, ValueError):return "unknown"+ @_serialized_operationdef close(self) -> None:"""Close the database connection."""if self._conn:@@ -367,7 +413,7 @@ class SessionSearchIndex:self._conn = None-_shared_index: Optional[SessionSearchIndex] = None+_shared_index: SessionSearchIndex | None = None_shared_lock = _threading.Lock()diff --git a/agent/tests/test_session_search_concurrent_consumers.py b/agent/tests/test_session_search_concurrent_consumers.pynew file mode 100644index 000000000..25dbca97f--- /dev/null+++ b/agent/tests/test_session_search_concurrent_consumers.py@@ -0,0 +1,162 @@+"""The shipping service and worker tools share one SQLite search connection."""++import asyncio+import json+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path++from src.session.events import EventBus+from src.session.search import SessionSearchIndex+from src.session.service import SessionService+from src.session.store import SessionStore+from src.tools.session_search_tool import SessionSearchTool+++def test_service_admission_can_overlap_worker_session_search(+ tmp_path: Path, monkeypatch+):+ index = SessionSearchIndex(tmp_path / "search.db")+ monkeypatch.setattr("src.session.service.get_shared_index", lambda: index)+ monkeypatch.setattr("src.session.search.get_shared_index", lambda: index)+ service = SessionService(+ store=SessionStore(tmp_path / "sessions"),+ event_bus=EventBus(),+ runs_dir=tmp_path / "runs",+ )+ session = service.create_session(title="Synthetic worker search")++ async def scenario():+ await service.send_message(session.session_id, "volatility", role="assistant")++ def search():+ return json.loads(SessionSearchTool().execute(query="volatility"))++ with ThreadPoolExecutor(max_workers=4) as pool:+ futures = [pool.submit(search) for _ in range(400)]+ for i in range(100):+ await service.send_message(+ session.session_id, f"volatility {i}", role="assistant"+ )+ replies = [f.result() for f in futures]+ assert all(reply["status"] == "ok" for reply in replies), [+ reply for reply in replies if reply["status"] != "ok"+ ]+ assert all(+ reply["results"][0]["session_id"] == session.session_id for reply in replies+ )+ assert (+ index._get_conn().execute("SELECT COUNT(*) FROM messages").fetchone()[0]+ == 101+ )+ assert len(service.store.get_messages(session.session_id, limit=200)) == 101++ try:+ asyncio.run(scenario())+ finally:+ index.close()+++def test_writer_waits_for_native_search_cursor(tmp_path: Path):+ from threading import Event++ index = SessionSearchIndex(tmp_path / "cursor.db")+ index.index_session("session", "Owned test")+ index.index_message("session", "user", "volatility")+ real = index._get_conn()+ entered, release, writer_entered = Event(), Event(), Event()++ class Cursor:+ def fetchall(self):+ entered.set()+ assert release.wait(3)+ return self.cursor.fetchall()++ def __iter__(self):+ entered.set()+ assert release.wait(3)+ yield from self.cursor++ class Connection:+ def execute(self, sql, *args):+ if "INSERT INTO messages" in sql:+ writer_entered.set()+ cursor = real.execute(sql, *args)+ if "FROM messages_fts" in sql:+ wrapped = Cursor()+ wrapped.cursor = cursor+ return wrapped+ return cursor++ def commit(self):+ return real.commit()++ index._conn = Connection()+ try:+ with ThreadPoolExecutor(max_workers=2) as pool:+ reader = pool.submit(index.search, "volatility")+ assert entered.wait(3)+ writer = pool.submit(+ index.index_message, "session", "user", "volatility new"+ )+ try:+ assert not writer_entered.wait(0.1)+ finally:+ release.set()+ assert reader.result(timeout=3)[0].session_id == "session"+ writer.result(timeout=3)+ assert writer_entered.is_set()+ assert real.execute("SELECT COUNT(*) FROM messages").fetchone()[0] == 2+ finally:+ release.set()+ index._conn = real+ index.close()+++def test_close_waits_for_native_search_cursor(tmp_path: Path):+ from threading import Event++ index = SessionSearchIndex(tmp_path / "close.db")+ index.index_session("session", "Owned test")+ index.index_message("session", "user", "volatility")+ real = index._get_conn()+ entered, release, closed = Event(), Event(), Event()++ class Cursor:+ def fetchall(self):+ entered.set()+ assert release.wait(3)+ return self.cursor.fetchall()++ def __iter__(self):+ entered.set()+ assert release.wait(3)+ yield from self.cursor++ class Connection:+ def execute(self, sql, *args):+ wrapped = Cursor()+ wrapped.cursor = real.execute(sql, *args)+ return wrapped++ def close(self):+ real.close()+ closed.set()++ index._conn = Connection()+ try:+ with ThreadPoolExecutor(max_workers=2) as pool:+ reader = pool.submit(index.search, "volatility")+ assert entered.wait(3)+ closer = pool.submit(index.close)+ try:+ assert not closed.wait(0.1)+ finally:+ release.set()+ assert reader.result(timeout=3)[0].session_id == "session"+ closer.result(timeout=3)+ assert closed.is_set()+ assert index._conn is None+ finally:+ release.set()+ if not closed.is_set():+ real.close()