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.

fix(model-hub): discard unreadable engine state and re-derive it (#1869)

Call Whitebfe4216d9dea
diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.py
index d922682ed..49a094166 100644
--- a/tests/test_model_hub_runtime.py
+++ b/tests/test_model_hub_runtime.py
@@ -1668,6 +1668,109 @@ def test_source_record_requires_valid_reasoning_state() -> None:
SourceRecord.from_payload(payload)
+ ("persisted", "expected_reason"),
+ [
+ pytest.param(
+ json.dumps(
+ {
+ "sources": [
+ {
+ "source_id": "src_fixture123",
+ "vendor": "custom",
+ "protocol": "openai_chat",
+ "base_url": "https://api.example.test/v1",
+ "credential_ref": "cred_fixture123",
+ "allowed_origins": [],
+ "model_ids": ["model-a"],
+ "prefix": "avibe-fixture",
+ }
+ ]
+ }
+ ),
+ "invalid engine source reasoning state",
+ id="missing-reasoning-state",
+ ),
+ pytest.param(
+ "{not-json",
+ "invalid engine state file: sources.json",
+ id="corrupt-json",
+ ),
+ ],
+)
+def test_unreadable_source_state_is_discarded_rebuilt_and_reaches_ready(
+ tmp_path: Path,
+ caplog: pytest.LogCaptureFixture,
+ persisted: str,
+ expected_reason: str,
+) -> None:
+ supervisor, store = _fixture_supervisor(tmp_path)
+ credential_ref = store.store_api_key(
+ "upstream-secret",
+ base_url="https://api.example.test/v1",
+ )
+ sources_path = store.root / "sources.json"
+ sources_path.write_text(persisted, encoding="utf-8")
+
+ with pytest.raises(EngineStateError):
+ store.revoke_credential(credential_ref)
+ assert store.credential_metadata(credential_ref)["value"] == "upstream-secret"
+ assert sources_path.read_text(encoding="utf-8") == persisted
+ assert not sources_path.with_name("sources.json.invalid").exists()
+
+ async def sync_and_start() -> None:
+ adapter = CLIProxyEngineAdapter(supervisor=supervisor, state_store=store)
+ await adapter.sync_sources([_binding(credential_ref)])
+ try:
+ status = await adapter.start()
+ assert status.health is EngineHealth.OK
+ finally:
+ await adapter.stop()
+
+ with caplog.at_level(logging.WARNING, logger="vibe.model_hub_runtime.state"):
+ asyncio.run(sync_and_start())
+
+ warnings = [
+ record
+ for record in caplog.records
+ if record.name == "vibe.model_hub_runtime.state"
+ and record.levelno == logging.WARNING
+ ]
+ assert [record.getMessage() for record in warnings] == [
+ f"Discarded invalid engine state file sources.json: {expected_reason}"
+ ]
+ assert sources_path.with_name("sources.json.invalid").read_text(encoding="utf-8") == persisted
+ rebuilt = json.loads(sources_path.read_text(encoding="utf-8"))
+ assert rebuilt["sources"][0]["model_reasoning_efforts"] == []
+
+def test_valid_source_state_is_loaded_without_touching_the_file(
+ tmp_path: Path,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ store = EngineStateStore(tmp_path / "state")
+ credential_ref = store.store_api_key(
+ "upstream-secret",
+ base_url="https://api.example.test/v1",
+ )
+ expected = store.sync_sources([_binding(credential_ref)])
+ sources_path = store.root / "sources.json"
+ persisted = sources_path.read_bytes()
+ persisted_mtime = sources_path.stat().st_mtime_ns
+
+ with caplog.at_level(logging.WARNING, logger="vibe.model_hub_runtime.state"):
+ assert store.list_sources() == expected
+
+ assert sources_path.read_bytes() == persisted
+ assert sources_path.stat().st_mtime_ns == persisted_mtime
+ assert not sources_path.with_name("sources.json.invalid").exists()
+ assert not [
+ record
+ for record in caplog.records
+ if record.name == "vibe.model_hub_runtime.state"
+ and record.levelno == logging.WARNING
+ ]
+
+
@pytest.mark.parametrize(
("vendor", "expected_base_url"),
[
diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.py
index 4f4490e26..e90b81db0 100644
--- a/vibe/model_hub_runtime/adapter.py
+++ b/vibe/model_hub_runtime/adapter.py
@@ -1326,7 +1326,10 @@ class CLIProxyEngineAdapter:
async def sync_sources(self, bindings: Sequence[SourceBinding]) -> None:
async with self._routing_lock:
- previous = await asyncio.to_thread(self.state_store.list_sources)
+ try:
+ previous = await asyncio.to_thread(self.state_store.list_sources)
+ except EngineStateError:
+ previous = []
was_running = await asyncio.to_thread(self.supervisor.client_if_running) is not None
await asyncio.to_thread(self.state_store.sync_sources, bindings)
try:
diff --git a/vibe/model_hub_runtime/state.py b/vibe/model_hub_runtime/state.py
index 8870ecb3f..21fa639ed 100644
--- a/vibe/model_hub_runtime/state.py
+++ b/vibe/model_hub_runtime/state.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import json
+import logging
import re
import secrets
import shutil
@@ -15,6 +16,8 @@ from config.v2_config import normalize_model_hub_base_url
from vibe.model_hub_runtime.api_key_vendors import pinned_api_key_protocol
+logger = logging.getLogger(__name__)
+
_CREDENTIAL_REF_RE = re.compile(r"^cred_[A-Za-z0-9_-]{6,128}$")
_SOURCE_ID_RE = re.compile(r"^src_[a-z0-9]{8,}$")
_PROTOCOLS = {"anthropic", "openai_responses", "openai_chat"}
@@ -120,11 +123,18 @@ class EngineStateStore:
def list_sources(self) -> list[SourceRecord]:
with self._lock:
- payload = self._read_json(self.root / "sources.json") or {}
- raw_sources = payload.get("sources", [])
- if not isinstance(raw_sources, list):
- raise EngineStateError("invalid engine source state")
- return [SourceRecord.from_payload(item) for item in raw_sources if isinstance(item, dict)]
+ try:
+ payload = self._read_json(self.root / "sources.json") or {}
+ raw_sources = payload.get("sources", [])
+ if not isinstance(raw_sources, list):
+ raise EngineStateError("invalid engine source state")
+ return [
+ SourceRecord.from_payload(item)
+ for item in raw_sources
+ if isinstance(item, dict)
+ ]
+ except (KeyError, TypeError, ValueError) as exc:
+ raise EngineStateError(f"invalid engine source state: {exc}") from exc
def get_source(self, source_id: str) -> SourceRecord | None:
return next((source for source in self.list_sources() if source.source_id == source_id), None)
@@ -198,7 +208,12 @@ class EngineStateStore:
def sync_sources(self, bindings: Sequence[Any]) -> list[SourceRecord]:
"""Atomically replace the engine projection using opaque credential refs."""
with self._lock:
- existing = {source.source_id: source for source in self.list_sources()}
+ path = self.root / "sources.json"
+ try:
+ existing = {source.source_id: source for source in self.list_sources()}
+ except EngineStateError as exc:
+ self._discard_invalid_state_file(path, exc)
+ existing = {}
records: list[SourceRecord] = []
seen: set[str] = set()
for binding in bindings:
@@ -501,6 +516,19 @@ class EngineStateStore:
raise EngineStateError("engine instance directory is unsafe")
shutil.rmtree(instance_dir)
+ @staticmethod
+ def _discard_invalid_state_file(path: Path, error: EngineStateError) -> None:
+ invalid_path = path.with_name(f"{path.name}.invalid")
+ try:
+ path.replace(invalid_path)
+ except FileNotFoundError:
+ pass
+ except OSError as exc:
+ raise EngineStateError(
+ f"unable to discard invalid engine state file: {path.name}"
+ ) from exc
+ logger.warning("Discarded invalid engine state file %s: %s", path.name, error)
+
@staticmethod
def _read_json(path: Path) -> dict[str, Any] | None:
try: