Repository navigation
fix(backend): protect device websocket reconnect storms #1384
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -25,6 +25,7 @@ | |
|
|
||
| import asyncio | ||
| import logging | ||
| import time | ||
| import uuid | ||
| from contextlib import contextmanager | ||
| from dataclasses import dataclass | ||
|
|
@@ -69,6 +70,10 @@ | |
|
|
||
| logger = logging.getLogger(__name__) | ||
| CODEX_RUNTIME = "codex" | ||
| DEVICE_CONNECT_RATE_LIMIT_WINDOW_SECONDS = 30 | ||
| DEVICE_CONNECT_RATE_LIMIT_MAX_ATTEMPTS = 30 | ||
| DEVICE_REGISTER_UPSERT_DEBOUNCE_SECONDS = 10 | ||
| REGISTER_CAPABILITY_SYNC_TIMEOUT_SECONDS = 5 | ||
|
|
||
|
|
||
| @contextmanager | ||
|
|
@@ -471,6 +476,68 @@ def __init__(self, namespace: str = "/local-executor"): | |
| # events arrive concurrently for the same subtask | ||
| self._subtask_locks: Dict[int, asyncio.Lock] = {} | ||
| self._runtime_auth_sync_inflight: set[tuple[int, str, str]] = set() | ||
| self._connection_attempts: Dict[str, list[float]] = {} | ||
| self._recent_registrations: Dict[tuple[int, str], tuple[float, str]] = {} | ||
| self._background_tasks: set[asyncio.Task] = set() | ||
|
|
||
| def _is_connection_rate_limited( | ||
| self, key: str, now: Optional[float] = None | ||
| ) -> bool: | ||
| """Return True when the connection attempt key exceeds the local window.""" | ||
| current = time.monotonic() if now is None else now | ||
| cutoff = current - DEVICE_CONNECT_RATE_LIMIT_WINDOW_SECONDS | ||
| attempts = [ | ||
| attempt | ||
| for attempt in self._connection_attempts.get(key, []) | ||
| if attempt > cutoff | ||
| ] | ||
| if len(attempts) >= DEVICE_CONNECT_RATE_LIMIT_MAX_ATTEMPTS: | ||
| self._connection_attempts[key] = attempts | ||
| return True | ||
|
|
||
| attempts.append(current) | ||
| self._connection_attempts[key] = attempts | ||
| return False | ||
|
|
||
| def _get_recent_registration_display_name( | ||
| self, user_id: int, device_id: str | ||
| ) -> Optional[str]: | ||
| """Return cached display name when a device just registered successfully.""" | ||
| key = (user_id, device_id) | ||
| cached = self._recent_registrations.get(key) | ||
| if not cached: | ||
| return None | ||
|
|
||
| registered_at, display_name = cached | ||
| if time.monotonic() - registered_at > DEVICE_REGISTER_UPSERT_DEBOUNCE_SECONDS: | ||
| self._recent_registrations.pop(key, None) | ||
| return None | ||
| return display_name | ||
|
|
||
| def _remember_registration( | ||
| self, user_id: int, device_id: str, display_name: str | ||
| ) -> None: | ||
| """Record a successful registration to absorb immediate reconnect storms.""" | ||
| self._recent_registrations[(user_id, device_id)] = ( | ||
| time.monotonic(), | ||
| display_name, | ||
| ) | ||
|
|
||
| def _schedule_background_task(self, coro, description: str) -> None: | ||
| """Run best-effort follow-up work without blocking device registration.""" | ||
| task = asyncio.create_task(coro) | ||
| self._background_tasks.add(task) | ||
|
|
||
| def _on_done(done_task: asyncio.Task) -> None: | ||
| self._background_tasks.discard(done_task) | ||
| try: | ||
| done_task.result() | ||
| except asyncio.CancelledError: | ||
| logger.debug("[Device WS] Background task cancelled: %s", description) | ||
| except Exception: | ||
| logger.exception("[Device WS] Background task failed: %s", description) | ||
|
|
||
| task.add_done_callback(_on_done) | ||
|
|
||
| def _get_subtask_lock(self, subtask_id: int) -> asyncio.Lock: | ||
| """Get or create a lock for the given subtask. | ||
|
|
@@ -646,6 +713,13 @@ async def on_connect(self, sid: str, environ: dict, auth: Optional[dict] = None) | |
| ) | ||
| raise ConnectionRefusedError("Server is shutting down") | ||
|
|
||
| rate_limit_key = f"ip:{client_ip or 'unknown'}" | ||
| if self._is_connection_rate_limited(rate_limit_key): | ||
| logger.warning( | ||
| f"[Device WS] Rate limited connection sid={sid}, key={rate_limit_key}" | ||
| ) | ||
| raise ConnectionRefusedError("Too many device connection attempts") | ||
|
|
||
| # Check auth token | ||
| if not auth or not isinstance(auth, dict): | ||
| logger.warning(f"[Device WS] Missing auth data sid={sid}") | ||
|
|
@@ -750,6 +824,21 @@ async def on_disconnect(self, sid: str): | |
| ) | ||
|
|
||
| if user_id and device_id: | ||
| online_info = await device_service.get_device_online_info( | ||
| user_id, device_id | ||
| ) | ||
| online_socket_id = online_info.get("socket_id") if online_info else None | ||
| if online_socket_id and online_socket_id != sid: | ||
| logger.info( | ||
| "[Device WS] Ignoring stale disconnect: user=%s, device=%s, " | ||
| "sid=%s, current_sid=%s", | ||
| user_id, | ||
| device_id, | ||
| sid, | ||
| online_socket_id, | ||
| ) | ||
| return | ||
|
|
||
| # Remove from Redis online status | ||
| await device_service.set_device_offline(user_id, device_id) | ||
|
|
||
|
|
@@ -830,17 +919,24 @@ async def on_device_register(self, sid: str, data: dict) -> dict: | |
| # Pass client_ip to _register_device for tracking | ||
| # Run in executor to avoid blocking event loop | ||
| if not is_cloud_device: | ||
| success, persisted_display_name, error = await run_sync_in_executor( | ||
| _register_device, | ||
| user_id, | ||
| payload.device_id, | ||
| payload.name, | ||
| payload.client_ip, | ||
| payload.device_type.value, | ||
| payload.bind_shell.value, | ||
| persisted_display_name = self._get_recent_registration_display_name( | ||
| user_id, payload.device_id | ||
| ) | ||
| if not success: | ||
| return {"error": f"Registration failed: {error}"} | ||
| if persisted_display_name is None: | ||
| success, persisted_display_name, error = await run_sync_in_executor( | ||
| _register_device, | ||
| user_id, | ||
| payload.device_id, | ||
| payload.name, | ||
| payload.client_ip, | ||
| payload.device_type.value, | ||
| payload.bind_shell.value, | ||
| ) | ||
| if not success: | ||
| return {"error": f"Registration failed: {error}"} | ||
| self._remember_registration( | ||
| user_id, payload.device_id, persisted_display_name or payload.name | ||
| ) | ||
| else: | ||
| persisted_display_name = payload.name | ||
|
|
||
|
|
@@ -869,9 +965,12 @@ async def on_device_register(self, sid: str, data: dict) -> dict: | |
| await self._broadcast_device_online( | ||
| user_id, payload.device_id, effective_device_name | ||
| ) | ||
| await self._sync_global_capabilities_to_registered_device( | ||
| user_id=user_id, | ||
| device_id=payload.device_id, | ||
| self._schedule_background_task( | ||
| self._sync_global_capabilities_to_registered_device( | ||
| user_id=user_id, | ||
| device_id=payload.device_id, | ||
| ), | ||
| "sync global capabilities after device registration", | ||
| ) | ||
|
Comment on lines
+968
to
974
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Debounced reconnects still fan out capability-sync storms. Every successful 🤖 Prompt for AI Agents |
||
|
|
||
| logger.info( | ||
|
|
@@ -897,6 +996,7 @@ async def _sync_global_capabilities_to_registered_device( | |
| user_id=user_id, | ||
| device_id=device_id, | ||
| payload=payload, | ||
| timeout_seconds=REGISTER_CAPABILITY_SYNC_TIMEOUT_SECONDS, | ||
| ) | ||
| if not result.success: | ||
| logger.warning( | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,168 @@ | ||
| # SPDX-FileCopyrightText: 2026 Weibo, Inc. | ||
| # | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| import asyncio | ||
| from unittest.mock import AsyncMock | ||
|
|
||
| import pytest | ||
|
|
||
| from app.api.ws import device_namespace | ||
| from app.api.ws.device_namespace import DeviceNamespace | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_device_register_does_not_wait_for_capability_sync(monkeypatch): | ||
| namespace = DeviceNamespace() | ||
| sync_started = asyncio.Event() | ||
| sync_release = asyncio.Event() | ||
|
|
||
| async def fake_get_session(sid): | ||
| return { | ||
| "user_id": 7, | ||
| "client_ip": "127.0.0.1", | ||
| } | ||
|
|
||
| async def fake_run_sync_in_executor(func, *args): | ||
| return True, "MacBook", None | ||
|
|
||
| async def slow_capability_sync(*, user_id, device_id): | ||
| sync_started.set() | ||
| await sync_release.wait() | ||
|
|
||
| monkeypatch.setattr(namespace, "get_session", fake_get_session) | ||
| monkeypatch.setattr(namespace, "save_session", AsyncMock()) | ||
| monkeypatch.setattr(namespace, "enter_room", AsyncMock()) | ||
| monkeypatch.setattr(namespace, "_match_cloud_device", AsyncMock(return_value=None)) | ||
| monkeypatch.setattr(namespace, "_broadcast_device_online", AsyncMock()) | ||
| monkeypatch.setattr( | ||
| namespace, | ||
| "_sync_global_capabilities_to_registered_device", | ||
| slow_capability_sync, | ||
| ) | ||
| monkeypatch.setattr( | ||
| device_namespace, | ||
| "run_sync_in_executor", | ||
| fake_run_sync_in_executor, | ||
| ) | ||
| monkeypatch.setattr( | ||
| device_namespace.device_service, | ||
| "set_device_online", | ||
| AsyncMock(return_value=True), | ||
| ) | ||
|
|
||
| register_task = asyncio.create_task( | ||
| namespace.on_device_register( | ||
| "sid-1", | ||
| { | ||
| "device_id": "device-1", | ||
| "name": "MacBook", | ||
| "executor_version": "1.8.0", | ||
| }, | ||
| ) | ||
| ) | ||
|
|
||
| await asyncio.wait_for(sync_started.wait(), timeout=0.5) | ||
| result = await asyncio.wait_for(register_task, timeout=0.5) | ||
|
|
||
| assert result == {"success": True, "device_id": "device-1"} | ||
| sync_release.set() | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_device_register_debounces_repeated_db_upserts(monkeypatch): | ||
| namespace = DeviceNamespace() | ||
| upsert_calls = 0 | ||
|
|
||
| async def fake_get_session(sid): | ||
| return { | ||
| "user_id": 7, | ||
| "client_ip": "127.0.0.1", | ||
| } | ||
|
|
||
| async def fake_run_sync_in_executor(func, *args): | ||
| nonlocal upsert_calls | ||
| upsert_calls += 1 | ||
| return True, "MacBook", None | ||
|
|
||
| monkeypatch.setattr(namespace, "get_session", fake_get_session) | ||
| monkeypatch.setattr(namespace, "save_session", AsyncMock()) | ||
| monkeypatch.setattr(namespace, "enter_room", AsyncMock()) | ||
| monkeypatch.setattr(namespace, "_match_cloud_device", AsyncMock(return_value=None)) | ||
| monkeypatch.setattr(namespace, "_broadcast_device_online", AsyncMock()) | ||
| monkeypatch.setattr( | ||
| namespace, | ||
| "_sync_global_capabilities_to_registered_device", | ||
| AsyncMock(), | ||
| ) | ||
| monkeypatch.setattr( | ||
| device_namespace, | ||
| "run_sync_in_executor", | ||
| fake_run_sync_in_executor, | ||
| ) | ||
| monkeypatch.setattr( | ||
| device_namespace.device_service, | ||
| "set_device_online", | ||
| AsyncMock(return_value=True), | ||
| ) | ||
|
|
||
| payload = { | ||
| "device_id": "device-1", | ||
| "name": "MacBook", | ||
| "executor_version": "1.8.0", | ||
| } | ||
|
|
||
| first = await namespace.on_device_register("sid-1", payload) | ||
| second = await namespace.on_device_register("sid-2", payload) | ||
|
|
||
| assert first == {"success": True, "device_id": "device-1"} | ||
| assert second == {"success": True, "device_id": "device-1"} | ||
| assert upsert_calls == 1 | ||
|
|
||
|
|
||
| def test_connection_rate_limit_tracks_attempt_window(): | ||
| namespace = DeviceNamespace() | ||
| key = "ip:127.0.0.1" | ||
|
|
||
| for _ in range(device_namespace.DEVICE_CONNECT_RATE_LIMIT_MAX_ATTEMPTS): | ||
| assert namespace._is_connection_rate_limited(key, now=100.0) is False | ||
|
|
||
| assert namespace._is_connection_rate_limited(key, now=100.0) is True | ||
|
|
||
| reset_at = 100.0 + device_namespace.DEVICE_CONNECT_RATE_LIMIT_WINDOW_SECONDS + 0.1 | ||
| assert namespace._is_connection_rate_limited(key, now=reset_at) is False | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_stale_disconnect_does_not_clear_newer_device_socket(monkeypatch): | ||
| namespace = DeviceNamespace() | ||
|
|
||
| async def fake_get_session(sid): | ||
| return { | ||
| "user_id": 7, | ||
| "device_id": "device-1", | ||
| "request_id": "req-1", | ||
| } | ||
|
|
||
| monkeypatch.setattr(namespace, "get_session", fake_get_session) | ||
| monkeypatch.setattr( | ||
| device_namespace.device_service, | ||
| "get_device_online_info", | ||
| AsyncMock(return_value={"socket_id": "sid-new"}), | ||
| ) | ||
| set_offline = AsyncMock() | ||
| monkeypatch.setattr( | ||
| device_namespace.device_service, "set_device_offline", set_offline | ||
| ) | ||
| monkeypatch.setattr( | ||
| device_namespace, | ||
| "run_sync_in_executor", | ||
| AsyncMock(return_value=[]), | ||
| ) | ||
| monkeypatch.setattr(namespace, "_broadcast_device_offline", AsyncMock()) | ||
|
|
||
| await namespace.on_disconnect("sid-old") | ||
|
|
||
| set_offline.assert_not_awaited() | ||
| device_namespace.run_sync_in_executor.assert_not_awaited() | ||
| namespace._broadcast_device_offline.assert_not_awaited() | ||
|
Comment on lines
+157
to
+168
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Patch the module-level executor helper here, not the namespace instance.
Suggested fix- monkeypatch.setattr(
- namespace,
- "run_sync_in_executor",
- AsyncMock(return_value=[]),
- )
+ run_sync_in_executor_mock = AsyncMock(return_value=[])
+ monkeypatch.setattr(
+ device_namespace,
+ "run_sync_in_executor",
+ run_sync_in_executor_mock,
+ )
monkeypatch.setattr(namespace, "_broadcast_device_offline", AsyncMock())
@@
- device_namespace.run_sync_in_executor.assert_not_awaited()
+ run_sync_in_executor_mock.assert_not_awaited()🤖 Prompt for AI Agents |
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Only debounce identical registration payloads.
This fast path keys the cache by
(user_id, device_id)and only reuses a cached display name, so a seconddevice:registerwithin the debounce window skips_register_device()even whenname,client_ip,device_type, orbind_shellchanged. That leaves the CRD stale and can also overwrite the fresh name with the previous cached display name. Please include a fingerprint of the persisted fields in the debounce lookup and add a regression test for changed metadata.