From 625b6030ed89d160dabd578b2d24d0c3d51034ac Mon Sep 17 00:00:00 2001 From: Clint Bodungen <126857035+R1ngZer0@users.noreply.github.com> Date: Tue, 29 Sep 2026 09:49:22 -0500 Subject: [PATCH] Run prekey and pubkey fleet lookups off the event loop dm_get_prekey_bundle and dm_get_pubkey are async but called the synchronous fetch_dm_prekey_bundle directly. When the lookup handle isn't local it calls peers over the network, which blocked the event loop so every endpoint stopped answering until it returned. Run it with asyncio.to_thread, as main.py does for other blocking calls, and add a regression test that checks the loop keeps ticking during a slow lookup. --- backend/main.py | 8 +- .../mesh/test_prekey_lookup_event_loop.py | 82 +++++++++++++++++++ 2 files changed, 88 insertions(+), 2 deletions(-) create mode 100644 backend/tests/mesh/test_prekey_lookup_event_loop.py diff --git a/backend/main.py b/backend/main.py index a0992421..1439d0a2 100644 --- a/backend/main.py +++ b/backend/main.py @@ -7610,7 +7610,9 @@ async def dm_get_pubkey( from services.mesh.mesh_wormhole_prekey import fetch_dm_prekey_bundle preferred_lookup_peer = str(lookup_peer_url or "").strip().rstrip("/") - remote_bundle = fetch_dm_prekey_bundle( + # Off the event loop: the fleet lookup makes blocking network calls. + remote_bundle = await asyncio.to_thread( + fetch_dm_prekey_bundle, agent_id="", lookup_token=resolved_lookup, lookup_peer_urls=[preferred_lookup_peer] if preferred_lookup_peer else None, @@ -7700,7 +7702,9 @@ async def dm_get_prekey_bundle( ) resolved_id, resolved_lookup = _preferred_dm_lookup_target(agent_id, lookup_token) preferred_lookup_peer = str(lookup_peer_url or "").strip().rstrip("/") - result = fetch_dm_prekey_bundle( + # Off the event loop: the fleet lookup makes blocking network calls. + result = await asyncio.to_thread( + fetch_dm_prekey_bundle, agent_id=resolved_id, lookup_token=resolved_lookup, lookup_peer_urls=[preferred_lookup_peer] if preferred_lookup_peer else None, diff --git a/backend/tests/mesh/test_prekey_lookup_event_loop.py b/backend/tests/mesh/test_prekey_lookup_event_loop.py new file mode 100644 index 00000000..c8feebd7 --- /dev/null +++ b/backend/tests/mesh/test_prekey_lookup_event_loop.py @@ -0,0 +1,82 @@ +"""Prekey and pubkey lookups don't block the event loop while they wait on the network.""" + +from __future__ import annotations + +import asyncio +import time +from unittest.mock import patch + +import pytest + + +def _request(path: str): + import main + + return main.Request( + { + "type": "http", + "method": "GET", + "path": path, + "headers": [], + "client": ("127.0.0.1", 12345), + } + ) + + +def _slow_lookup(*_args, **_kwargs): + # Stands in for a fleet lookup waiting on a slow or unreachable peer. + time.sleep(1.0) + return {"ok": False, "detail": "Prekey bundle not found"} + + +async def _longest_stall(endpoint) -> float: + """Runs the endpoint while a 50 ms ticker runs; returns the longest gap between ticks.""" + gaps: list[float] = [] + done = asyncio.Event() + + async def ticker(): + last = time.monotonic() + while not done.is_set(): + await asyncio.sleep(0.05) + now = time.monotonic() + gaps.append(now - last) + last = now + + task = asyncio.create_task(ticker()) + await asyncio.sleep(0) + try: + await endpoint() + finally: + done.set() + await task + return max(gaps) + + +@pytest.mark.asyncio +async def test_prekey_bundle_lookup_does_not_block_the_event_loop(): + import main + + request = _request("/api/mesh/dm/prekey-bundle") + with patch("main.fetch_dm_prekey_bundle", side_effect=_slow_lookup): + stall = await _longest_stall( + lambda: main.dm_get_prekey_bundle(request, lookup_token="unknown-handle-token") + ) + # A 1 s lookup on the loop stalls it about 1 s; off the loop, a 50 ms tick stays well under 0.5 s. + assert stall < 0.5, f"the event loop stalled for {stall:.2f}s during the lookup" + + +@pytest.mark.asyncio +async def test_pubkey_fleet_lookup_does_not_block_the_event_loop(): + import main + + request = _request("/api/mesh/dm/pubkey") + with patch("services.mesh.mesh_dm_relay.dm_relay") as relay, patch( + "services.mesh.mesh_wormhole_prekey.fetch_dm_prekey_bundle", + side_effect=_slow_lookup, + ): + relay.get_dh_key_by_lookup.return_value = (None, "") + stall = await _longest_stall( + lambda: main.dm_get_pubkey(request, lookup_token="unknown-handle-token") + ) + # A 1 s lookup on the loop stalls it about 1 s; off the loop, a 50 ms tick stays well under 0.5 s. + assert stall < 0.5, f"the event loop stalled for {stall:.2f}s during the lookup"