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): Gemini 3.1 rejected the rebuild's conversation seed — every transport rebuild died with 1007 and the call hung up mid-sentence (BUG-104)

Personal Jarvis Maintainer39a2d95d2da2
diff --git a/docs/BUGS.md b/docs/BUGS.md
index 8c69e6e3b1..3e82912fcd 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -7167,3 +7167,50 @@ the write/read/delete backend probe runs THROUGH the wrapper, proving the
vault lifecycle. Linux-simulation tests force `sys.platform = "linux"` so
they can never route into the real Mac Keychain. Guards:
`tests/unit/core/test_keychain_bundle.py`.
+
+## BUG-104: Gemini 3.1 rejects the rebuild's conversation seed — every transport rebuild dies with 1007 and the call hangs up mid-sentence (CRITICAL, FIXED 2026-07-21)
+
+**Live incident 2026-07-21 08:35 (Mac, realtime session `8f1ea55c`).** Two
+turns in, Gemini's server dropped the Live WebSocket (`1006 abnormal
+closure` — the known BUG-071 idle-drop right after a long surface-TTS
+fallback). The in-place rebuild (BUG-071) reconnected fine, then the
+BUG-088 history seed replayed the call transcript via
+`send_client_content(turns=..., turn_complete=False)` — and Gemini killed
+the fresh connection with `1007 Request contains an invalid argument`
+~70 ms after `ready`. All three rebuilds in the 120 s window failed
+identically, `RealtimeTransportDead` fired, and the call ended with
+`hangup_reason=error` while the user was mid-sentence; the words spoken
+during the death loop were never transcribed (the transport was already
+dead, and the committed-turn guard rightly refuses classic-voice replay).
+
+**Root cause — two API-contract violations in the seed, plus a blind
+guard.** Gemini 3.1 Live (`gemini-3.1-flash-live-preview`) accepts
+`client_content` ONLY as *declared* initial history: (1) the connect config
+must set `history_config.initial_history_in_client_content=True`, and
+(2) the server processes `client_content` until one arrives with
+`turn_complete=True` — only after that boundary is `realtime_input`
+(microphone audio) legal. The seed did neither. And because
+`send_client_content` succeeds client-side (the rejection arrives as a
+server-side close), the seed's fail-open `try/except` never saw the
+failure — the rebuild loop re-poisoned every fresh connection until the
+budget was gone. The seed path had never run on this install before
+(first-ever rebuild); it was only ever validated against fakes.
+
+**Fix (3 layers).**
+1. `gemini_live.open_session` declares
+ `history_config(initial_history_in_client_content=True)` whenever a
+ non-empty history seed is present — probed via the SDK's
+ `types.HistoryConfig` capability, never a model-name pin (AP-21); an SDK
+ without it skips the seed (amnesiac but alive).
+2. `_seed_history` ends the seed with `turn_complete=True` (closing the
+ declared history phase so microphone audio becomes legal), also when
+ every entry filtered out, and best-effort closes the phase even when
+ seed construction fails.
+3. `session._rebuild_transport` treats a second rapid death inside the
+ rebuild window as seed poisoning and retries WITHOUT the seed — a
+ server-side rejection can never again burn the whole rebuild budget,
+ for any provider adapter.
+
+Guards: `tests/unit/realtime/test_gemini_live.py` (seed declaration +
+terminator + SDK-capability skip + blank-history terminator),
+`tests/unit/realtime/test_session.py::test_second_rapid_rebuild_drops_the_poisoned_history_seed`.
diff --git a/jarvis/plugins/realtime/gemini_live.py b/jarvis/plugins/realtime/gemini_live.py
index 6d2154d7c1..b80d611b0f 100644
--- a/jarvis/plugins/realtime/gemini_live.py
+++ b/jarvis/plugins/realtime/gemini_live.py
@@ -277,11 +277,22 @@ async def _seed_history(session: Any, history: tuple[dict[str, str], ...]) -> No
Gemini fixes conversation state per connection: a mid-call transport
rebuild (session limit GoAway, 1006 abnormal closure) used to start the
fresh session with total amnesia, so follow-up questions lost their
- grounding (BUG-088). ``send_client_content`` with ``turn_complete=False``
- is Gemini's documented initial-history channel — it appends context
- without triggering a response generation. Seeding fails open: a session
- without history is exactly today's behavior and strictly better than no
- session at all.
+ grounding (BUG-088).
+
+ Gemini 3.1 Live accepts ``client_content`` ONLY as declared initial
+ history: the connection config must set
+ ``history_config.initial_history_in_client_content`` (done in
+ ``open_session``) and the server then processes ``client_content``
+ messages *until* one arrives with ``turn_complete=True`` — only after
+ that boundary is ``realtime_input`` (microphone audio) legal. The first
+ seed implementation sent ``turn_complete=False`` without the
+ declaration; the server closed every rebuilt connection with ``1007
+ invalid argument`` ~70 ms after ready, three rebuilds burned the whole
+ recovery window, and the call ended reason=error mid-sentence (live
+ incident 2026-07-21 08:35, BUG-104).
+
+ Seeding still fails open: a session without history is exactly the
+ pre-BUG-088 behavior and strictly better than no session at all.
"""
if not history:
return
@@ -305,9 +316,12 @@ async def _seed_history(session: Any, history: tuple[dict[str, str], ...]) -> No
parts=[types.Part(text=text)],
)
)
- if not turns:
- return
- await session.send_client_content(turns=turns, turn_complete=False)
+ # turn_complete=True closes the declared initial-history phase even
+ # when every entry was filtered out — the connection would otherwise
+ # sit in history mode and reject the first microphone frame.
+ await session.send_client_content(
+ turns=turns or None, turn_complete=True
+ )
except Exception: # noqa: BLE001 — an amnesiac session beats a dead call
log.warning(
"gemini-live: seeding %d prior turns into the fresh session "
@@ -315,6 +329,13 @@ async def _seed_history(session: Any, history: tuple[dict[str, str], ...]) -> No
len(history),
exc_info=True,
)
+ # The connection already declared initial-history mode; exit it even
+ # without content, otherwise the first microphone frame is the next
+ # invalid argument.
+ try:
+ await session.send_client_content(turns=None, turn_complete=True)
+ except Exception: # noqa: BLE001, S110 — transport is likely dead
+ pass
# Gemini function_declarations accept only an OpenAPI-style schema subset.
@@ -421,18 +442,42 @@ class GeminiLiveProvider:
voice_name=voice
)
)
+ # An unset window (None/0) omits realtime_input_config entirely so
+ # Gemini's native automatic activity detection decides the turn end;
+ # only an explicit override forces a fixed silence window.
+ silence_ms = getattr(cfg, "silence_duration_ms", None)
+ # Gemini 3.1 rejects client_content (1007, the whole connection dies)
+ # unless the setup declares it as initial history — so the declaration
+ # and the seed travel together, and neither happens without the other
+ # (BUG-104). Probed by SDK capability, never a model-name pin (AP-21):
+ # an SDK without HistoryConfig cannot seed legally, so it opens an
+ # amnesiac session instead of a doomed one.
+ history = tuple(getattr(cfg, "history", ()) or ())
+ history_config_cls = getattr(types, "HistoryConfig", None)
+ seed_declared = bool(history) and history_config_cls is not None
+ if history and not seed_declared:
+ log.warning(
+ "gemini-live: installed google-genai SDK has no HistoryConfig; "
+ "opening the rebuilt session without the %d-turn conversation "
+ "seed",
+ len(history),
+ )
live_config = types.LiveConnectConfig(
response_modalities=[types.Modality.AUDIO],
system_instruction=str(getattr(cfg, "instructions", "") or "") or None,
input_audio_transcription=types.AudioTranscriptionConfig(),
output_audio_transcription=types.AudioTranscriptionConfig(),
- realtime_input_config=types.RealtimeInputConfig(
- automatic_activity_detection=types.AutomaticActivityDetection(
- disabled=False,
- silence_duration_ms=int(
- getattr(cfg, "silence_duration_ms", 1_500) or 1_500
- ),
- )
+ **(
+ {
+ "realtime_input_config": types.RealtimeInputConfig(
+ automatic_activity_detection=types.AutomaticActivityDetection(
+ disabled=False,
+ silence_duration_ms=int(silence_ms),
+ )
+ )
+ }
+ if silence_ms
+ else {}
),
**(
{
@@ -452,6 +497,15 @@ class GeminiLiveProvider:
if speech_config
else {}
),
+ **(
+ {
+ "history_config": history_config_cls(
+ initial_history_in_client_content=True
+ )
+ }
+ if seed_declared
+ else {}
+ ),
)
connection_cm = client.aio.live.connect(
model=str(getattr(cfg, "model", "") or _MODEL),
@@ -466,7 +520,8 @@ class GeminiLiveProvider:
if hasattr(result, "__await__"):
await result
raise
- await _seed_history(session, tuple(getattr(cfg, "history", ()) or ()))
+ if seed_declared:
+ await _seed_history(session, history)
return _GeminiLiveSession(
session=session,
connection_cm=connection_cm,
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index 3268dec41a..eb27644c98 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -15,6 +15,7 @@ import logging
import random
import re
import time
+from collections import deque
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any
@@ -176,6 +177,59 @@ def _is_public_knowledge_question(text: str) -> bool:
return bool(_PUBLIC_KNOWLEDGE_QUESTION_RE.search(str(text or "").strip()))
+class _LoopLagProbe:
+ """Sample event-loop scheduling lag so audio-stall logs can tell a
+ silent provider from a starved receive loop.
+
+ The mid-reply stall diagnostic measures the gap between provider audio
+ ARRIVALS — but arrival is when OUR event loop reads the socket. Heavy
+ concurrent work in this process (live run 2026-07-21 08:40: the wiki
+ consolidator finished a 54 s Codex CLI turn right as a 1850 ms
+ "provider sent no audio" stall began) produces the identical signature
+ while the audio sits unread in the socket buffer. One sleeping task
+ measuring its own scheduling delay separates the two: provider silence
+ leaves the loop responsive; a blocked loop lags every task equally.
+ """
+
+ _INTERVAL_S = 0.25
+ _WINDOW_S = 30.0
+
+ def __init__(self) -> None:
+ self._samples: deque[tuple[float, float]] = deque()
+ self._task: asyncio.Task[None] | None = None
+
+ def start(self) -> None:
+ if self._task is None or self._task.done():
+ self._task = asyncio.create_task(
+ self._run(), name="rt-loop-lag-probe"
+ )
+
+ def stop(self) -> None:
+ task = self._task
+ self._task = None
+ if task is not None and not task.done():
+ task.cancel()
+
+ async def _run(self) -> None:
+ while True:
+ before = time.monotonic()
+ await asyncio.sleep(self._INTERVAL_S)
+ now = time.monotonic()
+ lag_ms = max(0.0, (now - before - self._INTERVAL_S) * 1_000.0)
+ self._samples.append((now, lag_ms))
+ cutoff = now - self._WINDOW_S
+ while self._samples and self._samples[0][0] < cutoff:
+ self._samples.popleft()
+
+ def max_lag_ms(self, window_s: float) -> float:
+ """Worst scheduling lag observed within the last ``window_s``."""
+ cutoff = time.monotonic() - max(0.0, float(window_s))
+ return max(
+ (lag for stamp, lag in self._samples if stamp >= cutoff),
+ default=0.0,
+ )
+
+
# A realtime bridge is useful only for a genuinely long delegated turn. Starting
# a second provider response after two seconds made ordinary 5-7 second searches
# slower: the trusted result had to wait for the interim response lifecycle to
@@ -875,6 +929,7 @@ class RealtimeVoiceSession:
self._last_audio_emit_monotonic = 0.0
self._last_audio_emit_turn = ""
self._embedded_silence_ms = 0.0
+ self._loop_lag = _LoopLagProbe()
# A write-only transport stall does not necessarily wake the provider
# receive iterator. Queue a rebuild request for the long-lived pump so
# it can cancel that iterator and reopen the session without ending the
@@ -886,6 +941,10 @@ class RealtimeVoiceSession:
# Monotonic timestamps of in-place transport rebuilds (BUG-071),
# pruned to the rolling _TRANSPORT_REBUILD_WINDOW_S budget window.
self._transport_rebuild_times: list[float] = []
+ # BUG-104: a history seed the provider's SERVER rejects kills every
+ # rebuilt connection right after ready — the client-side seed guard
+ # never sees the rejection, so repeated rapid deaths retry seedless.
+ self._suppress_history_seed = False
def _resolve_lang(self, *, text: str) -> str:
brain = getattr(self._config, "brain", None)
@@ -1103,8 +1162,14 @@ class RealtimeVoiceSession:
# Empty at the first open of a call; after an in-place
# transport rebuild (or a mid-call cross-family fallback) it
# carries the bounded call transcript so the fresh provider
- # session keeps understanding follow-up turns (BUG-088).
- history=self._history_seed(),
+ # session keeps understanding follow-up turns (BUG-088) —
+ # unless a rapid rebuild death loop marked the seed as
+ # poisoned (BUG-104), then an amnesiac session beats none.
+ history=(
+ ()
+ if self._suppress_history_seed
+ else self._history_seed()
+ ),
)
try:
providers_left = sum(
@@ -1178,6 +1243,7 @@ class RealtimeVoiceSession:
def _start_pump(self) -> None:
if self._pump_task is None or self._pump_task.done():
+ self._loop_lag.start()
self._pump_task = asyncio.create_task(
self._pump(), name=f"rt-pump-{self.session_id}"
)
@@ -2427,6 +2493,22 @@ class RealtimeVoiceSession:
)
return False
self._transport_rebuild_times.append(now)
+ # Second-or-later rebuild inside the window: the previous rebuilt
+ # transport died again almost immediately. The dominant cause is a
+ # server-side rejection of the conversation seed (1007 right after
+ # ready — invisible to the client-side seed guard, live incident
+ # 2026-07-21 08:35, BUG-104). Retry without the seed: an amnesiac
+ # session keeps the call alive instead of burning the whole rebuild
+ # budget and hanging up mid-sentence.
+ if len(self._transport_rebuild_times) >= 2 and not (
+ self._suppress_history_seed
+ ):
+ self._suppress_history_seed = True
+ log.warning(
+ "realtime[%s] rebuilt transport died again right away — "
+ "retrying without the in-call conversation seed",
+ self.session_id,
+ )
old_session, self._session = self._session, None
if self._transport_rebuild_pending is old_session:
self._transport_rebuild_pending = None
@@ -4584,11 +4666,21 @@ class RealtimeVoiceSession:
gap_ms = (now - self._last_audio_emit_monotonic) * 1_000.0
if gap_ms >= _AUDIO_FLOW_STALL_LOG_MS:
held_ms = float(getattr(self._gate, "last_hold_ms", 0.0) or 0.0)
- cause = (
- "the transcript needed to clear this audio arrived late"
- if held_ms >= gap_ms * 0.6
- else "the provider sent no audio for this span"
- )
+ loop_lag_ms = self._loop_lag.max_lag_ms(gap_ms / 1_000.0 + 1.0)
+ if held_ms >= gap_ms * 0.6:
+ cause = "the transcript needed to clear this audio arrived late"
+ elif loop_lag_ms >= gap_ms * 0.5:
+ # Arrival is when OUR loop reads the socket: a lag this
+ # close to the gap means the audio sat unread while this
+ # process was busy — not a silent provider.
+ cause = (
+ "this process's event loop stalled "
+ f"{int(loop_lag_ms)} ms in the same window — the "
+ "audio likely sat unread in the socket, not missing "
+ "from the provider"
+ )
+ else:
+ cause = "the provider sent no audio for this span"
log.info(
"realtime[%s] mid-reply audio stalled %d ms before this "
"chunk (scrub-gate hold %d ms, %d ms still gated) — %s",
@@ -4653,6 +4745,7 @@ class RealtimeVoiceSession:
if self._ended:
return
self._ended = True
+ self._loop_lag.stop()
self._cancel_tool_transcript_wait()
if self._end_call_timer is not None and not self._end_call_timer.done():
self._end_call_timer.cancel()
diff --git a/tests/unit/realtime/test_gemini_live.py b/tests/unit/realtime/test_gemini_live.py
index 692ed333ad..b60268fb01 100644
--- a/tests/unit/realtime/test_gemini_live.py
+++ b/tests/unit/realtime/test_gemini_live.py
@@ -325,6 +325,21 @@ async def test_every_selectable_model_uses_live_audio_and_transcriptions(
assert holder["client"].closed is True
+async def test_default_config_keeps_native_activity_detection(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ holder = _patch_genai_client(monkeypatch)
+ provider = GeminiLiveProvider(api_key="test-key")
+
+ session = await provider.open_session(RealtimeSessionConfig(voice="Puck"))
+ _selected, config = holder["client"].aio.live.connect_calls[0]
+ # No forced silence window: Gemini's native automatic activity detection
+ # decides the turn end (the Settings "Thinking pause" is pipeline-only).
+ assert config.realtime_input_config is None
+ await session.close()
+
+
@pytest.mark.asyncio
async def test_open_session_uses_current_default_model(
monkeypatch: pytest.MonkeyPatch,
@@ -508,9 +523,11 @@ def _patch_seedable_genai_client(monkeypatch: pytest.MonkeyPatch) -> dict:
class _SeedableLiveAPI:
def __init__(self) -> None:
self.last_cm: _SeedableConnectCM | None = None
+ self.last_config = None
def connect(self, *, model, config):
- del model, config
+ del model
+ self.last_config = config
self.last_cm = _SeedableConnectCM()
return self.last_cm
@@ -535,8 +552,10 @@ async def test_open_session_seeds_prior_call_history(
) -> None:
"""BUG-088: a mid-call transport rebuild reopens Gemini with a fresh,
empty conversation. The open must replay the bounded call transcript via
- send_client_content(turn_complete=False) — Gemini's initial-history
- channel — so follow-up questions keep their earlier-turn grounding."""
+ send_client_content — and per BUG-104 the connection must DECLARE the
+ seed (history_config.initial_history_in_client_content) and END it with
+ turn_complete=True, otherwise Gemini 3.1 closes the rebuilt connection
+ with 1007 right after ready and the call dies mid-sentence."""
holder = _patch_seedable_genai_client(monkeypatch)
await GeminiLiveProvider(api_key="test-key").open_session(
RealtimeSessionConfig(
@@ -549,9 +568,12 @@ async def test_open_session_seeds_prior_call_history(
)
live = holder["client"].aio.live
+ history_config = live.last_config.history_config
+ assert history_config is not None
+ assert history_config.initial_history_in_client_content is True
calls = live.last_cm.client_content_calls
assert len(calls) == 1
- assert calls[0]["turn_complete"] is False
+ assert calls[0]["turn_complete"] is True
turns = calls[0]["turns"]
assert [turn.role for turn in turns] == ["user", "model", "user"]
assert [turn.parts[0].text for turn in turns] == [
@@ -570,7 +592,11 @@ async def test_open_session_without_history_sends_no_client_content(
RealtimeSessionConfig()
)
- assert holder["client"].aio.live.last_cm.client_content_calls == []
+ live = holder["client"].aio.live
+ assert live.last_cm.client_content_calls == []
+ # No declared initial history either — the first open of a call must
+ # stay byte-identical to the proven-stable handshake (BUG-104).
+ assert live.last_config.history_config is None
@pytest.mark.asyncio
@@ -631,10 +657,55 @@ async def test_history_seed_construction_failure_keeps_the_session_alive(
RealtimeSessionConfig(history=({"role": "user", "text": "hello"},))
)
+ assert session is not None
+ # The connection declared initial-history mode, so the failed seed must
+ # still be closed out with an empty turn_complete=True — otherwise the
+ # first microphone frame is the next invalid argument (BUG-104).
+ assert holder["client"].aio.live.last_cm.client_content_calls == [
+ {"turns": None, "turn_complete": True}
+ ]
+
+
+async def test_sdk_without_history_config_skips_the_seed_entirely(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """BUG-104: on an SDK that cannot DECLARE initial history, sending the
+ seed anyway is a guaranteed server-side 1007 that kills the rebuilt
+ connection. The open must skip the seed (amnesiac but alive) — a
+ capability probe, never a model-name pin (AP-21)."""
+ holder = _patch_seedable_genai_client(monkeypatch)
+
+ from google.genai import types
+
+ monkeypatch.delattr(types, "HistoryConfig")
+ session = await GeminiLiveProvider(api_key="test-key").open_session(
+ RealtimeSessionConfig(history=({"role": "user", "text": "hello"},))
+ )
+
assert session is not None
assert holder["client"].aio.live.last_cm.client_content_calls == []
+async def test_blank_only_history_still_closes_the_declared_seed(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A history whose every entry filters out (blank text) still declared
+ initial-history mode at connect — the seed must send the empty
+ turn_complete=True terminator so realtime_input becomes legal."""
+ holder = _patch_seedable_genai_client(monkeypatch)
+ await GeminiLiveProvider(api_key="test-key").open_session(
+ RealtimeSessionConfig(history=({"role": "user", "text": " "},))
+ )
+
+ live = holder["client"].aio.live
+ assert live.last_config.history_config is not None
+ assert live.last_cm.client_content_calls == [
+ {"turns": None, "turn_complete": True}
+ ]
+
+
# --- function_declarations schema sanitizing --------------------------------
diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.py
index 080e51f39a..31e3a18037 100644
--- a/tests/unit/realtime/test_session.py
+++ b/tests/unit/realtime/test_session.py
@@ -5168,6 +5168,47 @@ async def test_transport_rebuild_storm_fails_honestly():
await sess.end(reason="test")
+async def test_second_rapid_rebuild_drops_the_poisoned_history_seed():
+ """BUG-104: Gemini's server rejected the conversation seed with 1007
+ right after every rebuilt connection reported ready — the client-side
+ seed guard never sees a server-side rejection, so each seeded rebuild
+ died again, three rebuilds burned the whole recovery budget in ~1.5 s,
+ and the call hung up with reason=error mid-sentence. The second rapid
+ death in the window must retry WITHOUT the seed: amnesiac but alive."""
+ from jarvis.core.protocols import BrainMessage
+
+ provider = RebuildingProvider(
+ [
+ lambda: DyingSession([]),
+ lambda: DyingSession([]),
+ lambda: StayOpenSession([]),
+ ]
+ )
+ sess = RealtimeVoiceSession(
+ session_id="rebuild-poisoned-seed",
+ send_binary=lambda _data: asyncio.sleep(0),
+ send_json=lambda _m: asyncio.sleep(0),
+ provider=provider,
+ config=_cfg(),
+ bus=None,
+ )
+ sess._delegate_history = [
+ BrainMessage(role="user", content="what about private law"),
+ BrainMessage(role="assistant", content="private autonomy governs it"),
+ ]
+ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})
+ await _wait_until(lambda: provider.open_calls >= 3)
+
+ assert not sess.failed
+ # Initial open + first rebuild carry the call transcript (BUG-088)...
+ assert provider.opened_cfgs[0].history
+ assert provider.opened_cfgs[1].history
+ # ...but the rebuild after another immediate death goes seedless.
+ assert provider.opened_cfgs[2].history == ()
+ await sess.end(reason="test")
+
+
@pytest.mark.asyncio
async def test_idle_stream_end_with_capability_rebuilds_instead_of_ending():
"""A graceful provider close at an idle boundary (Live-API session limit)