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(model-hub): the per-turn Model Hub mode stamp stops scanning messages on the loop (#2522)
Call White169c31333b56
diff --git a/core/controller.py b/core/controller.pyindex c62dde2d9..51f6179d6 100644--- a/core/controller.py+++ b/core/controller.py@@ -2604,6 +2604,12 @@ class Controller:model_hub_turn_gateway = getattr(self, "model_hub_turn_gateway", None)if model_hub_turn_gateway is not None:_stop_loop_coroutine(model_hub_turn_gateway.close(), "Model Hub turn gateway")+ # Turns settled up to here queued their mode stamps on the stamp writer.+ # Wait at most 2 s, then abandon what is left; the writer is a daemon+ # thread, so even a stamp blocked on a locked database cannot hold exit.+ from modules.agents.model_hub import drain_turn_mode_stamps++ drain_turn_mode_stamps(timeout=2.0)show_git_checkpoint_service = getattr(self, "show_git_checkpoint_service", None)if show_git_checkpoint_service is not None:show_git_checkpoint_service.stop()diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 7971e2640..adefc4bdb 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -14,7 +14,7 @@ from datetime import datetime, timedelta, timezonefrom pathlib import Pathfrom typing import Any, Awaitable, Callable, Iterable, Literal, Mapping, Optional, Protocol, cast-from sqlalchemy import func, select+from sqlalchemy import func, literal_column, selectfrom config import pathsfrom modules.agents.catalog import NATIVE_CLI_BACKENDS@@ -46,7 +46,7 @@ from core.agent_auth_service import BackendLoginInProgressErrorfrom core.os_errors import format_os_errno, local_error_detailfrom core.services.settings import default_configfrom storage.db import get_cached_sqlite_engine-from storage.models import agent_sessions, messages+from storage.models import MESSAGE_TURN_ID_SQL, agent_sessions, messagesfrom vibe.backend_model_catalog import (PROTOCOL_REASONING_EFFORT_DEFAULTS,builtin_display_name,@@ -7293,13 +7293,9 @@ class ModelHubService:with get_cached_sqlite_engine().begin() as conn:conn.execute(messages.update()- .where(- func.json_extract(- messages.c.metadata_json,- "$.turn_id",- )- == normalized- )+ # The indexed expression, verbatim: a seek on this turn's rows+ # instead of a scan of every Message under the write lock.+ .where(literal_column(MESSAGE_TURN_ID_SQL) == normalized).values(metadata_json=func.json_set(messages.c.metadata_json,@@ -7313,30 +7309,33 @@ class ModelHubService:def _known_turn(turn_id: str,) -> tuple[Optional[str], Optional[Literal["direct", "hub"]]]:+ # The turn's row is found alone, by the indexed expression: joined to+ # ``agent_sessions``, whose ``metadata_json`` shares the column name, the+ # expression's unqualified column would be ambiguous.+ turn_row = (+ select(+ messages.c.session_id,+ func.json_extract(+ messages.c.metadata_json,+ "$.model_hub_mode",+ ).label("mode"),+ )+ .where(literal_column(MESSAGE_TURN_ID_SQL) == turn_id)+ .limit(1)+ .subquery()+ )try:with get_cached_sqlite_engine().connect() as conn:row = conn.execute(select(agent_sessions.c.agent_backend.label("backend"),- func.json_extract(- messages.c.metadata_json,- "$.model_hub_mode",- ).label("mode"),- )- .select_from(- messages.join(+ turn_row.c.mode,+ ).select_from(+ turn_row.join(agent_sessions,- messages.c.session_id == agent_sessions.c.id,- )- )- .where(- func.json_extract(- messages.c.metadata_json,- "$.turn_id",+ turn_row.c.session_id == agent_sessions.c.id,)- == turn_id)- .limit(1)).mappings().first()except Exception:return None, Nonediff --git a/modules/agents/model_hub.py b/modules/agents/model_hub.pyindex 92994b8ab..a68432980 100644--- a/modules/agents/model_hub.py+++ b/modules/agents/model_hub.py@@ -6,9 +6,14 @@ import asyncioimport hashlibimport ipaddressimport json+import loggingimport os+import queueimport reimport shutil+import threading+from concurrent.futures import Future+from concurrent.futures import TimeoutError as FuturesTimeoutErrorfrom dataclasses import dataclass, field, replacefrom pathlib import Pathfrom typing import Any, Callable, Literal, Mapping, Optional, cast@@ -61,8 +66,89 @@ from vibe.i18n import tfrom vibe.opencode_config import managed_opencode_runtime_config_content+logger = logging.getLogger(__name__)+LaunchChannel = Literal["direct", "native_cli", "hub"]TurnMode = Literal["direct", "hub"]+class _TurnModeWriter:+ """Stamps each settled turn's mode on its Message rows, one at a time, in settlement order.++ Settlement runs on the service's event loop and never waits on this+ database write. The worker is a daemon thread: an abandoned stamp costs only+ that turn's provenance detail, and SQLite rolls back a write cut off+ mid-transaction, so nothing here may hold process exit.+ """++ def __init__(self, name: str) -> None:+ self._name = name+ self._jobs: queue.SimpleQueue[tuple[Future[None], Callable[..., object], tuple[Any, ...]]] = (+ queue.SimpleQueue()+ )+ self._start_lock = threading.Lock()+ self._thread: threading.Thread | None = None++ def submit(self, fn: Callable[..., object], *args: Any) -> Future[None]:+ future: Future[None] = Future()+ self._jobs.put((future, fn, args))+ with self._start_lock:+ if self._thread is None:+ self._thread = threading.Thread(target=self._run, name=self._name, daemon=True)+ self._thread.start()+ return future++ def _run(self) -> None:+ while True:+ future, fn, args = self._jobs.get()+ if not future.set_running_or_notify_cancel():+ continue+ try:+ fn(*args)+ except BaseException as error: # noqa: BLE001 - delivered through the future+ future.set_exception(error)+ else:+ future.set_result(None)++ def drain(self, timeout: float) -> bool:+ """Wait up to ``timeout`` for every queued stamp; on timeout discard the rest and return False."""++ drained = self.submit(lambda: None)+ try:+ drained.result(timeout=timeout)+ except FuturesTimeoutError:+ # Python 3.10's futures timeout is not the builtin TimeoutError.+ discarded = 0+ while True:+ try:+ future, _fn, _args = self._jobs.get_nowait()+ except queue.Empty:+ break+ if future.cancel() and future is not drained:+ discarded += 1+ logger.warning(+ "Model Hub turn mode stamps abandoned at shutdown after %.1fs: %d discarded",+ timeout,+ discarded,+ )+ return False+ return True+++_TURN_MODE_WRITER = _TurnModeWriter("model-hub-turn-mode")+++def _log_turn_mode_failure(stamp: Future[None]) -> None:+ if stamp.cancelled():+ return+ error = stamp.exception()+ if error is not None:+ logger.warning("Model Hub turn mode was not stored", exc_info=error)+++def drain_turn_mode_stamps(timeout: float) -> bool:+ """Wait up to ``timeout`` for every queued mode stamp; abandon the rest and return False on timeout."""++ return _TURN_MODE_WRITER.drain(timeout)+_CONTEXT_LAUNCH_ATTR = "_vibe_model_hub_launch"_CONTEXT_MODE_ATTR = "_vibe_model_hub_turn_mode"@@ -1080,16 +1166,16 @@ class ModelHubRuntimeRouter:mode: Optional[Literal["direct", "hub"]] = None,) -> asyncio.Task[None] | None:def finish() -> None:- try:- if mode is not None:- self.service.note_turn_mode(turn_id, mode)- finally:- if self.turn_gateway is not None:- self.turn_gateway.correlation.settle(- turn_id,- settled_by=settled_by,- ts=ts,- )+ if mode is not None:+ _TURN_MODE_WRITER.submit(self.service.note_turn_mode, turn_id, mode).add_done_callback(+ _log_turn_mode_failure+ )+ if self.turn_gateway is not None:+ self.turn_gateway.correlation.settle(+ turn_id,+ settled_by=settled_by,+ ts=ts,+ )if self.turn_gateway is not None:return self.turn_gateway.finalize_turn(turn_id, settled_by=settled_by, finish=finish)diff --git a/storage/alembic/versions/20261012_0064_messages_turn_id_index.py b/storage/alembic/versions/20261012_0064_messages_turn_id_index.pynew file mode 100644index 000000000..42cd12afc--- /dev/null+++ b/storage/alembic/versions/20261012_0064_messages_turn_id_index.py@@ -0,0 +1,77 @@+"""index the turn a Message row belongs to++Settling every Model Hub turn stamps its mode on the Message rows whose+``metadata_json`` names that turn (``ModelHubService.note_turn_mode``). The turn+id lives only in that JSON, so the stamp scanned every Message, overflow chains+included, while holding the database write lock. Measured on a copy of a+long-running host's database (195,468 Messages, about 405 MB)::++ SCAN messages++Indexing the turn-id EXPRESSION makes the stamp a seek on the handful of rows of+one turn. The index is partial, so the nine in ten Messages without a turn id+cost it nothing: SQLite implies the ``(expr) IS NOT NULL`` predicate from the+query's ``expr = ?`` term and uses the index (``SEARCH messages USING INDEX+ix_messages_turn_id (<expr>=?)`` on SQLite 3.50.4). Unlike the owed-notice+indexes of 0040, whose ``json_extract(...) = 'pending'`` predicate the planner+could not imply, this predicate is matched; the plan test pins that.++The ``CASE json_valid`` guard is load-bearing at WRITE time: an index expression+is evaluated on every INSERT and UPDATE, so a bare ``json_extract`` would make a+Message with an unparseable ``metadata_json`` unwritable.++The expression must stay byte-identical to ``MESSAGE_TURN_ID_SQL`` in+``storage/models.py``, which the stamp compiles, or the planner will not match+it; ``tests/test_model_hub_turn_mode_stamp.py`` asserts the plan names this index,+so a drift fails the suite rather than silently restoring the scan.++Revision ID: 20261012_0064+Revises: 20261002_0063+Create Date: 2026-10-12+"""++from __future__ import annotations++from alembic import op++revision = "20261012_0064"+down_revision = "20261002_0063"+branch_labels = None+depends_on = None+MIGRATION_SAFETY = "additive"++_INDEX = "ix_messages_turn_id"+# Unqualified column name: SQLite rejects the "." operator inside an index+# expression. The planner still matches the query's unqualified twin.+_TURN_ID_EXPR = (+ "CASE WHEN (json_valid(metadata_json) = 1) "+ "THEN json_extract(metadata_json, '$.turn_id') END"+)+# Exported so the head-schema repair path in ``storage/migrations.py`` executes THIS+# statement rather than a retyped copy, which the planner would not match.+DROP_INDEX_SQL = f"drop index if exists {_INDEX}"+CREATE_INDEX_SQL = (+ f"create index {_INDEX} on messages ({_TURN_ID_EXPR}) where ({_TURN_ID_EXPR}) is not null"+)+++def _tables(bind) -> set[str]:+ return {+ str(row[0])+ for row in bind.exec_driver_sql("select name from sqlite_master where type = 'table'")+ }+++def upgrade() -> None:+ bind = op.get_bind()+ if "messages" not in _tables(bind):+ return+ bind.exec_driver_sql(DROP_INDEX_SQL)+ bind.exec_driver_sql(CREATE_INDEX_SQL)+++def downgrade() -> None:+ bind = op.get_bind()+ if "messages" not in _tables(bind):+ return+ bind.exec_driver_sql(DROP_INDEX_SQL)diff --git a/storage/migrations.py b/storage/migrations.pyindex cbbe2a60d..c3d26e18e 100644--- a/storage/migrations.py+++ b/storage/migrations.py@@ -923,6 +923,20 @@ def _ensure_messages_query_indexes(conn: sqlite3.Connection, tables: set[str]) -):conn.execute(transcript_index.DROP_INDEX_SQL)conn.execute(transcript_index.CREATE_INDEX_SQL)+ # The turn-id expression index, from the revision that owns its DDL: the+ # planner matches an index expression by text, so a retyped copy is ignored.+ turn_id_index = import_module(+ "storage.alembic.versions.20261012_0064_messages_turn_id_index"+ )+ turn_id_row = conn.execute(+ "select sql from sqlite_master where type = 'index' and name = ?",+ (turn_id_index._INDEX,),+ ).fetchone()+ if turn_id_row is None or _normalized_index_sql(turn_id_row[0]) != _normalized_index_sql(+ turn_id_index.CREATE_INDEX_SQL+ ):+ conn.execute(turn_id_index.DROP_INDEX_SQL)+ conn.execute(turn_id_index.CREATE_INDEX_SQL)conn.execute('create index if not exists ix_messages_session_created_id on messages (session_id, created_at, id)')conn.execute('create index if not exists ix_messages_session_type_created_id on messages (session_id, type, created_at, id)')conn.execute('create index if not exists ix_messages_platform_session_created_id on messages (platform, session_id, created_at, id)')diff --git a/storage/models.py b/storage/models.pyindex bad52652f..4d122bad5 100644--- a/storage/models.py+++ b/storage/models.py@@ -741,6 +741,16 @@ messages = Table(),)+#: The turn a Message row belongs to, as ``ix_messages_turn_id`` indexes it+#: (``20261012_0064``). A query must compile THIS text, through ``literal_column``,+#: for the planner to use the index: SQLite matches an index expression by text,+#: and a bound JSON path or a qualified column name is a different expression.+#: The ``CASE json_valid`` guard keeps a malformed ``metadata_json`` writable.+MESSAGE_TURN_ID_SQL = (+ "CASE WHEN (json_valid(metadata_json) = 1) "+ "THEN json_extract(metadata_json, '$.turn_id') END"+)+# Durable execution ownership for one logical Agent Turn per Session. The Turn# references its initial Delivery even before native acceptance has materialized# a Message. Accepted steer participants reference the Turn from their Delivery.diff --git a/tests/test_agent_context_seq_migration.py b/tests/test_agent_context_seq_migration.pyindex 0087a7133..d1a8234e8 100644--- a/tests/test_agent_context_seq_migration.py+++ b/tests/test_agent_context_seq_migration.py@@ -56,7 +56,7 @@ def test_context_seq_upgrade_and_downgrade_keep_released_rows(tmp_path):migrations.run_migrations(path)with sqlite3.connect(path) as conn:- assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20261002_0063",)+ assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20261012_0064",)assert_released_rows_unchanged(conn)assert _index_sql(conn, "ix_agent_events_turn_sequence_id") is not Nonefor table, (first, same_session, other_session) in _IDS.items():diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.pyindex b5f006115..55451073c 100644--- a/tests/test_model_hub_l3.py+++ b/tests/test_model_hub_l3.py@@ -5713,13 +5713,14 @@ def test_settlement_retires_correlation_when_mode_persistence_fails(turn_gateway=ModelHubTurnGateway(service, correlation=correlation),)- with pytest.raises(OSError, match="mode store unavailable"):- router.settle_turn(- "turn_mode_failure",- settled_by=SETTLED_BY_TERMINAL_RESULT,- ts=NOW.isoformat(),- mode="hub",- )+ # The stamp runs on its own writer thread: its failure is logged there and+ # never reaches, or holds up, settlement.+ router.settle_turn(+ "turn_mode_failure",+ settled_by=SETTLED_BY_TERMINAL_RESULT,+ ts=NOW.isoformat(),+ mode="hub",+ )correlation.settle.assert_called_once_with("turn_mode_failure",diff --git a/tests/test_model_hub_turn_mode_stamp.py b/tests/test_model_hub_turn_mode_stamp.pynew file mode 100644index 000000000..701570e57--- /dev/null+++ b/tests/test_model_hub_turn_mode_stamp.py@@ -0,0 +1,307 @@+"""Settling a Model Hub turn stamps its mode on that turn's Message rows by index, off the event loop.++The stamp used to scan every Message (``SCAN messages``) on the event loop while holding the+database write lock; on a long-running host that is hundreds of megabytes per settled turn.+"""++from __future__ import annotations++import json+import sqlite3+import subprocess+import sys+import threading+import time+from concurrent.futures import Future+from concurrent.futures import TimeoutError as FuturesTimeoutError+from contextlib import closing+from importlib import import_module+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import Mock++import pytest+from sqlalchemy import event, select++from core.handlers.model_hub.service import ModelHubService+from modules.agents import model_hub+from storage.db import create_sqlite_engine+from storage.migrations import _normalized_index_sql, run_migrations+from storage.models import agent_sessions, messages, metadata++pytestmark = pytest.mark.no_sqlite_template++_REVISION = import_module("storage.alembic.versions.20261012_0064_messages_turn_id_index")+_NOW = "2026-10-12T00:00:00.000000Z"+++def _seed(engine, rows: dict[str, str]) -> None:+ """One session, and one agent Message per ``id -> metadata_json``."""++ with engine.begin() as conn:+ conn.execute(+ agent_sessions.insert().values(+ id="ses_stamp",+ agent_backend="codex",+ agent_variant="codex",+ session_anchor="anchor",+ native_session_id="",+ status="active",+ metadata_json="{}",+ created_at=_NOW,+ updated_at=_NOW,+ )+ )+ for message_id, metadata_json in rows.items():+ conn.execute(+ messages.insert().values(+ id=message_id,+ session_id="ses_stamp",+ platform="avibe",+ author="agent",+ type="result",+ source="agent",+ content_json="{}",+ metadata_json=metadata_json,+ created_at=_NOW,+ updated_at=_NOW,+ )+ )+++def migrated_engine(tmp_path: Path, monkeypatch):+ db_path = tmp_path / "vibe.sqlite"+ run_migrations(db_path)+ engine = create_sqlite_engine(db_path)+ monkeypatch.setattr("core.handlers.model_hub.service.get_cached_sqlite_engine", lambda: engine)+ yield engine+ engine.dispose()+++def _index_sql(db_path: Path) -> str | None:+ with closing(sqlite3.connect(db_path)) as conn:+ row = conn.execute(+ "select sql from sqlite_master where type = 'index' and name = ?", (_REVISION._INDEX,)+ ).fetchone()+ return row[0] if row else None+++ "operation",+ [+ pytest.param(lambda: ModelHubService.note_turn_mode("turn_a", "hub"), id="mode-stamp"),+ pytest.param(lambda: ModelHubService._known_turn("turn_a"), id="provenance-read"),+ ],+)+def test_the_turn_is_found_by_the_turn_id_index_instead_of_a_scan(migrated_engine, operation) -> None:+ statements: list[tuple[str, tuple]] = []++ @event.listens_for(migrated_engine, "before_cursor_execute")+ def capture(_conn, _cursor, statement, parameters, _context, _executemany):+ if "messages" in statement:+ statements.append((statement, tuple(parameters)))++ operation()++ [(statement, parameters)] = statements+ with migrated_engine.connect() as conn:+ plan = " ".join(+ str(row[3]) for row in conn.exec_driver_sql(f"EXPLAIN QUERY PLAN {statement}", parameters)+ )+ assert f"USING INDEX {_REVISION._INDEX}" in plan+ assert "SCAN messages" not in plan+++def test_the_stamp_lands_on_every_row_of_its_turn_and_on_no_other(migrated_engine) -> None:+ _seed(+ migrated_engine,+ {+ "msg_result": json.dumps({"turn_id": "turn_a"}),+ "msg_output": json.dumps({"turn_id": "turn_a", "kind": "output"}),+ "msg_other_turn": json.dumps({"turn_id": "turn_b"}),+ "msg_no_turn": json.dumps({"source": "agent"}),+ # The index guards json_valid, so an unparseable row stays writable and is skipped.+ "msg_malformed": "{not json",+ },+ )++ ModelHubService.note_turn_mode("turn_a", "hub")++ with migrated_engine.connect() as conn:+ stored = dict(conn.execute(select(messages.c.id, messages.c.metadata_json)).all())+ assert json.loads(stored["msg_result"]) == {"turn_id": "turn_a", "model_hub_mode": "hub"}+ assert json.loads(stored["msg_output"]) == {"turn_id": "turn_a", "kind": "output", "model_hub_mode": "hub"}+ assert json.loads(stored["msg_other_turn"]) == {"turn_id": "turn_b"}+ assert json.loads(stored["msg_no_turn"]) == {"source": "agent"}+ assert stored["msg_malformed"] == "{not json"+++def test_turn_provenance_reads_the_stamped_mode_by_turn(migrated_engine) -> None:+ _seed(+ migrated_engine,+ {+ "msg_result": json.dumps({"turn_id": "turn_a", "model_hub_mode": "hub"}),+ "msg_other_turn": json.dumps({"turn_id": "turn_b", "model_hub_mode": "direct"}),+ "msg_malformed": "{not json",+ },+ )++ assert ModelHubService._known_turn("turn_a") == ("codex", "hub")+ assert ModelHubService._known_turn("turn_b") == ("codex", "direct")+ assert ModelHubService._known_turn("turn_missing") == (None, None)+++def test_the_migration_indexes_a_released_database_and_downgrades_cleanly(tmp_path: Path) -> None:+ db_path = tmp_path / "vibe.sqlite"+ run_migrations(db_path, revision=_REVISION.down_revision)+ engine = create_sqlite_engine(db_path)+ try:+ _seed(engine, {"msg_released": json.dumps({"turn_id": "turn_released"}), "msg_malformed": "{not json"})+ finally:+ engine.dispose()+ assert _index_sql(db_path) is None++ run_migrations(db_path)++ assert _normalized_index_sql(_index_sql(db_path)) == _normalized_index_sql(_REVISION.CREATE_INDEX_SQL)+ with closing(sqlite3.connect(db_path)) as conn:+ found = conn.execute(+ f"select id from messages where {_REVISION._TURN_ID_EXPR} = ?", ("turn_released",)+ ).fetchall()+ assert found == [("msg_released",)]++ from alembic import command+ from storage import migrations++ command.downgrade(migrations.alembic_config(db_path), _REVISION.down_revision)+ assert _index_sql(db_path) is None+++def test_a_head_shaped_database_gets_the_index_from_its_revision(tmp_path: Path) -> None:+ # A database born from ``metadata.create_all`` reaches head through the repair path.+ db_path = tmp_path / "vibe.sqlite"+ engine = create_sqlite_engine(db_path)+ try:+ metadata.create_all(engine)+ finally:+ engine.dispose()++ run_migrations(db_path)++ assert _normalized_index_sql(_index_sql(db_path)) == _normalized_index_sql(_REVISION.CREATE_INDEX_SQL)+++def test_the_query_expression_is_the_indexed_one() -> None:+ from storage.models import MESSAGE_TURN_ID_SQL++ assert MESSAGE_TURN_ID_SQL == _REVISION._TURN_ID_EXPR+++def test_settling_a_turn_does_not_wait_for_its_mode_stamp() -> None:+ stamping = threading.Event()+ release = threading.Event()+ stamped: list[tuple[str, str]] = []++ def note_turn_mode(turn_id, mode):+ stamping.set()+ assert release.wait(10)+ stamped.append((turn_id, mode))++ correlation = Mock()+ router = model_hub.ModelHubRuntimeRouter(+ service=SimpleNamespace(note_turn_mode=note_turn_mode),+ turn_gateway=SimpleNamespace(+ finalize_turn=lambda turn_id, *, settled_by, finish: finish(),+ correlation=correlation,+ ),+ native_cli_ready=lambda backend: False,+ )++ router.settle_turn("turn_a", settled_by="terminal_result", ts=_NOW, mode="hub")++ # Settlement finished while the stamp was still blocked on its own thread.+ correlation.settle.assert_called_once_with("turn_a", settled_by="terminal_result", ts=_NOW)+ assert stamping.wait(10)+ assert stamped == []+ release.set()+ model_hub._TURN_MODE_WRITER.submit(lambda: None).result(timeout=10)+ assert stamped == [("turn_a", "hub")]+++def test_a_failed_mode_stamp_is_logged_and_never_fails_settlement(caplog) -> None:+ correlation = Mock()+ router = model_hub.ModelHubRuntimeRouter(+ service=SimpleNamespace(note_turn_mode=Mock(side_effect=OSError("mode store unavailable"))),+ turn_gateway=SimpleNamespace(+ finalize_turn=lambda turn_id, *, settled_by, finish: finish(),+ correlation=correlation,+ ),+ native_cli_ready=lambda backend: False,+ )++ router.settle_turn("turn_a", settled_by="terminal_result", ts=_NOW, mode="hub")+ model_hub._TURN_MODE_WRITER.submit(lambda: None).result(timeout=10)++ correlation.settle.assert_called_once()+ assert "Model Hub turn mode was not stored" in caplog.text+++def test_shutdown_waits_for_queued_stamps_only_up_to_its_bound_and_discards_the_rest(caplog) -> None:+ release = threading.Event()+ ran: list[int] = []+ model_hub._TURN_MODE_WRITER.submit(release.wait, 10)+ queued = [model_hub._TURN_MODE_WRITER.submit(ran.append, index) for index in range(3)]++ started = time.monotonic()+ assert model_hub.drain_turn_mode_stamps(timeout=0.2) is False+ assert time.monotonic() - started < 1.0+ assert all(stamp.cancelled() for stamp in queued)+ assert "3 discarded" in caplog.text++ release.set()+ assert model_hub.drain_turn_mode_stamps(timeout=10) is True+ assert ran == []+++def test_a_futures_timeout_from_the_drain_is_caught_on_every_python(monkeypatch) -> None:+ # Python 3.10 raises concurrent.futures.TimeoutError, which is not the builtin there.+ class TimingOut(Future):+ def result(self, timeout=None):+ raise FuturesTimeoutError()++ monkeypatch.setattr(model_hub._TURN_MODE_WRITER, "submit", lambda fn, *args: TimingOut())++ assert model_hub.drain_turn_mode_stamps(timeout=0.1) is False+++# A service process whose stamp writer is blocked on a write that will not finish, with more queued.+_EXIT_WITH_A_BLOCKED_STAMP = """+import sys, time+sys.path.insert(0, sys.argv[1])+from modules.agents import model_hub+marker = sys.argv[2]+model_hub._TURN_MODE_WRITER.submit(time.sleep, 60)+for _ in range(3):+ model_hub._TURN_MODE_WRITER.submit(lambda: open(marker, "a").write("ran"))+drained = model_hub.drain_turn_mode_stamps(timeout=0.5)+print(drained, time.time(), flush=True)+"""+++def test_a_blocked_stamp_never_holds_process_exit(tmp_path: Path) -> None:+ marker = tmp_path / "queued-stamp-ran"+ finished = subprocess.run(+ [sys.executable, "-c", _EXIT_WITH_A_BLOCKED_STAMP, str(Path(__file__).resolve().parents[1]), str(marker)],+ capture_output=True,+ text=True,+ timeout=60,+ )+ exited_at = time.time()++ assert finished.returncode == 0, finished.stderr+ drained, drained_at = finished.stdout.split()+ assert drained == "False"+ # From the drain's return to the process being gone, despite the stamp still sleeping.+ assert exited_at - float(drained_at) < 3.0+ assert not marker.exists()diff --git a/tests/test_skill_observability_migration.py b/tests/test_skill_observability_migration.pyindex aece5af4f..5f566c2ee 100644--- a/tests/test_skill_observability_migration.py+++ b/tests/test_skill_observability_migration.py@@ -35,7 +35,7 @@ def test_skill_schema_upgrade_downgrade_preserves_existing_events(tmp_path):migrations.run_migrations(path)with sqlite3.connect(path) as conn:assert conn.execute(f"SELECT {columns} FROM agent_events ORDER BY id").fetchall() == original- assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20261002_0063",)+ assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20261012_0064",)assert conn.execute("SELECT count(*) FROM skill_usage_daily").fetchone() == (0,)assert {row[2] for row in conn.execute("PRAGMA foreign_key_list(skill_usage_daily)")} == {"scopes",diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex a305ea724..fbd2c5987 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -38,7 +38,7 @@ from vibe.message_types import build_partial_index_predicatepytestmark = pytest.mark.no_sqlite_template-HEAD_REVISION = "20261002_0063"+HEAD_REVISION = "20261012_0064"# ``storage.models`` builds a bare ``MetaData()``, so its foreign keys are unnamed and# Alembic cannot re-emit them when batch mode recreates a table. Every migration that# rebuilds one therefore passes this convention; the rebuild simulated below has to passdiff --git a/tests/test_web_push_provider_invalidation_migration.py b/tests/test_web_push_provider_invalidation_migration.pyindex 9385ad512..f10c9e9ce 100644--- a/tests/test_web_push_provider_invalidation_migration.py+++ b/tests/test_web_push_provider_invalidation_migration.py@@ -69,7 +69,7 @@ def test_upgrade_keeps_legacy_disabled_failure_opted_out(tmp_path):web_push_service.mark_send_failure(conn, endpoint=enabled["endpoint"], disable=True)with sqlite3.connect(path) as conn:assert conn.execute("select version_num from alembic_version").fetchone() == (- "20261002_0063",+ "20261012_0064",)command.downgrade(migrations.alembic_config(path), "20260907_0061")