Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(wiki): demote recently-failed providers to the end of the fallback chain
Ruben Lütke7b0eb868f915
diff --git a/jarvis/memory/wiki/provider_chain.py b/jarvis/memory/wiki/provider_chain.pyindex 657f81c8f1..a0437278b2 100644--- a/jarvis/memory/wiki/provider_chain.py+++ b/jarvis/memory/wiki/provider_chain.py@@ -24,6 +24,7 @@ from __future__ import annotationsimport asyncioimport logging+import timefrom collections.abc import Callablefrom typing import Any@@ -32,6 +33,53 @@ from jarvis.memory.wiki import telemetrylog = logging.getLogger(__name__)+# How long a provider that just hard-failed (transport error, timeout, or+# unusable structured output) is demoted to the END of the chain instead of+# being retried first. Live 2026-07-18: three dead chain rungs (codex 429,+# antigravity malformed JSON, claude-api 401) were re-tried on EVERY wiki+# call, taxing each extraction with 10-15 s of doomed round-trips before a+# healthy provider answered. Demotion — never removal — keeps the AP-22+# honesty contract: when every healthy provider fails, the cooled ones are+# still tried before the chain gives up.+_PROVIDER_COOLDOWN_S = 900.0++# provider name -> (monotonic timestamp of last hard failure, short reason)+_provider_failures: dict[str, tuple[float, str]] = {}+++def _note_provider_failure(provider: str, reason: str) -> None:+ _provider_failures[provider] = (time.monotonic(), reason)+++def _in_cooldown(provider: str) -> bool:+ entry = _provider_failures.get(provider)+ if entry is None:+ return False+ if time.monotonic() - entry[0] >= _PROVIDER_COOLDOWN_S:+ del _provider_failures[provider]+ return False+ return True+++def reset_provider_failure_memory() -> None:+ """Forget every recorded provider failure (tests + explicit recovery)."""+ _provider_failures.clear()+++def _order_by_cooldown(+ chain: list[tuple[str, str | None]],+) -> tuple[list[tuple[str, str | None]], list[str]]:+ """Healthy providers first, recently-failed ones demoted to the end.++ Returns the reordered chain plus the demoted provider names (for the+ one honest log line). Relative order inside each group is preserved.+ """+ healthy: list[tuple[str, str | None]] = []+ cooled: list[tuple[str, str | None]] = []+ for entry in chain:+ (cooled if _in_cooldown(entry[0]) else healthy).append(entry)+ return healthy + cooled, [provider for provider, _model in cooled]+def _exception_summary(exc: Exception) -> str:"""Return diagnostic class/status metadata without persisting raw SDK text."""@@ -140,7 +188,16 @@ async def complete_with_fallback(failure_summaries: list[str] = []allowed_rejection_fallback: tuple[Any, str, str] | None = None- for index, (provider, model) in enumerate(chain):+ ordered, demoted = _order_by_cooldown(chain)+ if demoted and ordered != chain:+ log.info(+ "%s: demoting recently-failed provider(s) to the end of the "+ "chain: %s",+ label,+ ", ".join(demoted),+ )++ for index, (provider, model) in enumerate(ordered):try:brain = instantiate_curator_brain(registry, provider, model)except Exception as exc: # noqa: BLE001 — a bad provider must not abort the chain@@ -152,12 +209,16 @@ async def complete_with_fallback(detail,)failure_summaries.append(f"{provider} instantiate failed: {detail}")+ _note_provider_failure(provider, detail)continueif brain is None:failure_summaries.append(f"{provider} unavailable")continuetry:agg = await asyncio.wait_for(aggregate(brain.complete(request)), timeout=timeout_s)+ # Transport-level success: the provider is reachable again.+ # A validation rejection below re-records it as failed.+ _provider_failures.pop(provider, None)if validate is not None:try:rejection = validate(agg)@@ -172,6 +233,7 @@ async def complete_with_fallback(allow_last_rejection is not Noneand allow_last_rejection(rejection))+ last_in_chain = index == len(ordered) - 1if allowed:# Keep a semantically safe fallback (currently the# extractor's valid empty array) while still asking the@@ -191,7 +253,7 @@ async def complete_with_fallback(# If every later provider fails, their failure must not# erase this valid bounded answer.allowed_rejection_fallback = (agg, provider, rejection)- if index == len(chain) - 1 and allowed:+ if last_in_chain and allowed:log.info("%s: accepting final provider %s output after ""bounded second-opinion attempts (%s)",@@ -210,6 +272,7 @@ async def complete_with_fallback(failure_summaries.append(f"{provider} unusable output: {safe_rejection}")+ _note_provider_failure(provider, safe_rejection)try:telemetry.inc("wiki_provider_output_rejected")except Exception: # noqa: BLE001 - telemetry cannot break fallback@@ -228,6 +291,7 @@ async def complete_with_fallback(timeout_s,)failure_summaries.append(f"{provider} timeout ({timeout_s:.1f}s)")+ _note_provider_failure(provider, "timeout")continueexcept Exception as exc: # noqa: BLE001 — try the next family, never dead-end on onedetail = _exception_summary(exc)@@ -238,6 +302,7 @@ async def complete_with_fallback(detail,)failure_summaries.append(f"{provider} {detail}")+ _note_provider_failure(provider, detail)continueif allowed_rejection_fallback is not None:@@ -281,4 +346,5 @@ __all__ = ["build_wiki_provider_chain","complete_with_fallback","credential_ready_wiki_providers",+ "reset_provider_failure_memory",]diff --git a/tests/unit/memory/wiki/conftest.py b/tests/unit/memory/wiki/conftest.pyindex 291848ecaf..d5eda49bfa 100644--- a/tests/unit/memory/wiki/conftest.py+++ b/tests/unit/memory/wiki/conftest.py@@ -148,6 +148,22 @@ class FakePageRepository:# ---------------------------------------------------------------------[email protected](autouse=True)+def _reset_provider_failure_memory():+ """Isolate the provider-chain failure cooldown between tests.++ ``complete_with_fallback`` remembers hard provider failures in module+ state so live callers stop paying for dead chain rungs on every call.+ Tests that script failing providers must not demote those providers+ for every later test in the session.+ """+ from jarvis.memory.wiki.provider_chain import reset_provider_failure_memory++ reset_provider_failure_memory()+ yield+ reset_provider_failure_memory()++@pytest.fixturedef fake_repo() -> FakePageRepository:"""A fresh ``FakePageRepository`` per test."""diff --git a/tests/unit/memory/wiki/test_provider_chain.py b/tests/unit/memory/wiki/test_provider_chain.pyindex 9616c5ed73..0b40bf62c8 100644--- a/tests/unit/memory/wiki/test_provider_chain.py+++ b/tests/unit/memory/wiki/test_provider_chain.py@@ -347,6 +347,120 @@ async def test_two_valid_empty_opinions_stop_later_provider_attempts() -> None:assert reg.tried == ["openrouter", "antigravity", "gemini"]+# --- failure cooldown: dead rungs stop taxing every call ---------------------+++async def test_recently_failed_provider_is_demoted_behind_healthy_ones() -> None:+ reg = _FakeRegistry(fail_providers={"openrouter"})+ chain = [("openrouter", None), ("gemini", None)]++ first = await complete_with_fallback(+ registry=reg,+ chain=chain,+ request=object(),+ timeout_s=5.0,+ label="test",+ aggregate=_aggregate,+ )+ assert first is not None and first[1] == "gemini"+ assert reg.tried == ["openrouter", "gemini"] # the failure that arms the cooldown++ second = await complete_with_fallback(+ registry=reg,+ chain=chain,+ request=object(),+ timeout_s=5.0,+ label="test",+ aggregate=_aggregate,+ )+ assert second is not None and second[1] == "gemini"+ # Within the cooldown the dead provider is no longer tried FIRST — the+ # healthy one answers before the doomed round-trip is even attempted.+ assert reg.tried == ["openrouter", "gemini", "gemini"]+++async def test_cooldown_never_removes_the_last_resort() -> None:+ """AP-22 honesty: when every healthy provider fails, cooled ones still run."""+ reg = _FakeRegistry(fail_providers={"openrouter"})+ chain = [("openrouter", None), ("gemini", None)]++ await complete_with_fallback(+ registry=reg,+ chain=chain,+ request=object(),+ timeout_s=5.0,+ label="test",+ aggregate=_aggregate,+ ) # arms the cooldown for openrouter++ reg._fail = {"gemini"} # now the previously-healthy provider dies...+ reg.tried.clear()+ result = await complete_with_fallback(+ registry=reg,+ chain=chain,+ request=object(),+ timeout_s=5.0,+ label="test",+ aggregate=_aggregate,+ )+ # ...and the cooled provider, tried last, saves the call.+ assert result is not None and result[1] == "openrouter"+ assert reg.tried == ["gemini", "openrouter"]+++async def test_transport_success_clears_the_cooldown() -> None:+ from jarvis.memory.wiki import provider_chain as pc++ reg = _FakeRegistry(fail_providers={"openrouter"})+ chain = [("openrouter", None), ("gemini", None)]+ await complete_with_fallback(+ registry=reg,+ chain=chain,+ request=object(),+ timeout_s=5.0,+ label="test",+ aggregate=_aggregate,+ )+ assert pc._in_cooldown("openrouter")++ reg._fail = set() # provider recovered+ reg.tried.clear()+ result = await complete_with_fallback(+ registry=reg,+ chain=[("gemini", None), ("openrouter", None)],+ request=object(),+ timeout_s=5.0,+ label="test",+ aggregate=_aggregate,+ )+ assert result is not None and result[1] == "gemini"+ # gemini answered first, so openrouter stays cooled until it is needed…+ reg.tried.clear()+ result2 = await complete_with_fallback(+ registry=reg,+ chain=[("openrouter", None)],+ request=object(),+ timeout_s=5.0,+ label="test",+ aggregate=_aggregate,+ )+ # …a single-provider chain still tries it (demotion, never removal) and+ # the success clears the memory.+ assert result2 is not None and result2[1] == "openrouter"+ assert not pc._in_cooldown("openrouter")+++async def test_cooldown_expires_by_time(monkeypatch: pytest.MonkeyPatch) -> None:+ from jarvis.memory.wiki import provider_chain as pc++ clock = {"now": 1000.0}+ monkeypatch.setattr(pc.time, "monotonic", lambda: clock["now"])+ pc._note_provider_failure("openrouter", "429")+ assert pc._in_cooldown("openrouter")+ clock["now"] += pc._PROVIDER_COOLDOWN_S + 1+ assert not pc._in_cooldown("openrouter")++@pytest.mark.asyncioasync def test_provider_failures_never_expose_raw_exception_secrets(monkeypatch: pytest.MonkeyPatch,