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.

feat(model-hub): refresh Source model inventories in the background (#2398)

Call Whited328a1de5c51
diff --git a/core/controller.py b/core/controller.py
index e55b98b47..f76021167 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -1156,6 +1156,21 @@ class Controller:
e,
exc_info=True,
)
+ try:
+ # The service's own `stop()` retires the schedule at shutdown.
+ start_discovery = getattr(
+ getattr(self, "model_hub_service", None),
+ "start_background_discovery",
+ None,
+ )
+ if callable(start_discovery):
+ start_discovery()
+ except Exception as e:
+ logger.error(
+ "Failed to start Model Hub background discovery: %s",
+ e,
+ exc_info=True,
+ )
try:
if self.cleanup_task is None or self.cleanup_task.done():
diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.py
index de36f6b43..da85930d1 100644
--- a/core/handlers/model_hub/adapter.py
+++ b/core/handlers/model_hub/adapter.py
@@ -682,8 +682,14 @@ class EngineAdapter(Protocol):
protocol: str,
base_url: str | None,
credential_ref: str,
+ *,
+ start_engine: bool = True,
) -> Sequence[DiscoveredModel]:
- """Refresh supplyable models for a saved Source using its stored protocol."""
+ """Refresh supplyable models for a saved Source using its stored protocol.
+
+ With ``start_engine=False`` an engine-held credential is listed only
+ from an engine that is already running; it is never started for this.
+ """
...
async def observe_source(
diff --git a/core/handlers/model_hub/rpc.py b/core/handlers/model_hub/rpc.py
index e8a298f14..94ad72d6d 100644
--- a/core/handlers/model_hub/rpc.py
+++ b/core/handlers/model_hub/rpc.py
@@ -76,6 +76,7 @@ async def dispatch_model_hub_rpc(
payload: dict[str, Any],
) -> Any:
if operation == "list_sources":
+ service.request_inventory_refresh()
return service.list_sources()
if operation == "observe_source":
return await service.observe_source(payload.get("observation"))
@@ -120,6 +121,7 @@ async def dispatch_model_hub_rpc(
backend,
)
if operation == "agent_model_candidates":
+ service.request_inventory_refresh()
backend = payload.get("backend")
if backend in ("claude", "codex", "opencode"):
await _refresh_agent_presence(service, (backend,))
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 79c42b15f..7e24b095d 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -276,6 +276,21 @@ AGENT_CHAIN_CONTRACT_VERSION = 10
PROBE_RESULT_CONTRACT_VERSION = 10
_SOURCE_DISCOVERY_TIMEOUT_SECONDS = 15
_SOURCE_PROBE_TIMEOUT_SECONDS = 60
+# Background inventory refresh. The first tick doubles as the startup delay, so
+# a stale Source catches up shortly after boot without boot waiting on upstream.
+_BACKGROUND_DISCOVERY_INTERVAL = timedelta(hours=6)
+_BACKGROUND_DISCOVERY_JITTER = 0.2
+_BACKGROUND_DISCOVERY_TICK = timedelta(minutes=5)
+_BACKGROUND_DISCOVERY_RETRY_BASE = timedelta(minutes=15)
+_BACKGROUND_DISCOVERY_RETRY_CAP = timedelta(hours=6)
+# A viewer of Source inventory asks for listings at most this old.
+_VIEWED_DISCOVERY_AGE = timedelta(minutes=30)
+# A credential waiting on the user cannot list models until the user acts.
+_UNDISCOVERABLE_SOURCE_DETAILS = frozenset({
+ "models.source.needs_action.oauth_expired",
+ "models.source.needs_action.credential_revoked",
+ "models.source.needs_action.account_banned",
+})
_REORDER_ORDER_UNSET = object()
# Settlement generations are minted per attempt start and live only in this
# runtime's ledger, which restarts with the process. Every generation this
@@ -568,7 +583,15 @@ class UnavailableEngineAdapter:
async def sync_sources(self, bindings) -> None:
raise EngineUnavailableError
- async def discover_models(self, vendor: str, protocol: str, base_url: str | None, credential_ref: str):
+ async def discover_models(
+ self,
+ vendor: str,
+ protocol: str,
+ base_url: str | None,
+ credential_ref: str,
+ *,
+ start_engine: bool = True,
+ ):
raise EngineUnavailableError
async def observe_source(
@@ -653,6 +676,26 @@ AttemptObserver = Callable[
]
+@dataclass(frozen=True)
+class _DiscoveryRetry:
+ identity: tuple
+ failed_at: datetime
+ delay: timedelta
+
+
+def _background_discovery_period(source_id: str) -> timedelta:
+ """A stable per-Source period within the jitter window around the interval.
+
+ Sources listed together then drift apart instead of refreshing in lockstep,
+ and a restart keeps each Source's phase.
+ """
+
+ fraction = int.from_bytes(hashlib.sha256(source_id.encode()).digest()[:8], "big") / 2**64
+ return _BACKGROUND_DISCOVERY_INTERVAL * (
+ 1 - _BACKGROUND_DISCOVERY_JITTER + 2 * _BACKGROUND_DISCOVERY_JITTER * fraction
+ )
+
+
def _same_json_value(left: object, right: object) -> bool:
try:
options = {
@@ -1089,6 +1132,15 @@ class ModelHubService:
self._runtime_install_reconciled = False
self._runtime_lifecycle_lock = asyncio.Lock()
self._runtime_resume_task: asyncio.Task[None] | None = None
+ self._background_discovery_task: asyncio.Task[None] | None = None
+ self._background_discovery_stop: asyncio.Event | None = None
+ # Process-local schedule state: an unchanged listing persists nothing,
+ # and a restart rediscovers stale Sources one tick after startup.
+ self._background_discovery_checked: dict[str, datetime] = {}
+ self._background_discovery_retries: dict[str, _DiscoveryRetry] = {}
+ self._background_discovery_caught_up = False
+ self._background_discovery_inflight: set[str] = set()
+ self._viewed_discovery_task: asyncio.Task[None] | None = None
self._builtin_snapshot_generations: dict[BackendName, str] = {}
self._builtin_snapshot_cache: dict[BackendName, list[dict[str, Any]]] = {}
self._pending_builtin_catalog_refresh: set[BackendName] = set()
@@ -1765,6 +1817,18 @@ class ModelHubService:
# that cancellation cannot stop, and the adapter must not stop
# beneath it. A retired resume never starts the engine.
await await_owned_task(resume)
+ discovery, self._background_discovery_task = self._background_discovery_task, None
+ viewed, self._viewed_discovery_task = self._viewed_discovery_task, None
+ if self._background_discovery_stop is not None:
+ self._background_discovery_stop.set()
+ # Background listings never start the engine, and an upstream listing
+ # is cancelled outright. An engine listing's worker is owned and
+ # bounded, so these return only once nothing still uses the engine
+ # that `adapter.stop()` retires.
+ retiring = [task for task in (discovery, viewed) if task is not None and not task.done()]
+ for task in retiring:
+ task.cancel()
+ await asyncio.gather(*retiring, return_exceptions=True)
async with self._runtime_lifecycle_lock:
await self.adapter.stop()
@@ -1877,7 +1941,12 @@ class ModelHubService:
return False
return True
- async def _discover(self, source: ModelHubSourceConfig) -> list[DiscoveredModel]:
+ async def _discover(
+ self,
+ source: ModelHubSourceConfig,
+ *,
+ start_engine: bool = True,
+ ) -> list[DiscoveredModel]:
if not source.credential_ref:
return [
DiscoveredModel(id=model.id)
@@ -1891,6 +1960,7 @@ class ModelHubService:
source.protocol,
source.base_url,
source.credential_ref,
+ start_engine=start_engine,
)
)
)
@@ -4111,21 +4181,13 @@ class ModelHubService:
if normalized_model_hub_override(route) is None:
agent.routes.pop(menu_model)
- def _guard_inventory_mutation(
+ def _inventory_removed_hops(
self,
previous: ModelHubConfig,
updated: ModelHubConfig,
- source_id: str,
- *,
- force: bool,
- confirmed_remove_hops: object,
- confirmed_interruptions: object,
- ) -> tuple[list[dict], list[dict]]:
- invalidated = self._invalidated_route_hops(updated, source_id)
- self._prune_invalidated_route_hops(updated, invalidated)
+ ) -> list[dict]:
# Inventory evidence narrows speculative candidates without deleting routes.
- # Keep explicit invalidations and newly introduced supply gaps guarded below.
- would_remove_hops = [
+ return [
item for item in self._removed_effective_hops(previous, updated)
if not (
effective_model_route(
@@ -4136,6 +4198,21 @@ class ModelHubService:
).route_origin == "automatic"
)
]
+
+ def _guard_inventory_mutation(
+ self,
+ previous: ModelHubConfig,
+ updated: ModelHubConfig,
+ source_id: str,
+ *,
+ force: bool,
+ confirmed_remove_hops: object,
+ confirmed_interruptions: object,
+ ) -> tuple[list[dict], list[dict]]:
+ invalidated = self._invalidated_route_hops(updated, source_id)
+ self._prune_invalidated_route_hops(updated, invalidated)
+ # Keep explicit invalidations and newly introduced supply gaps guarded below.
+ would_remove_hops = self._inventory_removed_hops(previous, updated)
would_remove_hops.extend(item for item in invalidated if item not in would_remove_hops)
would_interrupt = self._introduced_interruptions(previous, updated)
self._require_guard_plan(
@@ -4294,6 +4371,262 @@ class ModelHubService:
"interrupted": would_interrupt,
}
+ def start_background_discovery(self) -> None:
+ """Keep Hub Source inventories current until `stop()` retires the schedule."""
+
+ task = self._background_discovery_task
+ if task is not None and not task.done():
+ return
+ stopping = asyncio.Event()
+ self._background_discovery_stop = stopping
+ self._background_discovery_task = asyncio.create_task(
+ self._background_discovery_loop(stopping),
+ name="model-hub-background-discovery",
+ )
+
+ async def _background_discovery_loop(self, stopping: asyncio.Event) -> None:
+ while True:
+ try:
+ await asyncio.wait_for(
+ stopping.wait(), _BACKGROUND_DISCOVERY_TICK.total_seconds(),
+ )
+ return
+ except asyncio.TimeoutError:
+ pass
+ await self._refresh_due_sources_logged()
+
+ async def _refresh_due_sources_logged(self, *, max_age: timedelta | None = None) -> None:
+ try:
+ await self._refresh_due_sources(max_age=max_age)
+ except Exception as exc:
+ logger.warning(
+ "Model Hub background discovery pass failed: %s", type(exc).__name__,
+ )
+
+ def request_inventory_refresh(self) -> None:
+ """A viewer read Source inventory: list Sources older than 30 minutes.
+
+ Fire-and-forget and coalesced into one pass. It runs only while the
+ background schedule does, so it shares that schedule's backoff and
+ shutdown and never starts work for a stopped runtime.
+ """
+
+ schedule = self._background_discovery_task
+ stopping = self._background_discovery_stop
+ if schedule is None or schedule.done() or stopping is None or stopping.is_set():
+ return
+ viewed = self._viewed_discovery_task
+ if viewed is not None and not viewed.done():
+ return
+ self._viewed_discovery_task = asyncio.get_running_loop().create_task(
+ self._refresh_due_sources_logged(max_age=_VIEWED_DISCOVERY_AGE),
+ name="model-hub-viewed-discovery",
+ )
+
+ async def _refresh_due_sources(self, *, max_age: timedelta | None = None) -> None:
+ """Refresh, one at a time, each Hub Source whose background listing is due.
+
+ ``max_age`` tightens the period for a viewer's pass; backoff still holds.
+ """
+
+ config = self.store.load()
+ if not config.enabled:
+ # A stopped runtime is an explicit opt-out, and an OAuth listing
+ # would start the engine.
+ return
+ sources = [
+ source for source in config.sources
+ if self._background_discovery_eligible(source)
+ ]
+ live_ids = {source.id for source in sources}
+ for table in (self._background_discovery_checked, self._background_discovery_retries):
+ for source_id in [item for item in table if item not in live_ids]:
+ del table[source_id]
+ now = self.now()
+ due = sorted(
+ (due_at, source.id)
+ for source in sources
+ if (due_at := self._background_discovery_due(source, now, max_age=max_age)) <= now
+ )
+ if max_age is None:
+ self._background_discovery_caught_up = True
+ for _due_at, source_id in due:
+ stopping = self._background_discovery_stop
+ if stopping is not None and stopping.is_set():
+ return
+ await self._refresh_source_in_background(source_id)
+
+ @staticmethod
+ def _background_discovery_eligible(source: ModelHubSourceConfig) -> bool:
+ # A native CLI keeps its own catalog.
+ return (
+ source.supply_channel == "hub"
+ and bool(source.credential_ref)
+ and source.state.detail_key not in _UNDISCOVERABLE_SOURCE_DETAILS
+ )
+
+ def _background_listed_at(self, source: ModelHubSourceConfig) -> datetime | None:
+ """The latest successful listing, persisted or process-local."""
+
+ listed = [
+ instant for instant in (
+ parse_model_hub_timestamp(source.last_discovered_at)
+ if source.last_discovered_at else None,
+ self._background_discovery_checked.get(source.id),
+ )
+ if instant is not None
+ ]
+ return max(listed, default=None)
+
+ def _background_discovery_retry(self, source: ModelHubSourceConfig) -> _DiscoveryRetry | None:
+ retry = self._background_discovery_retries.get(source.id)
+ if retry is None or retry.identity != source_identity(source):
+ return None
+ listed_at = self._background_listed_at(source)
+ # Any later successful listing, including a manual refresh, resets backoff.
+ return None if listed_at is not None and listed_at > retry.failed_at else retry
+
+ def _background_discovery_due(
+ self,
+ source: ModelHubSourceConfig,
+ now: datetime,
+ *,
+ max_age: timedelta | None = None,
+ ) -> datetime:
+ retry = self._background_discovery_retry(source)
+ if retry is not None:
+ return retry.failed_at + retry.delay
+ listed_at = self._background_listed_at(source)
+ if listed_at is None:
+ return now
+ period = _background_discovery_period(source.id)
+ if not self._background_discovery_caught_up:
+ # The first pass catches up every Source past the nominal interval.
+ period = min(period, _BACKGROUND_DISCOVERY_INTERVAL)
+ if max_age is not None:
+ period = min(period, max_age)
+ return listed_at + period
+
+ async def _refresh_source_in_background(self, source_id: str) -> None:
+ """Add newly listed models without touching health or removing anything.
+
+ A listing is not inference evidence, and removals move supply, so Source
+ state, removals, and their guards stay with a manual `refresh_source`.
+ """
+
+ if source_id in self._background_discovery_inflight:
+ # The schedule and a viewer's pass never list one Source twice at once.
+ return
+ self._background_discovery_inflight.add(source_id)
+ try:
+ await self._refresh_listed_source_in_background(source_id)
+ finally:
+ self._background_discovery_inflight.discard(source_id)
+
+ async def _refresh_listed_source_in_background(self, source_id: str) -> None:
+ config = self.store.load()
+ if not config.enabled:
+ # Re-read per Source: a runtime stopped mid-pass is not listed again.
+ return
+ observed = next(
+ (item for item in config.sources if item.id == source_id),
+ None,
+ )
+ if observed is None or not self._background_discovery_eligible(observed):
+ return
+ basis = (source_identity(observed), observed.last_discovered_at)
+ try:
+ discovered = await asyncio.wait_for(
+ self._discover(observed, start_engine=False),
+ timeout=_SOURCE_DISCOVERY_TIMEOUT_SECONDS,
+ )
+ async with self._mutation_lock:
+ previous = self.store.load()
+ current = next(
+ (item for item in previous.sources if item.id == source_id),
+ None,
+ )
+ if current is None or (
+ source_identity(current), current.last_discovered_at,
+ ) != basis:
+ # The listing describes a Source another owner has changed
+ # since; the next tick lists the current one.
+ return
+ updated = self._clone_config(previous)
+ source = self._source(updated, source_id)
+ overrides = self._merge_discovered_models(source, discovered)
+ if self._inventory_fingerprint(source) != self._inventory_fingerprint(current):
+ if self._inventory_removed_hops(previous, updated) or self._introduced_interruptions(
+ previous, updated,
+ ):
+ logger.info(
+ "Model Hub background discovery left a supply change "
+ "for Source %s to a manual refresh",
+ source_id,
+ )
+ else:
+ await self._commit_synced(previous, updated)
+ self._record_reasoning_tier_overrides(source, overrides)
+ except Exception as exc:
+ self._record_background_discovery_failure(observed, exc)
+ return
+ self._background_discovery_checked[source_id] = self.now()
+
+ def _record_background_discovery_failure(
+ self,
+ source: ModelHubSourceConfig,
+ error: Exception,
+ ) -> None:
+ previous = self._background_discovery_retry(source)
+ delay = (
+ _BACKGROUND_DISCOVERY_RETRY_BASE
+ if previous is None
+ else min(previous.delay * 2, _BACKGROUND_DISCOVERY_RETRY_CAP)
+ )
+ self._background_discovery_retries[source.id] = _DiscoveryRetry(
+ source_identity(source), self.now(), delay,
+ )
+ # Codes and type names only: engine and upstream errors may carry
+ # upstream context.
+ logger.warning(
+ "Model Hub background discovery failed for Source %s (%s); retrying in %d minutes",
+ source.id,
+ error.code if isinstance(error, ModelHubError) else type(error).__name__,
+ delay.total_seconds() // 60,
+ )
+
+ def _merge_discovered_models(
+ self,
+ source: ModelHubSourceConfig,
+ discovered: list[DiscoveredModel],
+ ) -> list[tuple[str, Literal["upstream", "catalog"]]]:
+ """Admit newly listed models and refresh listed metadata; keep every row."""
+
+ existing = list(source.models)
+ manual = [model for model in existing if model.provenance == "manual"]
+ overrides = self._apply_discovered_models(source, manual, discovered, allow_empty=True)
+ listed = {model.id: model for model in source.models}
+ merged = [listed.pop(model.id, model) for model in existing]
+ # Existing rows keep their order, so an upstream that reorders its
+ # listing changes nothing; new rows follow the active discovered slice.
+ insert_at = max(
+ (
+ index + 1 for index, model in enumerate(existing)
+ if model.provenance == "discovered" and not model.retired
+ ),
+ default=0,
+ )
+ source.models = [*merged[:insert_at], *listed.values(), *merged[insert_at:]]
+ return overrides
+
+ @staticmethod
+ def _inventory_fingerprint(source: ModelHubSourceConfig) -> list[dict]:
+ # When a model was last listed is not inventory.
+ return [
+ {key: value for key, value in model.to_payload().items() if key != "discovered_at"}
+ for model in source.models
+ ]
+
@staticmethod
def _eligible_for_agent(source: ModelHubSourceConfig, backend: str) -> bool:
return source_eligible_for_backend(source, backend)
diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.py
index de36f6b43..da85930d1 100644
--- a/docs/plans/model-hub-contracts/adapter-interface.py
+++ b/docs/plans/model-hub-contracts/adapter-interface.py
@@ -682,8 +682,14 @@ class EngineAdapter(Protocol):
protocol: str,
base_url: str | None,
credential_ref: str,
+ *,
+ start_engine: bool = True,
) -> Sequence[DiscoveredModel]:
- """Refresh supplyable models for a saved Source using its stored protocol."""
+ """Refresh supplyable models for a saved Source using its stored protocol.
+
+ With ``start_engine=False`` an engine-held credential is listed only
+ from an engine that is already running; it is never started for this.
+ """
...
async def observe_source(
diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.md
index f7c2e8e1e..f1e71fc51 100644
--- a/docs/plans/model-hub.md
+++ b/docs/plans/model-hub.md
@@ -171,7 +171,8 @@ URL (api_key kind; prefilled for known vendors), a **model list** it can supply
(auto-discovered where possible, e.g. `/models`; manually extendable via custom
model entries), billing type (包月 | 按量 ¥), state (§4.5), and usage
(subscription cycle % / monthly spend). Existing `last_discovered_at` records the last
-successful full inventory replacement; it is not a connectivity-check timestamp.
+committed discovery: a full inventory replacement, or a background refresh that changed
+the inventory. It is not a connectivity-check timestamp.
Every Source read also carries the server-derived
`adopted_by: [{backend, menu_model}]` projection of persisted Route references for
backends currently in Hub mode. That unique projection is sorted by backend then menu
@@ -209,15 +210,16 @@ The Source workflow is complete at both entry points:
tests the stored protocol, rediscovers inventory, updates Source health, and clears a
`needs_action` or `error` blocker only when current evidence proves recovery. Before
committing a smaller inventory it runs §4.5's configured-hop and supply-gap guards.
- This is the **only saved-Source test/discovery mutation and the only corresponding
- Source-details button**, labelled “Refresh models” / 「重新拉取」. Its request,
+ This is the **only user-triggered saved-Source test/discovery mutation and the only
+ corresponding Source-details button**, labelled “Refresh models” / 「重新拉取」. Its request,
guarded refusal, and success are exactly the refresh row of §4.5's authoritative
Source-mutation matrix. The UI displays the resulting inventory and state and never
presents a second “Test connectivity” action.
- **Model discovery.** Third-party Anthropic-compatible and OpenAI-compatible Sources
expose an explicit “Fetch models” action while they are still in Add Source. A saved
Source gets the same discovery behavior only through the refresh operation above;
- there is no parallel saved discovery route. Discovery uses the observed protocol
+ there is no parallel saved discovery route, and the background refresh below only
+ adds. Discovery uses the observed protocol
adapter, replaces only the discovered slice, preserves manual entries, and renders
added, removed, unchanged, and failed results. Rediscovering an unchanged model id
preserves its edited `reasoning_efforts`, `display_name`, `discovered_at`, and
@@ -230,6 +232,29 @@ The Source workflow is complete at both entry points:
The saved Source surface may render freshness only as “Model list updated at …” /
「型号列表更新于…」 from `last_discovered_at`. It carries no latency or “last checked”
field or copy.
+- **Background inventory refresh.** While the runtime is enabled, the controller-owned
+ service lists every Hub-channel Source, API-key and OAuth alike, in the background;
+ native CLI Sources and credentials waiting on the user (`oauth_expired`,
+ `credential_revoked`, `account_banned`) are skipped. Each Source is due about every
+ 6 hours, at a stable per-Source period within ±20% so Sources listed together drift
+ apart. The first pass runs one 5-minute tick after startup, never at boot, and catches up
+ every Source never listed or last listed more than 6 hours ago. The refresh is add-only:
+ it admits newly listed models and updates listed metadata such as reasoning tiers
+ through the same discovery application, but never removes a model or route hop, and
+ it leaves any listing that would remove effective hops or open a supply gap to the
+ manual refresh and its confirmation. Success never changes Source state: cooldown,
+ `needs_action`, `error`, and live recovery stay, because a listing is not inference
+ evidence, and no recovery event is recorded. An unchanged listing writes neither
+ config nor the engine projection; it advances only the process-local schedule. A
+ failure changes nothing persisted and records no event: it logs one redacted warning
+ and retries after 15 minutes, doubling up to 6 hours, until any later successful
+ listing, background or manual, resets the backoff. Discovery runs outside the mutation
+ lock, and its result applies only if the Source still has the identity and
+ `last_discovered_at` it was listed with. A viewer's read of Source inventory
+ (`list_sources`, `agent_model_candidates`) also requests one coalesced background pass
+ with a 30-minute age instead of the period, so a model released upstream appears when
+ someone looks. The read never waits for it, the pass honors the same backoff and
+ rules, it runs only while the schedule runs, and no Source is listed twice at once.
- **Model inventory and manual entries.** Model `id` is unique within a Source. Every
model-list item has
`{id, origin: "discovered" | "manual", reasoning_efforts: string[], retired?:
diff --git a/tests/scenario_harness/model_hub.py b/tests/scenario_harness/model_hub.py
index 503354d24..fec9d8cd7 100644
--- a/tests/scenario_harness/model_hub.py
+++ b/tests/scenario_harness/model_hub.py
@@ -212,6 +212,8 @@ class ModelHubScenarioAdapter:
protocol: str,
base_url: str | None,
credential_ref: str,
+ *,
+ start_engine: bool = True,
) -> tuple[DiscoveredModel, ...]:
self.discovery_calls.append((vendor, protocol, base_url, credential_ref))
return tuple(DiscoveredModel(id=model_id) for model_id in self.refresh_models)
diff --git a/tests/scenario_harness/model_hub_native_oauth.py b/tests/scenario_harness/model_hub_native_oauth.py
index 6032743eb..1f2ee4737 100644
--- a/tests/scenario_harness/model_hub_native_oauth.py
+++ b/tests/scenario_harness/model_hub_native_oauth.py
@@ -380,7 +380,7 @@ class FakeHubOAuthAdapter(UnavailableEngineAdapter):
async def sync_sources(self, bindings) -> None:
self.synced.append(tuple(bindings))
- async def discover_models(self, vendor, protocol, base_url, credential_ref):
+ async def discover_models(self, vendor, protocol, base_url, credential_ref, *, start_engine=True):
return (DiscoveredModel(id="claude-opus-4-6"),)
async def observe_source(
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index b550c40c3..4ed6a2882 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -62,6 +62,7 @@ capabilities:
- tests/test_codex_request_provenance.py
- tests/test_codex_request_routing.py
- tests/test_model_hub_resolution.py
+ - tests/test_model_hub_background_discovery.py
- tests/test_model_hub_routing_modes.py
- tests/test_model_hub_transport_leases.py
- tests/test_model_hub_injection.py
diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
index 959420bb1..d03423ec8 100644
--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
@@ -3952,7 +3952,7 @@ def test_hub_oauth_model_free_observation_closed_loop(
}
state_store._secure_write_json(state_store.auth_dir / auth_name, grant)
- def management_request(method, path, *, query=None, payload=None):
+ def management_request(method, path, *, query=None, payload=None, timeout=None):
if path == "/auth-files":
return {"files": [{
"id": "codex-test", "auth_index": "auth-index-test",
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 128938121..f3bce1e7b 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -8,6 +8,7 @@ capability:
- tests/test_model_hub_legacy_opencode_migration.py
- tests/test_member_management_parity.py
- tests/test_model_hub_resolution.py
+ - tests/test_model_hub_background_discovery.py
- tests/test_model_hub_injection.py
- tests/test_codex_request_routing.py
- tests/test_model_hub_runtime.py
@@ -902,6 +903,22 @@ scenarios:
kind: observation
layer: unit
test: tests/test_model_hub_quota.py::test_quota_parsers_reject_a_malformed_body_as_one_source_failure
+ - id: MH-DISCOVERY-SCHEDULE-001
+ name: Hub Source inventories refresh in the background, add-only, without changing Source state
+ status: covered
+ kind: lifecycle
+ layer: unit
+ test: tests/test_model_hub_background_discovery.py::test_due_sources_gain_new_models_and_fresh_sources_are_left_alone
+ related_tests:
+ - tests/test_model_hub_background_discovery.py::test_background_failure_keeps_source_untouched_and_backs_off_until_a_success
+ - tests/test_model_hub_background_discovery.py::test_background_success_keeps_a_blocked_source_state
+ - tests/test_model_hub_background_discovery.py::test_background_refresh_never_removes_a_model_or_route_hop
+ - tests/test_model_hub_background_discovery.py::test_unchanged_listing_writes_nothing_and_still_counts_as_a_listing
+ - tests/test_model_hub_background_discovery.py::test_listing_for_a_source_changed_during_discovery_is_dropped
+ - tests/test_model_hub_background_discovery.py::test_schedule_covers_hub_sources_and_skips_native_and_waiting_credentials
+ - tests/test_model_hub_background_discovery.py::test_stale_sources_catch_up_together_then_refresh_at_different_times
+ - tests/test_model_hub_background_discovery.py::test_listing_that_would_strand_a_menu_model_is_left_to_manual_refresh
+ - tests/test_model_hub_background_discovery.py::test_stop_retires_the_background_schedule
- id: MH-QUOTA-005
name: Each subscription's quota is re-read at most every five minutes and concurrent reads share one fetch
status: covered
diff --git a/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py
index 24ba226c7..0b31729eb 100644
--- a/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py
+++ b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py
@@ -186,6 +186,8 @@ class MigrationAdapter:
protocol: str,
base_url: str | None,
credential_ref: str,
+ *,
+ start_engine: bool = True,
) -> tuple[DiscoveredModel, ...]:
return (DiscoveredModel(id=f"{vendor}-model"),)
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index 6ee9ba808..d89688d4f 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -300,7 +300,7 @@ class FakeAdapter:
if self.fail_sync:
raise RuntimeError("upstream failure with sk-secret-material")
- async def discover_models(self, vendor, protocol, base_url, credential_ref):
+ async def discover_models(self, vendor, protocol, base_url, credential_ref, *, start_engine=True):
self.discovery_credential_refs.append(credential_ref)
return (
DiscoveredModel(id="claude-opus-4-6"),
@@ -1774,7 +1774,7 @@ def test_runtime_install_rejects_unsupported_server_host_without_mutation(
def test_discovery_probe_failure_is_not_reported_as_engine_down(tmp_path):
class DiscoveryFailureAdapter(FakeAdapter):
- async def discover_models(self, vendor, protocol, base_url, credential_ref):
+ async def discover_models(self, vendor, protocol, base_url, credential_ref, *, start_engine=True):
raise ModelDiscoveryError("upstream rejected the credential")
store = MemoryStore()
@@ -6799,7 +6799,7 @@ def test_refresh_empty_inventory_returns_success_without_route_removal_confirmat
store.config.agents["codex"].mode = mode
models = [model.id for model in store.config.agents["codex"].models]
- async def discover(*_args):
+ async def discover(*_args, **_kwargs):
return tuple(DiscoveredModel(id=model) for model in models)
adapter.discover_models = discover
@@ -6870,7 +6870,7 @@ def test_discovered_source_model_delete_persists_retirement_tombstone(
assert store.config.sources[0].models[0].retired is True
assert store.config.sources[0].models[0].reasoning_efforts == ["high"]
- async def rediscover(*_args):
+ async def rediscover(*_args, **_kwargs):
return (DiscoveredModel(id="gpt-5"), DiscoveredModel(id="gpt-5.1"))
adapter.discover_models = rediscover
@@ -7085,7 +7085,7 @@ def test_refresh_overrides_user_tiers_only_after_commit_and_records_one_event(
)
store.config.sources.append(source)
- async def discover(*_args):
+ async def discover(*_args, **_kwargs):
return (metadata,)
adapter.discover_models = discover
@@ -7688,6 +7688,8 @@ def test_concurrent_completed_hub_reauth_materializes_once(tmp_path):
protocol,
base_url,
credential_ref,
+ *,
+ start_engine=True,
):
self.discovery_calls += 1
if self.discovery_calls > 1:
@@ -8578,7 +8580,7 @@ def test_failed_same_handle_hub_reauth_requires_user_action(
}
)
- async def fail_discovery(vendor, protocol, base_url, credential_ref):
+ async def fail_discovery(vendor, protocol, base_url, credential_ref, *, start_engine=True):
raise ModelDiscoveryError("safe discovery failure")
if failure == "discovery":
@@ -8730,7 +8732,7 @@ def test_failed_hub_reauth_preserves_prior_source_and_revokes_replacement(
separators=(",", ":"),
)
- async def fail_discovery(vendor, protocol, base_url, credential_ref):
+ async def fail_discovery(vendor, protocol, base_url, credential_ref, *, start_engine=True):
raise ModelDiscoveryError("safe discovery failure")
adapter.discover_models = fail_discovery
@@ -8891,7 +8893,7 @@ def test_credential_inventory_narrowing_preserves_exact_routes(
store.requested_model = lambda backend: ("claude-opus-4-6" if backend == "claude" else "")
service.named_agents_override = lambda backend: ([("claude", "claude-opus-4-6")] if backend == "claude" else [])
- async def discover_narrower(vendor, protocol, base_url, credential_ref):
+ async def discover_narrower(vendor, protocol, base_url, credential_ref, *, start_engine=True):
return (DiscoveredModel(id="replacement-only-model"),)
adapter.discover_models = discover_narrower
@@ -9827,7 +9829,7 @@ def test_concurrent_source_creates_preserve_both_aggregate_updates(tmp_path):
self.secret_lengths.append(len(secret))
return credential_ref
- async def discover_models(self, vendor, protocol, base_url, credential_ref):
+ async def discover_models(self, vendor, protocol, base_url, credential_ref, *, start_engine=True):
self.discover_started += 1
if self.discover_started == 2:
self.all_discovering.set()
@@ -10176,7 +10178,7 @@ def test_source_patch_rejects_credential_bearing_discovered_model_id(tmp_path):
)
)
- async def credential_bearing_models(vendor, protocol, base_url, credential_ref):
+ async def credential_bearing_models(vendor, protocol, base_url, credential_ref, *, start_engine=True):
return (DiscoveredModel(id="sk-model-never-persist-this"),)
adapter.discover_models = credential_bearing_models
@@ -10203,7 +10205,7 @@ def test_admitted_model_ids_are_stored_in_their_canonical_form(tmp_path):
service, store, adapter = _service(tmp_path)
- async def padded_models(vendor, protocol, base_url, credential_ref):
+ async def padded_models(vendor, protocol, base_url, credential_ref, *, start_engine=True):
return (DiscoveredModel(id=" discovered-model "),)
adapter.discover_models = padded_models
@@ -10242,7 +10244,7 @@ def test_long_identity_source_lifecycle_preserves_api_binding_and_reload(monkeyp
head = "模型🧪/e\u0301" * 3000
discovered = [head + "-one", head + "-two", "é", "e\u0301"]
- async def models(*_args):
+ async def models(*_args, **_kwargs):
return tuple(DiscoveredModel(id=" " + identity + " ") for identity in discovered)
adapter.discover_models = models
@@ -10462,7 +10464,7 @@ def test_source_patch_rejects_one_discovered_model_under_two_spellings(tmp_path,
)
)
- async def duplicate_spellings(vendor, protocol, base_url, credential_ref):
+ async def duplicate_spellings(vendor, protocol, base_url, credential_ref, *, start_engine=True):
return (
DiscoveredModel(id=identity),
DiscoveredModel(id=" " + identity),
@@ -10500,7 +10502,7 @@ def test_base_url_change_preserves_missing_inventory_exact_hops(
old_credential_ref = source["credential_ref"]
discovery_refs: list[str] = []
- async def discover_narrower(vendor, protocol, base_url, credential_ref):
+ async def discover_narrower(vendor, protocol, base_url, credential_ref, *, start_engine=True):
discovery_refs.append(credential_ref)
return (DiscoveredModel(id="replacement-only-model"),)
diff --git a/tests/test_model_hub_background_discovery.py b/tests/test_model_hub_background_discovery.py
new file mode 100644
index 000000000..f5d90bb3a
--- /dev/null
+++ b/tests/test_model_hub_background_discovery.py
@@ -0,0 +1,473 @@
+"""Background refresh of Hub Source model inventories at the service boundary."""
+
+from __future__ import annotations
+
+import asyncio
+import copy
+import logging
+from datetime import timedelta
+
+import pytest
+
+from config.v2_config import ModelHubModelConfig, ModelHubSourceStateConfig
+from core.handlers.model_hub.errors import ModelDiscoveryError
+from core.handlers.model_hub.rpc import dispatch_model_hub_rpc
+from core.handlers.model_hub.service import UnavailableEngineAdapter
+from tests.test_model_hub_resolution import FakeAdapter, _config, _service, _source
+from tests.test_model_hub_retry_policy import Clock
+
+
+MENU_MODEL = "claude-opus-4-6"
+TICK = timedelta(minutes=5)
+
+
+class ListingAdapter(FakeAdapter):
+ """Records the credential of every listing it answers."""
+
+ def __init__(self, discovered: tuple[str, ...] = (MENU_MODEL,)):
+ super().__init__(discovered)
+ self.listed: list[str] = []
+
+ async def discover_models(self, vendor, protocol, base_url, credential_ref, *, start_engine=True):
+ self.listed.append(credential_ref)
+ self.started_engine = getattr(self, "started_engine", False) or start_engine
+ return await super().discover_models(vendor, protocol, base_url, credential_ref)
+
+
+def _hub_source(source_id: str, model_ids=(MENU_MODEL,), **kwargs):
+ return _source(source_id, model_ids, credential_ref=f"cred_{source_id}", **kwargs)
+
+
+def _listed(source, clock: Clock, *, hours_ago: float):
+ source.last_discovered_at = (clock.now() - timedelta(hours=hours_ago)).isoformat()
+ return source
+
+
+def _background(tmp_path, sources, adapter=None):
+ clock = Clock()
+ service, store, adapter = _service(tmp_path, _config(sources), adapter or ListingAdapter())
+ service.now = clock.now
+ return service, store, adapter, clock
+
+
+def _model_ids(store, index=0):
+ return [model.id for model in store.load().sources[index].models]
+
+
+def _refresh(service):
+ asyncio.run(service._refresh_due_sources())
+
+
+ ("listed_hours_ago", "refreshed"),
+ [(None, True), (6 + 1 / 60, True), (1, False)],
+ ids=["never-listed", "stale-at-startup", "fresh"],
+)
+def test_due_sources_gain_new_models_and_fresh_sources_are_left_alone(
+ tmp_path, listed_hours_ago, refreshed,
+):
+ """MH-DISCOVERY-SCHEDULE-001: a Source not listed within the interval is refreshed in the background; a fresh one is not."""
+
+ clock = Clock()
+ source = _hub_source("src_sched001")
+ if listed_hours_ago is not None:
+ _listed(source, clock, hours_ago=listed_hours_ago)
+ service, store, adapter, clock = _background(
+ tmp_path, [source], ListingAdapter((MENU_MODEL, "claude-new-model")),
+ )
+ before = store.load().sources[0].last_discovered_at
+
+ _refresh(service)
+
+ persisted = store.load().sources[0]
+ # A background listing never starts the engine.
+ assert getattr(adapter, "started_engine", False) is False
+ if refreshed:
+ assert adapter.listed == ["cred_src_sched001"]
+ assert _model_ids(store) == [MENU_MODEL, "claude-new-model"]
+ assert persisted.last_discovered_at == clock.now().isoformat()
+ else:
+ assert adapter.listed == []
+ assert _model_ids(store) == [MENU_MODEL]
+ assert persisted.last_discovered_at == before
+
+
+def test_background_failure_keeps_source_untouched_and_backs_off_until_a_success(tmp_path, caplog):
+ source = _listed(_hub_source("src_backoff1"), Clock(), hours_ago=7)
+ service, store, adapter, clock = _background(tmp_path, [source])
+ adapter.discovery_error = ModelDiscoveryError("upstream echoed sk-live-secret")
+ before = copy.deepcopy(store.load().to_payload())
+
+ def attempts_after(minutes: int) -> int:
+ clock.advance(minutes * 60)
+ listed = len(adapter.listed)
+ _refresh(service)
+ return len(adapter.listed) - listed
+
+ with caplog.at_level(logging.WARNING, logger="core.handlers.model_hub.service"):
+ assert attempts_after(0) == 1
+ for delay in (15, 30, 60, 120, 240, 360, 360):
+ assert attempts_after(delay - 1) == 0
+ assert attempts_after(1) == 1
+
+ assert store.load().to_payload() == before
+ assert service.list_events() == []
+ failures = [record.getMessage() for record in caplog.records]
+ assert len(failures) == 8
+ assert all("src_backoff1" in message and "discovery_failed" in message for message in failures)
+ assert not any("sk-live-secret" in message for message in failures)
+
+ adapter.discovery_error = None
+ adapter.discovered = (MENU_MODEL, "claude-new-model")
+ assert attempts_after(360) == 1
+ assert _model_ids(store) == [MENU_MODEL, "claude-new-model"]
+
+ # A success resets the backoff: the next failure retries after the base delay.
+ adapter.discovery_error = ModelDiscoveryError("down again")
+ assert attempts_after(int(7.2 * 60)) == 1
+ assert attempts_after(14) == 0
+ assert attempts_after(1) == 1
+
+
+def test_background_listing_without_an_engine_fails_as_engine_down(tmp_path, caplog):
+ """MH-DISCOVERY-SCHEDULE-001: the fail-closed adapter answers a background listing as an engine failure."""
+
+ service, store, _, _ = _background(tmp_path, [_hub_source("src_noengine")], UnavailableEngineAdapter())
+
+ with caplog.at_level(logging.WARNING, logger="core.handlers.model_hub.service"):
+ _refresh(service)
+
+ assert [record.getMessage() for record in caplog.records] == [
+ "Model Hub background discovery failed for Source src_noengine (engine_down); retrying in 15 minutes"
+ ]
+ assert _model_ids(store) == [MENU_MODEL]
+
+
+ "state",
+ [
+ ModelHubSourceStateConfig(
+ status="cooldown",
+ retry_at="2099-01-01T00:00:00+00:00",
+ detail_key="models.source.cooldown.rate_limited",
+ ),
+ ModelHubSourceStateConfig(
+ status="needs_action",
+ detail_key="models.source.needs_action.balance_exhausted",
+ ),
+ ModelHubSourceStateConfig(
+ status="error",
+ detail_key="models.source.error.unclassified",
+ ),
+ ],
+ ids=lambda state: state.status,
+)
+def test_background_success_keeps_a_blocked_source_state(tmp_path, state):
+ source = _listed(_hub_source("src_blocked1"), Clock(), hours_ago=7)
+ source.state = copy.deepcopy(state)
+ service, store, _, _ = _background(
+ tmp_path, [source], ListingAdapter((MENU_MODEL, "claude-new-model")),
+ )
+
+ _refresh(service)
+
+ assert _model_ids(store) == [MENU_MODEL, "claude-new-model"]
+ assert store.load().sources[0].state == state
+ assert service.list_events() == []
+
+
+def test_background_refresh_never_removes_a_model_or_route_hop(tmp_path):
+ source = _listed(_hub_source("src_addonly1", (MENU_MODEL, "claude-old-model")), Clock(), hours_ago=7)
+ source.models.append(ModelHubModelConfig(id="claude-manual-model", provenance="manual"))
+ service, store, adapter, _ = _background(
+ tmp_path, [source], ListingAdapter(("claude-new-model",)),
+ )
+ hops = store.load().agents["claude"].routes[MENU_MODEL].hops
+
+ _refresh(service)
+
+ assert adapter.listed == ["cred_src_addonly1"]
+ assert _model_ids(store) == [
+ MENU_MODEL, "claude-old-model", "claude-new-model", "claude-manual-model",
+ ]
+ assert store.load().agents["claude"].routes[MENU_MODEL].hops == hops
+
+
[email protected]("upstream_order", ["same", "reversed"])
+def test_unchanged_listing_writes_nothing_and_still_counts_as_a_listing(tmp_path, upstream_order):
+ inventory = (MENU_MODEL, "claude-other-model")
+ service, store, adapter, clock = _background(
+ tmp_path, [_hub_source("src_nochange", ())], ListingAdapter(inventory),
+ )
+ # The inventory exactly as a completed discovery leaves it.
+ asyncio.run(service.refresh_source("src_nochange"))
+ clock.advance(timedelta(hours=7).total_seconds())
+ adapter.listed.clear()
+ adapter.synced.clear()
+ if upstream_order == "reversed":
+ adapter.discovered = tuple(reversed(inventory))
+ before = copy.deepcopy(store.load().to_payload())
+ saves = []
+ save = store.save
+ store.save = lambda config: (saves.append(config), save(config))
+
+ _refresh(service)
+ # Past every jittered period counted from the persisted timestamp, but
+ # within the shortest one counted from the unchanged listing.
+ clock.advance(timedelta(hours=2).total_seconds())
+ _refresh(service)
+
+ assert adapter.listed == ["cred_src_nochange"]
+ assert saves == []
+ assert adapter.synced == []
+ assert store.load().to_payload() == before
+
+
+def _replace_credential(source):
+ source.credential_ref = "cred_replaced"
+
+
+def _retarget(source):
+ source.base_url = "https://new-relay.example/v1"
+
+
+def _switch_protocol(source):
+ source.protocol = "openai_chat"
+
+
+def _await_verification(source):
+ source.verification_pending = "vp_" + "0" * 32
+
+
+def _land_manual_refresh(source):
+ source.last_discovered_at = "2026-07-29T12:00:01+00:00"
+
+
+ "change",
+ [_replace_credential, _retarget, _switch_protocol, _await_verification, _land_manual_refresh, None],
+ ids=["credential", "base-url", "protocol", "verification", "manual-refresh", "deleted"],
+)
+def test_listing_for_a_source_changed_during_discovery_is_dropped(tmp_path, change):
+ source = _listed(_hub_source("src_identity", vendor="custom"), Clock(), hours_ago=7)
+ source.base_url = "https://old-relay.example/v1"
+ service, store, adapter, _ = _background(
+ tmp_path, [source], ListingAdapter((MENU_MODEL, "claude-new-model")),
+ )
+
+ async def run():
+ adapter.discovery_started = asyncio.Event()
+ adapter.discovery_block = asyncio.Event()
+ refresh = asyncio.create_task(service._refresh_due_sources())
+ await adapter.discovery_started.wait()
+ changed = service._clone_config(store.load())
+ if change is None:
+ changed.sources.clear()
+ else:
+ change(changed.sources[0])
+ store.config = changed
+ adapter.discovery_block.set()
+ await refresh
+ return changed.to_payload()
+
+ expected = asyncio.run(run())
+
+ assert adapter.listed == ["cred_src_identity"]
+ assert store.load().to_payload() == expected
+ assert adapter.synced == []
+
+
[email protected](("enabled", "listed"), [(True, {"cred_src_apikey1", "cred_src_oauth01"}), (False, set())])
+def test_schedule_covers_hub_sources_and_skips_native_and_waiting_credentials(tmp_path, enabled, listed):
+ clock = Clock()
+ api_key = _listed(_hub_source("src_apikey1"), clock, hours_ago=7)
+ oauth = _listed(_hub_source("src_oauth01", ("gpt-5.5",), kind="subscription", vendor="openai"), clock, hours_ago=7)
+ expired = _listed(_hub_source("src_expired", ("gpt-5.5",), kind="subscription", vendor="openai"), clock, hours_ago=7)
+ expired.state = ModelHubSourceStateConfig(
+ status="needs_action",
+ detail_key="models.source.needs_action.oauth_expired",
+ )
+ native = _source("src_native01", (MENU_MODEL,), kind="subscription", channel="native_cli", credential_ref=None)
+ service, store, adapter, _ = _background(
+ tmp_path, [api_key, oauth, expired, native], ListingAdapter((MENU_MODEL, "gpt-5.5")),
+ )
+ store.load().enabled = enabled
+
+ _refresh(service)
+
+ assert set(adapter.listed) == listed
+ assert len(adapter.listed) == len(listed)
+
+
+def test_stale_sources_catch_up_together_then_refresh_at_different_times(tmp_path):
+ clock = Clock()
+ source_ids = [f"src_jitter{index:02d}" for index in range(6)]
+ credentials = sorted(f"cred_{source_id}" for source_id in source_ids)
+ sources = [_listed(_hub_source(source_id), clock, hours_ago=6 + 1 / 60) for source_id in source_ids]
+ service, _, adapter, clock = _background(tmp_path, sources)
+
+ _refresh(service)
+
+ assert sorted(adapter.listed) == credentials
+ adapter.listed.clear()
+ start = clock.now()
+ refreshed_at = {}
+
+ elapsed = timedelta(0)
+ while elapsed <= timedelta(hours=7.2) + TICK:
+ _refresh(service)
+ for credential_ref in adapter.listed:
+ refreshed_at.setdefault(credential_ref, clock.now() - start)
+ adapter.listed.clear()
+ clock.advance(TICK.total_seconds())
+ elapsed += TICK
+
+ assert sorted(refreshed_at) == credentials
+ assert all(
+ timedelta(hours=4.8) <= offset <= timedelta(hours=7.2) + TICK
+ for offset in refreshed_at.values()
+ )
+ assert len(set(refreshed_at.values())) > 1
+
+
+def test_listing_that_would_strand_a_menu_model_is_left_to_manual_refresh(tmp_path):
+ clock = Clock()
+ healthy = _listed(_hub_source("src_healthy1", ("claude-other-a",)), clock, hours_ago=1)
+ blocked = _listed(_hub_source("src_blocked2", ("claude-other-b",)), clock, hours_ago=7)
+ blocked.state = ModelHubSourceStateConfig(
+ status="needs_action",
+ detail_key="models.source.needs_action.balance_exhausted",
+ )
+ service, store, adapter, _ = _background(
+ tmp_path, [healthy, blocked], ListingAdapter(("claude-other-b", MENU_MODEL)),
+ )
+ # Without an exact Route the menu model passes through to the healthy key.
+ # Listing it on the blocked Source alone would narrow it onto that Source.
+ store.load().agents["claude"].routes.pop(MENU_MODEL)
+ before = copy.deepcopy(store.load().to_payload())
+
+ _refresh(service)
+
+ assert adapter.listed == ["cred_src_blocked2"]
+ assert store.load().to_payload() == before
+ assert adapter.synced == []
+
+
[email protected]("read", ["list_sources", "agent_model_candidates"])
+def test_viewing_inventory_lists_sources_older_than_thirty_minutes_once(tmp_path, read):
+ """MH-DISCOVERY-SCHEDULE-001: a viewer's read lists Sources older than 30 minutes, once, in the background."""
+
+ clock = Clock()
+ stale = _listed(_hub_source("src_viewed01"), clock, hours_ago=1)
+ fresh = _listed(_hub_source("src_viewed02"), clock, hours_ago=0.25)
+ # Also due for the schedule, which may list it while a viewer's pass runs.
+ overdue = _listed(_hub_source("src_viewed03"), clock, hours_ago=7)
+ class HeldListingAdapter(ListingAdapter):
+ """Holds every listing open so repeated reads overlap it."""
+
+ released: asyncio.Event
+
+ async def discover_models(self, vendor, protocol, base_url, credential_ref, *, start_engine=True):
+ self.listed.append(credential_ref)
+ await self.released.wait()
+ return await FakeAdapter.discover_models(self, vendor, protocol, base_url, credential_ref)
+
+ service, store, adapter, clock = _background(
+ tmp_path, [stale, fresh, overdue], HeldListingAdapter((MENU_MODEL, "claude-new-model")),
+ )
+ payload = {"backend": "claude"} if read == "agent_model_candidates" else {}
+
+ async def run():
+ adapter.released = asyncio.Event()
+ # No schedule, no listing: a stopped runtime is never woken by a read.
+ await dispatch_model_hub_rpc(service, read, payload)
+ await asyncio.sleep(0.05)
+ assert adapter.listed == []
+ service.start_background_discovery()
+ try:
+ scheduled = asyncio.create_task(service._refresh_due_sources())
+ for _ in range(3):
+ await dispatch_model_hub_rpc(service, read, payload)
+ await asyncio.sleep(0.02)
+ adapter.released.set()
+ await scheduled
+ for _ in range(100):
+ if _model_ids(store, 0) != [MENU_MODEL] and _model_ids(store, 2) != [MENU_MODEL]:
+ break
+ await asyncio.sleep(0.01)
+ finally:
+ adapter.released.set()
+ await asyncio.wait_for(service.stop(), 2)
+
+ asyncio.run(run())
+
+ assert sorted(adapter.listed) == ["cred_src_viewed01", "cred_src_viewed03"]
+ assert _model_ids(store, 0) == [MENU_MODEL, "claude-new-model"]
+ assert _model_ids(store, 1) == [MENU_MODEL]
+ assert _model_ids(store, 2) == [MENU_MODEL, "claude-new-model"]
+
+
+class _HeldAdapter(ListingAdapter):
+ """Holds each listing open until released."""
+
+ released: asyncio.Event
+
+ async def discover_models(self, vendor, protocol, base_url, credential_ref, *, start_engine=True):
+ self.listed.append(credential_ref)
+ await self.released.wait()
+ return await FakeAdapter.discover_models(self, vendor, protocol, base_url, credential_ref)
+
+
+def test_stop_retires_the_background_schedule_without_waiting_for_a_listing(tmp_path):
+ """MH-DISCOVERY-SCHEDULE-001: shutdown retires a listing that upstream is still holding."""
+
+ service, _, adapter, _ = _background(tmp_path, [_hub_source("src_lifecyc1")], _HeldAdapter())
+
+ async def run():
+ adapter.released = asyncio.Event()
+ service.start_background_discovery()
+ service.request_inventory_refresh()
+ for _ in range(100):
+ if adapter.listed:
+ break
+ await asyncio.sleep(0.01)
+ assert adapter.listed == ["cred_src_lifecyc1"]
+ # The listing is never released: shutdown must not wait for upstream.
+ loop = asyncio.get_running_loop()
+ started = loop.time()
+ await asyncio.wait_for(service.stop(), 30)
+ elapsed = loop.time() - started
+ return elapsed, [
+ task for task in asyncio.all_tasks()
+ if task.get_name() in {"model-hub-background-discovery", "model-hub-viewed-discovery"}
+ and not task.done()
+ ]
+
+ elapsed, running = asyncio.run(run())
+ # Well inside the controller's 10-second runtime-work shutdown grace.
+ assert elapsed < 1
+ assert running == []
+
+
+def test_runtime_stopped_mid_pass_lists_no_further_source(tmp_path):
+ """MH-DISCOVERY-SCHEDULE-001: a runtime stopped during a pass is not listed again by it."""
+
+ first, second = _hub_source("src_midpass1"), _hub_source("src_midpass2")
+ service, store, adapter, _ = _background(tmp_path, [first, second], _HeldAdapter())
+
+ async def run():
+ adapter.released = asyncio.Event()
+ passing = asyncio.create_task(service._refresh_due_sources())
+ for _ in range(100):
+ if adapter.listed:
+ break
+ await asyncio.sleep(0.01)
+ config = store.load()
+ config.enabled = False
+ store.save(config)
+ adapter.released.set()
+ await asyncio.wait_for(passing, 1)
+
+ asyncio.run(run())
+
+ assert len(adapter.listed) == 1
diff --git a/tests/test_model_hub_credential_replacement.py b/tests/test_model_hub_credential_replacement.py
index 31934e9fe..11a9f0766 100644
--- a/tests/test_model_hub_credential_replacement.py
+++ b/tests/test_model_hub_credential_replacement.py
@@ -107,7 +107,7 @@ def test_cancelled_replacement_keeps_old_credential_and_settles_the_new_one(
discovering = asyncio.Event()
replacement: list[str] = []
- async def discover_until_cancelled(vendor, protocol, base_url, credential_ref):
+ async def discover_until_cancelled(vendor, protocol, base_url, credential_ref, *, start_engine=True):
replacement.append(credential_ref)
discovering.set()
await asyncio.Event().wait()
diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.py
index 157946f54..5878ccb4b 100644
--- a/tests/test_model_hub_resolution.py
+++ b/tests/test_model_hub_resolution.py
@@ -252,7 +252,7 @@ class FakeAdapter:
if self.sync_block is not None:
await self.sync_block.wait()
- async def discover_models(self, vendor, protocol, base_url, credential_ref):
+ async def discover_models(self, vendor, protocol, base_url, credential_ref, *, start_engine=True):
if self.discovery_started is not None:
self.discovery_started.set()
if self.discovery_block is not None:
diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.py
index fea440f86..a84fc001d 100644
--- a/tests/test_model_hub_runtime.py
+++ b/tests/test_model_hub_runtime.py
@@ -40,6 +40,7 @@ from core.handlers.model_hub.classification import (
classify_outcome,
terminal_outcome_category,
)
+from core.handlers.model_hub.errors import ModelDiscoveryError
from core.handlers.model_hub.events import redact_untrusted_text
from core.handlers.model_hub.request import ModelHubRequest
from core.handlers.model_hub.stream_wire import (
@@ -8384,6 +8385,92 @@ def test_oauth_model_discovery_accepts_engine_definition_fields(tmp_path: Path)
asyncio.run(run())
[email protected]("engine_running", [True, False])
+def test_background_oauth_discovery_never_starts_the_engine(tmp_path: Path, engine_running: bool) -> None:
+ """MH-DISCOVERY-SCHEDULE-001: a background listing reads a running engine and never starts one."""
+
+ class Client:
+ def management_request(self, method, path, *, query=None, payload=None, timeout=None):
+ return {"models": [{"id": "model-id"}]}
+
+ class Supervisor:
+ def __init__(self) -> None:
+ self.started = False
+
+ def client(self):
+ self.started = True
+ return Client()
+
+ def client_if_running(self):
+ return Client() if engine_running else None
+
+ async def run() -> tuple[Supervisor, object]:
+ store = EngineStateStore(tmp_path / "state")
+ store.prepare_instance("install-1")
+ (store.auth_dir / "claude-account.json").write_text("{}", encoding="utf-8")
+ credential_ref = store.bind_oauth_credential("src_fixture123", "anthropic", "claude-account.json")
+ supervisor = Supervisor()
+ adapter = CLIProxyEngineAdapter(supervisor=supervisor, state_store=store) # type: ignore[arg-type]
+ try:
+ listed = await adapter.discover_models(
+ "anthropic", "anthropic", None, credential_ref, start_engine=False,
+ )
+ except ModelDiscoveryError as error:
+ listed = error
+ return supervisor, listed
+
+ supervisor, listed = asyncio.run(run())
+
+ assert supervisor.started is False
+ if engine_running:
+ assert listed == (DiscoveredModel(id="model-id"),)
+ else:
+ assert isinstance(listed, ModelDiscoveryError)
+
+
+def test_cancelled_background_oauth_listing_returns_after_its_engine_worker(tmp_path: Path) -> None:
+ """MH-DISCOVERY-SCHEDULE-001: shutdown cannot stop the engine beneath a cancelled listing."""
+
+ from core.controller import _RUNTIME_WORK_SHUTDOWN_GRACE_SECONDS
+
+ entered, release = threading.Event(), threading.Event()
+ timeouts: list[float | None] = []
+
+ class Client:
+ def management_request(self, method, path, *, query=None, payload=None, timeout=None):
+ timeouts.append(timeout)
+ entered.set()
+ release.wait(5)
+ return {"models": [{"id": "model-id"}]}
+
+ class Supervisor:
+ def client_if_running(self):
+ return Client()
+
+ async def run() -> bool:
+ store = EngineStateStore(tmp_path / "state")
+ store.prepare_instance("install-1")
+ (store.auth_dir / "claude-account.json").write_text("{}", encoding="utf-8")
+ credential_ref = store.bind_oauth_credential("src_fixture123", "anthropic", "claude-account.json")
+ adapter = CLIProxyEngineAdapter(supervisor=Supervisor(), state_store=store) # type: ignore[arg-type]
+ listing = asyncio.create_task(
+ adapter.discover_models("anthropic", "anthropic", None, credential_ref, start_engine=False)
+ )
+ assert await asyncio.to_thread(entered.wait, 5)
+ listing.cancel()
+ done, _ = await asyncio.wait({listing}, timeout=0.2)
+ release.set()
+ with pytest.raises(asyncio.CancelledError):
+ await listing
+ return bool(done)
+
+ returned_while_worker_ran = asyncio.run(run())
+
+ assert returned_while_worker_ran is False
+ assert timeouts and timeouts[0] is not None
+ assert timeouts[0] < _RUNTIME_WORK_SHUTDOWN_GRACE_SECONDS
+
+
@pytest.mark.parametrize(
"oauth_record_case",
[
diff --git a/tests/test_model_hub_source_probe.py b/tests/test_model_hub_source_probe.py
index 5dd72e830..1fa34d757 100644
--- a/tests/test_model_hub_source_probe.py
+++ b/tests/test_model_hub_source_probe.py
@@ -561,7 +561,7 @@ def test_discovery_deadline_saves_manual_inventory_and_drains_cancelled_work(tmp
async def scenario():
cancelled = asyncio.Event()
- async def stalled(*args):
+ async def stalled(*args, **_kwargs):
try:
await asyncio.Event().wait()
finally:
diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.py
index 5a91e283e..9b5d043f6 100644
--- a/vibe/model_hub_runtime/adapter.py
+++ b/vibe/model_hub_runtime/adapter.py
@@ -139,6 +139,8 @@ _HUB_SUBSCRIPTION_PROTOCOLS = {
_INSTALL_RECOVERY_WAIT_SECONDS = 30.0
_INSTALL_RECOVERY_INITIAL_DELAY_SECONDS = 0.25
_INSTALL_RECOVERY_MAX_DELAY_SECONDS = 4.0
+# The engine answers a credential's model list from memory.
+_ENGINE_MODEL_LISTING_TIMEOUT_SECONDS = 5.0
logger = logging.getLogger(__name__)
@@ -2217,6 +2219,8 @@ class CLIProxyEngineAdapter:
protocol: str,
base_url: str | None,
credential_ref: str,
+ *,
+ start_engine: bool = True,
) -> Sequence[DiscoveredModel]:
metadata = await asyncio.to_thread(
self.state_store.credential_metadata,
@@ -2226,12 +2230,21 @@ class CLIProxyEngineAdapter:
if metadata["kind"] == "oauth":
if metadata.get("vendor") != normalized_vendor or base_url is not None:
raise EngineStateError("credential does not match discovery target")
- client = await asyncio.to_thread(self.supervisor.client)
- payload = await asyncio.to_thread(
+ if start_engine:
+ client = await asyncio.to_thread(self.supervisor.client)
+ else:
+ client = await run_owned_in_thread(self.supervisor.client_if_running)
+ if client is None:
+ raise ModelDiscoveryError("engine is not running")
+ # Owned and bounded: a cancelled listing (Hub shutdown) returns only
+ # once its worker has stopped using the engine, within the
+ # controller's runtime-work shutdown grace.
+ payload = await run_owned_in_thread(
client.management_request,
"GET",
"/auth-files/models",
query={"name": str(metadata["auth_name"])},
+ timeout=_ENGINE_MODEL_LISTING_TIMEOUT_SECONDS,
)
prefix = metadata.get("prefix")
return _discovered_models(