Skip to content

πŸ™Œ OpenHands: AI-Driven Development

Fix several async lockups (#5734)

Robert Brennand646b2089d1d
diff --git a/openhands/events/stream.py b/openhands/events/stream.py
index 68585ba00f..d592c17a8f 100644
--- a/openhands/events/stream.py
+++ b/openhands/events/stream.py
@@ -12,7 +12,7 @@ from openhands.events.serialization.event import event_from_dict, event_to_dict
from openhands.storage import FileStore
from openhands.storage.locations import (
get_conversation_dir,
- get_conversation_event_file,
+ get_conversation_event_filename,
get_conversation_events_dir,
)
from openhands.utils.async_utils import call_sync_from_async
@@ -77,7 +77,7 @@ class EventStream:
self._cur_id = id + 1
def _get_filename_for_id(self, id: int) -> str:
- return get_conversation_event_file(self.sid, id)
+ return get_conversation_event_filename(self.sid, id)
@staticmethod
def _get_id_from_filename(filename: str) -> int:
diff --git a/openhands/server/routes/github.py b/openhands/server/routes/github.py
index 99d299ab1f..7ec225767b 100644
--- a/openhands/server/routes/github.py
+++ b/openhands/server/routes/github.py
@@ -3,12 +3,13 @@ from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import JSONResponse
from openhands.server.shared import openhands_config
+from openhands.utils.async_utils import call_sync_from_async
app = APIRouter(prefix='/api')
@app.get('/github/repositories')
-def get_github_repositories(
+async def get_github_repositories(
request: Request,
page: int = 1,
per_page: int = 10,
@@ -44,7 +45,9 @@ def get_github_repositories(
# Fetch repositories from GitHub
try:
- response = requests.get(github_api_url, headers=headers, params=params)
+ response = await call_sync_from_async(
+ requests.get, github_api_url, headers=headers, params=params
+ )
response.raise_for_status() # Raise an error for HTTP codes >= 400
except requests.exceptions.RequestException as e:
raise HTTPException(
@@ -54,6 +57,7 @@ def get_github_repositories(
# Create response with the JSON content
json_response = JSONResponse(content=response.json())
+ response.close()
# Forward the Link header if it exists
if 'Link' in response.headers:
diff --git a/openhands/server/session/agent_session.py b/openhands/server/session/agent_session.py
index c04daa1a57..a3f87bf72f 100644
--- a/openhands/server/session/agent_session.py
+++ b/openhands/server/session/agent_session.py
@@ -15,7 +15,7 @@ from openhands.runtime import get_runtime_cls
from openhands.runtime.base import Runtime
from openhands.security import SecurityAnalyzer, options
from openhands.storage.files import FileStore
-from openhands.utils.async_utils import call_async_from_sync
+from openhands.utils.async_utils import call_async_from_sync, call_sync_from_async
from openhands.utils.shutdown_listener import should_continue
WAIT_TIME_BEFORE_CLOSE = 300
@@ -238,9 +238,10 @@ class AgentSession:
self.runtime.clone_repo(github_token, selected_repository)
if agent.prompt_manager:
- agent.prompt_manager.load_microagent_files(
- self.runtime.get_custom_microagents(selected_repository)
+ microagents = await call_sync_from_async(
+ self.runtime.get_custom_microagents, selected_repository
)
+ agent.prompt_manager.load_microagent_files(microagents)
logger.debug(
f'Runtime initialized with plugins: {[plugin.name for plugin in self.runtime.plugins]}'
diff --git a/openhands/server/session/manager.py b/openhands/server/session/manager.py
index e0d9a618f6..b8c0a4d869 100644
--- a/openhands/server/session/manager.py
+++ b/openhands/server/session/manager.py
@@ -13,11 +13,15 @@ from openhands.server.session.conversation import Conversation
from openhands.server.session.session import ROOM_KEY, Session
from openhands.server.session.session_init_data import SessionInitData
from openhands.storage.files import FileStore
+from openhands.utils.async_utils import call_sync_from_async
from openhands.utils.shutdown_listener import should_continue
_REDIS_POLL_TIMEOUT = 1.5
_CHECK_ALIVE_INTERVAL = 15
+_CLEANUP_INTERVAL = 15
+_CLEANUP_EXCEPTION_WAIT_TIME = 15
+
class ConversationDoesNotExistError(Exception):
pass
@@ -207,6 +211,8 @@ class SessionManager:
async def _cleanup_detached_conversations(self):
while should_continue():
+ logger.info(f'Attached conversations: {len(self._active_conversations)}')
+ logger.info(f'Detached conversations: {len(self._detached_conversations)}')
try:
async with self._conversations_lock:
# Create a list of items to process to avoid modifying dict during iteration
@@ -215,7 +221,7 @@ class SessionManager:
await conversation.disconnect()
self._detached_conversations.pop(sid, None)
- await asyncio.sleep(60)
+ await asyncio.sleep(_CLEANUP_INTERVAL)
except asyncio.CancelledError:
async with self._conversations_lock:
for conversation, _ in self._detached_conversations.values():
@@ -224,7 +230,7 @@ class SessionManager:
return
except Exception:
logger.warning('error_cleaning_detached_conversations', exc_info=True)
- await asyncio.sleep(15)
+ await asyncio.sleep(_CLEANUP_EXCEPTION_WAIT_TIME)
async def _is_session_running_in_cluster(self, sid: str) -> bool:
"""As the rest of the cluster if a session is running. Wait a for a short timeout for a reply"""
@@ -324,35 +330,30 @@ class SessionManager:
async def disconnect_from_session(self, connection_id: str):
sid = self.local_connection_id_to_session_id.pop(connection_id, None)
+ logger.info(f'disconnect_from_session:{connection_id}:{sid}')
if not sid:
# This can occur if the init action was never run.
logger.warning(f'disconnect_from_uninitialized_session:{connection_id}')
return
- session = self.local_sessions_by_sid.get(sid)
- if session:
- logger.info(f'close_session:{connection_id}:{sid}')
- if should_continue():
- asyncio.create_task(self._cleanup_session_later(session))
- else:
- await self._close_session(session)
+ if should_continue():
+ asyncio.create_task(self._cleanup_session_later(sid))
+ else:
+ await self._close_session(sid)
- async def _cleanup_session_later(self, session: Session):
+ async def _cleanup_session_later(self, sid: str):
# Once there have been no connections to a session for a reasonable period, we close it
try:
await asyncio.sleep(self.config.sandbox.close_delay)
finally:
# If the sleep was cancelled, we still want to close these
- await self._cleanup_session(session)
+ await self._cleanup_session(sid)
- async def _cleanup_session(self, session: Session):
+ async def _cleanup_session(self, sid: str) -> bool:
# Get local connections
+ logger.info(f'_cleanup_session:{sid}')
has_local_connections = next(
- (
- True
- for v in self.local_connection_id_to_session_id.values()
- if v == session.sid
- ),
+ (True for v in self.local_connection_id_to_session_id.values() if v == sid),
False,
)
if has_local_connections:
@@ -360,33 +361,38 @@ class SessionManager:
# If no local connections, get connections through redis
redis_client = self._get_redis_client()
- if redis_client and await self._has_remote_connections(session.sid):
+ if redis_client and await self._has_remote_connections(sid):
return False
# We alert the cluster in case they are interested
if redis_client:
await redis_client.publish(
'oh_event',
- json.dumps({'sid': session.sid, 'message_type': 'session_closing'}),
+ json.dumps({'sid': sid, 'message_type': 'session_closing'}),
)
- await self._close_session(session)
+ await self._close_session(sid)
return True
- async def _close_session(self, session: Session):
- logger.info(f'_close_session:{session.sid}')
+ async def _close_session(self, sid: str):
+ logger.info(f'_close_session:{sid}')
# Clear up local variables
connection_ids_to_remove = list(
connection_id
for connection_id, sid in self.local_connection_id_to_session_id.items()
- if sid == session.sid
+ if sid == sid
)
+ logger.info(f'removing connections: {connection_ids_to_remove}')
for connnnection_id in connection_ids_to_remove:
self.local_connection_id_to_session_id.pop(connnnection_id, None)
- self.local_sessions_by_sid.pop(session.sid, None)
+ session = self.local_sessions_by_sid.pop(sid, None)
+ if not session:
+ logger.warning(f'no_session_to_close:{sid}')
+ return
+ logger.info(f'closing_session:{session.sid}')
# We alert the cluster in case they are interested
redis_client = self._get_redis_client()
if redis_client:
@@ -395,4 +401,5 @@ class SessionManager:
json.dumps({'sid': session.sid, 'message_type': 'session_closing'}),
)
- session.close()
+ await call_sync_from_async(session.close)
+ logger.info(f'closed_session:{session.sid}')
diff --git a/openhands/storage/conversation/conversation_store.py b/openhands/storage/conversation/conversation_store.py
index e225e77503..461c1a98b7 100644
--- a/openhands/storage/conversation/conversation_store.py
+++ b/openhands/storage/conversation/conversation_store.py
@@ -4,7 +4,8 @@ from dataclasses import dataclass
from openhands.core.config.app_config import AppConfig
from openhands.storage import get_file_store
from openhands.storage.files import FileStore
-from openhands.storage.locations import get_conversation_metadata_file
+from openhands.storage.locations import get_conversation_metadata_filename
+from openhands.utils.async_utils import call_sync_from_async
@dataclass
@@ -20,18 +21,18 @@ class ConversationStore:
async def save_metadata(self, metadata: ConversationMetadata):
json_str = json.dumps(metadata.__dict__)
- path = get_conversation_metadata_file(metadata.conversation_id)
- self.file_store.write(path, json_str)
+ path = get_conversation_metadata_filename(metadata.conversation_id)
+ await call_sync_from_async(self.file_store.write, path, json_str)
async def get_metadata(self, conversation_id: str) -> ConversationMetadata:
- path = get_conversation_metadata_file(conversation_id)
- json_str = self.file_store.read(path)
+ path = get_conversation_metadata_filename(conversation_id)
+ json_str = await call_sync_from_async(self.file_store.read, path)
return ConversationMetadata(**json.loads(json_str))
async def exists(self, conversation_id: str) -> bool:
- path = get_conversation_metadata_file(conversation_id)
+ path = get_conversation_metadata_filename(conversation_id)
try:
- self.file_store.read(path)
+ await call_sync_from_async(self.file_store.read, path)
return True
except FileNotFoundError:
return False
diff --git a/openhands/storage/file_settings_store.py b/openhands/storage/file_settings_store.py
index f05bae4169..b3cb9bb8ea 100644
--- a/openhands/storage/file_settings_store.py
+++ b/openhands/storage/file_settings_store.py
@@ -8,6 +8,7 @@ from openhands.server.settings import Settings
from openhands.storage import get_file_store
from openhands.storage.files import FileStore
from openhands.storage.settings_store import SettingsStore
+from openhands.utils.async_utils import call_sync_from_async
@dataclass
@@ -17,7 +18,7 @@ class FileSettingsStore(SettingsStore):
async def load(self) -> Settings | None:
try:
- json_str = self.file_store.read(self.path)
+ json_str = await call_sync_from_async(self.file_store.read, self.path)
kwargs = json.loads(json_str)
settings = Settings(**kwargs)
return settings
@@ -26,7 +27,7 @@ class FileSettingsStore(SettingsStore):
async def store(self, settings: Settings):
json_str = json.dumps(settings.__dict__)
- self.file_store.write(self.path, json_str)
+ await call_sync_from_async(self.file_store.write, self.path, json_str)
@classmethod
async def get_instance(cls, config: AppConfig, token: str | None):
diff --git a/openhands/storage/locations.py b/openhands/storage/locations.py
index 8c57e1a5ba..88212f0195 100644
--- a/openhands/storage/locations.py
+++ b/openhands/storage/locations.py
@@ -9,9 +9,9 @@ def get_conversation_events_dir(sid: str) -> str:
return f'{get_conversation_dir(sid)}events/'
-def get_conversation_event_file(sid: str, id: int) -> str:
+def get_conversation_event_filename(sid: str, id: int) -> str:
return f'{get_conversation_events_dir(sid)}{id}.json'
-def get_conversation_metadata_file(sid: str) -> str:
+def get_conversation_metadata_filename(sid: str) -> str:
return f'{get_conversation_dir(sid)}metadata.json'