Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
perf(storage): reuse sqlite engines on hot paths (#773)
Call White366015282c4c
diff --git a/core/internal_server.py b/core/internal_server.pyindex 7db58161f..9d9c591e3 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -43,6 +43,7 @@ from sqlalchemy.exc import IntegrityErrorfrom config import pathsfrom core.services.dispatch import SOURCE_HUMAN, SOURCE_SCHEDULED, dispatch_turnfrom modules.im.base import MessageContext+from storage.db import get_cached_sqlite_engineif TYPE_CHECKING: # pragma: no cover - typing onlyfrom core.controller import Controller@@ -136,9 +137,8 @@ def create_app(controller: "Controller") -> FastAPI:if active_message_id == native_message_id:return "duplicate"from storage import messages_service- from storage.db import create_sqlite_engine- engine = create_sqlite_engine()+ engine = get_cached_sqlite_engine()with engine.connect() as conn:if messages_service.native_message_exists(conn,@@ -151,14 +151,13 @@ def create_app(controller: "Controller") -> FastAPI:from core.message_mirror import _scope_id_for_sessionfrom core.session_turns import SCHEDULED_PROVENANCE_KEY, capture_scheduled_provenancefrom storage import messages_service- from storage.db import create_sqlite_engine# Persist the scheduled run's delivery / attribution provenance on the# queued row's metadata so flush_queue re-runs it as SOURCE_SCHEDULED with# that restored — keeping suppress_delivery / the delivery target / the task# attribution instead of degrading to a plain user turn (#84). The key's# PRESENCE also marks this row as a scheduled segment for the flush.- engine = create_sqlite_engine()+ engine = get_cached_sqlite_engine()with engine.begin() as conn:scope_id = _scope_id_for_session(conn, session_id)if scope_id is not None:@@ -244,7 +243,7 @@ def create_app(controller: "Controller") -> FastAPI:``show.dispatch`` for the open Show page."""payload = await _safe_json(request)try:- text, context = _build_dispatch_payload(payload)+ text, context = await _build_dispatch_payload(payload)except ValueError as err:return JSONResponse(status_code=400, content={"ok": False, "error": str(err)})@@ -357,7 +356,7 @@ def create_app(controller: "Controller") -> FastAPI:"""payload = await _safe_json(request)try:- text, context = _build_dispatch_payload(payload)+ text, context = await _build_dispatch_payload(payload)except ValueError as err:return JSONResponse(status_code=400, content={"ok": False, "error": str(err)})@@ -370,9 +369,8 @@ def create_app(controller: "Controller") -> FastAPI:# it to ``queued`` so it drains via the queue after the active turn.if isinstance(user_message_id, str) and user_message_id:from storage import messages_service- from storage.db import create_sqlite_engine- engine = create_sqlite_engine()+ engine = get_cached_sqlite_engine()with engine.begin() as conn:messages_service.promote_pending(conn, user_message_id, messages_service.QUEUED_TYPE)@@ -605,7 +603,7 @@ async def _safe_json(request: Request) -> dict[str, Any]:return body if isinstance(body, dict) else {}-def _build_dispatch_payload(payload: dict[str, Any]) -> tuple[str, MessageContext]:+async def _build_dispatch_payload(payload: dict[str, Any]) -> tuple[str, MessageContext]:"""Translate the JSON payload into a ``(text, MessageContext)`` pair.Raises ``ValueError`` with a caller-friendly message when the@@ -636,7 +634,8 @@ def _build_dispatch_payload(payload: dict[str, Any]) -> tuple[str, MessageContexif not text.strip() and not files:raise ValueError("text or files is required")- context = _build_session_context(+ context = await asyncio.to_thread(+ _build_session_context,session_id,user_id=payload.get("user_id"),channel_id=payload.get("channel_id"),@@ -720,9 +719,8 @@ def _lookup_session(session_id: str) -> Optional[dict[str, Any]]:try:from core.services import sessions as sessions_service- from storage.db import create_sqlite_engine- engine = create_sqlite_engine()+ engine = get_cached_sqlite_engine()with engine.connect() as conn:return sessions_service.get_session(conn, session_id)except LookupError:diff --git a/core/message_mirror.py b/core/message_mirror.pyindex c53ea548d..c4e55f410 100644--- a/core/message_mirror.py+++ b/core/message_mirror.py@@ -30,7 +30,7 @@ from sqlalchemy.exc import IntegrityErrorfrom modules.im.base import MessageContextfrom storage import agent_events_service, messages_service, settings_service-from storage.db import create_sqlite_engine+from storage.db import get_cached_sqlite_enginelogger = logging.getLogger(__name__)@@ -203,7 +203,7 @@ def persist_agent_message(returnsession_id = (context.platform_specific or {}).get("agent_session_id")try:- engine = create_sqlite_engine()+ engine = get_cached_sqlite_engine()inbox_row = Noneappended_row = Nonewith engine.begin() as conn:@@ -340,7 +340,7 @@ def mirror_harness_inbound(context: MessageContext, text: str) -> None:definition_id = spec.get("task_definition_id")session_id = spec.get("agent_session_id")try:- engine = create_sqlite_engine()+ engine = get_cached_sqlite_engine()appended_row = Noneinbox_row = Nonewith engine.begin() as conn:@@ -421,7 +421,7 @@ def mirror_inbound(context: MessageContext, text: str) -> None:# mirroring here would double-count the row.returntry:- engine = create_sqlite_engine()+ engine = get_cached_sqlite_engine()with engine.begin() as conn:scope_id = _resolve_scope_id(conn, context)if scope_id is None:@@ -462,7 +462,7 @@ def link_inbound_message_session(*, platform: str, native_message_id: str, sessifrom storage.models import messages as _messages- engine = create_sqlite_engine()+ engine = get_cached_sqlite_engine()with engine.begin() as conn:conn.execute(_sa_update(_messages)diff --git a/core/session_turns.py b/core/session_turns.pyindex 6911be1b0..56831b13b 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -24,11 +24,13 @@ from datetime import datetime, timezonefrom typing import TYPE_CHECKING, Any, Callable, Optionalfrom sqlalchemy import select+from sqlalchemy.engine import Enginefrom sqlalchemy.exc import IntegrityErrorfrom core.web_push_notifications import WEB_PUSH_USER_KEY_METADATA, WEB_PUSH_USER_KEYS_METADATAfrom core.services.dispatch import SOURCE_HUMAN, SOURCE_SCHEDULED, dispatch_turnfrom storage import messages_service+from storage.db import get_cached_sqlite_enginefrom storage.models import messagesfrom vibe.i18n import t as i18n_t@@ -554,6 +556,7 @@ class SessionTurnManager:) -> None:self.controller = controllerself._build_context = build_context+ self._engine: Engine | None = Noneself.in_flight: dict[str, Turn] = {}# The live streaming turn sink per SESSION KEY (avibe/web-Chat only; IM/CLI# turns register none). Each is ``{on_chunk, done_event, turn_token}`` — the@@ -562,6 +565,11 @@ class SessionTurnManager:# carrying a stale per-turn context still resolves the current turn's sink.self.active_turn_sinks: dict[str, dict] = {}+ def _sqlite_engine(self) -> Engine:+ if self._engine is None:+ self._engine = get_cached_sqlite_engine()+ return self._engine+def is_in_flight(self, session_id: Optional[str]) -> bool:"""True when ``session_id`` has an active (RUNNING) turn."""return bool(session_id) and session_id in self.in_flight@@ -602,9 +610,6 @@ class SessionTurnManager:await self._run(None, context, text, source=source)return "ran"- from storage import messages_service- from storage.db import create_sqlite_engine-entry = self.in_flight.get(session_id)busy = entry is not None and not entry.task.done()# Enqueue when a turn is running OR a prior Stop left queued rows behind — the@@ -612,8 +617,7 @@ class SessionTurnManager:if busy:should_enqueue = Trueelse:- engine = create_sqlite_engine()- with engine.connect() as conn:+ with self._sqlite_engine().connect() as conn:should_enqueue = bool(messages_service.list_queued(conn, session_id))if should_enqueue:if enqueue is not None:@@ -747,9 +751,7 @@ class SessionTurnManager:on an empty queue / failure."""from core.inbox_events import busfrom core.workbench_media import file_attachments_from_specs, resolve_attachment_specs- from storage import messages_servicefrom storage.background import run_update_event_transaction- from storage.db import create_sqlite_engineif not session_id:return False@@ -766,8 +768,8 @@ class SessionTurnManager:pending_agent_run_ids: list[str] = []pending_scheduled_segment: list[dict] = []claimed_agent_run_ids: list[str] = []+ engine = self._sqlite_engine()try:- engine = create_sqlite_engine()with run_update_event_transaction(engine) as conn:rows = messages_service.list_queued(conn, session_id)if not rows:@@ -921,7 +923,7 @@ class SessionTurnManager:logger.error("queue flush: no build_context bound for session=%s", session_id)return Falsetry:- context = self._build_context(session_id)+ context = await asyncio.to_thread(self._build_context, session_id)except Exception:logger.exception("queue flush: failed to build context for session=%s", session_id)return False@@ -949,7 +951,6 @@ class SessionTurnManager:if pending_agent_run_ids:retry_agent_run_flush = Falsetry:- engine = create_sqlite_engine()with run_update_event_transaction(engine) as conn:claimed_run_ids = _claim_agent_run_segment_and_retire_queue(conn,@@ -995,7 +996,6 @@ class SessionTurnManager:try:from storage.background import reset_workbench_claimed_runs_in_connection- engine = create_sqlite_engine()with run_update_event_transaction(engine) as conn:reset_workbench_claimed_runs_in_connection(conn, claimed_agent_run_ids)_restore_queued_rows(conn, pending_scheduled_segment)@@ -1005,12 +1005,10 @@ class SessionTurnManager:return Falseif not pending_agent_run_ids:if pending_scheduled_segment:- engine = create_sqlite_engine()with engine.begin() as conn:messages_service.delete_queued(conn, [r["id"] for r in pending_scheduled_segment])bus.publish("queue.updated", {"session_id": session_id})try:- engine = create_sqlite_engine()with engine.begin() as conn:_write_coalesced_native_id_markers(conn, segment)except Exception:@@ -1168,16 +1166,12 @@ class SessionTurnManager:the queue is empty. Returns a result dict (``code='stop_failed'`` → 409 forthe HTTP adapter)."""- from storage import messages_service- from storage.db import create_sqlite_engine-turn = self.in_flight.get(session_id)if turn is not None and not turn.task.done():# Don't interrupt a live turn unless there is actually something queued to# cut in with — a stale queue item already flushed by another tab would# otherwise make send-now an unintended Stop (Codex P2).- engine = create_sqlite_engine()- with engine.connect() as conn:+ with self._sqlite_engine().connect() as conn:has_queue = bool(messages_service.list_queued(conn, session_id))if not has_queue:return {"ok": True, "session_id": session_id, "status": "empty"}@@ -1509,14 +1503,10 @@ class SessionTurnManager:reconciles by refetching sessions when its inbox stream (re)connects."""try:from core.services import sessions as workbench_sessions_service- from storage.db import create_sqlite_engine- engine = create_sqlite_engine()- try:- with engine.begin() as conn:- reset = workbench_sessions_service.reset_running_agent_status(conn)- finally:- engine.dispose()+ engine = get_cached_sqlite_engine()+ with engine.begin() as conn:+ reset = workbench_sessions_service.reset_running_agent_status(conn)if reset:logger.info("Reset %s stale 'running' agent session(s) to idle on startup", reset)except Exception:diff --git a/storage/db.py b/storage/db.pyindex 9989957d0..5c896cb04 100644--- a/storage/db.py+++ b/storage/db.py@@ -1,6 +1,7 @@from __future__ import annotationsfrom pathlib import Path+from threading import RLockfrom sqlalchemy import Engine, create_engine, eventfrom sqlalchemy.engine import URL@@ -19,13 +20,17 @@ def escape_sql_like(value: str) -> str:return str(value).replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")+def _resolve_sqlite_path(db_path: Path | None = None) -> Path:+ return (db_path or paths.get_sqlite_state_path()).expanduser().resolve()++def sqlite_url(db_path: Path | None = None) -> str:- path = (db_path or paths.get_sqlite_state_path()).expanduser().resolve()+ path = _resolve_sqlite_path(db_path)return URL.create("sqlite", database=str(path)).render_as_string(hide_password=False)def create_sqlite_engine(db_path: Path | None = None) -> Engine:- path = (db_path or paths.get_sqlite_state_path()).expanduser().resolve()+ path = _resolve_sqlite_path(db_path)path.parent.mkdir(parents=True, exist_ok=True)engine = create_engine(sqlite_url(path), future=True)@@ -40,6 +45,40 @@ def create_sqlite_engine(db_path: Path | None = None) -> Engine:return engine+_cached_engine_lock = RLock()+_cached_engines: dict[Path, Engine] = {}+++def get_cached_sqlite_engine(db_path: Path | None = None) -> Engine:+ """Return a process-local SQLite engine for hot write paths.++ ``create_sqlite_engine`` intentionally remains a fresh-engine factory for+ tests, migrations, and short one-off tools. Controller hot paths should use+ this cache so every emitted chunk or queue tick does not allocate a new+ SQLAlchemy engine and SQLite connection pool.+ """+ path = _resolve_sqlite_path(db_path)+ with _cached_engine_lock:+ engine = _cached_engines.get(path)+ if engine is None:+ engine = create_sqlite_engine(path)+ _cached_engines[path] = engine+ return engine+++def dispose_cached_sqlite_engines() -> None:+ """Dispose process-local cached SQLite engines.++ Production relies on process lifetime cleanup. Tests call this around+ isolated homes so cached connections never point at a previous test's state.+ """+ with _cached_engine_lock:+ engines = list(_cached_engines.values())+ _cached_engines.clear()+ for engine in engines:+ engine.dispose()++class SqliteInvalidationProbe:"""Detect external SQLite writes with PRAGMA data_version.diff --git a/tests/conftest.py b/tests/conftest.pyindex 920acbf98..f1743e5e5 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -72,6 +72,19 @@ def _isolate_vibe_remote_home(request, tmp_path, monkeypatch):monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(isolated_home / ".claude"))[email protected](autouse=True)+def _reset_cached_sqlite_engines():+ """Keep process-local SQLite engine caches scoped to each isolated test."""+ try:+ from storage.db import dispose_cached_sqlite_engines+ except Exception:+ yield+ return+ dispose_cached_sqlite_engines()+ yield+ dispose_cached_sqlite_engines()++@pytest.fixture(autouse=True)def _reset_oauth_runtime_state():"""Reset module-level in-memory OAuth caches between tests.diff --git a/tests/test_message_mirror.py b/tests/test_message_mirror.pyindex 13e7583d1..cd0fd340f 100644--- a/tests/test_message_mirror.py+++ b/tests/test_message_mirror.py@@ -116,6 +116,43 @@ def test_persist_agent_writes_typed_agent_row_on_same_scope(isolated_state):assert agent_row["scope_id"] == user_row["scope_id"]+def test_persist_agent_reuses_cached_sqlite_engine(isolated_state, monkeypatch):+ import storage.db as sqlite_db++ sqlite_db.dispose_cached_sqlite_engines()+ create_calls = 0+ real_create = sqlite_db.create_sqlite_engine++ def counting_create(db_path=None):+ nonlocal create_calls+ create_calls += 1+ return real_create(db_path)++ monkeypatch.setattr(sqlite_db, "create_sqlite_engine", counting_create)+ ctx = _slack_ctx()++ persist_agent_message(ctx, "assistant", "first stream chunk")+ persist_agent_message(ctx, "assistant", "second stream chunk")++ assert create_calls == 1++ engine = real_create()+ try:+ with engine.connect() as conn:+ rows = (+ conn.execute(+ select(messages)+ .where(messages.c.platform == "slack", messages.c.author == "agent")+ .order_by(messages.c.created_at, messages.c.id)+ )+ .mappings()+ .all()+ )+ finally:+ engine.dispose()+ assert [row["content_text"] for row in rows] == ["first stream chunk", "second stream chunk"]++def test_persist_agent_toolcall_writes_event_not_message(isolated_state):ctx = _slack_ctx()mirror_inbound(ctx, "ping")