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(session): never wait for SQLite's writer in the turn-state running-projection repair (#2708)
Call White695537a00466
diff --git a/core/session_turns.py b/core/session_turns.pyindex e9ba9be98..8cad2ea8b 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -28,6 +28,7 @@ from typing import TYPE_CHECKING, Any, Awaitable, Callable, ContextManager, Iterfrom sqlalchemy import and_, exists, literal, or_, select, updatefrom sqlalchemy.engine import Connection, Engine+from sqlalchemy.exc import OperationalErrorfrom core.delivery_target import normalize_message_kindfrom core.agent_input import AgentInputMetadata@@ -631,6 +632,23 @@ class _RuntimeStartOwner:identity: RuntimeActivationIdentity | None = None++def _try_reserve_write_lock(conn: Connection) -> bool:+ """``reserve_write_lock`` without waiting: ``False`` when another connection holds+ SQLite's writer, instead of blocking the caller for the busy timeout."""++ previous = conn.exec_driver_sql("PRAGMA busy_timeout").scalar()+ conn.exec_driver_sql("PRAGMA busy_timeout = 0")+ try:+ reserve_write_lock(conn)+ except OperationalError as exc:+ if "locked" not in str(exc).lower() and "busy" not in str(exc).lower():+ raise+ return False+ finally:+ conn.exec_driver_sql(f"PRAGMA busy_timeout = {int(previous)}")+ return True+class SessionTurnManager:"""Owns the live per-session turn state + lifecycle for avibe sessions.@@ -7931,15 +7949,31 @@ class SessionTurnManager:return recovereddef _repair_ownerless_running_projection(self, session_id: str) -> bool:- """Clear a legacy running projection only after an exact owner recheck."""+ """Clear a legacy running projection only after an exact owner recheck.++ Runs on the controller loop, so no loop-side section that writes the running+ projection before it creates the owner (an agent-initiated Turn's ``on_running``,+ then ``register_agent_initiated_turn``) can interleave with the recheck. It+ therefore never WAITS for SQLite's writer, which another process may hold for+ the whole busy timeout (#2706): a busy writer skips the repair, and the next+ turn-state read retries it.+ """engine = self._sqlite_engine()if not callable(getattr(engine, "connect", None)):return Falseif not self._durable_schema_available():return False+ # Most sessions are not projected running: answer them without the writer.+ with engine.connect() as conn:+ status = conn.execute(+ select(agent_sessions.c.agent_status).where(agent_sessions.c.id == session_id)+ ).scalar_one_or_none()+ if status != "running":+ return Falsewith engine.begin() as conn:- reserve_write_lock(conn)+ if not _try_reserve_write_lock(conn):+ return Falseif delivery_store.active_turn(conn, session_id) is not None:return Falserepaired = conn.execute(diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex 02c8fb7c9..611f8a087 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -32,7 +32,7 @@ from unittest.mock import AsyncMock, MagicMock, Mock, callimport httpximport pytest-from sqlalchemy import select+from sqlalchemy import select, updatesys.path.insert(0, str(Path(__file__).resolve().parents[1]))@@ -2836,6 +2836,66 @@ def test_turn_state_reflects_in_flight():assert busy["backend"] == "opencode"+def test_turn_state_repairs_a_stale_running_projection_without_waiting_for_the_writer(tmp_path, monkeypatch):+ """#2706: ``/internal/turn-state`` clears a stale ``running`` projection only after rechecking, under SQLite's+ writer, that no turn owns the session. The endpoint runs on the controller loop, and another process may hold that+ writer for the whole busy timeout, so the repair never waits for it: while the writer is held the read answers at+ once and leaves the projection for the next read, which repairs it."""+ import sqlite3+ import threading+ import time++ from storage.models import agent_sessions++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ engine, session = _create_test_session(tmp_path, native_id="proj_turn_state_repair")+ session_id = session["id"]+ with engine.begin() as conn:+ conn.execute(+ update(agent_sessions).where(agent_sessions.c.id == session_id).values(agent_status="running")+ )+ app = internal_server.create_app(_build_controller_double())+ transport = httpx.ASGITransport(app=app)+ held, release = threading.Event(), threading.Event()++ def another_process_holds_the_writer() -> None:+ holder = sqlite3.connect(engine.url.database, timeout=10)+ try:+ holder.execute("BEGIN IMMEDIATE")+ held.set()+ release.wait(2.0)+ holder.rollback()+ finally:+ holder.close()++ def stored_status() -> str:+ with engine.connect() as conn:+ return conn.execute(+ select(agent_sessions.c.agent_status).where(agent_sessions.c.id == session_id)+ ).scalar_one()++ async def _go():+ holder = threading.Thread(target=another_process_holds_the_writer)+ holder.start()+ assert await asyncio.to_thread(held.wait, 5)+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:+ started = time.monotonic()+ contended = (await client.get(f"/internal/turn-state/{session_id}")).json()+ answered_in = time.monotonic() - started+ status_while_held = stored_status()+ release.set()+ await asyncio.to_thread(holder.join, 5)+ repaired = (await client.get(f"/internal/turn-state/{session_id}")).json()+ return answered_in, contended, status_while_held, repaired++ answered_in, contended, status_while_held, repaired = asyncio.run(_go())+ assert answered_in < 0.5, f"the turn-state read waited {answered_in:.2f}s for SQLite's writer on the loop"+ assert contended["in_flight"] is False and contended["recovered_agent_status"] is False+ assert status_while_held == "running"+ assert repaired["recovered_agent_status"] is True+ assert stored_status() == "idle"++def test_turn_state_projects_a_restored_durable_owner_without_in_flight(tmp_path,monkeypatch,