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(realtime): Vertex Live 1011 resource exhaustion is spoken, not silently retried

Harald592d49d26ef4
diff --git a/jarvis/brain/provider_test.py b/jarvis/brain/provider_test.py
index 4b055a1cc5..ec8ae38f28 100644
--- a/jarvis/brain/provider_test.py
+++ b/jarvis/brain/provider_test.py
@@ -113,6 +113,14 @@ _RATE_LIMIT_TOKEN_MARKERS = (
"rate_limit_exceeded",
"rate limit exceeded",
"too many requests",
+ # Google Live / Vertex close the WebSocket with 1011 and this gRPC
+ # status when the region is at capacity or the per-minute quota is
+ # spent — "Please try again later", not a billing wall. The spending-
+ # cap twin still matches BILLING_LIMIT_MARKERS first ("spending cap")
+ # and stays no_credits. Reconnecting the same Live socket immediately
+ # is the 1011 storm this marker exists to stop.
+ "resource exhausted",
+ "resource_exhausted",
)
# Back-compat alias (anything importing the old private name keeps working).
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index 08669c50f4..cfa8f132d5 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -473,6 +473,22 @@ _CREDENTIAL_TERMINAL_STATUSES = frozenset(
_PROVIDER_FAILOVER_STATUSES = frozenset(
{MODEL_UNAVAILABLE, RATE_LIMITED, UNREACHABLE}
)
+# A throttle clears by itself, but NOT on the socket that just closed
+# with it. Immediate same-provider rebuild is the live 1011 "Resource
+# exhausted" reconnect storm: three silent retries, then listening as
+# if nothing happened. Cross to another family if one is ready; otherwise
+# end the call honestly (and speak, if classic voice cannot continue it).
+_NO_SAME_PROVIDER_RETRY_STATUSES = frozenset({RATE_LIMITED})
+
+
+def _retrying_this_provider_cannot_recover(status: str) -> bool:
+ """True when reopening the same adapter cannot clear ``status``."""
+ return (
+ status in _CREDENTIAL_TERMINAL_STATUSES
+ or status in _NO_SAME_PROVIDER_RETRY_STATUSES
+ )
+
+
def _pcm16_peak(pcm: bytes) -> int:
"""Peak absolute amplitude of little-endian int16 PCM (C-speed, no numpy)."""
usable = len(pcm) - (len(pcm) % 2)
@@ -1554,6 +1570,39 @@ _HANDSHAKE_FAILURE_MESSAGES: dict[str, dict[str, str]] = {
"No pude establecer la conexión de voz ahora mismo."
),
},
+ "rate_limited": {
+ "de": ( # i18n-allow: localized runtime voice output
+ "Die Sprachverbindung ist gerade überlastet. " # i18n-allow
+ "Bitte versuch es gleich noch einmal." # i18n-allow
+ ),
+ "en": (
+ "The voice connection is busy right now. "
+ "Please try again in a moment."
+ ),
+ "es": ( # i18n-allow: localized runtime voice output
+ "La conexión de voz está saturada ahora mismo. "
+ "Inténtalo de nuevo en un momento."
+ ),
+ },
+ "no_credits": {
+ "de": ( # i18n-allow: localized runtime voice output
+ "Das Sprachkontingent ist aufgebraucht, " # i18n-allow
+ "deshalb musste ich das Gespräch beenden." # i18n-allow
+ ),
+ "en": "The voice quota is used up, so I had to end the call.",
+ "es": ( # i18n-allow: localized runtime voice output
+ "Se agotó la cuota de voz, así que tuve que terminar la llamada."
+ ),
+ },
+ "dropped": {
+ "de": ( # i18n-allow: localized runtime voice output
+ "Die Sprachverbindung ist abgebrochen." # i18n-allow
+ ),
+ "en": "The voice connection dropped.",
+ "es": ( # i18n-allow: localized runtime voice output
+ "Se cortó la conexión de voz."
+ ),
+ },
}
@@ -1564,6 +1613,15 @@ def _handshake_failure_message(cause: str, language: str) -> str:
return variants.get(language) or variants["en"]
+def _live_call_failure_cause(status: str) -> str:
+ """Map a classified provider status to a spoken live-call ending."""
+ if status == RATE_LIMITED:
+ return "rate_limited"
+ if status == NO_CREDITS:
+ return "no_credits"
+ return "dropped"
+
+
def _delegate_bridge_texts(language: str) -> tuple[str, ...]:
return _DELEGATE_BRIDGE_TEXTS.get(language, _DELEGATE_BRIDGE_TEXTS["en"])
@@ -2546,6 +2604,11 @@ class RealtimeVoiceSession:
#: item REPLACES its entry instead of double-booking the utterance.
self._user_transcript_parts: list[tuple[str, str]] = []
self._input_turn_observed = False
+ # Sticky for the whole call. Per-turn flags reset at every boundary;
+ # classic fallback is refused once ANY turn has run, so a later 1011
+ # on idle-listen must still be spoken.
+ self._call_had_semantic_turn = False
+ self._failure_already_spoken = False
self._output_transcript: list[str] = []
# BUG-089: text-level self-echo backstop. The realtime path's acoustic
# gates leak on open speakers next to a built-in mic (macOS), so every
@@ -2714,6 +2777,8 @@ class RealtimeVoiceSession:
self._last_user_text = " ".join(
t for _, t in self._user_transcript_parts
).strip()
+ if self._last_user_text:
+ self._call_had_semantic_turn = True
# The turn has real text now; the live caption served its purpose.
self._last_user_text_preview = ""
if not self._first_final_monotonic:
@@ -3452,9 +3517,13 @@ class RealtimeVoiceSession:
self._blocked_credential_families.add(
self._credential_family(provider)
)
- elif terminal or (
- status in _PROVIDER_FAILOVER_STATUSES
- and self._has_viable_alternate(provider)
+ elif (
+ status in _NO_SAME_PROVIDER_RETRY_STATUSES
+ or terminal
+ or (
+ status in _PROVIDER_FAILOVER_STATUSES
+ and self._has_viable_alternate(provider)
+ )
):
self._blocked_provider_ids.add(self._provider_id(provider))
else:
@@ -3680,16 +3749,21 @@ class RealtimeVoiceSession:
if self.allow_classic_fallback:
return
lowered = summary.lower()
- cause = (
- "timeout"
- if (
- "timeouterror" in lowered
- or "budget" in lowered
- or "in time" in lowered
- )
- else "unavailable"
- )
+ status = classify_provider_error(summary)
+ if status == RATE_LIMITED:
+ cause = "rate_limited"
+ elif status == NO_CREDITS:
+ cause = "no_credits"
+ elif (
+ "timeouterror" in lowered
+ or "budget" in lowered
+ or "in time" in lowered
+ ):
+ cause = "timeout"
+ else:
+ cause = "unavailable"
spoken = _handshake_failure_message(cause, self._language)
+ self._failure_already_spoken = True
log.warning(
"realtime[%s] no voice engine could be opened and metered "
"fallback is refused — ending the call with a spoken reason "
@@ -3708,6 +3782,56 @@ class RealtimeVoiceSession:
exc_info=True,
)
+ def _call_has_committed_turn(self) -> bool:
+ """True when classic replay of this call would duplicate work.
+
+ The desktop pipeline refuses classic fallback once a user or assistant
+ turn has already happened. A failure in that window must be spoken:
+ the call is ending, not continuing elsewhere. Per-turn flags reset at
+ every boundary, so this is sticky for the whole call.
+ """
+ return bool(
+ self._call_had_semantic_turn
+ or self._input_turn_observed
+ or str(self._last_user_text or "").strip()
+ or self._user_transcript_parts
+ or self._output_transcript
+ or self._output_samples_sent > 0
+ or self._surface_spoke_this_turn
+ )
+
+ async def _announce_live_call_failure(self, status: str) -> None:
+ """Say why a live call is ending, when nobody else will.
+
+ Silent when the classic pipeline can still pick the same call up
+ (no committed turn, usage-billed fallback allowed) — announcing a
+ failure there would be false. Once a turn has run, classic replay
+ is refused and a silent hangup is the live 1011 Resource-exhausted
+ defect: ERROR lines in the log, then listening, nothing said.
+ """
+ if self._failure_already_spoken:
+ return
+ if self.allow_classic_fallback and not self._call_has_committed_turn():
+ return
+ cause = _live_call_failure_cause(status)
+ spoken = _handshake_failure_message(cause, self._language)
+ self._failure_already_spoken = True
+ log.warning(
+ "realtime[%s] live call ending with a spoken reason "
+ "(cause=%s status=%s)",
+ self.session_id,
+ cause,
+ status,
+ )
+ try:
+ await self._send_json(self._surface_speech_message(spoken))
+ except Exception: # noqa: BLE001 — the call still ends
+ log.warning(
+ "realtime[%s] could not voice the live-call failure notice",
+ self.session_id,
+ exc_info=True,
+ )
+
def _start_pump(self) -> None:
if self._pump_task is None or self._pump_task.done():
self._loop_lag.start()
@@ -6056,11 +6180,12 @@ class RealtimeVoiceSession:
status = classify_provider_error(message)
# A provider may label a failed response as recoverable
# even though its account says there is no money/quota or
- # the key is invalid. Retrying that same credential family
- # cannot recover and caused the live 1011 reconnect storm.
+ # the key is invalid — or the Live socket just closed
+ # with 1011 Resource exhausted. Retrying that same
+ # adapter cannot recover and caused the reconnect storm.
recoverable = (
declared_recoverable
- and status not in _CREDENTIAL_TERMINAL_STATUSES
+ and not _retrying_this_provider_cannot_recover(status)
)
failover_ready = False
if not recoverable:
@@ -6133,6 +6258,7 @@ class RealtimeVoiceSession:
)
self._failure_detail = message
self._failed.set()
+ await self._announce_live_call_failure(status)
await self._send_json(
{"type": "provider_error", "error": message}
)
@@ -6253,9 +6379,9 @@ class RealtimeVoiceSession:
message,
terminal=not same_provider_rebuild,
)
- credential_terminal = status in _CREDENTIAL_TERMINAL_STATUSES
+ retry_is_futile = _retrying_this_provider_cannot_recover(status)
can_recover = failover_ready or (
- same_provider_rebuild and not credential_terminal
+ same_provider_rebuild and not retry_is_futile
)
await self._publish_error(
type(exc).__name__,
@@ -6282,10 +6408,11 @@ class RealtimeVoiceSession:
f"{provider_id} transport failed ({status}); "
"switching realtime provider"
)
- if same_provider_rebuild and not credential_terminal:
+ if same_provider_rebuild and not retry_is_futile:
return message
self._failure_detail = message
self._failed.set()
+ await self._announce_live_call_failure(status)
try:
await self._send_json(
{"type": "provider_error", "error": message}
@@ -6564,9 +6691,11 @@ class RealtimeVoiceSession:
self._failure_detail = message
self._failed.set()
log.warning("realtime[%s] %s", self.session_id, message)
+ status = classify_provider_error(message)
await self._publish_error(
"RealtimeTransportDead", message, recoverable=False
)
+ await self._announce_live_call_failure(status)
try:
await self._send_json({"type": "provider_error", "error": message})
except Exception: # noqa: BLE001, S110 — surface may already be gone
@@ -12318,6 +12447,8 @@ class RealtimeVoiceSession:
self.active_provider,
)
self._output_samples_sent += len(pcm) // 2
+ if self._output_samples_sent > 0:
+ self._call_had_semantic_turn = True
rate = max(1, int(getattr(chunk, "sample_rate", 0) or 24_000))
if audible:
# Real audible provider audio: advance the echo guard's playback
diff --git a/tests/unit/brain/test_provider_test.py b/tests/unit/brain/test_provider_test.py
index ca6c95ca78..143066aeb8 100644
--- a/tests/unit/brain/test_provider_test.py
+++ b/tests/unit/brain/test_provider_test.py
@@ -11,6 +11,7 @@ Error strings below are VERBATIM from live probes against the real providers
(Anthropic 401, an OpenAI-compatible 403 out-of-credits, OpenAI missing-key
RuntimeError).
"""
+
from __future__ import annotations
import pytest
@@ -111,6 +112,32 @@ def test_gemini_monthly_spending_cap_is_no_credits(msg: str) -> None:
assert classify_provider_error(msg) == "no_credits"
+ "msg",
+ (
+ (
+ "1011 None. Resource exhausted. Please try again later. Please "
+ "refer to https://cloud.google.com/vertex-ai/generative-ai/docs/"
+ "model-reference/gemini-live"
+ ),
+ "APIError: 1011 None. Resource exhausted. Please try again later.",
+ 'ClientError: status: "RESOURCE_EXHAUSTED"',
+ ),
+)
+def test_google_live_resource_exhausted_without_billing_is_rate_limited(
+ msg: str,
+) -> None:
+ """Vertex/Gemini Live 1011 capacity throttle is not a spending cap.
+
+ Live 2026-08-20 21:15: vertex-live closed three times with this exact
+ wording, the classifier returned ``error``, and the rebuild-capable
+ transport treated it as a 1006-style wire death — silent reconnect
+ storm, then listening, nothing said. Billing markers must still win
+ when the same gRPC status carries a spending cap.
+ """
+ assert classify_provider_error(msg) == "rate_limited"
+
+
def test_plain_429_rate_limit_is_rate_limited() -> None:
msg = "RateLimitError: Error code: 429 - rate limit exceeded, please slow down"
assert classify_provider_error(msg) == "rate_limited"
diff --git a/tests/unit/brain/test_redacted_provider_error_tokens.py b/tests/unit/brain/test_redacted_provider_error_tokens.py
index 11b01b48d2..c014c4e3fa 100644
--- a/tests/unit/brain/test_redacted_provider_error_tokens.py
+++ b/tests/unit/brain/test_redacted_provider_error_tokens.py
@@ -31,6 +31,8 @@ from jarvis.brain.provider_test import (
"Codex app-server rejected thread/realtime/start: rate_limit_exceeded",
"{'error': {'type': 'rate_limit_exceeded'}}",
"Too many requests",
+ "1011 None. Resource exhausted. Please try again later.",
+ "status: RESOURCE_EXHAUSTED",
],
)
def test_throttle_token_without_an_http_status_is_rate_limited(message: str) -> None:
@@ -73,8 +75,6 @@ def test_no_throttle_token_can_dead_list_a_funded_account() -> None:
def test_an_unrecognised_redacted_refusal_stays_an_honest_error() -> None:
"""No token, no guess: the classifier must not invent an account state."""
assert (
- classify_provider_error(
- "Codex app-server rejected thread/realtime/start (code -32603)."
- )
+ classify_provider_error("Codex app-server rejected thread/realtime/start (code -32603).")
== "error"
)
diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.py
index cd2c0fe1e9..1eec161832 100644
--- a/tests/unit/realtime/test_session.py
+++ b/tests/unit/realtime/test_session.py
@@ -7551,6 +7551,128 @@ async def test_terminal_account_failure_without_alternate_does_not_reconnect():
await sess.end(reason="test")
+_VERTEX_LIVE_RESOURCE_EXHAUSTED = (
+ "1011 None. Resource exhausted. Please try again later. Please refer to "
+ "https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/"
+ "gemini-live"
+)
+
+
+async def test_live_resource_exhausted_does_not_reconnect_the_same_provider():
+ """Vertex Live 1011 Resource exhausted is a throttle, not a 1006.
+
+ Live 2026-08-20 21:15: the socket closed three times in 21 s, each
+ reconnect was silent, then the deck went back to listening. Immediate
+ same-provider rebuild is the storm; one honest failure is the fix.
+ """
+ vertex = RebuildingProvider(
+ [lambda: DyingSession([], error=_VERTEX_LIVE_RESOURCE_EXHAUSTED)]
+ )
+ vertex.name = "vertex-live"
+ vertex.credential_family = "vertex"
+ jsons = []
+ sess = RealtimeVoiceSession(
+ session_id="vertex-resource-exhausted-no-retry",
+ send_binary=lambda _data: asyncio.sleep(0),
+ send_json=lambda message: jsons.append(message) or asyncio.sleep(0),
+ provider=vertex,
+ config=_cfg(),
+ bus=None,
+ )
+
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ await asyncio.wait_for(sess.wait_finished(), timeout=2)
+
+ assert sess.failed
+ assert vertex.open_calls == 1
+ assert len([m for m in jsons if m.get("type") == "provider_error"]) == 1
+ assert [m for m in jsons if m.get("type") == "error_spoken"] == []
+ await sess.end(reason="test")
+
+
+async def test_live_resource_exhausted_mid_call_is_spoken():
+ """Once a turn has run, classic fallback is refused — the user must hear why."""
+ vertex = RebuildingProvider(
+ [
+ lambda: DyingSession(
+ [
+ RealtimeEvent(
+ type="input_transcript",
+ text="spiel etwas entspannendes", # i18n-allow: live forensic
+ is_final=True,
+ ),
+ ],
+ error=_VERTEX_LIVE_RESOURCE_EXHAUSTED,
+ )
+ ]
+ )
+ vertex.name = "vertex-live"
+ vertex.credential_family = "vertex"
+ jsons = []
+ sess = RealtimeVoiceSession(
+ session_id="vertex-resource-exhausted-spoken",
+ send_binary=lambda _data: asyncio.sleep(0),
+ send_json=lambda message: jsons.append(message) or asyncio.sleep(0),
+ provider=vertex,
+ config=_cfg(reply_language="de"),
+ bus=None,
+ )
+
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ await asyncio.wait_for(sess.wait_finished(), timeout=2)
+
+ assert sess.failed
+ assert vertex.open_calls == 1
+ spoken = [m for m in jsons if m.get("type") == "error_spoken"]
+ assert spoken, "a committed turn that dies of a throttle must be spoken"
+ texts = " ".join(str(m.get("text") or "") for m in spoken)
+ assert "überlastet" in texts # i18n-allow: spoken DE fixture
+ assert any(m.get("language") == "de" for m in spoken)
+ await sess.end(reason="test")
+
+
+async def test_live_resource_exhausted_crosses_family_without_retrying():
+ """A capacity throttle on one Live family must still cross to another."""
+ vertex = RebuildingProvider(
+ [lambda: DyingSession([], error=_VERTEX_LIVE_RESOURCE_EXHAUSTED)]
+ )
+ vertex.name = "vertex-live"
+ vertex.credential_family = "vertex"
+ openai = RebuildingProvider([lambda: StayOpenSession([])])
+ openai.name = "openai-realtime"
+ openai.credential_family = "openai"
+ jsons = []
+ sess = RealtimeVoiceSession(
+ session_id="vertex-resource-exhausted-cross-family",
+ send_binary=lambda _data: asyncio.sleep(0),
+ send_json=lambda message: jsons.append(message) or asyncio.sleep(0),
+ providers=[vertex, openai],
+ config=_cfg(),
+ bus=None,
+ )
+
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ try:
+ await _wait_until(lambda: sess.active_provider == "openai-realtime")
+
+ assert vertex.open_calls == 1
+ assert openai.open_calls == 1
+ assert not sess.failed
+ assert [m for m in jsons if m.get("type") == "provider_error"] == []
+ fallback = next(
+ m
+ for m in jsons
+ if m.get("type") == "provider_fallback"
+ and m.get("provider") == "vertex-live"
+ )
+ assert fallback["status"] == "rate_limited"
+ finally:
+ await sess.end(reason="test")
+
+
@pytest.mark.asyncio
async def test_audio_send_timeout_rebuilds_without_ending_the_call(monkeypatch):
"""A write-only stall and a later stale timeout preserve the live call."""
@@ -8953,6 +9075,27 @@ async def test_the_handshake_notice_names_the_cause_it_actually_hit():
await other_sess.end(reason="test")
+async def test_a_handshake_resource_exhausted_says_busy_not_unreachable():
+ """Vertex Live 1011 at open is a throttle, not a generic outage."""
+ jsons = []
+ sess = _no_metered_fallback_session(
+ _UnreachableProvider(
+ RuntimeError(
+ "1011 None. Resource exhausted. Please try again later."
+ )
+ ),
+ jsons=jsons,
+ language_cfg="en",
+ )
+ with pytest.raises(RuntimeError):
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+
+ notice = next(m for m in jsons if m.get("type") == "error_spoken")
+ assert "busy" in notice["text"].lower()
+ await sess.end(reason="test")
+
+
@pytest.mark.asyncio
async def test_the_handshake_notice_follows_the_pinned_reply_language():
"""One resolver decides, here as everywhere (CLAUDE.md §1 runtime rule 1).