diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.py index daa8ca1c1..4280a517f 100644 --- a/deeptutor/api/routers/settings.py +++ b/deeptutor/api/routers/settings.py @@ -1932,6 +1932,22 @@ async def apply_provider_edit(payload: ProviderEditPayload): return {"catalog": redact_catalog_secrets(catalog), "draft": public_draft} +def _preserve_llm_fallbacks( + service: str, incoming: dict[str, Any], current: dict[str, Any] +) -> dict[str, Any]: + """Keep the fallback chain when an ``llm`` payload does not carry one. + + The settings UI edits providers, not the chain (#2693 P3). Replacing the + service wholesale would delete a hand-configured chain on the next Apply, + so an absent key means "leave it as it is" rather than "clear it". + """ + payload = dict(incoming) + if service == "llm" and "fallbacks" not in payload: + existing = (current.get("services") or {}).get("llm", {}).get("fallbacks") + payload["fallbacks"] = deepcopy(existing or []) + return payload + + @router.post("/apply/service") async def apply_catalog_service(payload: CatalogServicePayload): """Apply one model service while leaving every other draft untouched. @@ -1947,7 +1963,9 @@ async def apply_catalog_service(payload: CatalogServicePayload): draft_service = get_settings_draft_service() stored_draft = draft_service.load() proposed = deepcopy(current) - proposed.setdefault("services", {})[payload.service] = deepcopy(payload.config) + proposed.setdefault("services", {})[payload.service] = _preserve_llm_fallbacks( + payload.service, payload.config, current + ) restored = restore_catalog_secrets(proposed, stored_draft.get("catalog") or current) restored = restore_catalog_secrets(restored, current) if payload.service == "task" and payload.config.get("mode") == "reference": diff --git a/deeptutor/services/config/model_catalog.py b/deeptutor/services/config/model_catalog.py index 5763171d6..a8860beaa 100644 --- a/deeptutor/services/config/model_catalog.py +++ b/deeptutor/services/config/model_catalog.py @@ -186,9 +186,14 @@ _CONNECTION_CREDENTIAL_FIELDS: tuple[str, ...] = ( "app_id", ) -# Services whose profiles are LLM-shaped and therefore carry an API format. +#: Services whose profiles are LLM-shaped and therefore carry an API format. LLM_SHAPED_SERVICES: tuple[str, ...] = ("llm", "task") +#: Upper bound on the ordered fallback chain (#2693). Mirrors +#: ``services/llm/failover.MAX_CANDIDATES`` without importing it: the catalog +#: layer must not depend on the runtime layer. +_MAX_FALLBACK_CANDIDATES = 4 + # Per-model capability overrides a user may set. Absent means "let the # built-in tables decide"; only explicit booleans are kept. MODEL_CAPABILITY_KEYS: tuple[str, ...] = ("tools", "vision", "json_output", "reasoning") @@ -214,6 +219,33 @@ def _normalize_model_capabilities(model: dict[str, Any]) -> bool: return False +def _normalized_fallbacks(value: Any) -> list[dict[str, str]]: + """Keep well-formed, de-duplicated ``{profile_id, model_id}`` entries. + + Bounded to the chain cap: every extra candidate multiplies the worst-case + time a failing turn spends retrying (#2693). + """ + if not isinstance(value, list): + return [] + entries: list[dict[str, str]] = [] + seen: set[tuple[str, str]] = set() + for item in value: + if not isinstance(item, dict): + continue + profile_id = str(item.get("profile_id") or "").strip() + model_id = str(item.get("model_id") or "").strip() + if not profile_id or not model_id: + continue + key = (profile_id, model_id) + if key in seen: + continue + seen.add(key) + entries.append({"profile_id": profile_id, "model_id": model_id}) + if len(entries) >= _MAX_FALLBACK_CANDIDATES: + break + return entries + + def _normalize_profile_api_format(profile: dict[str, Any]) -> bool: """Settle ``api_format`` and keep ``wire_api`` in step with it. @@ -478,6 +510,11 @@ class ModelCatalogService: for service_name in SERVICE_NAMES: service = services[service_name] profiles = service.setdefault("profiles", []) + if service_name == "llm": + # The ordered fallback chain (#2693). Malformed entries are + # dropped here so the runtime never has to defend against them; + # the bound keeps a failure from multiplying the retry budget. + service["fallbacks"] = _normalized_fallbacks(service.get("fallbacks")) for profile in profiles: profile.setdefault("id", f"{service_name}-profile-{uuid4().hex[:8]}") if service_name in CONNECTABLE_SERVICES and self._apply_connection( diff --git a/deeptutor/services/llm/factory.py b/deeptutor/services/llm/factory.py index 8592c484f..2bc07afb4 100644 --- a/deeptutor/services/llm/factory.py +++ b/deeptutor/services/llm/factory.py @@ -386,22 +386,34 @@ async def _complete_with_resolved_config( else allow_image_fallback ) - try: + async def _attempt(active_config: LLMConfig) -> Any: # Explicit-config callers own their isolated provider's lifecycle. lease = ( contextlib.nullcontext(provider) if provider is not None - else acquire_runtime_provider(config) + else acquire_runtime_provider(active_config) ) with lease as active_provider: - response = await active_provider.chat_with_retry( + return await active_provider.chat_with_retry( messages=request_messages, - model=config.model, - reasoning_effort=config.reasoning_effort, + model=active_config.model, + reasoning_effort=active_config.reasoning_effort, retry_delays=retry_delays, allow_image_fallback=image_fallback_enabled, **extra_kwargs, ) + + try: + from deeptutor.services.llm.failover import call_with_failover, chain_configured + + if provider is None and chain_configured(): + # A declared chain turns this one-shot call into an ordered attempt + # list; each candidate keeps its own retry budget (#2693 P2). + response = await call_with_failover( + lambda candidate: _attempt(candidate.config) + ) + else: + response = await _attempt(config) except Exception as exc: raise map_error(exc, provider=config.provider_name) from exc @@ -617,19 +629,36 @@ async def stream( async def _runner() -> None: nonlocal saw_output, in_think_block - try: + + async def _attempt(active_config: LLMConfig) -> Any: # The worker owns the lease, including cancellation by the reader. - with acquire_runtime_provider(config) as provider: - response = await provider.chat_stream_with_retry( + with acquire_runtime_provider(active_config) as provider: + return await provider.chat_stream_with_retry( messages=request_messages, - model=config.model, - reasoning_effort=config.reasoning_effort, + model=active_config.model, + reasoning_effort=active_config.reasoning_effort, on_content_delta=_on_content_delta, on_reasoning_delta=_on_reasoning_delta, retry_delays=retry_delays, allow_image_fallback=image_fallback_enabled, **extra_kwargs, ) + + try: + from deeptutor.services.llm.failover import ( + call_with_failover, + chain_configured, + ) + + if chain_configured(): + # Switching is only safe before any delta escaped; the attempt + # raises `partial_response=True` after output, which is not + # switchable, so this cannot splice two answers (#2693 P2). + response = await call_with_failover( + lambda candidate: _attempt(candidate.config) + ) + else: + response = await _attempt(config) if outcome is not None: outcome.finish_reason = str(response.finish_reason or "") outcome.usage = dict(response.usage or {}) diff --git a/tests/services/config/test_llm_fallbacks_catalog.py b/tests/services/config/test_llm_fallbacks_catalog.py new file mode 100644 index 000000000..911b28fe0 --- /dev/null +++ b/tests/services/config/test_llm_fallbacks_catalog.py @@ -0,0 +1,89 @@ +"""Catalog plumbing for the ordered fallback chain (#2693 P3 backend).""" + +from __future__ import annotations + +from deeptutor.api.routers.settings import _preserve_llm_fallbacks +from deeptutor.services.config.model_catalog import ( + ModelCatalogService, + _normalized_fallbacks, +) + + +def test_well_formed_entries_survive_and_duplicates_collapse() -> None: + assert _normalized_fallbacks( + [ + {"profile_id": "backup", "model_id": "m2"}, + {"profile_id": "backup", "model_id": "m2"}, + {"profile_id": " backup ", "model_id": " m3 "}, + {"profile_id": "", "model_id": "m4"}, + {"model_id": "m5"}, + "nonsense", + None, + ] + ) == [ + {"profile_id": "backup", "model_id": "m2"}, + {"profile_id": "backup", "model_id": "m3"}, + ] + + +def test_entries_are_bounded_and_non_list_values_are_ignored() -> None: + many = [{"profile_id": f"p{i}", "model_id": "m"} for i in range(10)] + + assert len(_normalized_fallbacks(many)) == 4 + assert _normalized_fallbacks({"profile_id": "x", "model_id": "y"}) == [] + assert _normalized_fallbacks(None) == [] + + +def test_catalog_save_keeps_the_chain(tmp_path) -> None: + service = ModelCatalogService(tmp_path / "model_catalog.json") + catalog = service.load() + catalog["services"]["llm"]["fallbacks"] = [ + {"profile_id": "backup", "model_id": "m2"} + ] + + saved = service.save(catalog) + + assert saved["services"]["llm"]["fallbacks"] == [ + {"profile_id": "backup", "model_id": "m2"} + ] + + +def test_catalog_save_drops_malformed_entries(tmp_path) -> None: + service = ModelCatalogService(tmp_path / "model_catalog.json") + catalog = service.load() + catalog["services"]["llm"]["fallbacks"] = [{"profile_id": "backup"}, "junk"] + + saved = service.save(catalog) + + assert saved["services"]["llm"]["fallbacks"] == [] + + +def test_apply_without_the_key_keeps_the_existing_chain() -> None: + current = { + "services": { + "llm": {"fallbacks": [{"profile_id": "backup", "model_id": "m2"}]} + } + } + + merged = _preserve_llm_fallbacks("llm", {"active_profile_id": "p"}, current) + + # The settings UI does not edit the chain; applying a provider must not + # delete a chain the operator configured by hand. + assert merged["fallbacks"] == [{"profile_id": "backup", "model_id": "m2"}] + assert merged["active_profile_id"] == "p" + + +def test_apply_with_the_key_replaces_the_chain() -> None: + current = {"services": {"llm": {"fallbacks": [{"profile_id": "old", "model_id": "m"}]}}} + + merged = _preserve_llm_fallbacks( + "llm", {"fallbacks": [{"profile_id": "new", "model_id": "m2"}]}, current + ) + + assert merged["fallbacks"] == [{"profile_id": "new", "model_id": "m2"}] + + +def test_other_services_are_untouched() -> None: + incoming = {"active_profile_id": "p"} + + assert _preserve_llm_fallbacks("embedding", incoming, {"services": {}}) == incoming