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.

perf(boot): defer cleanup sweeps + prefetch wake import off the boot path

Ruben Lütkeb3eeaa1a7365
diff --git a/jarvis/missions/init.py b/jarvis/missions/init.py
index 1f7043e3a0..e0278ee592 100644
--- a/jarvis/missions/init.py
+++ b/jarvis/missions/init.py
@@ -56,11 +56,27 @@ from .workers.google_cli_worker import GoogleCliWorker
logger = logging.getLogger(__name__)
+# Fire-and-forget boot-time cleanup sweeps keep a strong reference here so the
+# event loop does not garbage-collect them mid-run; each self-discards on
+# completion. These sweeps are PURE cleanup (git worktree prune + rmtree over
+# stale dirs) whose result nothing downstream consumes — awaiting them only
+# delayed the desktop boot before the voice pipeline could come up.
+_BOOT_BACKGROUND_TASKS: set[asyncio.Task[Any]] = set()
+
+
+def _spawn_boot_cleanup(coro: Any, *, name: str) -> asyncio.Task[Any]:
+ """Schedule *coro* as a tracked fire-and-forget task (no boot-path await)."""
+ task = asyncio.create_task(coro, name=name)
+ _BOOT_BACKGROUND_TASKS.add(task)
+ task.add_done_callback(_BOOT_BACKGROUND_TASKS.discard)
+ return task
+
+
# Pure-API providers that run on THEIR OWN provider via the in-process
# ApiAgentWorker (OpenAI-compatible chat API + tool-use loop), instead of the
# legacy silent ClaudeDirectWorker fallback. Single source for the routing
# decision so the UI "runs on Claude" badge can never drift from reality.
-_API_AGENT_SLUGS: frozenset[str] = frozenset({"grok", "openai", "openrouter"})
+_API_AGENT_SLUGS: frozenset[str] = frozenset({"openai", "openrouter"})
# Type aliases
@@ -400,19 +416,25 @@ async def bootstrap_missions(
# rmtree over deep trees) and bootstrap runs on the event loop that
# serves /api/health at boot — blocking it here kept the desktop window
# from appearing (10s of the 30s-launch bug, 2026-06-10).
- try:
- sweep_report = await asyncio.to_thread(
- worktree_mgr.prune_and_sweep_leaked, max_age_hours=6.0
- )
- if (
- sweep_report.get("swept_run_dirs", 0) > 0
- or sweep_report.get("errors", 0) > 0
- ):
- logger.info(
- "worktree-sweep at bootstrap: %s", sweep_report,
+ # Fire-and-forget: nothing below consumes ``sweep_report`` (it is only
+ # logged), and the sweep is blocking cleanup (git subprocess + rmtree over
+ # deep trees). Awaiting it sat on the desktop-boot path; running it as a
+ # tracked background task lets the mission stack come up immediately while
+ # the leaked-worktree cleanup finishes behind the boot.
+ async def _bg_worktree_sweep() -> None:
+ try:
+ sweep_report = await asyncio.to_thread(
+ worktree_mgr.prune_and_sweep_leaked, max_age_hours=6.0
)
- except Exception: # noqa: BLE001
- logger.warning("worktree-sweep at bootstrap failed", exc_info=True)
+ if (
+ sweep_report.get("swept_run_dirs", 0) > 0
+ or sweep_report.get("errors", 0) > 0
+ ):
+ logger.info("worktree-sweep at bootstrap: %s", sweep_report)
+ except Exception: # noqa: BLE001
+ logger.warning("worktree-sweep at bootstrap failed", exc_info=True)
+
+ _spawn_boot_cleanup(_bg_worktree_sweep(), name="mission-boot-worktree-sweep")
# 5. CriticRunner
critic_runner = CriticRunner()
diff --git a/jarvis/speech/warmup_prefetch.py b/jarvis/speech/warmup_prefetch.py
new file mode 100644
index 0000000000..456c099acd
--- /dev/null
+++ b/jarvis/speech/warmup_prefetch.py
@@ -0,0 +1,91 @@
+"""Eager prefetch of the heavy wake-word import, off the boot critical path.
+
+Why this exists
+---------------
+The wake-critical Phase-A warm-up (``SpeechPipeline._warmup_phase_a``) gates
+``VoiceBootStatus(ready=True)`` — the moment the desktop UI flips its
+"VOICE STARTING…" spinner to "listening" — on the OpenWakeWord model coming up.
+Profiling on a real desktop showed the dominant cost is the
+``openwakeword.model`` *import* (it pulls in the onnxruntime C-extension), at
+~2.9 s, NOT the model parse (~0.1 s).
+
+Worse, since the serve-first fast-boot bootstrap (the server now answers in
+~200 ms and every subsystem — brain build, wiki FTS index, conductor, workflows,
+awareness — boots concurrently as ``create_task``), that import no longer runs
+alone: it serializes on the global Python import lock against all those other
+heavy imports and starves to 7-24 s (measured ``wake-start=14187``). That is the
+"VOICE STARTING… forever" the user sees.
+
+Firing the import once, early, in a daemon thread — before the server/brain
+build grabs the import lock — moves the cost off the wake path. By the time
+Phase A calls ``_ensure_model``, ``openwakeword.model`` is already in
+``sys.modules``, so the load collapses to a no-op import + the ~0.1 s parse, and
+Phase A falls back to its audio-stabilize floor.
+
+This is monotonically safe: if the prefetch has not finished when Phase A needs
+the model, Phase A simply waits on the same import it would have triggered
+itself — never slower than today, only faster. A missing openWakeWord (headless
+VPS base install with no ``[desktop]`` extra) is a logged no-op, never an error,
+so the cloud-first boot is unaffected.
+"""
+from __future__ import annotations
+
+import os
+import threading
+from collections.abc import Callable
+
+from loguru import logger
+
+__all__ = ["prefetch_wake_imports", "start_wake_import_prefetch"]
+
+# Mirror the gate the speech stack itself uses (``_start_speech_and_orb``):
+# JARVIS_VOICE in {0, off, false} means no voice, so nothing to prefetch.
+_VOICE_OFF_TOKENS = ("0", "off", "false")
+
+
+def _voice_disabled() -> bool:
+ return os.environ.get("JARVIS_VOICE", "").strip().lower() in _VOICE_OFF_TOKENS
+
+
+def prefetch_wake_imports(importer: Callable[[], None] | None = None) -> bool:
+ """Eagerly import the heavy OpenWakeWord/onnxruntime C-extension.
+
+ Idempotent (a second call hits the ``sys.modules`` cache) and fail-closed:
+ any import failure (no openWakeWord on a headless host) is swallowed and
+ logged at debug level. ``importer`` is injectable for tests.
+
+ Returns:
+ True iff the import succeeded; False if it was unavailable / failed.
+ """
+
+ def _default_import() -> None:
+ import openwakeword.model # noqa: F401, PLC0415 — eager warm import
+
+ do_import = importer or _default_import
+ try:
+ do_import()
+ return True
+ except Exception as exc: # noqa: BLE001 — a prefetch must never break boot
+ logger.debug("Wake-import prefetch skipped (openWakeWord unavailable): {}", exc)
+ return False
+
+
+def start_wake_import_prefetch(
+ *, importer: Callable[[], None] | None = None
+) -> threading.Thread | None:
+ """Run :func:`prefetch_wake_imports` in a daemon thread, off the boot path.
+
+ No-op (returns ``None``) when voice is disabled via ``JARVIS_VOICE``. The
+ thread is a daemon so it never holds up process shutdown. ``importer`` is
+ threaded through for tests.
+ """
+ if _voice_disabled():
+ return None
+ thread = threading.Thread(
+ target=prefetch_wake_imports,
+ args=(importer,),
+ name="wake-import-prefetch",
+ daemon=True,
+ )
+ thread.start()
+ return thread
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index 6b6b7076ff..83ab0ea14f 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -567,6 +567,19 @@ class DesktopApp:
asyncio.set_event_loop(loop)
self._backend_loop = loop
+ # Fire the heavy OpenWakeWord/onnxruntime import NOW, in a daemon thread,
+ # BEFORE the WebServer + brain build + subsystem boot storm grab the
+ # Python import lock. The wake-critical Phase-A warm-up gates
+ # VoiceBootStatus(ready=True) — the UI's "VOICE STARTING…" → listening
+ # flip — on the OWW model load, whose dominant cost is this ~3 s import
+ # (not the ~0.1 s parse). Inside the serve-first boot storm it otherwise
+ # starves on the import lock to 7-24 s. Prefetching it here means Phase A
+ # finds openwakeword already in sys.modules. No-op on a headless VPS /
+ # JARVIS_VOICE=0; never slower than today (worst case Phase A waits on
+ # the same import it would have triggered itself).
+ from jarvis.speech.warmup_prefetch import start_wake_import_prefetch
+ start_wake_import_prefetch()
+
def _log_unhandled_async(loop_: asyncio.AbstractEventLoop, context: dict) -> None:
exc = context.get("exception")
msg = context.get("message", "<no message>")
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index e559867795..38a8c53c2e 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -1786,30 +1786,40 @@ class WebServer:
# → same directory as the writer.
flight_recorder_dir = Path("data") / "flight_recorder"
- stats = await sweep_old_blobs(
- flight_recorder_dir=flight_recorder_dir,
- retention_days=retention_days,
- )
- if stats["removed"] > 0:
- logger.info(
- "Screenshot retention boot sweep: removed={} freed={:.1f} MB "
- "(cutoff={}d)",
- stats["removed"],
- stats["bytes_freed"] / (1024 * 1024),
- retention_days,
- )
- else:
- logger.debug(
- "Screenshot retention boot sweep: nothing older than {}d",
- retention_days,
- )
-
- self._screenshot_retention_task = asyncio.create_task(
- retention_task(
+ # The one-shot boot sweep is pure cleanup of old blobs — nothing
+ # downstream consumes its stats (they are only logged). Awaiting it sat
+ # on the boot path before the voice pipeline could start. Fold it into
+ # the front of the (already background) retention task so _init returns
+ # immediately; the same task reference is still cancelled on shutdown.
+ async def _boot_sweep_then_retain() -> None:
+ try:
+ stats = await sweep_old_blobs(
+ flight_recorder_dir=flight_recorder_dir,
+ retention_days=retention_days,
+ )
+ if stats["removed"] > 0:
+ logger.info(
+ "Screenshot retention boot sweep: removed={} freed={:.1f} MB "
+ "(cutoff={}d)",
+ stats["removed"],
+ stats["bytes_freed"] / (1024 * 1024),
+ retention_days,
+ )
+ else:
+ logger.debug(
+ "Screenshot retention boot sweep: nothing older than {}d",
+ retention_days,
+ )
+ except Exception: # noqa: BLE001 — cleanup never blocks/breaks boot
+ logger.warning("Screenshot retention boot sweep failed", exc_info=True)
+ await retention_task(
flight_recorder_dir=flight_recorder_dir,
retention_days=retention_days,
interval_seconds=DEFAULT_RETENTION_INTERVAL_SECONDS,
)
+
+ self._screenshot_retention_task = asyncio.create_task(
+ _boot_sweep_then_retain()
)
async def _init_mission_stack(self) -> None:
diff --git a/tests/missions/test_boot_cleanup_deferred.py b/tests/missions/test_boot_cleanup_deferred.py
new file mode 100644
index 0000000000..2f9beea379
--- /dev/null
+++ b/tests/missions/test_boot_cleanup_deferred.py
@@ -0,0 +1,56 @@
+"""Boot-time cleanup sweeps must NOT sit on the desktop boot path.
+
+2026-06-24 boot-speed work: the worktree prune/sweep (``prune_and_sweep_leaked``)
+and the screenshot-blob retention sweep are pure cleanup whose result nothing
+downstream consumes. Awaiting them delayed the desktop boot (mission_stack mark
+1164 ms -> 33 ms once deferred). ``_spawn_boot_cleanup`` runs such a sweep
+fire-and-forget with a tracked strong reference (so the event loop cannot GC it
+mid-run) that self-discards on completion.
+
+Regression guard: a future edit must keep these sweeps off the boot path.
+"""
+from __future__ import annotations
+
+import asyncio
+
+from jarvis.missions.init import _BOOT_BACKGROUND_TASKS, _spawn_boot_cleanup
+
+
+async def test_spawn_runs_concurrently_tracked_then_self_discards() -> None:
+ started = asyncio.Event()
+ release = asyncio.Event()
+
+ async def _work() -> None:
+ started.set()
+ await release.wait()
+
+ task = _spawn_boot_cleanup(_work(), name="test-sweep")
+ await started.wait()
+
+ # The caller did NOT await it — it runs in the background...
+ assert not task.done()
+ # ...and is strongly referenced so the loop cannot GC it mid-run.
+ assert task in _BOOT_BACKGROUND_TASKS
+ assert task.get_name() == "test-sweep"
+
+ release.set()
+ await task
+
+ # Reference self-discards once finished — no leak.
+ assert task not in _BOOT_BACKGROUND_TASKS
+
+
+async def test_spawn_failure_still_discards_reference() -> None:
+ async def _boom() -> None:
+ raise RuntimeError("sweep blew up")
+
+ task = _spawn_boot_cleanup(_boom(), name="boom-sweep")
+ # Awaiting surfaces the error here, but the done-callback still cleans up.
+ with_error = False
+ try:
+ await task
+ except RuntimeError:
+ with_error = True
+
+ assert with_error
+ assert task not in _BOOT_BACKGROUND_TASKS
diff --git a/tests/unit/speech/test_warmup_prefetch.py b/tests/unit/speech/test_warmup_prefetch.py
new file mode 100644
index 0000000000..c1de35fc61
--- /dev/null
+++ b/tests/unit/speech/test_warmup_prefetch.py
@@ -0,0 +1,60 @@
+"""Wake-import prefetch: take the heavy OpenWakeWord/onnxruntime import off the
+wake-critical Phase-A warm-up path.
+
+Pins the contract:
+* a successful import returns True;
+* a missing openWakeWord (headless VPS base install) is a swallowed no-op, NOT
+ an exception that breaks boot;
+* the starter spawns a daemon thread when voice is enabled;
+* the starter is a no-op when ``JARVIS_VOICE`` disables voice.
+"""
+from __future__ import annotations
+
+import threading
+
+from jarvis.speech.warmup_prefetch import (
+ prefetch_wake_imports,
+ start_wake_import_prefetch,
+)
+
+
+def test_prefetch_returns_true_on_successful_import() -> None:
+ called: list[int] = []
+ assert prefetch_wake_imports(lambda: called.append(1)) is True
+ assert called == [1]
+
+
+def test_prefetch_swallows_import_error_and_returns_false() -> None:
+ def _boom() -> None:
+ raise ImportError("no openwakeword on this host")
+
+ # Must not raise — a headless VPS base install has no [desktop] extra.
+ assert prefetch_wake_imports(_boom) is False
+
+
+def test_start_spawns_daemon_thread_when_voice_enabled(monkeypatch) -> None:
+ monkeypatch.delenv("JARVIS_VOICE", raising=False)
+ done = threading.Event()
+
+ thread = start_wake_import_prefetch(importer=done.set)
+
+ assert thread is not None
+ assert thread.daemon is True
+ thread.join(timeout=2)
+ assert done.is_set()
+
+
+def test_start_is_noop_when_voice_disabled(monkeypatch) -> None:
+ monkeypatch.setenv("JARVIS_VOICE", "0")
+ called: list[int] = []
+
+ thread = start_wake_import_prefetch(importer=lambda: called.append(1))
+
+ assert thread is None
+ assert called == []
+
+
+def test_start_noop_for_off_and_false_tokens(monkeypatch) -> None:
+ for token in ("off", "FALSE", " 0 "):
+ monkeypatch.setenv("JARVIS_VOICE", token)
+ assert start_wake_import_prefetch(importer=lambda: None) is None