Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
126 changes: 113 additions & 13 deletions backend/app/api/ws/device_namespace.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

import asyncio
import logging
import time
import uuid
from contextlib import contextmanager
from dataclasses import dataclass
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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}")
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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
)
Comment on lines +922 to +939

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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 second device:register within the debounce window skips _register_device() even when name, client_ip, device_type, or bind_shell changed. 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.

else:
persisted_display_name = payload.name

Expand Down Expand Up @@ -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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Debounced reconnects still fan out capability-sync storms.

Every successful device:register schedules _sync_global_capabilities_to_registered_device(), including the cached fast path above. A reconnect burst for one device now skips the DB upsert but still enqueues one capability-sync task per reconnect, which turns the storm into repeated DB reads and Socket.IO RPCs. Gate this with an in-flight/recent-sync key per (user_id, device_id) or only schedule after a real registration change.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/app/api/ws/device_namespace.py` around lines 968 - 974, The code
currently schedules _sync_global_capabilities_to_registered_device for every
device:register (via _schedule_background_task), causing repeated syncs on
debounced reconnects; update the registration handling to avoid scheduling when
a recent sync is in-flight or recently completed for the same (user_id,
device_id): add a short-lived in-memory lock/cache keyed by (user_id, device_id)
(e.g., _capability_sync_inflight or _recent_capability_sync) that is set before
scheduling in _schedule_background_task and cleared after the task finishes (or
expires after N seconds), and only call _schedule_background_task for
_sync_global_capabilities_to_registered_device if the lock/cache is absent;
alternatively, only schedule when the registration actually changed (compare
previous registration state before enqueuing) inside the device:register
handling code that currently invokes _schedule_background_task.


logger.info(
Expand All @@ -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(
Expand Down
3 changes: 2 additions & 1 deletion backend/app/services/device/capability_sync_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,7 @@ async def sync_device_payload(
user_id: int,
device_id: str,
payload: dict[str, Any],
timeout_seconds: int = SYNC_TIMEOUT_SECONDS,
) -> DeviceCapabilitySyncResult:
"""Push an already-built desired payload to one online device."""
online_info = await device_service.get_device_online_info(user_id, device_id)
Expand Down Expand Up @@ -253,7 +254,7 @@ async def sync_device_payload(
payload,
to=socket_id,
namespace=SYNC_NAMESPACE,
timeout=SYNC_TIMEOUT_SECONDS,
timeout=timeout_seconds,
)
except Exception as exc:
logger.warning(
Expand Down
168 changes: 168 additions & 0 deletions backend/tests/api/ws/test_device_reconnect_storm.py
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Patch the module-level executor helper here, not the namespace instance.

DeviceNamespace does not expose a run_sync_in_executor attribute, so this monkeypatch.setattr(namespace, "run_sync_in_executor", ...) call fails before the test reaches on_disconnect(). Even if it did not, on_disconnect() resolves run_sync_in_executor from app.api.ws.device_namespace, so the final assertion is checking the wrong object.

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
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/tests/api/ws/test_device_reconnect_storm.py` around lines 157 - 168,
The monkeypatch targets the instance `namespace` but `on_disconnect()` resolves
`run_sync_in_executor` from the module-level `device_namespace`, and
`DeviceNamespace` has no instance attribute `run_sync_in_executor`; update the
test to patch `device_namespace.run_sync_in_executor` (the module-level helper)
instead of `namespace`, i.e. replace the `monkeypatch.setattr(namespace,
"run_sync_in_executor", AsyncMock(...))` with
`monkeypatch.setattr(device_namespace, "run_sync_in_executor", AsyncMock(...))`;
keep the other patches and final assertions for `set_offline`,
`device_namespace.run_sync_in_executor`, and
`namespace._broadcast_device_offline` as-is so they assert the correct objects
called by `namespace.on_disconnect`.

Loading