Skip to content

Dashboard backend blocks its event loop with synchronous work, starving HTTP/WS during desktop boot #45072

Closed as not planned

Description

@bionicbutterfly13

While debugging intermittent desktop boot failures ("Hermes couldn't start … Timed out connecting to Hermes backend after 60000ms") I found several places where the dashboard backend does heavy synchronous work directly on the asyncio event loop, making the whole server unresponsive (all HTTP plus the gateway WS ready frame) for tens of seconds:

  • GET /api/cron/jobs (profile=all) calls profiles.list_profiles() inline — filesystem scans + per-profile YAML parsing on the loop (37s on my machine before perf(cli): skip large foreign binaries in profile alias scan, use libyaml loader #44930, still ~2-4s after).
  • GET /api/model/options — ~9s on the loop.
  • MCP server connection at startup blocks the gateway-ready frame: a slow connect_timeout on one MCP server delays every client's WS handshake by that amount (server-side signature: ws accepted followed by ws ready frame send failed in the gateway log).

Evidence: a 1s curl pulse against /api/status goes from ~0.4s responses to total silence for ~50s the moment the desktop renderer boots (it fires these endpoints in parallel), then recovers. sample of the backend process shows the event loop inside synchronous read_text/readdir/YAML work within coroutines.

Environment: macOS 15 (Darwin 24.6), Python 3.11.15, 11 profiles, Hermes v0.16.0.

Suggested direction: wrap these handlers' bodies in asyncio.to_thread(...) (the cron path already serializes via _CRON_PROFILE_LOCK, a threading lock), and/or move MCP connection out of the WS-accept critical path. Happy to contribute if maintainers agree on the approach.

Related PRs for the two worst concrete instances: #44930 (alias scan reading large binaries), #44931 (renderer-side initial-connect retry so cold-start stalls don't fail boot).

Activity

  1. added
    type/perfPerformance improvement or optimization
    comp/gatewayGateway runner, session dispatch, delivery
    P2Medium — degraded but workaround exists
    on Jun 12, 2026
  2. AIalliAI commented on Jun 12, 2026

    @AIalliAI

    Triaged this against current main — the headline symptom and the cron-endpoint mechanism check out; the other two cited mechanisms need corrections.

    Confirmed: GET /api/cron/jobs?profile=all blocks the event loop. list_cron_jobs is async def (hermes_cli/web_server.py:6693) and runs everything inline on the loop: _cron_profile_dicts() → profiles.list_profiles() (filesystem scan + per-profile YAML parsing), then per-profile _call_cron_for_profile doing jobs.json file I/O while holding _CRON_PROFILE_LOCK — which is indeed a threading.RLock (:6612). With 11 profiles that's exactly the read_text/readdir/YAML frames your sample shows. And since /api/status is also async def (:1541), a starved loop silences it — your 1s curl-pulse observation is the expected signature. This is the real kernel of the issue.

    The fix is small either way:

    • cheapest: drop the async — FastAPI runs plain def path operations in its worker threadpool (that's already how GET /api/model/options runs, see below), and _CRON_PROFILE_LOCK being a threading lock means the path is already thread-safe;
    • or keep async def and wrap the body in asyncio.to_thread(...) as you suggest — POST /api/mcp/servers/{name}/test is the in-file precedent (:7083, "run in a thread so the FastAPI event loop is never blocked").

    Either way the same treatment should cover the handlers that call _find_cron_job_profile (it iterates every profile × list_jobs).

    Correction: GET /api/model/options does not run on the loop. That handler is a plain def, not async def (web_server.py:3043) — FastAPI executes sync path operations in a threadpool, so its ~9s is real wall-clock latency for that request but it cannot starve /api/status or the WS handshake (beyond GIL contention during CPU-bound parsing; the provider probes are network-bound and release the GIL). The 9s itself is the known model-options slowness — sequential uncached provider probes, same kernel as #44560 on the tui_gateway RPC side, where PR #44577 is already open. Worth cross-linking rather than re-fixing here.

    Needs evidence: MCP connect shouldn't be in the WS-handshake path on your version. Since 0c6e133 ("perf(cli): stop eager MCP discovery from blocking agent-capable startup", 2026-05-30 — an ancestor of the v2026.6.5 release, so present in a v0.16.0 install from it):

    • dashboard MCP discovery runs in a background daemon thread (start_background_mcp_discovery, started by the dashboard command in hermes_cli/main.py with an explicit "slow/dead server can't block dashboard startup" comment);
    • the agent tool snapshot waits at most 0.75s for it (wait_for_mcp_discovery, hermes_cli/mcp_startup.py:54);
    • WS RPC dispatch runs via asyncio.to_thread(server.dispatch, ...) (tui_gateway/ws.py:248);
    • the gateway.ready frame is sent immediately after ws.accept() (tui_gateway/ws.py:170-191) — nothing MCP-shaped sits between them.

    The ws accepted → ws ready frame send failed pair (ws.py:175/:192) is fully explained without MCP: while the loop is blocked by the cron scan, both the accept and the ready-send steps are delayed; the renderer gives up at 60s (Timed out connecting to Hermes backend after 60000ms, apps/desktop/electron/main.cjs:2530) and closes; once the loop unblocks, the accept completes on a dying socket and the ready send fails. If you actually observed the handshake delayed by exactly one server's connect_timeout while the cron path was quiet, that would be a new finding — could you share hermes --version (in case the install predates 0c6e133) plus the surrounding gateway log lines?

    Given #44930/#44931 you're clearly set up to PR this — the list_cron_jobs change plus its _find_cron_job_profile consumers is a tight, low-risk scope, and either fix shape above should be uncontroversial.

  3. Hypnogamma commented on Jun 15, 2026

    @Hypnogamma

    Additional data point: 36-second delay on setup.runtime_check response with a parallel gateway process present

    I encountered a very similar failure pattern and traced the exact call chain. This comment adds concrete timing evidence that aligns with this issue's diagnosis.

    Observed timeline

    gui.log:
    17:52:07.054  ws accepted peer=127.0.0.1:65437
    17:52:43.733  ws send failed (WebSocketDisconnect)
    17:52:43.734  ws response send failed id=2 method=setup.runtime_check
    17:52:43.750  ws closed
    
    • 36.68s gap between WS accept and the point where _safe_send attempted ws.send_text() and got WebSocketDisconnect
    • The delay is between asyncio.to_thread(dispatch) returning and write_async's _safe_send actually executing

    What the handler does

    setup.runtime_check is a lightweight synchronous handler (tui_gateway/server.py:7595):

    def _(rid, params):
        runtime = resolve_runtime_provider(requested=None)
        provider_configured = bool(_has_any_provider_configured())
        credential_ok = has_usable_secret(runtime.get("api_key", ""))
        return {"ok": credential_ok, ...}

    For a standard API-key provider (DeepSeek in my case), the entire chain is config/env-var reads only — no network, no subprocesses. Should complete in <50ms.

    What happened to the response

    The handler returned its response normally. The WS response send at await self._ws.send_text(line) in _safe_send (tui_gateway/ws.py) failed 36 seconds later with WebSocketDisconnect.

    During the same window:

    • Two gateway run --replace processes were running simultaneously (PID ~1700 and PID ~17800), competing for gateway.lock — visible as repeated PID file race / Another gateway instance... in gateway.error.log
    • MCP reconnection attempts (cdp-bridge and n8n) were retrying in the background (visible as MCP server 'n8n' initial connection failed in the error log)
    • The Desktop side has a 30s RPC timeout (DEFAULT_GATEWAY_REQUEST_TIMEOUT_MS = 30_000 in apps/desktop/src/hermes.ts), which fired before the response could be delivered

    What's still unclear

    I was unable to determine whether the response was:

    1. Computed immediately but never scheduled on the event loop for 36s, or
    2. Scheduled immediately but the _WS_WRITE_TIMEOUT_S = 10.0 transport delay hid the actual send time

    Adding a logger.debug() at entry/exit of _safe_send and write_async would resolve this.

    Symptom user sees

    Desktop: "Timed out connecting to Hermes backend after 15000ms"
    

    Full clean restart (killing all hermes processes, restarting gateway, relaunching Desktop) resolves the issue consistently.

    Environment

    • macOS 15 (Darwin arm64)
    • Hermes v0.15.1
    • Single user, single profile (default)
    • Provider: DeepSeek (API key)

    This observation was contributed with AI assistance under human direction. The investigation followed standard diagnostic procedures — process inspection, log analysis, source code tracing, and existing issue search.

  4. teknium1 commented on Jul 14, 2026

    @teknium1
    Collaborator

    Thanks for the detailed profiling and for separating the concrete cron path from the other hypotheses. This automated hermes-sweeper review found that the confirmed event-loop starvation path is now implemented on main.

    • 346e5673de8dd2e2ccc11817c81323dbb16e78f2 (fix(dashboard): offload cron profile scans) moved GET /api/cron/jobs and the profile-discovering cron handlers to an off-loop wrapper.
    • Current hermes_cli/web_server.py:10258-10270 runs the synchronous multi-profile scan through run_in_threadpool.
    • Current regression coverage at tests/hermes_cli/test_web_server_cron_profiles.py:306-344 asserts the scan and profile lookup do not execute on the event-loop thread.
    • Follow-up commit 74609f926c353129c73bfc3704f0deed152733fa covers residual cron lookup/blueprint handlers; tests/hermes_cli/test_cron_dashboard_off_loop.py:33-86 pins that guarantee.
    • The MCP/WS concern is also addressed by the current daemon-thread discovery and immediate ready-frame path in tui_gateway/ws.py:303-328.

    Closing as implemented on main.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2Medium — degraded but workaround existscomp/gatewayGateway runner, session dispatch, deliverysweeper:implemented-on-mainSweeper: behavior already present on current maintype/perfPerformance improvement or optimization

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions