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.

5.4 KB
Raw Blame
from __future__ import annotations

from pathlib import Path
from threading import RLock

from sqlalchemy import Engine, create_engine, event
from sqlalchemy.engine import URL

from config import paths
from storage import loop_writers


def escape_sql_like(value: str) -> str:
    """Escape the LIKE/ILIKE metacharacters in *value* for use with ``escape="\\"``.

    Backslash first (so the escapes we add aren't re-escaped), then the two
    wildcards ``%`` and ``_`` — a literal one in a user query must match itself,
    not widen the pattern. Shared by every LIKE-based search (session title +
    message content) so the escaping can't drift between call sites.
    """
    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 = _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, *, read_only: bool = False) -> Engine:
    """Open normal state, or existing state without creation or journal changes."""
    path = _resolve_sqlite_path(db_path)
    if not read_only:
        path.parent.mkdir(parents=True, exist_ok=True)
    # ``hide_parameters`` keeps bound values out of ``str(exc)`` on every
    # SQLAlchemy error. Those values are the user's identity and access-control
    # data -- emails, subjects, instance and scope ids, serialized authorization
    # claims -- and any caller that logs a database failure with a traceback
    # otherwise writes them into the unrotated service log. Owning it here rather
    # than at each log site is what makes that true for callers not yet written:
    # this is the only ``create_engine`` in the codebase, so every engine
    # inherits it. The statement text, the traceback, and the underlying sqlite3
    # error all survive, which is what a diagnostic actually needs.
    url = (
        URL.create("sqlite", database=path.as_uri(), query={"mode": "ro", "uri": "true"})
        if read_only else sqlite_url(path)
    )
    # Every connection is a ``CensusConnection`` so the loop-writer census (#2710)
    # can time a loop transaction to the end of SQLite's own commit.
    engine = create_engine(
        url,
        future=True,
        hide_parameters=True,
        connect_args={"factory": loop_writers.CensusConnection},
    )

    @event.listens_for(engine, "connect")
    def _set_sqlite_pragmas(dbapi_connection, _connection_record) -> None:
        cursor = dbapi_connection.cursor()
        if not read_only:
            with loop_writers.track_autocommit_write(dbapi_connection):
                cursor.execute("PRAGMA journal_mode = WAL")
        cursor.execute("PRAGMA foreign_keys = ON")
        cursor.execute("PRAGMA busy_timeout = 5000")
        cursor.close()

    loop_writers.watch_engine(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.

    SQLite data_version values are only meaningful when compared across
    repeated calls on the same connection, so this probe keeps one dedicated
    connection for its lifetime.
    """

    def __init__(self, engine: Engine):
        self._connection = engine.connect()
        self._last_data_version: int | None = None
        self._lock = RLock()

    def has_external_write(self) -> bool:
        # Runtime work lanes may ask the same store to refresh from separate
        # executor workers. The probe deliberately owns one persistent
        # connection, so its read-and-compare operation must remain single-file.
        with self._lock:
            version = int(
                self._connection.exec_driver_sql("PRAGMA data_version").scalar_one()
            )
            changed = (
                self._last_data_version is not None
                and version != self._last_data_version
            )
            self._last_data_version = version
            return changed

    def close(self) -> None:
        with self._lock:
            self._connection.close()

    def __enter__(self) -> "SqliteInvalidationProbe":
        return self

    def __exit__(self, _exc_type, _exc, _tb) -> None:
        self.close()