Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(storage): ensure the sqlite state once per process, not per request

cyha4c82b42612e
diff --git a/storage/importer.py b/storage/importer.py
index e1d42f071..44fe8e834 100644
--- a/storage/importer.py
+++ b/storage/importer.py
@@ -4,6 +4,7 @@ import json
import logging
import shutil
import tempfile
+import threading
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
@@ -53,16 +54,47 @@ class MigrationImportReport:
counts: dict[str, int] = field(default_factory=dict)
+_ensured_lock = threading.Lock()
+_ensured_targets: dict[tuple[Path, Path], MigrationImportReport] = {}
+
+
+def reset_ensured_sqlite_state() -> None:
+ """Forget which targets this process already ensured.
+
+ Production relies on process lifetime: a target is ensured once and stays
+ ensured. Tests call this around isolated homes so a rebuilt database is
+ migrated again instead of trusting a previous test's result.
+ """
+
+ with _ensured_lock:
+ _ensured_targets.clear()
+
+
def ensure_sqlite_state(
*,
db_path: Path | None = None,
state_dir: Path | None = None,
primary_platform: str | None = None,
) -> MigrationImportReport:
- """Create/migrate the SQLite DB and import existing JSON state once."""
+ """Create/migrate the SQLite DB and import existing JSON state once.
+
+ Callers treat this as a cheap precondition and put it in front of ordinary
+ operations, so repeating it must cost nothing. The full body takes a
+ cross-process migration lock and re-runs the whole Alembic upgrade
+ pipeline; running that per request serializes unrelated work machine-wide
+ and turns any transient SQLite contention into a user-visible failure. Once
+ a target is ensured, this process is done with it.
+ """
target_db = (db_path or paths.get_sqlite_state_path()).expanduser().resolve()
target_state_dir = (state_dir or paths.get_state_dir()).expanduser().resolve()
+ ensured_key = (target_db, target_state_dir)
+ with _ensured_lock:
+ ensured = _ensured_targets.get(ensured_key)
+ # The database file is the evidence; a caller that removed it out from
+ # under us gets a real migration rather than a stale promise.
+ if ensured is not None and target_db.exists():
+ return ensured
guard_source_checkout_default_state_migration(target_db)
_ensure_sqlite_target_dirs(
target_state_dir=target_state_dir,
@@ -134,6 +166,8 @@ def ensure_sqlite_state(
if report is None:
raise RuntimeError("SQLite state initialization completed without a report")
prune_state_backups(target_state_dir / "backups")
+ with _ensured_lock:
+ _ensured_targets[ensured_key] = report
return report
diff --git a/tests/conftest.py b/tests/conftest.py
index 8df3fa3fa..7799ed8b0 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -222,15 +222,24 @@ def _seed_sqlite_state_template(
@pytest.fixture(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()
+ """Keep process-local SQLite caches scoped to each isolated test.
+
+ Both caches key on the resolved database path, so a rebuilt home never
+ inherits a previous test's engine or its "already migrated" result.
+ """
+
+ def _reset() -> None:
+ try:
+ from storage.db import dispose_cached_sqlite_engines
+ from storage.importer import reset_ensured_sqlite_state
+ except Exception:
+ return
+ dispose_cached_sqlite_engines()
+ reset_ensured_sqlite_state()
+
+ _reset()
yield
- dispose_cached_sqlite_engines()
+ _reset()
@pytest.fixture(autouse=True)
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index 69efea920..8166bed61 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -20,8 +20,9 @@ from sqlalchemy.schema import CreateIndex
from config import paths
from config.v2_settings import ChannelSettings, RoutingSettings, SettingsState, SettingsStore
from storage.db import SqliteInvalidationProbe, create_sqlite_engine
-from storage.importer import JSON_IMPORT_MARKER, ensure_sqlite_state
-from storage import message_deliveries, messages_service, migrations
+from storage.importer import JSON_IMPORT_MARKER, ensure_sqlite_state, reset_ensured_sqlite_state
+from storage.lock import MigrationFileLock
+from storage import importer, message_deliveries, messages_service, migrations
from storage.background import SQLiteBackgroundTaskStore
from storage.migrations import UnsafeDefaultStateMigrationError, background_tables_ready, run_migrations
from storage.models import metadata
@@ -5228,6 +5229,11 @@ def test_ensure_sqlite_state_imports_json_once(tmp_path: Path) -> None:
_write_discovered_chats(state_dir / "discovered_chats.json")
first = ensure_sqlite_state(db_path=db_path, state_dir=state_dir, primary_platform="slack")
+ # Drop the process-local "already ensured" result so the second call really
+ # replays the pipeline against the migrated database, the way the next
+ # process to start will. Without the reset this would assert the
+ # short-circuit (covered separately) instead of re-run idempotence.
+ reset_ensured_sqlite_state()
second = ensure_sqlite_state(db_path=db_path, state_dir=state_dir, primary_platform="slack")
assert first.imported is True
@@ -5314,6 +5320,62 @@ def test_ensure_sqlite_state_imports_json_once(tmp_path: Path) -> None:
}
+def test_ensure_sqlite_state_short_circuits_after_first_success(tmp_path: Path, monkeypatch) -> None:
+ # Callers put ensure_sqlite_state in front of ordinary operations (a login,
+ # a read-only query, a skill delete), so a repeat call must cost nothing.
+ # Re-running the pipeline per request serialized unrelated work on the
+ # cross-process migration lock and turned transient SQLite contention into a
+ # failed login (page: error=oauth_exchange_failed reason=OperationalError).
+ state_dir = tmp_path / "state"
+ state_dir.mkdir()
+ db_path = state_dir / "vibe.sqlite"
+
+ first = ensure_sqlite_state(db_path=db_path, state_dir=state_dir, primary_platform="slack")
+
+ migrations_run = 0
+ real_run_migrations = importer.run_migrations
+
+ def counting_run_migrations(*args, **kwargs):
+ nonlocal migrations_run
+ migrations_run += 1
+ return real_run_migrations(*args, **kwargs)
+
+ monkeypatch.setattr(importer, "run_migrations", counting_run_migrations)
+
+ # An already-held migration lock is exactly the contention that failed the
+ # login. The repeat call must not queue behind it, so holding it here would
+ # deadlock the test if the short-circuit regressed.
+ with MigrationFileLock(state_dir / "migration.lock", timeout_seconds=1.0):
+ second = ensure_sqlite_state(db_path=db_path, state_dir=state_dir, primary_platform="slack")
+
+ assert second is first
+ assert migrations_run == 0
+
+ # The guard is per target, not process-global: a different home still migrates.
+ other_state_dir = tmp_path / "other"
+ other_state_dir.mkdir()
+ other = ensure_sqlite_state(
+ db_path=other_state_dir / "vibe.sqlite",
+ state_dir=other_state_dir,
+ primary_platform="slack",
+ )
+ assert other.db_path != first.db_path
+ assert migrations_run == 1
+
+ # Both homes are migrated now, so nothing on disk distinguishes them any
+ # more -- only the key does. A memo that is not per target would hand the
+ # first home's caller the second home's report, with the wrong db_path and
+ # the wrong counts, and no call would ever notice.
+ assert ensure_sqlite_state(db_path=db_path, state_dir=state_dir, primary_platform="slack") is first
+ assert migrations_run == 1
+
+ # A database that disappeared is no longer ensured, whatever we remember.
+ for suffix in ("", "-wal", "-shm"):
+ db_path.with_name(db_path.name + suffix).unlink(missing_ok=True)
+ ensure_sqlite_state(db_path=db_path, state_dir=state_dir, primary_platform="slack")
+ assert migrations_run == 2
+
+
def test_ensure_sqlite_state_collapses_multi_backend_anchor_on_import(tmp_path: Path) -> None:
# ensure_sqlite_state runs the migration (installing the (scope, anchor) unique
# index) BEFORE importing sessions.json. Legacy JSON can list several backends
@@ -5431,6 +5493,11 @@ def test_ensure_sqlite_state_preserves_backend_aliases_without_deprecated_backen
conn.commit()
first = ensure_sqlite_state(db_path=db_path, state_dir=state_dir, primary_platform="slack")
+ # Drop the process-local "already ensured" result so the second call really
+ # replays the pipeline against the migrated database, the way the next
+ # process to start will. Without the reset this would assert the
+ # short-circuit (covered separately) instead of re-run idempotence.
+ reset_ensured_sqlite_state()
second = ensure_sqlite_state(db_path=db_path, state_dir=state_dir, primary_platform="slack")
with sqlite3.connect(db_path) as conn: