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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
perf(boot): stop wasting a whole boot on elevation, and stop to_thread stalling the loop
Ruben Lütke36c7f302ded6
diff --git a/jarvis/core/loop_executor.py b/jarvis/core/loop_executor.pynew file mode 100644index 0000000000..7eedf40808--- /dev/null+++ b/jarvis/core/loop_executor.py@@ -0,0 +1,130 @@+"""A default executor that is already at full size when the loop first needs it.++``asyncio.to_thread`` is the app's standard way of keeping blocking work off the+event loop, and it is used in roughly 420 places. It is not, however, free of the+loop: every call goes through ``loop.run_in_executor(None, ...)``, which calls+``ThreadPoolExecutor._adjust_thread_count()``, and when no worker is idle and the+pool has not reached ``max_workers`` yet, that method calls ``Thread.start()``+**synchronously, on the calling thread** — the event loop. ``Thread.start()``+waits for the new thread to signal that it is running, so a host under load pays+that wait with the whole loop stopped.++Measured on the maintainer's box 2026-07-29 (``data/jarvis_desktop.log``), that+is not theoretical. Three of the session's worst stalls had this exact stack::++ audio/topology.py:225 watch_topology+ asyncio/threads.py:25 to_thread+ base_events.py:867 run_in_executor+ concurrent/futures/thread.py:203 _adjust_thread_count+ threading.py:999 Thread.start+ threading.py:655 wait <-- 75.7 s++While the loop is stopped, every WebSocket frame, every HTTP route, every brain+turn and every terminal pane's output is stopped with it — which is what the user+reports as "the whole app is dead" and as a coding-CLI pane that never draws.++The fix is not to audit 420 call sites: it is to make the pool never have to+grow. :func:`install_prewarmed_default_executor` installs a pool of a known size+and brings every worker up **from a background thread**, so the one place where+``Thread.start()`` is unavoidable is a thread nobody is waiting on. Afterwards+``num_threads == max_workers`` forever, ``_adjust_thread_count`` returns without+starting anything, and ``to_thread`` costs the loop a queue append.++This does not make blocking work free — a call that blocks for a minute still+occupies a worker for a minute, and with every worker busy the next ``to_thread``+waits in the queue. That is the correct failure mode: work queues, the loop keeps+running, and the app stays answerable.+"""++from __future__ import annotations++import logging+import os+import threading+from concurrent.futures import ThreadPoolExecutor++log = logging.getLogger(__name__)++#: Ceiling on the pool. Above this the threads cost more (stack reservation,+#: scheduler pressure) than the parallelism is worth: the work behind+#: ``to_thread`` here is filesystem, subprocess and native-library calls, none of+#: which get faster past a few dozen in flight. Matches CPython's own default+#: ceiling so the change is a shape change, not a capacity change.+MAX_WORKERS = 32++#: Floor, independent of core count. The pool exists to absorb BLOCKING calls,+#: and how many of those are in flight has nothing to do with how many cores the+#: host has — a 2-core VPS still probes audio devices, scans folders and shells+#: out to CLIs concurrently. CPython's ``cpu_count + 4`` would put such a host at+#: 6 workers and reintroduce the growth stall this module exists to remove.+MIN_WORKERS = 16++#: How long a prewarm worker parks before giving its thread back. Only an upper+#: bound for a gate that is released within milliseconds — it exists so a+#: prewarm that somehow loses its gate cannot pin the pool.+_PREWARM_TIMEOUT_S = 30.0+++def default_worker_count(cpu_count: int | None = None) -> int:+ """How many workers to keep resident."""+ cores = cpu_count if cpu_count is not None else (os.cpu_count() or 4)+ return max(MIN_WORKERS, min(MAX_WORKERS, cores + 4))+++def prewarm(pool: ThreadPoolExecutor, workers: int) -> threading.Thread:+ """Bring ``pool`` up to ``workers`` live threads, off the caller's thread.++ Returns the thread doing it, so a test can join. Growing a pool means+ ``Thread.start()`` per worker and that blocks whoever asks — so this asks+ from a thread of its own, which is the entire point.++ Each task parks on one shared gate so the pool cannot satisfy them by+ reusing a single worker; releasing the gate frees all of them at once.+ """++ def _fill() -> None:+ gate = threading.Event()+ try:+ futures = [pool.submit(gate.wait, _PREWARM_TIMEOUT_S) for _ in range(workers)]+ except RuntimeError: # pragma: no cover — pool already shut down+ gate.set()+ return+ finally:+ # Before any wait on the futures: a submit that raised half-way+ # through must not leave the workers it did create parked.+ gate.set()+ for future in futures:+ try:+ future.result(timeout=_PREWARM_TIMEOUT_S)+ except Exception: # noqa: BLE001,S110 - the worker exists either way,+ # which is all this is for; what it returned is of no interest.+ pass+ log.debug("Default executor prewarmed to %d workers", workers)++ thread = threading.Thread(target=_fill, name="executor-prewarm", daemon=True)+ thread.start()+ return thread+++def install_prewarmed_default_executor(loop, *, workers: int | None = None):+ """Give ``loop`` a default executor that will never grow under it.++ Call once, before the loop starts running. Returns the pool so the owner can+ shut it down; the prewarm continues in the background and never gates the+ caller — filling it is exactly the blocking work this module keeps off the+ critical path (AP-26).+ """+ count = workers if workers is not None else default_worker_count()+ pool = ThreadPoolExecutor(max_workers=count, thread_name_prefix="jarvis-io")+ loop.set_default_executor(pool)+ prewarm(pool, count)+ return pool+++__all__ = [+ "MAX_WORKERS",+ "MIN_WORKERS",+ "default_worker_count",+ "install_prewarmed_default_executor",+ "prewarm",+]diff --git a/jarvis/platform/deescalate.py b/jarvis/platform/deescalate.pyindex 709fde97c7..b29844786f 100644--- a/jarvis/platform/deescalate.py+++ b/jarvis/platform/deescalate.py@@ -364,10 +364,69 @@ def current_process_is_elevated() -> bool | None:return windows_process_is_elevated()+#: Set on the child so a relaunch that comes back elevated anyway stops here+#: instead of spawning forever. It can come back elevated legitimately — an+#: account whose shell itself runs elevated hands out an elevated token — and a+#: boot loop is far worse than the isolation this repairs.+DEESCALATION_ATTEMPTED_ENV = "JARVIS_DEESCALATION_ATTEMPTED"++#: Opt-out for someone who deliberately runs elevated and accepts the trade.+KEEP_ELEVATION_ENV = "JARVIS_KEEP_ELEVATION"+++def maybe_relaunch_unelevated(+ argv: list[str],+ *,+ cwd: str,+ env: dict[str, str] | None = None,+ creationflags: int = 0,+ _elevated=current_process_is_elevated,+ _spawn=spawn_unelevated,+) -> DeescalationResult | None:+ """Hand this boot over to an unelevated copy of ourselves, before it costs.++ ``None`` means "carry on booting in this process" and is the answer for+ every ordinary launch: not Windows, not elevated, already tried, or opted+ out. A :class:`DeescalationResult` means a decision was reached — ``ok``+ for "the replacement is starting, exit now", and a failure otherwise, which+ the caller reports and then keeps booting elevated.++ **Why this belongs at the very start of a launch.** The app already knows+ how to escape elevation (:meth:`DesktopApp.request_unelevated_restart`), but+ that path only opens once there is a window to restart — so an elevated+ launch first pays for a COMPLETE boot and throws it away. Measured+ 2026-07-29 on the maintainer's box: 102 s of boot discarded, then 18 s to+ come back, for a start the user experienced as several minutes of nothing.+ Deciding here costs one token probe.++ The in-app path stays exactly as it was: it is the recovery for an app+ already running elevated (a failed relaunch here, or an install that starts+ elevated by other means), and the banner it drives is what makes the+ condition visible at all.+ """+ if sys.platform != "win32":+ return None+ if os.environ.get(KEEP_ELEVATION_ENV) == "1":+ return None+ if os.environ.get(DEESCALATION_ATTEMPTED_ENV) == "1":+ return None+ # Only a positive measurement acts. An unreadable token is "unknown", and+ # relaunching on a guess would strand a user whose app is perfectly fine.+ if _elevated() is not True:+ return None++ child_env = dict(os.environ if env is None else env)+ child_env[DEESCALATION_ATTEMPTED_ENV] = "1"+ return _spawn(argv, cwd=cwd, env=child_env, creationflags=creationflags)++__all__ = [+ "DEESCALATION_ATTEMPTED_ENV",+ "KEEP_ELEVATION_ENV","DeescalationResult","current_process_is_elevated","environment_block",+ "maybe_relaunch_unelevated","spawn_unelevated","token_creationflags",]diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex accec91c7b..180273bfb9 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -938,6 +938,26 @@ class DesktopApp:asyncio.set_event_loop(loop)self._backend_loop = loop+ # Before anything can await: hand the loop a default executor that is+ # already at full size, so ``asyncio.to_thread`` never has to grow one+ # under it. Growing costs a synchronous ``Thread.start()`` ON the loop,+ # and three of the worst stalls measured 2026-07-29 (75.7 s, 16.6 s,+ # 15.3 s) were exactly that. Filling it happens on a background thread,+ # so this call itself is a pool allocation (AP-26).+ try:+ from jarvis.core.loop_executor import install_prewarmed_default_executor++ self._io_executor = install_prewarmed_default_executor(loop)+ except Exception: # noqa: BLE001 — a loop that can still stall is the+ # behaviour we shipped yesterday; a boot that fails is not.+ from loguru import logger as _ex_log++ _ex_log.opt(exception=True).warning(+ "Could not install the prewarmed default executor — "+ "asyncio.to_thread may stall the loop while the pool grows."+ )+ self._io_executor = None+# Cold-boot profiling (gated behind JARVIS_BOOT_PROFILE=1; production# stdout unchanged). The desktop window only appears once# ``_wait_for_backend`` sees ``/api/health`` 200, which the backend can@@ -1999,6 +2019,17 @@ class DesktopApp:loop.close()except Exception: # noqa: BLE001pass+ # Never waited on: a worker still inside a blocking native call+ # would hold the quit open, and this process is on its way out+ # anyway (the restart path depends on the port and the+ # single-instance mutex being released promptly).+ executor = getattr(self, "_io_executor", None)+ if executor is not None:+ try:+ executor.shutdown(wait=False, cancel_futures=True)+ except Exception: # noqa: BLE001,S110 - last statement of a+ # process that is exiting; the OS reclaims the threads.+ pass# ---- Event-loop watchdog -------------------------------------------------diff --git a/jarvis/ui/web/launcher.py b/jarvis/ui/web/launcher.pyindex c426b65cc7..9593299f74 100644--- a/jarvis/ui/web/launcher.py+++ b/jarvis/ui/web/launcher.py@@ -309,6 +309,19 @@ async def _run_headless(args) -> int:print(f"[BOOT_PROFILE] lx_{_name}={(_now - _bp_last) * 1000.0:.1f}", flush=True)_bp_last = _now+ # Same contract as the desktop loop: a default executor that is already at+ # full size, so ``asyncio.to_thread`` never grows one under the loop (a+ # synchronous ``Thread.start()`` ON the loop — see+ # ``jarvis/core/loop_executor.py``). A headless host runs the same 420+ # ``to_thread`` call sites and has no window to hide the stall behind.+ try:+ from jarvis.core.loop_executor import install_prewarmed_default_executor++ install_prewarmed_default_executor(asyncio.get_running_loop())+ except Exception: # noqa: BLE001,S110 - a loop that can still stall is the+ # behaviour we had yesterday; a boot that fails is not.+ pass+# The single-instance lock (and its heavy ``desktop_app`` import — pywebview +# win32, ~420 ms) is acquired in the deferred section below, OFF the# time-to-serving path. It only needs to set JARVIS_PRIMARY_INSTANCE before@@ -1034,6 +1047,56 @@ def main(argv: list[str] | None = None) -> int:_raw_argv = argv if argv is not None else sys.argv[1:]args = _parse_args(_raw_argv)+ # Drop administrator rights BEFORE booting, not after.+ #+ # An elevated window is unreachable for dictation apps, text expanders and+ # password-manager auto-type (Windows UIPI — see+ # ``jarvis/platform/input_isolation.py``), and elevation survives every+ # in-app restart. The app can already escape it, but only once there is a+ # window to restart — so an elevated launch used to pay for a COMPLETE boot+ # and throw it away. Measured 2026-07-29: 102 s discarded, then 18 s to come+ # back. Here it costs one token probe.+ #+ # Desktop only (UIPI is about a window; a headless host has none), and fully+ # best-effort: anything other than "the replacement is starting" boots on in+ # this process, where the input-isolation banner remains the fallback.+ if not args.headless:+ try:+ from pathlib import Path as _Path++ import jarvis as _jarvis+ from jarvis.platform.deescalate import maybe_relaunch_unelevated+ from jarvis.ui.relauncher import detached_creationflags, fresh_user_env++ _drop = maybe_relaunch_unelevated(+ [sys.executable, "-m", "jarvis.ui.web.launcher", *_raw_argv],+ cwd=str(_Path(_jarvis.__file__).resolve().parent.parent),+ env=fresh_user_env(),+ creationflags=detached_creationflags(),+ )+ if _drop is not None:+ import logging as _dlog++ if _drop.ok:+ _dlog.getLogger(__name__).info(+ "Started with administrator rights — handing this boot to an "+ "unelevated copy so dictation and text expanders can reach the "+ "window (%s). Set %s=1 to keep the elevation instead.",+ _drop.detail,+ "JARVIS_KEEP_ELEVATION",+ )+ return 0+ _dlog.getLogger(__name__).warning(+ "Running with administrator rights and could not drop them (%s) — "+ "booting elevated. Dictation apps and text expanders will not be "+ "able to type into this window.",+ _drop.detail,+ )+ except Exception: # noqa: BLE001,S110 - an app that boots elevated is+ # degraded; one that fails to boot is not an app. The banner still+ # reports the condition, and the in-app restart still repairs it.+ pass+# Windows taskbar branding: the taskbar button icon is the LAUNCHING EXE's# embedded icon, which no window-icon / class-icon / AUMID / Start-Menu /# registry / icon-cache work can override (all verified to have no effect ondiff --git a/tests/unit/core/test_loop_executor.py b/tests/unit/core/test_loop_executor.pynew file mode 100644index 0000000000..6dfd3a4d3d--- /dev/null+++ b/tests/unit/core/test_loop_executor.py@@ -0,0 +1,119 @@+"""Guards for the prewarmed default executor.++The bug these protect against is invisible in a functional test: a pool that+grows lazily still returns the right answers, it just stops the event loop for+as long as ``Thread.start()`` takes while doing it (measured 75.7 s on a loaded+host, 2026-07-29). So the assertions here are about the pool's SHAPE — that+every worker exists before the loop asks for one — not about results.+"""++from __future__ import annotations++import asyncio+import threading+import time+from concurrent.futures import ThreadPoolExecutor++from jarvis.core.loop_executor import (+ MAX_WORKERS,+ MIN_WORKERS,+ default_worker_count,+ install_prewarmed_default_executor,+ prewarm,+)+++class TestWorkerCount:+ def test_a_tiny_host_still_gets_the_floor(self):+ """A 2-core VPS runs the same blocking call sites as a workstation.+ CPython's ``cpu_count + 4`` would put it at 6 and reintroduce growth."""+ assert default_worker_count(cpu_count=2) == MIN_WORKERS++ def test_a_large_host_is_capped(self):+ assert default_worker_count(cpu_count=128) == MAX_WORKERS++ def test_an_unknown_core_count_does_not_crash(self):+ assert MIN_WORKERS <= default_worker_count(cpu_count=None) <= MAX_WORKERS+++class TestPrewarm:+ def test_every_worker_exists_afterwards(self):+ """The whole point: once this returns, ``_adjust_thread_count`` can no+ longer reach ``Thread.start()``, because the pool is already full."""+ pool = ThreadPoolExecutor(max_workers=8)+ try:+ prewarm(pool, 8).join(timeout=30)+ assert len(pool._threads) == 8+ finally:+ pool.shutdown(wait=False)++ def test_it_does_not_block_the_caller(self):+ """Filling the pool is the blocking work; doing it on the caller's+ thread would just move the stall onto the boot path (AP-26)."""+ pool = ThreadPoolExecutor(max_workers=16)+ try:+ started = time.monotonic()+ thread = prewarm(pool, 16)+ assert time.monotonic() - started < 0.5+ thread.join(timeout=30)+ finally:+ pool.shutdown(wait=False)++ def test_workers_are_released_again(self):+ """A prewarm that parked its workers forever would hand the loop a pool+ with nothing free — the same stall, one step later."""+ pool = ThreadPoolExecutor(max_workers=4)+ try:+ prewarm(pool, 4).join(timeout=30)+ done = threading.Event()+ pool.submit(done.set)+ assert done.wait(timeout=10), "prewarm left the pool occupied"+ finally:+ pool.shutdown(wait=False)++ def test_a_shut_down_pool_is_survived(self):+ pool = ThreadPoolExecutor(max_workers=2)+ pool.shutdown(wait=True)+ prewarm(pool, 2).join(timeout=10) # must not raise+++class TestInstall:+ def test_to_thread_never_grows_the_pool_afterwards(self):+ """The regression itself. A lazily-grown pool reaches ``Thread.start()``+ from ``run_in_executor``, ON the loop; a prewarmed one cannot."""+ loop = asyncio.new_event_loop()+ try:+ pool = install_prewarmed_default_executor(loop, workers=8)+ while len(pool._threads) < 8: # prewarm is asynchronous by design+ time.sleep(0.01)++ grew: list[int] = []+ original = pool._adjust_thread_count++ def watched() -> None:+ before = len(pool._threads)+ original()+ if len(pool._threads) != before:+ grew.append(len(pool._threads))++ pool._adjust_thread_count = watched++ async def hammer() -> None:+ await asyncio.gather(*(asyncio.to_thread(lambda: None) for _ in range(40)))++ loop.run_until_complete(hammer())+ assert grew == [], "the pool grew under the loop"+ finally:+ loop.close()++ def test_the_loop_uses_the_installed_pool(self):+ loop = asyncio.new_event_loop()+ try:+ pool = install_prewarmed_default_executor(loop, workers=4)+ name = loop.run_until_complete(+ asyncio.to_thread(lambda: threading.current_thread().name)+ )+ assert name.startswith("jarvis-io")+ pool.shutdown(wait=False)+ finally:+ loop.close()diff --git a/tests/unit/platform/test_deescalate.py b/tests/unit/platform/test_deescalate.pyindex f0507c673e..ac096c887f 100644--- a/tests/unit/platform/test_deescalate.py+++ b/tests/unit/platform/test_deescalate.py@@ -8,9 +8,14 @@ that reported success — is the worst possible outcome.from __future__ import annotations+import pytest+from jarvis.platform.deescalate import (+ DEESCALATION_ATTEMPTED_ENV,+ KEEP_ELEVATION_ENV,DeescalationResult,environment_block,+ maybe_relaunch_unelevated,spawn_unelevated,token_creationflags,)@@ -109,3 +114,127 @@ class TestFailureContainment:assert spawn_unelevated(["py"], cwd=".", env={}, _platform="win32", _spawn=refuse).pid is None+++def _spawner(record: list, *, ok: bool = True):+ def spawn(argv, *, cwd, env, creationflags):+ record.append({"argv": argv, "cwd": cwd, "env": env})+ return DeescalationResult(ok, 99 if ok else None, "shell token")++ return spawn++[email protected](autouse=True)+def _clean_deescalation_env(monkeypatch):+ """Neither guard variable may leak in from the host running the tests."""+ monkeypatch.delenv(DEESCALATION_ATTEMPTED_ENV, raising=False)+ monkeypatch.delenv(KEEP_ELEVATION_ENV, raising=False)+++class TestBootTimeDeescalation:+ """The pre-boot decision. ``None`` means "carry on in this process", and+ getting that wrong either wastes a whole boot or loops forever."""++ def test_an_elevated_launch_hands_over_before_booting(self, monkeypatch):+ monkeypatch.setattr("sys.platform", "win32")+ calls: list = []++ result = maybe_relaunch_unelevated(+ ["py", "-m", "jarvis.ui.web.launcher"],+ cwd="C:\\repo",+ env={"A": "1"},+ _elevated=lambda: True,+ _spawn=_spawner(calls),+ )++ assert result is not None and result.ok is True+ assert calls[0]["argv"] == ["py", "-m", "jarvis.ui.web.launcher"]++ def test_the_child_is_marked_so_a_still_elevated_relaunch_stops(self, monkeypatch):+ """Without this the app boot-loops on an account whose shell token is+ itself elevated — strictly worse than the isolation being repaired."""+ monkeypatch.setattr("sys.platform", "win32")+ calls: list = []++ maybe_relaunch_unelevated(+ ["py"], cwd=".", env={"A": "1"}, _elevated=lambda: True, _spawn=_spawner(calls)+ )++ assert calls[0]["env"][DEESCALATION_ATTEMPTED_ENV] == "1"++ def test_a_marked_process_never_tries_again(self, monkeypatch):+ monkeypatch.setattr("sys.platform", "win32")+ monkeypatch.setenv(DEESCALATION_ATTEMPTED_ENV, "1")+ calls: list = []++ assert (+ maybe_relaunch_unelevated(+ ["py"], cwd=".", _elevated=lambda: True, _spawn=_spawner(calls)+ )+ is None+ )+ assert calls == []++ def test_an_ordinary_unelevated_launch_is_untouched(self, monkeypatch):+ monkeypatch.setattr("sys.platform", "win32")+ calls: list = []++ assert (+ maybe_relaunch_unelevated(+ ["py"], cwd=".", _elevated=lambda: False, _spawn=_spawner(calls)+ )+ is None+ )+ assert calls == []++ def test_an_unreadable_token_boots_on_rather_than_guessing(self, monkeypatch):+ """``None`` is "could not measure". Relaunching on a guess would strand+ a user whose app was never elevated in the first place."""+ monkeypatch.setattr("sys.platform", "win32")+ calls: list = []++ assert (+ maybe_relaunch_unelevated(+ ["py"], cwd=".", _elevated=lambda: None, _spawn=_spawner(calls)+ )+ is None+ )+ assert calls == []++ def test_the_opt_out_is_honoured(self, monkeypatch):+ monkeypatch.setattr("sys.platform", "win32")+ monkeypatch.setenv(KEEP_ELEVATION_ENV, "1")+ calls: list = []++ assert (+ maybe_relaunch_unelevated(+ ["py"], cwd=".", _elevated=lambda: True, _spawn=_spawner(calls)+ )+ is None+ )+ assert calls == []++ def test_posix_is_a_no_op(self, monkeypatch):+ """Dropping from root to "whoever ran sudo" is guesswork that would+ strand file ownership — the user is told instead."""+ monkeypatch.setattr("sys.platform", "linux")+ calls: list = []++ assert (+ maybe_relaunch_unelevated(+ ["py"], cwd=".", _elevated=lambda: True, _spawn=_spawner(calls)+ )+ is None+ )+ assert calls == []++ def test_a_refused_handover_is_reported_not_swallowed(self, monkeypatch):+ """The caller must be able to tell "exit now" from "boot elevated and+ warn", so a failure has to come back as a result, never as ``None``."""+ monkeypatch.setattr("sys.platform", "win32")++ result = maybe_relaunch_unelevated(+ ["py"], cwd=".", _elevated=lambda: True, _spawn=_spawner([], ok=False)+ )++ assert result is not None and result.ok is Falsediff --git a/tests/unit/ui/test_desktop_backend_start_order.py b/tests/unit/ui/test_desktop_backend_start_order.pyindex 5b9c2ab8b1..156ec0fd26 100644--- a/tests/unit/ui/test_desktop_backend_start_order.py+++ b/tests/unit/ui/test_desktop_backend_start_order.py@@ -117,6 +117,11 @@ class _FakeLoop:def set_exception_handler(self, _handler: Any) -> None:pass+ def set_default_executor(self, executor: Any) -> None:+ # The backend hands the loop a prewarmed pool before anything awaits+ # (``jarvis/core/loop_executor.py``); a fake loop has to accept it.+ self.default_executor = executor+def run_until_complete(self, coro: Any) -> Any:return asyncio.run(coro)