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): fail fast while managed server warms

rubenluetke10-beep4a3738ebce98
diff --git a/jarvis/plugins/realtime/openai_realtime.py b/jarvis/plugins/realtime/openai_realtime.py
index 1903f32468..fe97dc79e2 100644
--- a/jarvis/plugins/realtime/openai_realtime.py
+++ b/jarvis/plugins/realtime/openai_realtime.py
@@ -1392,6 +1392,10 @@ _LOCAL_RESPONSE_START_TIMEOUT_S = 90.0
#: call hostage.
_LOCAL_CONNECT_SHORT_WINDOW_S = 8.0
_LOCAL_CONNECT_RETRY_STEP_S = 2.0
+#: A cold spawn may spend up to 30 seconds preparing its bounded Ollama model
+#: before the child even exists. Interactive readiness waits only this long;
+#: the same supervisor operation then continues on its worker thread.
+_LOCAL_MANAGED_PREFLIGHT_WAIT_S = 0.75
#: A managed pool that just reported an idle slot should accept the first
#: interactive handshake promptly. If that readiness becomes stale, bound the
#: race here instead of falling back to the 120-second recovery window. Long
@@ -1573,6 +1577,7 @@ class LocalRealtimeProvider:
# the cache so the first real call never pays the probe either.
_model_cache: dict[str, tuple[str, float]] = {}
_MODEL_CACHE_TTL_S = 300.0
+ _background_start_tasks: set[asyncio.Task[bool]] = set()
def __init__(
self,
@@ -1676,7 +1681,38 @@ class LocalRealtimeProvider:
)
return False
- return bool(await asyncio.to_thread(_ready_or_warming))
+ task = asyncio.create_task(
+ asyncio.to_thread(_ready_or_warming),
+ name="local-realtime-interactive-preflight",
+ )
+ LocalRealtimeProvider._background_start_tasks.add(task)
+
+ def _consume_background_start(done: asyncio.Task[bool]) -> None:
+ LocalRealtimeProvider._background_start_tasks.discard(done)
+ if done.cancelled():
+ return
+ try:
+ done.result()
+ except Exception: # noqa: BLE001 - background failure was already degraded
+ log.warning(
+ "local-realtime: background managed start failed",
+ exc_info=True,
+ )
+
+ task.add_done_callback(_consume_background_start)
+ try:
+ return bool(
+ await asyncio.wait_for(
+ asyncio.shield(task),
+ timeout=_LOCAL_MANAGED_PREFLIGHT_WAIT_S,
+ )
+ )
+ except TimeoutError:
+ log.info(
+ "local-realtime: managed server is still starting in the "
+ "background; refusing to hold this call on Connecting"
+ )
+ return False
async def _resolve_model(self) -> str:
"""The configured model, else the first one the server serves.
diff --git a/tests/unit/realtime/test_local_realtime.py b/tests/unit/realtime/test_local_realtime.py
index d9a0d0f35f..707f79adc1 100644
--- a/tests/unit/realtime/test_local_realtime.py
+++ b/tests/unit/realtime/test_local_realtime.py
@@ -138,6 +138,124 @@ async def test_open_session_without_an_address_says_what_to_do() -> None:
assert "server URL" in str(err.value)
+async def test_cold_managed_server_starts_but_does_not_hold_the_call(
+ monkeypatch,
+) -> None:
+ """Cold loading continues under supervision while the interactive probe
+ returns immediately instead of spending 120 seconds without a pool slot."""
+ from jarvis.realtime.local_server import supervisor
+
+ calls: list[str] = []
+ monkeypatch.setattr(
+ supervisor, "is_managed_launch_command", lambda command: True
+ )
+ monkeypatch.setattr(
+ supervisor,
+ "ensure_running",
+ lambda **kwargs: calls.append(f"run:{kwargs['reason']}") or "spawned",
+ )
+ monkeypatch.setattr(
+ supervisor,
+ "start_runtime_monitor",
+ lambda **kwargs: calls.append("monitor") or True,
+ )
+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: None)
+ provider = LocalRealtimeProvider(
+ base_url="http://127.0.0.1:8765",
+ launch_command="managed-server --mode realtime",
+ )
+
+ assert await provider.can_open_duplex_session() is False
+ assert calls == ["run:interactive-preflight", "monitor"]
+
+
+async def test_slow_managed_spawn_continues_after_the_call_fails_fast(
+ monkeypatch,
+) -> None:
+ import asyncio
+ import time
+
+ from jarvis.plugins.realtime import openai_realtime as module
+ from jarvis.realtime.local_server import supervisor
+
+ calls: list[str] = []
+ monkeypatch.setattr(module, "_LOCAL_MANAGED_PREFLIGHT_WAIT_S", 0.005)
+ monkeypatch.setattr(
+ supervisor, "is_managed_launch_command", lambda command: True
+ )
+
+ def slow_start(**kwargs: Any) -> str:
+ time.sleep(0.05)
+ calls.append(kwargs["reason"])
+ return "spawned"
+
+ monkeypatch.setattr(supervisor, "ensure_running", slow_start)
+ monkeypatch.setattr(
+ supervisor,
+ "start_runtime_monitor",
+ lambda **kwargs: calls.append("monitor") or True,
+ )
+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: None)
+ provider = LocalRealtimeProvider(
+ base_url="http://127.0.0.1:8765",
+ launch_command="managed-server --mode realtime",
+ )
+
+ assert (
+ await asyncio.wait_for(provider.can_open_duplex_session(), timeout=0.2)
+ is False
+ )
+ assert calls == []
+ await asyncio.gather(*LocalRealtimeProvider._background_start_tasks)
+ assert calls == ["interactive-preflight", "monitor"]
+
+
+async def test_ready_managed_pool_opens_only_with_idle_capacity(monkeypatch) -> None:
+ from jarvis.realtime.local_server import supervisor
+
+ pool = {"size": 1, "in_use": 0, "available": 1, "active": 0}
+ monkeypatch.setattr(
+ supervisor, "is_managed_launch_command", lambda command: True
+ )
+ monkeypatch.setattr(
+ supervisor, "ensure_running", lambda **kwargs: "already-running"
+ )
+ monkeypatch.setattr(supervisor, "start_runtime_monitor", lambda **kwargs: True)
+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: pool)
+ provider = LocalRealtimeProvider(
+ base_url="http://127.0.0.1:8765",
+ launch_command="managed-server --mode realtime",
+ )
+
+ assert await provider.can_open_duplex_session() is True
+ pool.update({"in_use": 1, "available": 0, "active": 1})
+ assert await provider.can_open_duplex_session() is False
+
+
+async def test_byo_server_never_requires_the_private_pool(monkeypatch) -> None:
+ from jarvis.realtime.local_server import supervisor
+
+ monkeypatch.setattr(
+ supervisor, "is_managed_launch_command", lambda command: False
+ )
+ monkeypatch.setattr(
+ supervisor,
+ "ensure_running",
+ lambda **kwargs: pytest.fail("BYO launch must retain protocol-only behavior"),
+ )
+ monkeypatch.setattr(
+ supervisor,
+ "probe_runtime",
+ lambda *args, **kwargs: pytest.fail("BYO server need not implement /v1/pool"),
+ )
+ provider = LocalRealtimeProvider(
+ base_url="http://127.0.0.1:8765",
+ launch_command="custom-realtime-server --flag",
+ )
+
+ assert await provider.can_open_duplex_session() is True
+
+
# ── Credentials come from the environment, never from the config file ────
def test_optional_key_is_read_from_the_environment(monkeypatch) -> None:
monkeypatch.setenv("JARVIS_LOCAL_REALTIME_API_KEY", "sk-local-proxy")
@@ -384,6 +502,53 @@ async def test_cancellation_is_never_retried(monkeypatch) -> None:
assert attempts == 1
+async def test_managed_initial_open_race_never_uses_the_recovery_window(
+ monkeypatch,
+) -> None:
+ """A pool can disappear between readiness and WebSocket acquisition. That
+ first-call race is bounded separately from the patient mid-call rebuild."""
+ import asyncio
+
+ from jarvis.plugins.realtime import openai_realtime as module
+ from jarvis.realtime.local_server import supervisor
+
+ monkeypatch.setattr(module, "_LOCAL_MANAGED_INTERACTIVE_OPEN_S", 0.02)
+ monkeypatch.setattr(
+ supervisor, "is_managed_launch_command", lambda command: True
+ )
+ monkeypatch.setattr(
+ supervisor, "ensure_running", lambda **kwargs: "already-running"
+ )
+ monkeypatch.setattr(supervisor, "start_runtime_monitor", lambda **kwargs: True)
+ monkeypatch.setattr(
+ supervisor,
+ "probe_runtime",
+ lambda *args, **kwargs: {
+ "size": 1,
+ "in_use": 0,
+ "available": 1,
+ "active": 0,
+ },
+ )
+ provider = LocalRealtimeProvider(
+ base_url="http://127.0.0.1:8765",
+ model="m",
+ launch_command="managed-server --mode realtime",
+ )
+ assert await provider.can_open_duplex_session() is True
+
+ async def wedged_handshake(cfg: Any) -> str:
+ await asyncio.sleep(1.0)
+ return "too-late"
+
+ monkeypatch.setattr(provider, "_open_session_once", wedged_handshake)
+ with pytest.raises(TimeoutError):
+ await asyncio.wait_for(
+ provider.open_session(SimpleNamespace(model="m")),
+ timeout=0.5,
+ )
+
+
def test_patience_is_earned_by_a_launch_command() -> None:
"""Without a launch command nobody revives the server — a long silent
wait would hold the call hostage for nothing."""