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
fix(storage): count loop-side autocommit SQLite writes (#3060)
Call White184375a72b0f
diff --git a/storage/db.py b/storage/db.pyindex 4f7d6119a..f1893a3b7 100644--- a/storage/db.py+++ b/storage/db.py@@ -61,7 +61,8 @@ def create_sqlite_engine(db_path: Path | None = None, *, read_only: bool = Falsedef _set_sqlite_pragmas(dbapi_connection, _connection_record) -> None:cursor = dbapi_connection.cursor()if not read_only:- cursor.execute("PRAGMA journal_mode = WAL")+ 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()diff --git a/storage/loop_writers.py b/storage/loop_writers.pyindex a3a375368..e648ba1d0 100644--- a/storage/loop_writers.py+++ b/storage/loop_writers.py@@ -16,6 +16,10 @@ slower event-dispatch path.(``mark_write_attempt``). They add the loop time since the record started, up tothe end of SQLite's own commit or rollback (``fsync`` included), to the totals ofthe code location that ended the transaction, and start the next record.+- Known autocommit writers use ``track_autocommit_write`` around their complete+ operation. It counts only on the bound loop thread, without inspecting every+ cursor statement, and leaves a real SQLite transaction for the normal commit or+ rollback census so one operation cannot be counted twice.The location is two frames: the first outside SQLAlchemy, ``contextlib`` and thismodule, and its caller, so a write behind a shared transaction helper still names@@ -24,8 +28,9 @@ nothing is formatted until a report. The totals live in memory only. A locationlogged once when it first appears, a ranked summary at most every``SUMMARY_INTERVAL_SECONDS`` while new writes arrive, and a complete one at shutdown.-Not counted: writes SQLite runs outside a transaction, such as DDL and-``PRAGMA journal_mode`` (#2747).+Autocommit writes are counted only at explicit call sites, such as DDL and+``PRAGMA journal_mode`` during connection setup (#2747). Other statements outside+a transaction remain uncounted until their path is deliberately marked.A write that cannot wait for another writer, because it takes the writer with azero busy timeout (``_try_reserve_write_lock``), is marked with@@ -126,12 +131,71 @@ class CensusConnection(sqlite3.Connection):_count(_site(sys._getframe(1)), now - record[0], never_waits=record[1])+class _AutocommitWrite:+ """Close one explicitly marked write, including failures, exactly once."""++ def __init__(self, connection: CensusConnection, site: _Site) -> None:+ self._connection = connection+ self._record = connection._census+ self._site = site+ self._started_at: float | None = None+ self._closed = False++ def __enter__(self) -> "_AutocommitWrite":+ self._started_at = time.perf_counter()+ return self++ def __exit__(self, _exc_type: Any, _exc: Any, _tb: Any) -> bool:+ if self._closed:+ return False+ self._closed = True+ started_at = self._started_at+ if started_at is None:+ return False+ # A commit or rollback replaces the checkout's record. Identity, rather+ # than ``in_transaction`` alone, catches a transaction that finished+ # inside this context before SQLite cleared that flag.+ if self._connection._census is not self._record:+ return False+ # If the marked operation opened a real SQLite transaction, its eventual+ # commit/rollback owns the timing and site. This keeps an explicit marker+ # from double-counting a transaction that happened not to be autocommit.+ if self._connection.in_transaction:+ return False+ _count(self._site, time.perf_counter() - started_at, never_waits=False)+ return False+++def _dbapi_connection(conn: Any) -> Any:+ if isinstance(conn, CensusConnection):+ return conn+ try:+ return conn.connection.dbapi_connection+ except AttributeError:+ return None+++def track_autocommit_write(conn: Any) -> contextlib.AbstractContextManager[Any]:+ """Measure one known autocommit write without inspecting every statement.++ ``conn`` may be a SQLAlchemy connection or the raw ``CensusConnection`` used+ during engine connection setup. Off-loop and non-census connections use a+ no-op context, so read statements and unrelated worker activity pay no+ per-statement cost.+ """++ dbapi_connection = _dbapi_connection(conn)+ if threading.get_ident() != _loop_thread or not isinstance(dbapi_connection, CensusConnection):+ return contextlib.nullcontext()+ return _AutocommitWrite(dbapi_connection, _site(sys._getframe(1)))++def watch_engine(engine: Engine) -> None:event.listen(engine, "checkout", _on_checkout)def _record(conn: Any) -> list[Any] | None:- return getattr(conn.connection.dbapi_connection, "_census", None)+ return getattr(_dbapi_connection(conn), "_census", None)def mark_never_waits(conn: Any) -> None:diff --git a/storage/sessions_service.py b/storage/sessions_service.pyindex c98aaf59f..e0967eee9 100644--- a/storage/sessions_service.py+++ b/storage/sessions_service.py@@ -17,7 +17,8 @@ from modules.agents.catalog import AGENT_BACKENDS, display_name_for_backendfrom config.v2_config import V2Configfrom config.v2_sessions import ActivePollInfo, SessionStatefrom config.v2_settings import _split_scoped_key-from storage.db import SqliteInvalidationProbe, create_sqlite_engine+from storage import loop_writers+from storage import message_deliveries as delivery_storefrom storage.agent_session_rows import (SUPERSEDED_ANCHOR_INFIX,create_agent_session_row,@@ -32,6 +33,7 @@ from storage.agent_session_rows import (reserve_write_lock,snapshot_scope_workdir,)+from storage.db import SqliteInvalidationProbe, create_sqlite_enginefrom storage.models import (agents,agent_events,@@ -56,7 +58,6 @@ from storage.session_reclaim import (retire_session_delivery_owners,)from storage.settings_service import make_scope_id, upsert_scope-from storage import message_deliveries as delivery_store_RUNTIME_RECORD_ROWID = literal_column("runtime_records.rowid")@@ -325,7 +326,9 @@ class SQLiteSessionsService:def __init__(self, db_path: Path):self.db_path = db_pathself.engine = create_sqlite_engine(db_path)- metadata.create_all(self.engine)+ with self.engine.begin() as conn:+ with loop_writers.track_autocommit_write(conn):+ metadata.create_all(conn)self._probe = SqliteInvalidationProbe(self.engine)def close(self) -> None:diff --git a/tests/test_loop_writers.py b/tests/test_loop_writers.pyindex eab35b6b9..b514ce2e0 100644--- a/tests/test_loop_writers.py+++ b/tests/test_loop_writers.py@@ -45,6 +45,14 @@ def _sites() -> dict[str, list[float]]:}+def _matching_sites(*, filename: str, name: str) -> list[tuple[tuple, list[float]]]:+ return [+ (site, totals)+ for site, totals in loop_writers._totals.items()+ if site and site[0][0].endswith(filename) and site[0][2] == name+ ]++def _explicit_write(engine) -> None:with engine.begin() as conn:conn.execute(text("INSERT INTO notes (body) VALUES ('a')"))@@ -92,6 +100,120 @@ def _timed_out_writer_wait(engine, db_path) -> None:holder.close()+def test_loop_side_metadata_ddl_is_counted(census, tmp_path) -> None:+ """The known ``metadata.create_all`` path reports its autocommit DDL once."""++ from storage.sessions_service import SQLiteSessionsService++ loop_writers._totals.clear()+ service = SQLiteSessionsService(tmp_path / "metadata.sqlite")+ service.close()++ matches = _matching_sites(filename="storage/sessions_service.py", name="__init__")+ assert len(matches) == 1+ _site, totals = matches[0]+ assert totals[0] == 1+ assert totals[1] > 0+ assert totals[2] > 0+ assert totals[3] == 0+++def test_loop_side_journal_mode_setup_is_counted(census, tmp_path) -> None:+ """The connection-initialization WAL change is visible when setup runs on-loop."""++ loop_writers._totals.clear()+ engine = create_sqlite_engine(tmp_path / "journal.sqlite")+ try:+ with engine.connect() as conn:+ assert conn.exec_driver_sql("PRAGMA journal_mode").scalar_one() == "wal"+ finally:+ engine.dispose()++ matches = _matching_sites(filename="storage/db.py", name="_set_sqlite_pragmas")+ assert len(matches) == 1+ _site, totals = matches[0]+ assert totals[0] == 1+ assert totals[1] > 0+ assert totals[2] > 0+++def test_off_loop_connection_setup_is_not_counted(census, tmp_path) -> None:+ """A worker opening a normal engine does not enter the controller census."""++ loop_writers._totals.clear()+ errors: list[BaseException] = []++ def setup() -> None:+ try:+ engine = create_sqlite_engine(tmp_path / "off-loop.sqlite")+ with engine.connect():+ pass+ engine.dispose()+ except BaseException as exc: # pragma: no cover - assertion below reports it+ errors.append(exc)++ worker = threading.Thread(target=setup)+ worker.start()+ worker.join()++ assert errors == []+ assert loop_writers._totals == {}+++def test_read_only_pragmas_are_not_counted(census) -> None:+ """Connection-local pragma settings and data-version reads are not writers."""++ loop_writers._totals.clear()+ with census.connect() as conn:+ conn.exec_driver_sql("PRAGMA foreign_keys = ON")+ conn.exec_driver_sql("PRAGMA busy_timeout = 5000")+ conn.exec_driver_sql("PRAGMA data_version").scalar_one()++ assert loop_writers._totals == {}+++def test_a_failed_marked_autocommit_write_is_closed_once(census) -> None:+ """A failed marked operation is counted, and its checkout record stays clean."""++ def failed_ddl() -> None:+ with census.connect() as conn:+ with loop_writers.track_autocommit_write(conn):+ conn.exec_driver_sql("CREATE TABLE broken (")++ with pytest.raises(OperationalError, match="incomplete input"):+ failed_ddl()++ matches = _matching_sites(filename="tests/test_loop_writers.py", name="failed_ddl")+ assert len(matches) == 1+ _site, totals = matches[0]+ assert totals[0] == 1+ assert totals[1] > 0++ failed_counts = [+ totals[0]+ for site, totals in loop_writers._totals.items()+ if site[0][2] == "failed_ddl"+ ]+ assert failed_counts == [1]++[email protected]("finish", ("commit", "rollback"))+def test_a_marked_transaction_is_counted_once(census, finish) -> None:+ """A transaction finished inside the marker is owned by its census record."""++ def finish_inside_marker() -> None:+ with census.connect() as conn:+ with loop_writers.track_autocommit_write(conn):+ conn.execute(text("INSERT INTO notes (body) VALUES ('marker')"))+ getattr(conn, finish)()++ finish_inside_marker()++ matches = _matching_sites(filename="tests/test_loop_writers.py", name="finish_inside_marker")+ assert len(matches) == 1+ assert matches[0][1][0] == 1++def test_the_census_counts_exactly_the_loops_write_transactions(census) -> None:"""Every write the loop thread runs is counted under the function that ran it,whether it began explicitly or on its first statement, committed or rolled back.