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(local-realtime): recover the managed server from the failures it could not see

rubenluetke10-beep0c08f21fd965
diff --git a/jarvis/plugins/realtime/openai_realtime.py b/jarvis/plugins/realtime/openai_realtime.py
index 51affe297d..da086280ae 100644
--- a/jarvis/plugins/realtime/openai_realtime.py
+++ b/jarvis/plugins/realtime/openai_realtime.py
@@ -2107,7 +2107,6 @@ class LocalRealtimeProvider:
ready = bool(
supervisor.wait_until_ready(
provider._base_url,
- timeout=supervisor.RUNTIME_READY_TIMEOUT_S,
launch_command=provider._launch_command,
cleanup_on_timeout=True,
)
diff --git a/jarvis/realtime/local_server/configure.py b/jarvis/realtime/local_server/configure.py
index 2c3d7a1bf4..6b92c46655 100644
--- a/jarvis/realtime/local_server/configure.py
+++ b/jarvis/realtime/local_server/configure.py
@@ -75,7 +75,6 @@ async def apply_and_test_stack(
ready = await asyncio.to_thread(
lambda: supervisor.wait_until_ready(
base_url,
- timeout=supervisor.RUNTIME_READY_TIMEOUT_S,
launch_command=new_command,
cleanup_on_timeout=True,
)
@@ -157,7 +156,6 @@ async def _rollback_stack(
ready = await asyncio.to_thread(
lambda: supervisor.wait_until_ready(
base_url,
- timeout=supervisor.RUNTIME_READY_TIMEOUT_S,
launch_command=previous_command,
cleanup_on_timeout=True,
)
diff --git a/jarvis/realtime/local_server/supervisor.py b/jarvis/realtime/local_server/supervisor.py
index ebc6d5b809..b62971bbe0 100644
--- a/jarvis/realtime/local_server/supervisor.py
+++ b/jarvis/realtime/local_server/supervisor.py
@@ -49,6 +49,12 @@ log = logging.getLogger(__name__)
#: historical revive rate limit.
SPAWN_MIN_INTERVAL_S = 60.0
+#: Ceiling for the failure-widened spawn spacing below. A generation that never
+#: reaches a ready pool still loads gigabytes of weights onto the accelerator
+#: before it dies, so an endlessly failing install must not keep paying that
+#: cost every minute forever.
+SPAWN_MAX_INTERVAL_S = 900.0
+
# Installed checkpoints are already local after the mandatory smoke boot, but
# imports, CUDA graph capture, STT warm-up and the local brain can still take
# more than two minutes on a contended 16 GB host. This five-minute ceiling is
@@ -56,6 +62,9 @@ SPAWN_MIN_INTERVAL_S = 60.0
# provider-owned connection budget. It is deliberately bounded so a genuine
# native hang is still reclaimed.
RUNTIME_READY_TIMEOUT_S = 300.0
+#: Floor for the measured readiness budget: never judge a boot by a median so
+#: small that one contended run looks like a hang.
+RUNTIME_READY_MIN_TIMEOUT_S = 120.0
RUNTIME_READY_POLL_S = 0.5
OWNED_STARTUP_TIMEOUT_S = RUNTIME_READY_TIMEOUT_S
@@ -71,11 +80,23 @@ RUNTIME_MONITOR_UNREADY_GRACE_S = 30.0
_MAX_POOL_RESPONSE_BYTES = 64 * 1024
+#: Rotate the shared server log once it passes this size. Large enough that a
+#: whole boot transcript plus a long session's noise stays in one file for the
+#: crash tail, small enough that an always-on host cannot silently fill a disk.
+MAX_SERVER_LOG_BYTES = 8 * 1024 * 1024
+
#: How long the Ollama brain model stays resident after a warm ping. Slides on
#: every warm call (the desktop warm worker re-arms after each voice session),
#: so only a genuinely idle multi-hour gap pays a reload.
BRAIN_KEEP_ALIVE = "2h"
+#: How often the runtime monitor re-arms that residency. The keep-alive above
+#: is a DEADLINE, not a subscription: an overnight gap with no voice session
+#: expires it, and the first sentence of the morning then pays a cold model
+#: load on top of an otherwise warm server. Re-pinging well inside the window
+#: costs one empty HTTP request from a thread that is already polling.
+BRAIN_REWARM_INTERVAL_S = 45 * 60.0
+
# Ollama's OpenAI-compatible endpoints cannot accept a per-request context
# size. Current long-context models can therefore reserve their full native
# window (qwen3.5:4b used 262,144 tokens and spilled 5+ GiB into shared GPU
@@ -278,10 +299,69 @@ def _pool_has_no_usable_capacity(pool: dict[str, int]) -> bool:
)
+def _recorded_boot_stats() -> Any:
+ """The persisted boot statistics, or ``None`` when they cannot be read."""
+ try:
+ from jarvis.realtime.local_server import boot_progress # lazy (AP-26)
+
+ return boot_progress.load_stats(_boot_stats())
+ except Exception: # noqa: BLE001 - statistics never gate a lifecycle decision
+ log.debug("supervisor: boot statistics unavailable", exc_info=True)
+ return None
+
+
+def ready_timeout_s() -> float:
+ """How long a fresh generation may take to report a ready model pool.
+
+ The fixed five-minute ceiling was sized for the slowest imaginable host,
+ which means every machine pays five minutes to notice a boot that hung —
+ including one whose own measured boots take a minute. The recorded median
+ is the honest local expectation, and three times it absorbs a contended
+ run without turning a genuine native hang into a five-minute wait. Without
+ history the full ceiling stands: a first boot on unknown hardware is
+ exactly when patience is warranted.
+ """
+ stats = _recorded_boot_stats()
+ if stats is None:
+ return RUNTIME_READY_TIMEOUT_S
+ try:
+ from jarvis.realtime.local_server import boot_progress # lazy (AP-26)
+
+ expected = boot_progress.expected_boot_s(stats)
+ except Exception: # noqa: BLE001 - a bad statistic keeps the safe ceiling
+ log.debug("supervisor: expected boot time unavailable", exc_info=True)
+ return RUNTIME_READY_TIMEOUT_S
+ if expected is None or expected <= 0:
+ return RUNTIME_READY_TIMEOUT_S
+ return max(
+ RUNTIME_READY_MIN_TIMEOUT_S,
+ min(RUNTIME_READY_TIMEOUT_S, 3.0 * expected),
+ )
+
+
+def _spawn_min_interval_s() -> float:
+ """Minimum spawn spacing, widened by consecutive never-ready boots.
+
+ ``failed_streak`` counts only generations that never reached a ready pool
+ inside their whole budget, and :func:`boot_progress.record_ready` clears it
+ the moment one succeeds. So a server that crashes after a healthy hour
+ keeps the plain one-minute window and recovers promptly, while an install
+ that can no longer boot at all stops re-loading gigabytes of weights onto
+ the accelerator every minute forever.
+ """
+ stats = _recorded_boot_stats()
+ if stats is None:
+ return SPAWN_MIN_INTERVAL_S
+ streak = int(stats["failed_streak"])
+ if streak <= 0:
+ return SPAWN_MIN_INTERVAL_S
+ return min(SPAWN_MAX_INTERVAL_S, SPAWN_MIN_INTERVAL_S * 2.0 ** min(streak, 4))
+
+
def wait_until_ready(
base_url: str,
*,
- timeout: float = RUNTIME_READY_TIMEOUT_S,
+ timeout: float | None = None,
poll_interval: float = RUNTIME_READY_POLL_S,
launch_command: str = "",
cleanup_on_timeout: bool = False,
@@ -292,8 +372,11 @@ def wait_until_ready(
A timed-out managed child is torn down when requested so it cannot remain
as an owned-but-never-ready zombie. Cancellation is different from a
timeout: callers stopping the server set ``cancel_event`` and no second
- lifecycle operation is started from this waiter.
+ lifecycle operation is started from this waiter. ``timeout`` defaults to
+ the measured budget from :func:`ready_timeout_s`.
"""
+ if timeout is None:
+ timeout = ready_timeout_s()
cleanup_root = managed_install_root(launch_command) if cleanup_on_timeout else None
expected_generation = _owned_generation() if cleanup_root is not None else None
deadline = time.monotonic() + max(0.0, timeout)
@@ -362,15 +445,33 @@ def _json_float(value: object) -> float | None:
def _process_create_time(pid: int) -> float | None:
- """The process's kernel start stamp, or ``None`` when unverifiable."""
+ """The process's kernel start stamp, or ``None`` when unverifiable.
+
+ A POSIX child that has exited but was never reaped keeps its process-table
+ entry: ``/proc/<pid>/stat`` still answers, so ``create_time()`` and
+ ``os.kill(pid, 0)`` both keep reporting the CRASHED server as a healthy
+ one. :func:`_spawn` deliberately drops its ``Popen`` handle (the server
+ outlives this app by design), so nothing reaps that entry until some other
+ subprocess in this interpreter happens to trigger ``subprocess._cleanup``.
+ Until then the monitor would never see the alive→gone transition and would
+ never recover the crash. A zombie is a dead process; say so here, once, on
+ the one path every ownership question already goes through.
+ """
try:
import psutil # type: ignore[import-untyped] # lazy, optional
except ImportError:
return None
try:
- return float(psutil.Process(pid).create_time())
+ process = psutil.Process(pid)
+ created = float(process.create_time())
except Exception: # noqa: BLE001 — gone/denied both mean "not verifiable"
return None
+ try:
+ if process.status() == psutil.STATUS_ZOMBIE:
+ return None
+ except Exception: # noqa: BLE001 — an unreadable status must not revoke ownership
+ log.debug("supervisor: process status probe failed for pid %s", pid, exc_info=True)
+ return created
def _owned_process() -> tuple[int | None, bool]:
@@ -754,9 +855,9 @@ def _recorded_spawn_age() -> float | None:
return age if age >= 0.0 else None
-def _recorded_spawn_is_recent() -> bool:
+def _recorded_spawn_is_recent(interval_s: float = SPAWN_MIN_INTERVAL_S) -> bool:
age = _recorded_spawn_age()
- return age is not None and age < SPAWN_MIN_INTERVAL_S
+ return age is not None and age < interval_s
def _command_references_root(command: str, root: Path) -> bool:
@@ -962,6 +1063,7 @@ def ensure_running(
base_url: str,
reason: str,
replace_unavailable_generation: tuple[int, float, str] | None = None,
+ honor_failure_backoff: bool = True,
) -> str:
"""Start the server if — and only if — starting can help.
@@ -972,6 +1074,11 @@ def ensure_running(
the exact generation it observed with no usable capacity; replacement then
happens only after the pool and ownership are verified again under the
lifecycle lease.
+
+ ``honor_failure_backoff`` widens the spawn spacing after repeated
+ never-ready boots (see :func:`_spawn_min_interval_s`). Autonomous callers
+ keep it; a human pressing Start has just supplied new information the
+ statistics cannot have, and sets it to ``False``.
"""
command = (launch_command or "").strip()
if not command:
@@ -1100,7 +1207,8 @@ def ensure_running(
global _last_spawn_at
now = time.monotonic()
- if now - _last_spawn_at < SPAWN_MIN_INTERVAL_S or _recorded_spawn_is_recent():
+ interval = _spawn_min_interval_s() if honor_failure_backoff else SPAWN_MIN_INTERVAL_S
+ if now - _last_spawn_at < interval or _recorded_spawn_is_recent(interval):
return "refused:rate-limited"
# A crash between Popen and the old non-atomic pidfile write left an
@@ -1245,9 +1353,32 @@ def _server_creationflags(*, platform_name: str | None = None) -> int:
return _WINDOWS_NO_WINDOW | _WINDOWS_DETACHED_PROCESS | _WINDOWS_BREAKAWAY_FROM_JOB
+def _rotate_server_log_if_large() -> None:
+ """Keep the shared append-only server log from growing without bound.
+
+ Every readiness poll writes one uvicorn access line, so a server that is
+ doing its job perfectly still appends around a megabyte a day forever —
+ and the crash forensics only ever read the tail. Rotating at the spawn
+ boundary is the one moment no process holds the file open on Windows, and
+ it additionally guarantees a fresh generation's stage parse cannot meet a
+ predecessor's lines. One generation of history is kept.
+ """
+ path = _server_log()
+ try:
+ if path.stat().st_size <= MAX_SERVER_LOG_BYTES:
+ return
+ os.replace(path, path.with_name(f"{path.name}.1"))
+ except OSError:
+ # A held handle or a racing writer simply means no rotation this time.
+ log.debug("supervisor: server-log rotation skipped", exc_info=True)
+ return
+ log.info("local-realtime supervisor: rotated the managed server log")
+
+
def _spawn(command: str, *, reason: str) -> int | None:
"""Detached, window-less, log-sinked spawn. ``None`` when it failed."""
+ _rotate_server_log_if_large()
try:
_server_log().parent.mkdir(parents=True, exist_ok=True)
sink = open(_server_log(), "ab") # noqa: SIM115 — handed to the child
@@ -1392,7 +1523,6 @@ def _revive_from_monitor(
return outcome
ready = wait_until_ready(
base_url,
- timeout=RUNTIME_READY_TIMEOUT_S,
launch_command=launch_command,
cleanup_on_timeout=True,
cancel_event=cancel_event,
@@ -1415,6 +1545,7 @@ def _runtime_monitor(
) -> None:
"""Detect an idle process exit promptly and a wedged pool conservatively."""
next_pool_probe = time.monotonic() + RUNTIME_MONITOR_POOL_INTERVAL_S
+ next_brain_warm = time.monotonic() + BRAIN_REWARM_INTERVAL_S
unready_since: float | None = None
unhealthy_kind = ""
last_outcome = ""
@@ -1452,6 +1583,8 @@ def _runtime_monitor(
unready_since = None
unhealthy_kind = ""
next_pool_probe = time.monotonic() + RUNTIME_MONITOR_POOL_INTERVAL_S
+ # The revive warmed the brain itself.
+ next_brain_warm = time.monotonic() + BRAIN_REWARM_INTERVAL_S
elif outcome != last_outcome:
log.warning(
"local-realtime monitor: crash recovery deferred (%s)",
@@ -1476,6 +1609,12 @@ def _runtime_monitor(
unready_since = None
unhealthy_kind = ""
last_outcome = ""
+ if now >= next_brain_warm:
+ # Re-arm the brain's residency deadline on a proven
+ # healthy server, so an overnight gap cannot make the
+ # first sentence of the morning pay a cold model load.
+ next_brain_warm = now + BRAIN_REWARM_INTERVAL_S
+ warm_brain(launch_command=launch_command)
continue
if unready_since is None or unhealthy_kind != kind:
unready_since = now
@@ -1517,6 +1656,8 @@ def _runtime_monitor(
unready_since = None
unhealthy_kind = ""
next_pool_probe = time.monotonic() + RUNTIME_MONITOR_POOL_INTERVAL_S
+ # The revive warmed the brain itself.
+ next_brain_warm = time.monotonic() + BRAIN_REWARM_INTERVAL_S
elif outcome != last_outcome:
log.warning(
"local-realtime monitor: unready recovery deferred (%s)",
diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.py
index 5d27ab52aa..0b9e110f08 100644
--- a/jarvis/ui/web/provider_routes.py
+++ b/jarvis/ui/web/provider_routes.py
@@ -2579,7 +2579,6 @@ async def _finish_managed_server_warm(
ready = await asyncio.to_thread(
lambda: supervisor.wait_until_ready(
base_url,
- timeout=supervisor.RUNTIME_READY_TIMEOUT_S,
launch_command=command,
cleanup_on_timeout=True,
cancel_event=cancel_event,
@@ -2688,7 +2687,13 @@ async def managed_server_start(request: Request) -> dict[str, Any]:
)
outcome = await asyncio.to_thread(
lambda: supervisor.ensure_running(
- launch_command=command, base_url=base_url, reason="rest-start"
+ launch_command=command,
+ base_url=base_url,
+ reason="rest-start",
+ # A human pressing Start has just supplied information the failure
+ # statistics cannot have (a freed GPU, a fixed driver), so the
+ # crash-loop backoff must not make them wait out its widened window.
+ honor_failure_backoff=False,
)
)
if outcome.startswith("refused:"):
diff --git a/tests/unit/realtime/local_server/test_supervisor.py b/tests/unit/realtime/local_server/test_supervisor.py
index 3ccc82d8c0..5b079f4a65 100644
--- a/tests/unit/realtime/local_server/test_supervisor.py
+++ b/tests/unit/realtime/local_server/test_supervisor.py
@@ -1858,3 +1858,234 @@ def test_readiness_timeout_cleanup_counts_toward_the_crash_loop_streak(
assert outcome == "completed"
stats = boot_progress.load_stats(tmp_path / "local_realtime_server.boot.json")
assert stats["failed_streak"] == 1
+
+
+# ── Measured budgets: the statistics decide, not two fixed constants ──────
+
+
+def _write_boot_stats(
+ root: Path, *, durations: list[float] | None = None, failed_streak: int = 0
+) -> None:
+ """Persist a boot-statistics file the supervisor will actually read."""
+ (root / "local_realtime_server.boot.json").write_text(
+ json.dumps(
+ {
+ "durations_s": durations or [],
+ "failed_streak": failed_streak,
+ "ready_token": "ready-token",
+ "timeout_token": "timeout-token",
+ }
+ ),
+ encoding="utf-8",
+ )
+
+
+def test_a_zombie_child_is_never_mistaken_for_a_live_server(monkeypatch) -> None:
+ """A crashed POSIX child that nobody reaped still answers create_time().
+
+ The server is spawned detached and its ``Popen`` handle is dropped on
+ purpose (it must outlive the app), so on POSIX a crash leaves a zombie
+ entry that ``/proc`` keeps serving until some unrelated subprocess in this
+ interpreter happens to reap it. Reading that as "alive" is what would stop
+ the monitor from ever seeing the alive→gone transition, so the crash would
+ never be recovered. Windows has no zombie state, which makes this the exact
+ path the maintainer's machine cannot exercise.
+ """
+ import psutil
+
+ class _Zombie:
+ def __init__(self, pid: int) -> None:
+ self.pid = pid
+
+ def create_time(self) -> float:
+ return 1000.0
+
+ def status(self) -> str:
+ return psutil.STATUS_ZOMBIE
+
+ monkeypatch.setattr(psutil, "Process", _Zombie)
+ assert supervisor._process_create_time(4711) is None
+
+
+def test_a_running_process_keeps_its_verified_ownership(monkeypatch) -> None:
+ """The zombie guard must not cost a healthy server its identity."""
+ import psutil
+
+ class _Running:
+ def __init__(self, pid: int) -> None:
+ self.pid = pid
+
+ def create_time(self) -> float:
+ return 1000.0
+
+ def status(self) -> str:
+ return psutil.STATUS_RUNNING
+
+ monkeypatch.setattr(psutil, "Process", _Running)
+ assert supervisor._process_create_time(4711) == 1000.0
+
+
+def test_an_unreadable_process_status_never_revokes_ownership(monkeypatch) -> None:
+ """A denied status probe is not evidence of death (macOS/hardened hosts)."""
+ import psutil
+
+ class _Opaque:
+ def __init__(self, pid: int) -> None:
+ self.pid = pid
+
+ def create_time(self) -> float:
+ return 1000.0
+
+ def status(self) -> str:
+ raise psutil.AccessDenied(self.pid)
+
+ monkeypatch.setattr(psutil, "Process", _Opaque)
+ assert supervisor._process_create_time(4711) == 1000.0
+
+
+def test_the_readiness_budget_follows_this_machines_measured_boots(monkeypatch, tmp_path) -> None:
+ """Three times the median, floored and capped — not one global constant.
+
+ A fixed five-minute ceiling makes every host pay five minutes to notice a
+ hung boot, including one whose own boots take a minute.
+ """
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
+
+ # No history at all: the safe ceiling stands (first boot, unknown machine).
+ assert supervisor.ready_timeout_s() == supervisor.RUNTIME_READY_TIMEOUT_S
+
+ _write_boot_stats(tmp_path, durations=[60.0, 70.0, 80.0])
+ assert supervisor.ready_timeout_s() == 210.0
+
+ # A very fast machine still gets the floor, not a hair-trigger deadline.
+ _write_boot_stats(tmp_path, durations=[10.0])
+ assert supervisor.ready_timeout_s() == supervisor.RUNTIME_READY_MIN_TIMEOUT_S
+
+ # A very slow one never exceeds the bounded ceiling.
+ _write_boot_stats(tmp_path, durations=[600.0])
+ assert supervisor.ready_timeout_s() == supervisor.RUNTIME_READY_TIMEOUT_S
+
+
+def test_repeated_never_ready_boots_widen_the_spawn_spacing(monkeypatch, tmp_path) -> None:
+ """An install that can no longer boot stops reloading weights every minute.
+
+ ``failed_streak`` counts only generations that never reached a ready pool,
+ and a single successful boot clears it — so a server that crashes after a
+ healthy hour keeps the plain one-minute window.
+ """
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
+
+ _write_boot_stats(tmp_path, failed_streak=0)
+ assert supervisor._spawn_min_interval_s() == supervisor.SPAWN_MIN_INTERVAL_S
+
+ _write_boot_stats(tmp_path, failed_streak=1)
+ assert supervisor._spawn_min_interval_s() == 120.0
+
+ _write_boot_stats(tmp_path, failed_streak=3)
+ assert supervisor._spawn_min_interval_s() == 480.0
+
+ _write_boot_stats(tmp_path, failed_streak=99)
+ assert supervisor._spawn_min_interval_s() == supervisor.SPAWN_MAX_INTERVAL_S
+
+
+def test_an_explicit_start_is_not_held_by_the_crash_loop_backoff(monkeypatch, tmp_path) -> None:
+ """A human pressing Start knows something the failure statistics cannot.
+
+ They may have freed the GPU or fixed a driver moments ago, so the widened
+ autonomous window must not also become their wait.
+ """
+ spawned = _spawn_ready(monkeypatch, tmp_path)
+ _write_boot_stats(tmp_path, failed_streak=4)
+ # Older than the plain window, younger than the widened one.
+ monkeypatch.setattr(supervisor, "_recorded_spawn_age", lambda: 90.0)
+
+ autonomous = supervisor.ensure_running(
+ launch_command="serve --model_name m",
+ base_url="http://127.0.0.1:8765",
+ reason="watchdog-exit",
+ )
+ explicit = supervisor.ensure_running(
+ launch_command="serve --model_name m",
+ base_url="http://127.0.0.1:8765",
+ reason="rest-start",
+ honor_failure_backoff=False,
+ )
+
+ assert autonomous == "refused:rate-limited"
+ assert explicit == "spawned"
+ assert len(spawned) == 1
+
+
+def test_an_oversized_server_log_is_rotated_at_the_spawn_boundary(monkeypatch, tmp_path) -> None:
+ """The append-only log grows forever otherwise — one poll line at a time."""
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
+ log_path = supervisor._server_log()
+ log_path.parent.mkdir(parents=True, exist_ok=True)
+ log_path.write_bytes(b"x" * (supervisor.MAX_SERVER_LOG_BYTES + 1))
+
+ supervisor._rotate_server_log_if_large()
+
+ assert not log_path.exists()
+ assert log_path.with_name(f"{log_path.name}.1").exists()
+
+
+def test_a_small_server_log_is_left_alone(monkeypatch, tmp_path) -> None:
+ """Rotation may never cost the crash tail of a normal-sized log."""
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
+ log_path = supervisor._server_log()
+ log_path.parent.mkdir(parents=True, exist_ok=True)
+ log_path.write_bytes(b"the traceback that matters")
+
+ supervisor._rotate_server_log_if_large()
+
+ assert log_path.read_bytes() == b"the traceback that matters"
+ assert not log_path.with_name(f"{log_path.name}.1").exists()
+
+
+def test_the_monitor_rearms_brain_residency_on_a_healthy_server(monkeypatch, tmp_path) -> None:
+ """``keep_alive`` is a deadline, not a subscription.
+
+ An overnight gap with no voice session expires the Ollama residency, and
+ the first sentence of the morning then pays a cold model load on an
+ otherwise warm server. The monitor is already polling; re-pinging well
+ inside the window costs one empty HTTP request.
+ """
+ root = tmp_path / "local_realtime"
+ command = f'"{root / "server.exe"}" --mode realtime'
+ healthy = {
+ "size": 1,
+ "in_use": 0,
+ "available": 1,
+ "active": 0,
+ "draining": 0,
+ "stuck": 0,
+ }
+ monkeypatch.setattr(supervisor, "RUNTIME_MONITOR_POLL_S", 0.0)
+ monkeypatch.setattr(supervisor, "RUNTIME_MONITOR_POOL_INTERVAL_S", 0.0)
+ monkeypatch.setattr(supervisor, "BRAIN_REWARM_INTERVAL_S", 0.0)
+ monkeypatch.setattr(supervisor, "managed_install_root", lambda value: root)
+ monkeypatch.setattr(supervisor, "_owned_process", lambda: (4711, True))
+ monkeypatch.setattr(supervisor, "probe_runtime", lambda *args, **kwargs: healthy)
+ monkeypatch.setattr(
+ supervisor,
+ "_revive_from_monitor",
+ lambda **kwargs: pytest.fail("a healthy server must never be revived"),
+ )
+ stop_event = threading.Event()
+ warmed: list[str] = []
+
+ def warm(**kwargs: Any) -> bool:
+ warmed.append(str(kwargs["launch_command"]))
+ stop_event.set()
+ return True
+
+ monkeypatch.setattr(supervisor, "warm_brain", warm)
+
+ supervisor._runtime_monitor(
+ command,
+ "http://127.0.0.1:8765",
+ stop_event,
+ (command, "http://127.0.0.1:8765/v1/pool"),
+ )
+
+ assert warmed == [command]
diff --git a/tests/unit/realtime/test_local_realtime.py b/tests/unit/realtime/test_local_realtime.py
index d1620ef097..e673c39aa9 100644
--- a/tests/unit/realtime/test_local_realtime.py
+++ b/tests/unit/realtime/test_local_realtime.py
@@ -170,8 +170,14 @@ async def test_cold_managed_server_starts_but_does_not_hold_the_call(
async def test_slow_managed_spawn_continues_after_the_call_fails_fast(
- monkeypatch,
+ monkeypatch, tmp_path
) -> None:
+ # Isolate the data dir: the refusal path asks the supervisor for live boot
+ # progress, which reads the REAL pidfile and server log of the developer's
+ # machine. On a host that happens to run a managed server, parsing that
+ # multi-megabyte log both changes the refusal text and costs enough time to
+ # invert this test's timing assertion.
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
import asyncio
import time
@@ -283,9 +289,16 @@ async def test_a_serving_pool_is_never_judged_by_the_cold_start_clock(
async def test_a_refusal_explains_itself_in_words_a_user_can_act_on(
- monkeypatch,
+ monkeypatch, tmp_path
) -> None:
- """Each refusal names a DIFFERENT next step, so it may not be one text."""
+ """Each refusal names a DIFFERENT next step, so it may not be one text.
+
+ The data dir is isolated because the starting refusal is deliberately
+ upgraded with live boot progress: without this, a developer machine with a
+ real managed server under way answers with its actual stage instead of the
+ static sentence pinned here.
+ """
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
from jarvis.plugins.realtime import openai_realtime as module
from jarvis.realtime.local_server import supervisor
@@ -950,6 +963,10 @@ async def test_warm_transport_prewarms_via_the_supervisor(
resident BEFORE the first call, which is what makes connects instant."""
from jarvis.realtime.local_server import install, supervisor
+ # Isolated data dir: the readiness budget is derived from THIS install's
+ # recorded boot durations, so without isolation the assertion below would
+ # measure whatever the developer's machine last booted in.
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path))
calls: list[str] = []
readiness_timeouts: list[float] = []
monkeypatch.setattr(
@@ -962,7 +979,13 @@ async def test_warm_transport_prewarms_via_the_supervisor(
def wait_until_ready(*args: Any, **kwargs: Any) -> bool:
del args
calls.append("ready")
- readiness_timeouts.append(float(kwargs["timeout"]))
+ # The prewarm passes no explicit budget — the supervisor's measured
+ # default IS the background budget. What matters here is that the warm
+ # worker never inherits the short interactive one.
+ timeout = kwargs.get("timeout")
+ readiness_timeouts.append(
+ float(timeout) if timeout is not None else supervisor.ready_timeout_s()
+ )
return True
monkeypatch.setattr(supervisor, "wait_until_ready", wait_until_ready)