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): review follow-ups for the thinking_config 400 recovery — budget-scoped memory, cache-safe retry, BUG-109 register entry

Personal Jarvis Maintainer2c774f88f93e
diff --git a/docs/BUGS.md b/docs/BUGS.md
index f38ed31758..5fffb738d0 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -7483,3 +7483,48 @@ The user hung up via hotkey at 11:55:11.
Related: BUG-102 (topology refresh), BUG-104 (rebuild seed), BUG-106
(the answer itself also missed the Gulfstream G800, in service since
2025 — fact-quality family, tracked there).
+
+## BUG-109: gemini-3.6-flash rejects the forced thinking_budget=0 with a parameterless 400 — every delegated realtime fallback turn bricked (HIGH, FIXED 2026-07-21)
+
+**Symptom (live 2026-07-21 18:27–18:33, sessions `62965e5d`, `dcd9d16a`,
+`43ca9ad6`).** In a realtime call, whenever the provider (Gemini Live) went
+silent after the user finished speaking, the deterministic-delegate fallback
+correctly detected the missing input boundary ("provider input boundary
+missing after 1.50s of stable local transcript") and dispatched the Brain
+chain — but EVERY gemini attempt died with `400 INVALID_ARGUMENT.
+"Request contains an invalid argument."`, OpenAI was quota-dead (429), so
+the user heard the canned outage phrase (or a stale/garbled provider line)
+instead of an answer. Perceived as: "Jarvis keeps listening after I finish
+my sentence and never starts thinking."
+
+**Root cause (reproduced 1:1 against the live API).** The router/tool tier
+hard-caps `thinking_budget = 0` (BUG-LATENCY mandate,
+`jarvis/brain/manager.py`). `gemini-3.5-flash` accepts that;
+`gemini-3.6-flash` — the live install's configured `tool_model` — rejects
+`thinking_config(thinking_budget=0)` with the PARAMETERLESS 400 above: no
+field name, no "thinking" token. The existing capability recovery
+(`_is_thinking_config_rejected_error`) requires "thinking" in the message,
+so it never matched, no retry happened, and the tier failed terminally on
+every call. Repro matrix: `plain`/`tools`/`system` all OK on 3.6;
+`thinking0` and `tools+thinking0` 400 on 3.6; all six OK on 3.5.
+
+**Fix (1299c063 + review follow-up).** In
+`jarvis/plugins/brain/gemini.py`: a parameterless 400 INVALID_ARGUMENT with
+`thinking_config` on the wire retries once without the field (capability
+probe, AP-21 — never a model-name pin). Blame is only remembered (per
+instance, per REJECTED BUDGET VALUE — brain instances are cached per
+(provider, model) and shared across tiers) once the retried request is
+accepted; an unrelated 400 propagates unchanged and disables nothing. If a
+`cached_content` reference was also on the wire, the retry clears and
+invalidates it too (a differently-worded dead-cache 400 must not survive
+the `attempt == 1` gate of the BUG-019 recovery) and then blames nothing —
+with two variables changed the accepted retry proves nothing.
+
+**Guards:** `tests/unit/brain/test_gemini_reasoning_effort.py` (
+`test_parameterless_400_recovers_and_is_remembered`,
+`test_unrelated_400_still_propagates_and_forgets_nothing`,
+`test_generic_400_with_live_cache_clears_cache_and_blames_nothing`).
+
+Related: BUG-019 (stale-cache recovery in the same except block), AP-21
+(capability probes), AP-22 (the single-provider brick this produced live:
+gemini 400 + openai 429 left zero reachable tool-tier families).
diff --git a/jarvis/plugins/brain/gemini.py b/jarvis/plugins/brain/gemini.py
index f188ba4b58..084cfedd16 100644
--- a/jarvis/plugins/brain/gemini.py
+++ b/jarvis/plugins/brain/gemini.py
@@ -89,33 +89,31 @@ def _is_stale_context_cache_error(exc: Exception) -> bool:
def _is_thinking_config_rejected_error(exc: Exception) -> bool:
- """True when the API rejected the ``thinking_config`` itself.
+ """True when the API rejected the ``thinking_config`` BY NAME — definitive.
Thinking-mandatory models answer 400 when asked to disable thinking
- (``thinking_budget=0``), in two message shapes both seen live:
-
- * The SPECIFIC form — "Budget 0 is invalid. This model only works in
- thinking mode." (thinking-mandatory Pro class, 2026-07-16).
- * The GENERIC form — a bare "Request contains an invalid argument." /
- INVALID_ARGUMENT with NO "thinking" or "budget" token at all (live
- forensic 2026-07-23: ``gemini-3.6-flash`` 400'd every Computer-Use step
- this way; the vision chain then fell through to a blind last-resort
- brain that burned ~68 s and the user heard the misleading "couldn't get
- a valid screen-control response"). Matching only the specific form left
- the generic one unrecovered.
+ (``thinking_budget=0``) with a message that names it: "Budget 0 is invalid.
+ This model only works in thinking mode." (thinking-mandatory Pro class,
+ 2026-07-16). Because the message points straight at the budget, the caller
+ may retire it immediately — no further evidence needed.
+
+ The bare, parameterless "Request contains an invalid argument." 400 — no
+ "thinking"/"budget" token at all (live forensic 2026-07-23:
+ ``gemini-3.6-flash`` 400'd every Computer-Use step this way) — is
+ deliberately NOT matched here. It is ambiguous: it could equally be a
+ dead-cache or an unrelated rejection. That shape is caught by
+ ``_is_generic_invalid_argument_error`` and STILL recovered, but blame is
+ assigned by the retry itself — dropping the field and having the request
+ accepted is the proof. Keeping the two apart is what lets an unrelated 400
+ (or a two-variable cache+budget retry) blame nothing permanently.
The concrete exception class differs across ``google-genai`` versions, so
- we match on the message. The caller consults this ONLY when a
- ``thinking_config`` is actually on the wire and no delta has been emitted
- yet, so treating a pre-stream INVALID_ARGUMENT as a thinking rejection is
- safe: the retry merely drops ``thinking_config``; an unrelated
- invalid-argument still fails the retry and degrades normally. A capability
- probe, never a model-name pin (AP-21).
+ we match on the message. A capability probe, never a model-name pin (AP-21).
"""
msg = str(exc).lower()
- if "thinking" in msg:
- return "budget" in msg or "invalid" in msg or "thinking mode" in msg
- return "invalid_argument" in msg or "invalid argument" in msg
+ if "thinking" not in msg:
+ return False
+ return "budget" in msg or "invalid" in msg or "thinking mode" in msg
def _is_generic_invalid_argument_error(exc: Exception) -> bool:
@@ -555,9 +553,14 @@ class GeminiBrain:
self._thinking_budget = thinking_budget
# 2026-07-21: some models reject ``thinking_config`` with a
# parameterless 400 ("Request contains an invalid argument."). Once
- # a retry without the field proves that blame, remember it for this
- # instance so later turns skip the doomed extra round trip.
- self._thinking_config_unsupported = False
+ # a retry without the field proves that blame, remember the REJECTED
+ # BUDGET VALUE so later turns skip the doomed extra round trip.
+ # Scoped per budget, not a whole-instance kill switch: brain
+ # instances are cached per (provider, model) and shared across
+ # tiers, so a rejection of the router's forced ``budget=0`` must
+ # not disable a different tier's positive budget on the same
+ # instance.
+ self._rejected_thinking_budgets: set[int] = set()
# Latency-Sprint-2: context-cache name (lazily created on the first
# call with system+tools). Key: (system_hash, tools_hash) → cache_name.
# ``_cached_content_name``/``_cache_signature`` hold the most recently
@@ -776,7 +779,7 @@ class GeminiBrain:
effective_thinking_budget = 0
if (
effective_thinking_budget is not None
- and not self._thinking_config_unsupported
+ and effective_thinking_budget not in self._rejected_thinking_budgets
):
try:
from google.genai import types as _genai_types
@@ -886,10 +889,13 @@ class GeminiBrain:
# the from-scratch retry yields no duplicate chunks.
attempt = 0
yielded_delta = False
- # Set when a parameterless 400 forced a retry without
- # ``thinking_config``; promoted to the instance flag only once the
- # retried request is accepted (that acceptance IS the blame proof).
- pending_thinking_config_blame = False
+ # The budget value stripped by a parameterless-400 retry; promoted
+ # into ``_rejected_thinking_budgets`` only once the retried request
+ # is accepted (that acceptance IS the blame proof). The probe
+ # assumes Gemini request validation is deterministic for a fixed
+ # payload — a flaky 400 that clears on the retry for unrelated
+ # reasons would mis-blame, but validation errors are not transient.
+ pending_rejected_budget: int | None = None
while True:
attempt += 1
try:
@@ -980,16 +986,17 @@ class GeminiBrain:
}
if final_usage is not None:
yield BrainDelta(usage=final_usage)
- if pending_thinking_config_blame:
+ if pending_rejected_budget is not None:
# The retry without ``thinking_config`` was accepted, so
# the parameterless 400 is attributed to it. Later turns
- # on this instance skip the field (and the extra 400)
+ # on this instance skip that budget (and the extra 400)
# entirely.
- self._thinking_config_unsupported = True
+ self._rejected_thinking_budgets.add(pending_rejected_budget)
log.info(
- "Gemini model %s accepts requests only without "
- "thinking_config — omitting it from now on",
+ "Gemini model %s rejects thinking_budget=%d — "
+ "omitting it from now on",
self._model,
+ pending_rejected_budget,
)
return
except Exception as exc: # noqa: BLE001 — BUG-019 stale-cache recovery
@@ -1033,13 +1040,39 @@ class GeminiBrain:
"Gemini model %s rejected thinking_config — retrying "
"once without it: %s", self._model, exc,
)
+ rejected_budget = getattr(
+ config_dict.get("thinking_config"),
+ "thinking_budget",
+ None,
+ )
config_dict.pop("thinking_config", None)
- if thinking_config_blamed:
- # The message names the thinking config — no further
- # evidence needed.
- self._thinking_config_unsupported = True
- else:
- pending_thinking_config_blame = True
+ # A generic 400 while a context-cache reference is on the
+ # wire could ALSO be a differently-worded dead-cache
+ # rejection this branch would otherwise consume — and the
+ # ``attempt == 1`` gate above would then keep the poisoned
+ # cache name forever (BUG-019's exact symptom). Clear it
+ # alongside, and skip blame promotion: with two variables
+ # changed the retry proves nothing about the budget.
+ dropped_cache = False
+ if (
+ not thinking_config_blamed
+ and cache_name
+ and "cached_content" in config_dict
+ ):
+ self.invalidate_cache()
+ config_dict.pop("cached_content", None)
+ if system_text:
+ config_dict["system_instruction"] = system_text
+ if tools_payload:
+ config_dict["tools"] = tools_payload
+ dropped_cache = True
+ if isinstance(rejected_budget, int):
+ if thinking_config_blamed:
+ # The message names the thinking config — no
+ # further evidence needed.
+ self._rejected_thinking_budgets.add(rejected_budget)
+ elif not dropped_cache:
+ pending_rejected_budget = rejected_budget
continue
if (
not yielded_delta
diff --git a/tests/unit/brain/test_gemini_reasoning_effort.py b/tests/unit/brain/test_gemini_reasoning_effort.py
index 436c1b832e..8df17df1a6 100644
--- a/tests/unit/brain/test_gemini_reasoning_effort.py
+++ b/tests/unit/brain/test_gemini_reasoning_effort.py
@@ -48,11 +48,13 @@ class _FakeGeminiClient:
"works in thinking mode."
),
reject_thinking_generic: bool = False,
+ reject_everything_generic: bool = False,
) -> None:
self.calls: list[dict[str, Any]] = []
self.reject_thinking = reject_thinking
self.reject_message = reject_message
self.reject_thinking_generic = reject_thinking_generic
+ self.reject_everything_generic = reject_everything_generic
self.aio = SimpleNamespace(models=self)
async def generate_content_stream(
@@ -66,8 +68,11 @@ class _FakeGeminiClient:
if self.reject_thinking and config.get("thinking_config") is not None:
raise RuntimeError(self.reject_message)
if (
- self.reject_thinking_generic
- and config.get("thinking_config") is not None
+ self.reject_everything_generic
+ or (
+ self.reject_thinking_generic
+ and config.get("thinking_config") is not None
+ )
):
# The parameterless rejection shape gemini-3.6-flash produced
# live 2026-07-21 — no field name, no "thinking" token.
@@ -212,3 +217,84 @@ async def test_parameterless_400_recovers_and_is_remembered() -> None:
await _drain(provider.complete(_request("none")))
assert len(fake.calls) == 3
assert "thinking_config" not in fake.calls[2]
+
+
+async def test_unrelated_400_still_propagates_and_forgets_nothing() -> None:
+ """A parameterless 400 whose retry ALSO fails is not the thinking
+ config's fault: the error must propagate and the instance must NOT stop
+ sending ``thinking_config`` on later turns."""
+ provider = GeminiBrain(model="gemini-3.6-flash")
+ fake = _FakeGeminiClient(reject_everything_generic=True)
+ provider._client = fake # type: ignore[assignment]
+
+ with pytest.raises(RuntimeError, match="invalid argument"):
+ await _drain(provider.complete(_request("none")))
+
+ # One original attempt + one blame-probe retry, then the error surfaced.
+ assert len(fake.calls) == 2
+
+ fake.reject_everything_generic = False
+ await _drain(provider.complete(_request("none")))
+ assert fake.calls[2].get("thinking_config") is not None, (
+ "an unproven blame must not permanently disable thinking_config"
+ )
+
+
+async def test_generic_400_with_live_cache_clears_cache_and_blames_nothing(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A parameterless 400 while a ``cached_content`` reference is on the
+ wire could be a differently-worded dead-cache rejection: the recovery
+ must clear the cache reference alongside ``thinking_config`` (else the
+ poisoned name survives forever — BUG-019's symptom) and must NOT blame
+ the thinking budget, because with two variables changed the accepted
+ retry proves nothing."""
+ monkeypatch.setenv("JARVIS_GEMINI_CONTEXT_CACHE", "1")
+
+ system_text = "X" * (4096 * 4 + 100) # above the _MIN_CACHE_TOKENS floor
+ provider = GeminiBrain(model="gemini-3.6-flash")
+ fake = _FakeGeminiClient()
+ provider._client = fake # type: ignore[assignment]
+ provider._cached_content_name = "cachedContents/dead-id"
+ provider._cache_signature = (str(hash(system_text)), "")
+
+ async def _reject_cache_or_thinking(
+ *, model: str, contents: list[Any], config: dict[str, Any]
+ ) -> Any:
+ fake.calls.append(dict(config))
+ if config.get("cached_content") or config.get("thinking_config"):
+ raise RuntimeError(
+ "400 INVALID_ARGUMENT. {'error': {'code': 400, 'message': "
+ "'Request contains an invalid argument.', 'status': "
+ "'INVALID_ARGUMENT'}}"
+ )
+
+ async def _stream() -> AsyncIterator[Any]:
+ yield SimpleNamespace(text="OK", candidates=[], usage_metadata=None)
+
+ return _stream()
+
+ fake.generate_content_stream = _reject_cache_or_thinking # type: ignore[method-assign]
+
+ req = BrainRequest(
+ messages=(BrainMessage(role="user", content="ping"),),
+ max_tokens=320,
+ system=system_text,
+ reasoning_effort="none", # type: ignore[arg-type]
+ )
+ deltas = await _drain(provider.complete(req))
+
+ assert len(fake.calls) == 2
+ assert fake.calls[0].get("cached_content") == "cachedContents/dead-id"
+ assert fake.calls[0].get("thinking_config") is not None
+ assert "cached_content" not in fake.calls[1]
+ assert "thinking_config" not in fake.calls[1]
+ assert any(d.content for d in deltas), "recovered stream must yield text"
+ assert provider._cached_content_name is None, (
+ "the possibly-dead cache reference must be invalidated"
+ )
+ assert provider._rejected_thinking_budgets == set(), (
+ "a two-variable retry must not blame the thinking budget"
+ )