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): save config off the controller loop (#2648)
Call White5965e91137c5
diff --git a/core/handlers/model_hub/migration.py b/core/handlers/model_hub/migration.pyindex 68dd1120b..62df10289 100644--- a/core/handlers/model_hub/migration.py+++ b/core/handlers/model_hub/migration.py@@ -138,7 +138,7 @@ class MigrationHost(Protocol):async def _ensure_runtime_dependency(self) -> Any: ...- def _save_config(self, config: ModelHubConfig) -> ModelHubConfig: ...+ async def _save_config(self, config: ModelHubConfig) -> ModelHubConfig: ...async def _seed_vibey(self, config: ModelHubConfig, *, fetch_catalog: bool = True) -> bool: ...@@ -1959,7 +1959,7 @@ async def _revert_takeover(host: MigrationHost, record: dict[str, Any]) -> None:if current.to_payload() not in (previous.to_payload(), updated.to_payload()):raise MigrationConflictErrorif current.to_payload() == updated.to_payload():- host._save_config(previous)+ await host._save_config(previous)host._engine_synced = Falsefor raw in reversed(record["files"]):edit = NativeFileEdit.from_payload(raw)@@ -2069,7 +2069,7 @@ async def _resume_takeover(await _verify_clean_native_stores(host, record)# Save the decision without projecting staged grants into CPA.# sync_sources is a runtime write, not a config-only operation.- host._save_config(updated)+ await host._save_config(updated)if previous.vibey_supply_pending and not updated.vibey_supply_pending:await host._announce_vibey_seed()host._engine_synced = False@@ -2113,7 +2113,7 @@ async def _resume_takeover(if terminal:# Every terminal path binds kept keys before its receipt.await _record_retained_store_revisions(host, record)- return _finish_rejected_takeover(host, record)+ return await _finish_rejected_takeover(host, record)for credential in record["credentials"]:if credential["kind"] == "oauth":await host._engine_call(host.adapter.activate_oauth_credential(credential["credential_ref"]))@@ -2162,7 +2162,7 @@ async def _resume_takeover("config": terminal_config.to_payload(),}host.migration_journal.save(record)- return _finish_rejected_takeover(host, record)+ return await _finish_rejected_takeover(host, record)host._reconcile_native_auth(tuple(record["backends"]))await _record_retained_store_revisions(host, record)host.migration_journal.complete(record)@@ -2176,10 +2176,10 @@ async def _resume_takeover(raise-def _finish_rejected_takeover(+async def _finish_rejected_takeover(host: MigrationHost, record: dict[str, Any],) -> tuple[int, list[dict]]:- host._save_config(ModelHubConfig.from_payload(record["terminal"]["config"]))+ await host._save_config(ModelHubConfig.from_payload(record["terminal"]["config"]))host._reconcile_native_auth(tuple(record["backends"]))host.migration_journal.complete(record)host.migration_blocked_backends.difference_update(record["backends"])diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 7d7d046f2..04c1180e7 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -95,7 +95,7 @@ from .address_repair import (payload_carries_credential_address,repair_credential_addresses,)-from .async_owner import await_owned_task+from .async_owner import await_owned_task, run_owned_in_threadfrom .catalog_admission import (admissible_backend_model,backend_model_admission_error,@@ -1647,8 +1647,43 @@ class ModelHubService:if self.migration_reconcile_auth is not None:self.migration_reconcile_auth(snapshot)- def _save_config(self, config: ModelHubConfig) -> ModelHubConfig:- canonical = ModelHubConfig.from_payload(config.to_payload())+ async def _save_config(self, config: ModelHubConfig) -> ModelHubConfig:+ """Persist the Model Hub section; the one door every config write goes through.++ The file work (the migration journal check, the cross-process config+ lock, the rewrite of the whole config file) runs on a worker thread, so+ the controller loop never waits on another process's lock or a slow+ disk. Callers hold ``_mutation_lock`` from the load they changed to this+ save, so writes stay serialized. The recovery reconcile and its waiters'+ wake-up are loop state and stay on the loop.+ """++ worker = asyncio.create_task(asyncio.to_thread(self._persist_config, config.to_payload()))+ try:+ canonical = await asyncio.shield(worker)+ except asyncio.CancelledError as cancelled:+ # The write is underway in its thread and will land. Hold the caller, and the mutation lock it holds,+ # until it has, and publish it: otherwise a later write could start from the older snapshot and be+ # overwritten when this one finishes.+ try:+ canonical = await await_owned_task(worker)+ except BaseException:+ raise cancelled from None+ self._publish_saved(canonical)+ raise cancelled+ return self._publish_saved(canonical)++ def _publish_saved(self, canonical: ModelHubConfig) -> ModelHubConfig:+ """The loop-side half of a save: recovery follows the saved Sources and its waiters wake."""++ self.recovery.reconcile(canonical)+ self.recovery.notify()+ return canonical++ def _persist_config(self, payload: dict) -> ModelHubConfig:+ """``_save_config``'s blocking half, run off the loop: canonicalize and write."""++ canonical = ModelHubConfig.from_payload(payload)try:pending = self.migration_journal.load()except (TakeoverStateError, OSError):@@ -1675,11 +1710,9 @@ class ModelHubService:)else:self.store.save(canonical)- self.recovery.reconcile(canonical)- self.recovery.notify()return canonical- def _save_projection_neutral(+ async def _save_projection_neutral(self,previous: ModelHubConfig,updated: ModelHubConfig,@@ -1688,9 +1721,21 @@ class ModelHubService:if self._bindings(previous) != self._bindings(updated):raise AssertionError("projection-neutral mutation changed engine bindings")- return self._save_config(updated)+ return await self._save_config(updated)++ def _save_projection_neutral_blocking(self, previous: ModelHubConfig, updated: ModelHubConfig) -> ModelHubConfig:+ """``_save_projection_neutral`` for a synchronous hook; it blocks the loop for the write.++ Only native reauth's irreversible-start hook uses it: that hook's contract (``AgentAuthService``'s+ ``on_irreversible_start``) is synchronous, and it writes once per user-started reauth. Everything else+ saves through ``_save_config``.+ """++ if self._bindings(previous) != self._bindings(updated):+ raise AssertionError("projection-neutral mutation changed engine bindings")+ return self._publish_saved(self._persist_config(updated.to_payload()))- def _save_runtime_config(+ async def _save_runtime_config(self,previous: ModelHubConfig,updated: ModelHubConfig,@@ -1698,7 +1743,7 @@ class ModelHubService:"""Best-effort persistence for runtime state during config recovery."""try:- self._save_projection_neutral(previous, updated)+ await self._save_projection_neutral(previous, updated)except ValueError as exc:if "recovery warnings" not in str(exc):raise@@ -1885,10 +1930,10 @@ class ModelHubService:# Route target order is not part of this projection, so a pure chain reorder# compares equal and does not touch the engine.if previous_bindings == updated_bindings:- self._save_config(updated)+ await self._save_config(updated)returnself._engine_synced = False- self._save_config(updated)+ await self._save_config(updated)try:await self._sync_sources(updated, force_empty=bool(previous_bindings))except asyncio.CancelledError:@@ -1899,7 +1944,7 @@ class ModelHubService:except Exception:if not rollback_on_sync_failure:raise- self._save_config(previous)+ await self._save_config(previous)try:await self._sync_sources(previous, force_empty=bool(updated_bindings))except ModelHubError:@@ -4606,7 +4651,7 @@ class ModelHubService:except ModelHubError:restored = Falsetry:- self._save_config(previous)+ await self._save_config(previous)restored = Trueself._engine_synced = Falseawait self._sync_sources(previous)@@ -8009,7 +8054,7 @@ class ModelHubService:)return "models.source.error.unclassified", "unclassified_error"- def _write_source_blocker_locked(+ async def _write_source_blocker_locked(self,config: ModelHubConfig,source: ModelHubSourceConfig,@@ -8036,7 +8081,7 @@ class ModelHubService:status=status,detail_key=detail_key,)- persisted = self._save_runtime_config(previous, config)+ persisted = await self._save_runtime_config(previous, config)if persisted:# A blocked grant must not keep reporting the windows it had while usable.self.quota.forget(source.id)@@ -8412,10 +8457,10 @@ class ModelHubService:status="needs_action",detail_key="models.source.needs_action.oauth_expired",)- self._save_projection_neutral(previous, config)+ self._save_projection_neutral_blocking(previous, config)def restore_after_spawn_failure() -> None:- self._save_projection_neutral(config, previous)+ self._save_projection_neutral_blocking(config, previous)return restore_after_spawn_failure@@ -8812,7 +8857,7 @@ class ModelHubService:updated = self._clone_config(previous)updated.enabled = Trueupdated.runtime_default_applied = True- self._save_projection_neutral(previous, updated)+ await self._save_projection_neutral(previous, updated)# A start renders the persisted projection, whose text-only# marks come from the catalog copy of its last sync. Syncing# here gives an explicit start the current copy's marks.@@ -8847,7 +8892,7 @@ class ModelHubService:updated = self._clone_config(previous)updated.enabled = Falseupdated.runtime_default_applied = True- self._save_projection_neutral(previous, updated)+ await self._save_projection_neutral(previous, updated)return _runtime_payload(status, enabled=False)def migration_scan(self) -> dict:@@ -8965,7 +9010,7 @@ class ModelHubService:previous = self._clone_config(config)source.state = ModelHubSourceStateConfig(status="standby")try:- self._save_runtime_config(previous, config)+ await self._save_runtime_config(previous, config)except OSError:# Inference is authoritative; the policy remembers exactly# which stale persisted cooldown must not be imported again.@@ -8983,7 +9028,7 @@ class ModelHubService:# actual streaming output is read separately from the handle observer.return outcome.kind is RawOutcomeKind.SUCCESS and outcome.recovery_verified- def _write_cooldown_locked(+ async def _write_cooldown_locked(self,config: ModelHubConfig,source: ModelHubSourceConfig,@@ -9010,7 +9055,7 @@ class ModelHubService:detail_key=detail_key or f"models.source.cooldown.{decision.reason}",)try:- persisted = self._save_runtime_config(previous, config)+ persisted = await self._save_runtime_config(previous, config)except OSError:# HTTP recovery already owns the live deadline. Failed telemetry# cannot replace the upstream result or erase temporary eligibility.@@ -9099,7 +9144,7 @@ class ModelHubService:from_label=current.display_name, now=self.now(),)return event_reason, False- persisted = self._write_cooldown_locked(+ persisted = await self._write_cooldown_locked(config,current,decision,@@ -9117,7 +9162,7 @@ class ModelHubService:"account_banned": "models.source.needs_action.account_banned","unclassified_error": "models.source.error.unclassified",}[event_reason]- persisted = self._write_source_blocker_locked(+ persisted = await self._write_source_blocker_locked(config,current,backend=backend,@@ -9309,7 +9354,8 @@ class ModelHubService:try:async with self._mutation_lock:- self.store.mutate(clear_current)+ # Held under the mutation lock until the write lands, even if the caller is cancelled.+ await run_owned_in_thread(self.store.mutate, clear_current)returnexcept ValueError as exc:if "recovery warnings" not in str(exc):diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex 731b58dfa..7f7b696e6 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -10727,3 +10727,57 @@ def test_quota_endpoints_serve_hub_subscriptions_and_rate_limit_forced_refresh(m_assert_valid("quota-summary.schema.json", refreshed.get_json()["quota"])# Inside the forced-refresh interval the cached snapshot answers.assert len(calls) == 2+++async def test_a_config_save_never_holds_the_controller_loop(tmp_path):+ """A save waits on the cross-process config lock and a full config rewrite (#2639); the controller loop runs+ every session's turns and the gateway, so it keeps running while a save is held."""+ import threading++ service, store, _adapter = _service(tmp_path)+ entered, release = threading.Event(), threading.Event()+ released_in_time = []+ save = store.save++ def held_save(config):+ entered.set()+ # Another process holds the config lock until the loop, still free, lets it go.+ released_in_time.append(release.wait(2))+ save(config)++ store.save = held_save+ writing = asyncio.create_task(service.set_hosted_tool("web_search", {"enabled": False}))+ assert await asyncio.to_thread(entered.wait, 5)+ release.set()+ await writing+ assert released_in_time == [True]+ assert store.config.hosted_tools["web_search"].enabled is False+++async def test_a_cancelled_save_holds_the_mutation_lock_until_its_write_lands(tmp_path):+ """The write runs on in its thread after the caller is cancelled; releasing the lock early would let a later+ write start from the older snapshot and be overwritten when this one lands."""+ import threading++ service, store, _adapter = _service(tmp_path)+ entered, release = threading.Event(), threading.Event()+ save = store.save++ def held_save(config):+ entered.set()+ assert release.wait(5)+ save(config)++ store.save = held_save+ writing = asyncio.create_task(service.set_hosted_tool("web_search", {"enabled": False}))+ assert await asyncio.to_thread(entered.wait, 5)+ writing.cancel()+ await asyncio.sleep(0.05)+ assert service._mutation_lock.locked()+ release.set()+ with pytest.raises(asyncio.CancelledError):+ await writing+ assert not service._mutation_lock.locked()+ assert store.config.hosted_tools["web_search"].enabled is Falsediff --git a/tests/test_model_hub_native_takeover.py b/tests/test_model_hub_native_takeover.pyindex 548355d54..609321875 100644--- a/tests/test_model_hub_native_takeover.py+++ b/tests/test_model_hub_native_takeover.py@@ -517,7 +517,7 @@ def test_rejected_refresh_finishes_custody_without_claiming_success(monkeypatch,assert repeated.value.code == "migration_credentials_invalid"assert len(adapter.validated) == 2# Normal Hub config/auth repair is not trapped behind the migration gate.- service._save_config(service._clone_config(store.config))+ asyncio.run(service._save_config(service._clone_config(store.config)))@pytest.mark.parametrize("crash_before_receipt", [False, True])