Skip to content

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.

fix(brain): back off Gemini context-cache creation after a durable failure

rubenluetke10-beepd1c5b014de26
diff --git a/jarvis/plugins/brain/gemini.py b/jarvis/plugins/brain/gemini.py
index d33acc79ce..786e948fca 100644
--- a/jarvis/plugins/brain/gemini.py
+++ b/jarvis/plugins/brain/gemini.py
@@ -18,7 +18,9 @@ import json
import logging
import os
import re
+import time
from collections.abc import AsyncIterator
+from functools import lru_cache
from typing import Any
from uuid import uuid4
@@ -60,6 +62,16 @@ _MAX_CACHE_SLOTS = 4
# depending on the model). For smaller prefixes the API either rejects it or
# the cache isn't worth it — then we skip it and fall back to the direct path.
_MIN_CACHE_TOKENS = 4096
+# How long a failed cache create blocks the next attempt on this instance.
+# Every failure seen live is durable for far longer than one call — a free-tier
+# key has NO cache storage at all (429 "...FreeTier limit=0"), a Vertex route
+# without Application Default Credentials cannot create one either — yet the
+# attempt was repeated on EVERY brain call and cost ~0.7 s of round trip each
+# time before the direct path even started (2026-08-22 18:40: four attempts in
+# one delegated voice turn, all identical 429s). The direct path is fully
+# functional without the cache, so backing off only trades token cost for
+# latency the caller feels.
+_CACHE_CREATE_RETRY_AFTER_S = 600.0
# Runtime capability memory shared by every short-lived GeminiBrain instance.
# Curator calls deliberately instantiate a fresh brain per item, so
@@ -399,35 +411,97 @@ def _convert_exclusive_bounds(schema: dict[str, Any]) -> dict[str, Any]:
return out
-def _sanitize_for_gemini(schema: dict[str, Any]) -> dict[str, Any]:
- """Recursively removes OpenAI-specific fields from a JSON schema.
+# The documented Gemini schema subset, used when the installed google-genai
+# cannot be introspected. Field names AND their JSON aliases, because a tool
+# schema arrives in either spelling.
+_GEMINI_SCHEMA_KEYS_FALLBACK: frozenset[str] = frozenset({
+ "additionalProperties", "additional_properties", "anyOf", "any_of",
+ "default", "defs", "description", "enum", "example", "format", "items",
+ "maxItems", "max_items", "maxLength", "max_length", "maxProperties",
+ "max_properties", "maximum", "minItems", "min_items", "minLength",
+ "min_length", "minProperties", "min_properties", "minimum", "nullable",
+ "pattern", "properties", "propertyOrdering", "property_ordering", "ref",
+ "required", "title", "type",
+})
+
+
+@lru_cache(maxsize=1)
+def _gemini_schema_keys() -> frozenset[str]:
+ """Every key google-genai's ``types.Schema`` accepts, names and aliases.
+
+ Read off the installed library rather than spelled out here, because that
+ model IS the validator that rejects the request (``extra="forbid"``): its
+ own field set is the only honest answer, and a library version that gains
+ a keyword gains it here in the same step. A library that cannot be
+ introspected falls back to the documented subset above — never to "allow
+ everything", which is the failure this exists to prevent.
+ """
+ try:
+ from google.genai import types
+
+ fields = types.Schema.model_fields
+ keys = set(fields)
+ keys.update(f.alias for f in fields.values() if f.alias)
+ if keys:
+ return frozenset(keys)
+ except Exception as exc: # noqa: BLE001 — the fallback list is the answer
+ log.debug("gemini: schema field set not introspectable (%s) — using the fallback", exc)
+ return _GEMINI_SCHEMA_KEYS_FALLBACK
+
- Gemini's google-genai SDK validates Tool.functionDeclarations.parameters
- via Pydantic with `extra="forbid"`. Fields like `strict`/`input_examples`
- are OpenAI tool-use conventions and not allowed in Gemini's schema
- subset. Instead of delivering a tool call without tools, we strip those
- fields out — the tools themselves keep working unchanged, only the
- OpenAI-specific hints are gone.
+#: Keys whose value is one nested schema.
+_GEMINI_SCHEMA_VALUED: frozenset[str] = frozenset({"items"})
+#: Keys whose value maps FREE names to schemas. Their keys are property names
+#: chosen by whoever wrote the tool ("owner", "repo") and must never be judged
+#: against the allow-list — only their values are schemas.
+_GEMINI_SCHEMA_MAP_VALUED: frozenset[str] = frozenset({"properties", "defs"})
+#: Keys whose value is a list of schemas.
+_GEMINI_SCHEMA_LIST_VALUED: frozenset[str] = frozenset({"anyOf", "any_of"})
+
+
+def _sanitize_for_gemini(schema: dict[str, Any]) -> dict[str, Any]:
+ """Reduce a JSON schema to the subset google-genai's Schema model accepts.
+
+ Gemini validates ``Tool.functionDeclarations.parameters`` through Pydantic
+ with ``extra="forbid"``: ONE unknown key anywhere in ONE tool's schema
+ fails the WHOLE GenerateContent request, so the brain dies and the turn
+ falls through the entire provider chain. This has now happened four times
+ with a different key each time — OpenAI's ``strict``, Pydantic's ``$defs``,
+ an MCP tool's ``propertyNames``, and the GitHub MCP server's
+ ``x-mcp-header`` (live 2026-08-26: 81 validation errors, gemini down,
+ the front page's chat answered "I can't reach my provider").
+
+ So this keeps an ALLOW-list, not a block-list: a key the library does not
+ know is dropped whatever it is called. A block-list can never be complete
+ — any connected MCP server may ship any extension key it likes — and
+ every one of those four outages was a block-list that was.
+
+ The walk is schema-aware, which the allow-list makes mandatory: under
+ ``properties`` the keys are property NAMES a tool author chose, and
+ judging those against the allow-list would delete the parameters
+ themselves. Values that are data rather than schemas (``example``,
+ ``default``, ``enum``) are passed through untouched.
Exclusive numeric bounds (``exclusiveMinimum``/``exclusiveMaximum`` from
Pydantic ``Field(gt=...)``/``Field(lt=...)``) are first converted to the
- inclusive ``minimum``/``maximum`` Gemini accepts, then the exclusive key is
- stripped via ``_GEMINI_FORBIDDEN_SCHEMA_KEYS``.
+ inclusive ``minimum``/``maximum`` Gemini accepts, then dropped.
+ ``_GEMINI_FORBIDDEN_SCHEMA_KEYS`` still runs in front of the allow-list,
+ for the keys the model accepts but the API does not.
"""
if not isinstance(schema, dict):
return schema
schema = _convert_exclusive_bounds(schema)
+ allowed = _gemini_schema_keys()
out: dict[str, Any] = {}
for k, v in schema.items():
- if k in _GEMINI_FORBIDDEN_SCHEMA_KEYS:
+ if k in _GEMINI_FORBIDDEN_SCHEMA_KEYS or k not in allowed:
continue
- if isinstance(v, dict):
+ if k in _GEMINI_SCHEMA_MAP_VALUED and isinstance(v, dict):
+ out[k] = {name: _sanitize_for_gemini(sub) for name, sub in v.items()}
+ elif k in _GEMINI_SCHEMA_LIST_VALUED and isinstance(v, list):
+ out[k] = [_sanitize_for_gemini(sub) if isinstance(sub, dict) else sub for sub in v]
+ elif k in _GEMINI_SCHEMA_VALUED and isinstance(v, dict):
out[k] = _sanitize_for_gemini(v)
- elif isinstance(v, list):
- out[k] = [
- _sanitize_for_gemini(item) if isinstance(item, dict) else item
- for item in v
- ]
else:
out[k] = v
return out
@@ -723,6 +797,9 @@ class GeminiBrain:
# multi-slot map lets each recurring variant keep its own server-side
# cache; insertion-ordered, oldest evicted beyond the cap.
self._cache_slots: dict[tuple[str, str], str] = {}
+ # Monotonic deadline before which no cache create is attempted again
+ # (see _CACHE_CREATE_RETRY_AFTER_S).
+ self._cache_create_blocked_until = 0.0
def _resolve_endpoint(self) -> Any:
"""Endpoint + credential for this brain's own provider identity."""
@@ -803,6 +880,14 @@ class GeminiBrain:
approx_tokens, _MIN_CACHE_TOKENS,
)
return None
+ remaining = self._cache_create_blocked_until - time.monotonic()
+ if remaining > 0:
+ log.debug(
+ "Gemini cache create skipped: the last attempt failed, retrying "
+ "in %.0fs — direct path",
+ remaining,
+ )
+ return None
try:
from google.genai import types as _genai_types
@@ -824,7 +909,15 @@ class GeminiBrain:
self._cached_content_name, approx_tokens)
return self._cached_content_name
except Exception as exc: # noqa: BLE001
- log.warning("Gemini cache create failed, falling back to direct: %s", exc)
+ self._cache_create_blocked_until = (
+ time.monotonic() + _CACHE_CREATE_RETRY_AFTER_S
+ )
+ log.warning(
+ "Gemini cache create failed, falling back to direct for the next "
+ "%.0fs: %s",
+ _CACHE_CREATE_RETRY_AFTER_S,
+ exc,
+ )
return None
def invalidate_cache(self) -> None:
diff --git a/tests/unit/brain/test_gemini_cache_slots.py b/tests/unit/brain/test_gemini_cache_slots.py
index 433fceae2e..8e39a9865c 100644
--- a/tests/unit/brain/test_gemini_cache_slots.py
+++ b/tests/unit/brain/test_gemini_cache_slots.py
@@ -91,3 +91,42 @@ async def test_invalidate_cache_drops_all_slots() -> None:
# The next call must CREATE again, never serve a dead id from a slot.
await provider._ensure_cache(_BIG, _tools("full-set"))
assert caches.creates == 3
+
+
+class _RefusingCaches:
+ """A server that cannot create caches for this key (free tier: limit=0)."""
+
+ def __init__(self) -> None:
+ self.creates = 0
+
+ async def create(self, *, model: str, config: Any) -> Any:
+ self.creates += 1
+ raise RuntimeError(
+ "429 RESOURCE_EXHAUSTED. TotalCachedContentStorageTokensPerModelFreeTier "
+ "limit exceeded: limit=0, requested=31250"
+ )
+
+
+async def test_a_failed_create_is_not_retried_on_every_call(monkeypatch) -> None:
+ """Live 2026-08-22 18:40: four identical 429s inside ONE delegated voice turn.
+
+ Each attempt cost ~0.7 s before the direct path even started. A failure is
+ remembered for ``_CACHE_CREATE_RETRY_AFTER_S`` and only then retried.
+ """
+ from jarvis.plugins.brain import gemini as gemini_module
+
+ provider = GeminiBrain(model="gemini-3.5-flash")
+ caches = _RefusingCaches()
+ provider._client = SimpleNamespace(aio=SimpleNamespace(caches=caches))
+ clock = {"now": 1000.0}
+ monkeypatch.setattr(gemini_module.time, "monotonic", lambda: clock["now"])
+
+ assert await provider._ensure_cache(_BIG, _tools("full-set")) is None
+ assert await provider._ensure_cache(_BIG, _tools("full-set")) is None
+ assert await provider._ensure_cache(_BIG, None) is None
+ assert caches.creates == 1, "the refusal must not be re-paid on every call"
+
+ clock["now"] += gemini_module._CACHE_CREATE_RETRY_AFTER_S + 1.0
+ assert await provider._ensure_cache(_BIG, _tools("full-set")) is None
+ assert caches.creates == 2, "after the backoff the cache is tried again"