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): restart an engine that lost its configuration once its streams end (#2753)
Call Whiteabd542f1ae4d
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex 37dd71a7b..7ce7f649f 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -101,6 +101,7 @@ capabilities:- tests/test_model_hub_declared_tools.py- tests/test_model_hub_l3.py- tests/test_model_hub_migration_bearer.py+ - tests/test_model_hub_transport_leases.py- tests/test_model_hub_hosted_executor.py- tests/test_model_hub_hosted_evidence.py- tests/test_model_hub_hosted_images.pydiff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex 1e88dd1be..276732dd3 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -44,6 +44,7 @@ capability:- tests/test_model_hub_declared_tools.py- tests/test_model_hub_l3.py- tests/test_model_hub_migration_bearer.py+ - tests/test_model_hub_transport_leases.py- tests/test_model_hub_hosted_executor.py- tests/test_model_hub_hosted_evidence.py- tests/test_model_hub_hosted_images.py@@ -1164,6 +1165,17 @@ scenarios:kind: timeout_cancellayer: contracttest: tests/test_model_hub_retry_lifecycle.py::test_a_silent_engine_stream_is_cancelled_and_retried_at_its_idle_bound+ - id: MH-RUNTIME-014+ name: >-+ An engine that refuses the credentials Avibe launched it with is reported once as having lost its configuration,+ admits no new work, and restarts from the rendered config only after its open streams end; the waiting save or+ turn then runs on the restarted engine+ status: covered+ kind: recovery+ layer: contract+ test:+ - tests/test_model_hub_transport_leases.py::test_an_engine_that_lost_its_configuration_restarts_only_once_its_streams_end+ - tests/test_model_hub_runtime.py::test_an_engine_that_lost_its_configuration_is_reported_once_and_restarted_by_its_drainer- id: MH-USAGE-001name: Tokens an upstream reported before the turn ended are still meteredstatus: covereddiff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.pyindex 11df32e3d..38f5de94e 100644--- a/tests/test_model_hub_runtime.py+++ b/tests/test_model_hub_runtime.py@@ -69,7 +69,9 @@ from vibe.model_hub_runtime.state import (SourceRecord,)from vibe.model_hub_runtime.supervisor import (+ MODEL_HUB_CONFIG_RELOAD_TIMEOUT_SECONDS,MODEL_HUB_STARTUP_TIMEOUT_SECONDS,+ EngineConfigLostError,EngineSupervisor,EngineUnavailableError,)@@ -2952,9 +2954,11 @@ def _write_mock_engine(exit_before_ready: int | None = None,reload_delay: float = 0.0,drop_reload_ack: bool = False,+ lose_config_on_reload: bool = False,) -> None:script = f"""#!{sys.executable}import json+import osimport sysimport threadingimport time@@ -3036,8 +3040,13 @@ class Handler(BaseHTTPRequestHandler):handle.write(body)def apply():- global config+ global config, gateway, managementconfig = yaml.safe_load(body)+ if {lose_config_on_reload!r} and not os.path.exists('config-lost'):+ # The 3.2.1rc8 race (#2686): the watcher applied a half-written+ # file, so the engine runs its defaults, not the config written.+ open('config-lost', 'w').close()+ gateway = management = 'engine-default'with open('config-reloads', 'a', encoding='utf-8') as handle:handle.write('reload\\n')@@ -3176,6 +3185,7 @@ def _fixture_supervisor(exit_before_ready: int | None = None,reload_delay: float = 0.0,drop_reload_ack: bool = False,+ lose_config_on_reload: bool = False,) -> tuple[EngineSupervisor, EngineStateStore]:tmp_path.mkdir(parents=True, exist_ok=True)binary = tmp_path / "mock-engine"@@ -3188,6 +3198,7 @@ def _fixture_supervisor(exit_before_ready=exit_before_ready,reload_delay=reload_delay,drop_reload_ack=drop_reload_ack,+ lose_config_on_reload=lose_config_on_reload,)installer = _FixtureInstaller(binary, tmp_path / "versions" / "install-1")store = EngineStateStore(tmp_path / "state")@@ -3226,6 +3237,46 @@ def test_source_sync_hot_reloads_a_running_engine_without_restart(tmp_path: Pathsupervisor.stop()+def test_an_engine_that_lost_its_configuration_is_reported_once_and_restarted_by_its_drainer(+ tmp_path: Path, caplog: pytest.LogCaptureFixture,+) -> None:+ """Scenario: MH-RUNTIME-014 -- an engine refusing its launch credentials is not running Avibe's config (#2687).++ The reload that lost it fails at once instead of waiting out its deadline,+ no caller restarts it under the streams it still serves, and the restart+ its drainer asks for renders the config again.+ """+ supervisor, store = _fixture_supervisor(tmp_path, lose_config_on_reload=True)+ credential_ref = store.store_api_key("upstream-secret", base_url="https://api.example.test/v1")+ store.sync_sources([_binding(credential_ref)])+ connection = supervisor.ensure_running()+ lost = supervisor._process+ try:+ store.sync_sources([_binding(credential_ref, route_model_ids=("model-b",))])+ started = time.monotonic()+ with caplog.at_level(logging.WARNING, logger=supervisor_module.__name__):+ with pytest.raises(EngineConfigLostError):+ supervisor.reload_config_if_running()+ assert time.monotonic() - started < MODEL_HUB_CONFIG_RELOAD_TIMEOUT_SECONDS+ with pytest.raises(EngineConfigLostError):+ supervisor.ensure_running()+ assert supervisor._process is lost and lost.poll() is None+ [report] = [record.getMessage() for record in caplog.records if "lost its configuration" in record.getMessage()]+ assert f"port={connection.base_url.rsplit(':', 1)[1]}" in report and "http_status=401" in report++ supervisor.restart_lost_engine()+ assert supervisor._process is not lost and lost.poll() is not None+ prefix = store.get_source("src_fixture123").prefix+ restored = EngineClient(supervisor.ensure_running())+ assert restored.list_model_ids() == {f"{prefix}/model-a", f"{prefix}/model-b"}+ # A second drainer of the same loss finds the engine answering.+ restarted = supervisor._process+ supervisor.restart_lost_engine()+ assert supervisor._process is restarted+ finally:+ supervisor.stop()++def test_source_sync_waits_for_an_id_preserving_reload_to_apply(tmp_path: Path) -> None:supervisor, store = _fixture_supervisor(tmp_path, reload_delay=0.3)credential_ref = store.store_api_key("upstream-secret", base_url="https://api.example.test/v1")diff --git a/tests/test_model_hub_transport_leases.py b/tests/test_model_hub_transport_leases.pyindex c52d68a4c..b94f90ef1 100644--- a/tests/test_model_hub_transport_leases.py+++ b/tests/test_model_hub_transport_leases.py@@ -11,7 +11,7 @@ from aiohttp import webfrom core.handlers.model_hub.adapter import RawOutcomeKind, SourceBindingfrom vibe.model_hub_runtime.adapter import CLIProxyEngineAdapterfrom vibe.model_hub_runtime.client import EngineClient, EngineConnection-from vibe.model_hub_runtime.supervisor import EngineUnavailableError+from vibe.model_hub_runtime.supervisor import EngineConfigLostError, EngineUnavailableErrorfrom vibe.model_hub_runtime.state import EngineStateStore@@ -27,10 +27,19 @@ class LeaseSupervisor:self.allow_reload.set()self.reload_count = 0self.fail_reload = False+ # Where the engine is next found to have lost its configuration, once.+ self.lose_config_at = None+ self.restarts = 0def client(self):+ if self.lose_config_at == "admission":+ self.lose_config_at = None+ raise EngineConfigLostError()return EngineClient(self.connection)+ def restart_lost_engine(self):+ self.restarts += 1+def client_if_running(self):return self.client()@@ -44,6 +53,9 @@ class LeaseSupervisor:if self.fail_reload:self.fail_reload = Falseraise EngineUnavailableError("models.engine.health_failed")+ if self.lose_config_at == "reload":+ self.lose_config_at = None+ raise EngineConfigLostError()@asynccontextmanager@@ -205,6 +217,42 @@ def test_cancelled_reload_holds_admission_until_commit_or_rollback(tmp_path, faiasyncio.run(run())[email protected]("lost_at", ["reload", "admission"])+def test_an_engine_that_lost_its_configuration_restarts_only_once_its_streams_end(tmp_path, lost_at):+ """Scenario: MH-RUNTIME-014 -- no new work is admitted, the open stream ends whole, then the waiting work runs (#2687)."""++ async def run():+ async with _transport(tmp_path) as (adapter, supervisor, binding, _received, finish, requests):+ handle = await adapter.invoke(binding.source_id, "unknown", {}, True, "opencode")+ assert await anext(handle.stream) == FIRST+ supervisor.lose_config_at = lost_at+ save = None+ if lost_at == "reload":+ save = asyncio.create_task(adapter.sync_sources([replace(binding, route_model_ids=("unknown", "new"))]))+ assert await asyncio.to_thread(supervisor.reload_started.wait, 2)+ later = asyncio.create_task(adapter.invoke(binding.source_id, "unknown", {}, False, "opencode"))+ await asyncio.sleep(0.1)+ assert supervisor.restarts == 0+ assert len(requests) == 1 and not later.done()+ finish.set()+ assert b"".join([part async for part in handle.stream]) == LAST+ assert (await handle.outcome()).kind is RawOutcomeKind.SUCCESS+ later_handle = await asyncio.wait_for(later, 2)+ assert supervisor.restarts == 1+ assert (await later_handle.outcome()).kind is RawOutcomeKind.SUCCESS+ await handle.close_stream()+ await later_handle.close_stream()+ if save is not None:+ await asyncio.wait_for(save, 2)+ # The save applies again on the restarted engine.+ assert supervisor.reload_count == 2+ assert set(adapter.state_store.list_sources()[0].route_model_ids) == {"unknown", "new"}+ assert adapter._active_transports == 0+ assert not adapter._routing_lock.locked()++ asyncio.run(run())++def test_two_concurrent_saves_are_serial_and_reload_failure_restores_projection(tmp_path):async def run():async with _transport(tmp_path) as (adapter, supervisor, binding, _received, _finish, _requests):diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.pyindex 241a67eae..90e63edc1 100644--- a/vibe/model_hub_runtime/adapter.py+++ b/vibe/model_hub_runtime/adapter.py@@ -13,7 +13,7 @@ import uuidfrom dataclasses import dataclass, field, replacefrom datetime import datetime, timedelta, timezonefrom enum import Enum-from typing import Any, Callable, Literal, Mapping, Sequence+from typing import Any, Callable, Literal, Mapping, Sequence, TypeVarimport aiohttp@@ -73,12 +73,15 @@ from vibe.model_hub_runtime.installer import ()from vibe.model_hub_runtime.state import EngineStateError, EngineStateStorefrom vibe.model_hub_runtime.supervisor import (+ EngineConfigLostError,EngineSupervisor,EngineUnavailableError,get_engine_supervisor,)+_T = TypeVar("_T")+# The subscription vendors the engine can start an OAuth flow for, and the three# names each one answers to on the way through it:#@@ -1505,7 +1508,7 @@ class CLIProxyEngineAdapter:EngineHealth.NOT_INSTALLED,}:return- await asyncio.to_thread(self.supervisor.ensure_running)+ await self._engine_call(self.supervisor.ensure_running)async def _run_installation(self,@@ -1728,7 +1731,7 @@ class CLIProxyEngineAdapter:self._start_after_install_task = start_taskstart_task.add_done_callback(self._start_after_install_done)return status- await asyncio.to_thread(self.supervisor.ensure_running)+ await self._engine_call(self.supervisor.ensure_running)return await self.status()async def stop_runtime(self) -> EngineStatus:@@ -1791,7 +1794,7 @@ class CLIProxyEngineAdapter:return projectedasync def gateway_token(self) -> str:- connection = await asyncio.to_thread(self.supervisor.ensure_running)+ connection = await self._engine_call(self.supervisor.ensure_running)return connection.gateway_tokenasync def sync_sources(self, bindings: Sequence[SourceBinding]) -> None:@@ -1804,7 +1807,14 @@ class CLIProxyEngineAdapter:# until the finite transaction has applied or restored the prior# projection.await self._requests_sent.wait()- await run_owned_in_thread(self._sync_sources_transaction, tuple(bindings))+ try:+ await run_owned_in_thread(self._sync_sources_transaction, tuple(bindings))+ except EngineConfigLostError:+ # The transaction kept the projection the engine was launched+ # with, so the restart renders that and the save then applies+ # as it would have. A second loss fails the save.+ await self._restart_lost_engine()+ await run_owned_in_thread(self._sync_sources_transaction, tuple(bindings))def _sync_sources_transaction(self, bindings: Sequence[SourceBinding]) -> None:try:@@ -1814,6 +1824,10 @@ class CLIProxyEngineAdapter:self.state_store.sync_sources(bindings)try:self.supervisor.reload_config_if_running(previous)+ except EngineConfigLostError:+ # Nothing the engine runs is Avibe's to restore.+ self.state_store.replace_sources(previous)+ raiseexcept Exception:applied = self.state_store.list_sources()self.state_store.replace_sources(previous)@@ -1857,6 +1871,33 @@ class CLIProxyEngineAdapter:return release+ async def _restart_lost_engine(self) -> None:+ """Restore an engine that lost its configuration; the caller holds the routing lock.++ Holding it admits no new work. The engine restarts from the config+ Avibe renders once the streams it still serves have ended, so none of+ them is cut.+ """+ await self._transports_idle.wait()+ await run_owned_in_thread(self.supervisor.restart_lost_engine)++ async def _locked_engine_call(self, call: Callable[[], _T]) -> _T:+ """Run a supervisor call that may start the engine, under the routing lock the caller holds."""+ try:+ return await asyncio.to_thread(call)+ except EngineConfigLostError:+ await self._restart_lost_engine()+ return await asyncio.to_thread(call)++ async def _engine_call(self, call: Callable[[], _T]) -> _T:+ """Run a supervisor call that may start the engine, restoring one that lost its configuration."""+ try:+ return await asyncio.to_thread(call)+ except EngineConfigLostError:+ async with self._routing_lock:+ await self._restart_lost_engine()+ return await asyncio.to_thread(call)+async def provision_credential(self,vendor: str,@@ -2237,7 +2278,7 @@ class CLIProxyEngineAdapter:if metadata.get("vendor") != normalized_vendor or base_url is not None:raise EngineStateError("credential does not match discovery target")if start_engine:- client = await asyncio.to_thread(self.supervisor.client)+ client = await self._engine_call(self.supervisor.client)else:client = await run_owned_in_thread(self.supervisor.client_if_running)if client is None:@@ -2334,7 +2375,7 @@ class CLIProxyEngineAdapter:elif credential_kind == "oauth":if normalized_base_url is not None:raise EngineStateError("credential does not match observation target")- client = await asyncio.to_thread(self.supervisor.client)+ client = await self._engine_call(self.supervisor.client)inventory = await asyncio.to_thread(_auth_inventory, client)auth_name = str(metadata.get("auth_name") or "")matches = [auth for auth in inventory.values() if auth.name == auth_name or auth.identity == auth_name]@@ -2601,7 +2642,7 @@ class CLIProxyEngineAdapter:raise EngineStateError("an OAuth flow for this provider is already active")self._active_oauth_providers.add(auth_provider)try:- client = await asyncio.to_thread(self.supervisor.client)+ client = await self._engine_call(self.supervisor.client)before = await asyncio.to_thread(_auth_inventory, client)payload = await asyncio.to_thread(client.management_request,@@ -2704,7 +2745,7 @@ class CLIProxyEngineAdapter:if flow.state in {"success", "failed", "cancelled"}:return flow.snapshot()try:- client = await asyncio.to_thread(self.supervisor.client)+ client = await self._engine_call(self.supervisor.client)payload = await asyncio.to_thread(client.management_request,"GET",@@ -2773,7 +2814,7 @@ class CLIProxyEngineAdapter:else:payload["code"] = submittedtry:- client = await asyncio.to_thread(self.supervisor.client)+ client = await self._engine_call(self.supervisor.client)await asyncio.to_thread(client.management_request,"POST",@@ -2793,7 +2834,7 @@ class CLIProxyEngineAdapter:if flow.state in {"success", "failed", "cancelled"}:returntry:- client = await asyncio.to_thread(self.supervisor.client)+ client = await self._engine_call(self.supervisor.client)await asyncio.to_thread(client.management_request,"DELETE",@@ -2823,7 +2864,7 @@ class CLIProxyEngineAdapter:if source.allowed_origins and origin not in source.allowed_origins:raise OriginNotAllowedError(f"origin {origin!r} is not allowed to use source {source_id!r}")try:- client = await asyncio.to_thread(self.supervisor.client)+ client = await self._locked_engine_call(self.supervisor.client)except EngineUnavailableError as exc:return completed_handle(RawCallOutcome(diff --git a/vibe/model_hub_runtime/supervisor.py b/vibe/model_hub_runtime/supervisor.pyindex c3aaa80f8..012445de9 100644--- a/vibe/model_hub_runtime/supervisor.py+++ b/vibe/model_hub_runtime/supervisor.py@@ -53,8 +53,11 @@ MODEL_HUB_CONFIG_RELOAD_TIMEOUT_SECONDS = 5.0# call checks only that the process is alive. The full check (two management# round trips, tens of milliseconds, which a request holds the adapter's routing# lock across) runs at start and once this expires. A failed one is not-# remembered: every call checks again, and a request restarts the engine.+# remembered: every call checks again, and a request restarts the engine, unless+# the engine refused Avibe's credentials (``EngineConfigLostError``).MODEL_HUB_HEALTH_TTL_SECONDS = 30.0+# What an engine-local endpoint answers a credential it does not hold.+_CREDENTIALS_REFUSED_STATUSES = frozenset({401, 403})_STARTUP_POLL_INTERVAL_SECONDS = 0.05# Durable identity of the engine this state root last spawned. A service that# dies without running ``atexit`` (SIGKILL, crash, forced restart) leaves its@@ -82,6 +85,20 @@ class EngineUnavailableError(RuntimeError):self.direct_mode_available = True+class EngineConfigLostError(EngineUnavailableError):+ """The running engine refuses the credentials Avibe launched it with.++ Its gateway key and management secret come only from the config Avibe+ rendered, so an engine-local endpoint refusing them proves it no longer runs+ that config. That is a broken invariant, not a transient failure: the owner+ of admissions restores it by admitting no new work, letting the streams the+ engine still serves end, and then calling ``restart_lost_engine``.+ """++ def __init__(self) -> None:+ super().__init__("models.engine.health_failed", reason="engine_config_lost")++class EngineSupervisor:"""Start-on-demand supervisor for one loopback-only Model Hub engine."""@@ -110,15 +127,51 @@ class EngineSupervisor:self._verified_at: float | None = Noneself._record_os_errno: int | None = Noneself._config_generation = 0+ self._config_loss_reported = Falsedef ensure_running(self) -> EngineConnection:with self._lock:- if self._is_running_locked() and self._healthy_locked():- assert self._connection is not None- return self._connection+ if self._is_running_locked():+ if self._healthy_locked():+ assert self._connection is not None+ return self._connection+ failure = self._health_failure_signature+ if failure is not None and failure[1] == "http_error" and failure[2] in _CREDENTIALS_REFUSED_STATUSES:+ # Stopping it here would cut the streams it still serves.+ raise self._config_lost_locked(failure[0], failure[2])self._stop_locked()return self._start_locked()+ def restart_lost_engine(self) -> None:+ """Restart an engine that lost its configuration, from the config Avibe renders.++ The caller has drained it: no new work is admitted and its streams have+ ended. The engine is checked again first, so a second caller that waited+ out the same drain finds it answering and leaves it. A restart whose+ engine still refuses the credentials fails its start like any other, and+ is not retried here.+ """+ with self._lock:+ if not self._is_running_locked() or self._connection is None:+ return+ if self._check_health_locked(EngineClient(self._connection, timeout=1.0)):+ self._verified_at = time.monotonic()+ return+ self._stop_locked()+ self._start_locked()++ def _config_lost_locked(self, endpoint: str, http_status: int) -> EngineConfigLostError:+ # Nothing it answered vouches for it any more, so the next call checks it.+ self._verified_at = None+ if not self._config_loss_reported:+ self._config_loss_reported = True+ assert self._connection is not None+ logger.warning(+ "Model Hub engine lost its configuration endpoint=%s http_status=%s port=%s",+ endpoint, http_status, self._connection.base_url.rsplit(":", 1)[1],+ )+ return EngineConfigLostError()+def stop(self) -> None:"""Shutdown stop: an unconfirmed survivor stays recorded for the next start."""with self._lock:@@ -189,6 +242,8 @@ class EngineSupervisor:try:client.put_config_yaml(text)except EngineClientError as exc:+ if exc.status_code in _CREDENTIALS_REFUSED_STATUSES:+ raise self._config_lost_locked("/v0/management/config.yaml", exc.status_code) from excif exc.status_code is not None:raise EngineUnavailableError("models.engine.health_failed") from excif not self._is_running_locked():@@ -253,6 +308,9 @@ class EngineSupervisor:try:listed = client.list_model_names(timeout=1.0)except EngineClientError as exc:+ if exc.status_code in _CREDENTIALS_REFUSED_STATUSES:+ # The applied file was not the one written: waiting cannot help.+ raise self._config_lost_locked("/v1/models", exc.status_code) from exclisted = Noneos_errno = local_os_errno(exc)if (@@ -544,6 +602,7 @@ class EngineSupervisor:self._verified_at = Noneself._health_failure_signature = Noneself._health_os_errno = None+ self._config_loss_reported = Falseif process is not None and process.poll() is None:signal_process_tree(process, signal.SIGTERM, logger, "Model Hub engine")try: