Skip to content

πŸ™Œ OpenHands: AI-Driven Development

Remove _get_sandbox_by_session_api_key_legacy to stop spurious runtime API queries on stopped sandboxes (#14706)

Tim O'Farrell7aa694fda209
diff --git a/openhands/app_server/sandbox/remote_sandbox_service.py b/openhands/app_server/sandbox/remote_sandbox_service.py
index 7a1bb67229..bf715e7ddb 100644
--- a/openhands/app_server/sandbox/remote_sandbox_service.py
+++ b/openhands/app_server/sandbox/remote_sandbox_service.py
@@ -352,74 +352,12 @@ class RemoteSandboxService(SandboxService):
return self._to_sandbox_info(stored_sandbox, runtime)
- async def _get_sandbox_by_session_api_key_legacy(
- self, session_api_key: str
- ) -> SandboxInfo | None:
- """Legacy method to get sandbox by session API key via runtime API.
-
- This is the fallback for sandboxes created before the session_api_key_hash
- column was added. It calls the remote runtime API which is less efficient.
- """
- try:
- response = await self._send_runtime_api_request(
- 'GET',
- '/list',
- )
- response.raise_for_status()
- content = response.json()
- for runtime in content['runtimes']:
- if session_api_key == runtime['session_api_key']:
- query = await self._secure_select()
- query = query.filter(
- StoredRemoteSandbox.id == runtime.get('session_id')
- )
- result = await self.db_session.execute(query)
- sandbox = result.scalar_one_or_none()
- if sandbox is None:
- raise ValueError('sandbox_not_found')
- # Backfill the hash for future lookups (Auto committed at end of request)
- sandbox.session_api_key_hash = _hash_session_api_key(
- session_api_key
- )
- return self._to_sandbox_info(sandbox, runtime)
- except Exception:
- _logger.exception(
- 'Error getting sandbox from session_api_key', stack_info=True
- )
-
- # Get all stored sandboxes for the current user
- stmt = await self._secure_select()
- result = await self.db_session.execute(stmt)
- stored_sandboxes = result.scalars().all()
-
- # Check each sandbox's runtime data for matching session_api_key
- for stored_sandbox in stored_sandboxes:
- try:
- runtime = await self._get_runtime(stored_sandbox.id)
- if runtime and runtime.get('session_api_key') == session_api_key:
- # Backfill the hash for future lookups (Auto committed at end of request)
- stored_sandbox.session_api_key_hash = _hash_session_api_key(
- session_api_key
- )
- return self._to_sandbox_info(stored_sandbox, runtime)
- except Exception:
- # Continue checking other sandboxes if one fails
- continue
-
- return None
-
async def get_sandbox_by_session_api_key(
self, session_api_key: str
) -> SandboxInfo | None:
- """Get a single sandbox by session API key.
-
- Uses the stored session_api_key_hash for efficient database lookup instead
- of calling the remote runtime API. Falls back to legacy API-based lookup
- for sandboxes created before the hash column was added.
- """
+ """Get a single sandbox by session API key using the stored hash."""
session_api_key_hash = _hash_session_api_key(session_api_key)
- # First try to find sandbox by hash in the database
stmt = await self._secure_select()
stmt = stmt.where(
StoredRemoteSandbox.session_api_key_hash == session_api_key_hash
@@ -427,19 +365,18 @@ class RemoteSandboxService(SandboxService):
result = await self.db_session.execute(stmt)
stored_sandbox = result.scalar_one_or_none()
- if stored_sandbox:
- try:
- runtime = await self._get_runtime(stored_sandbox.id)
- return self._to_sandbox_info(stored_sandbox, runtime)
- except Exception:
- _logger.exception(
- f'Error getting runtime for sandbox {stored_sandbox.id}',
- stack_info=True,
- )
- return self._to_sandbox_info(stored_sandbox, None)
+ if stored_sandbox is None:
+ return None
- # Fallback for sandboxes created before the hash column was added
- return await self._get_sandbox_by_session_api_key_legacy(session_api_key)
+ try:
+ runtime = await self._get_runtime(stored_sandbox.id)
+ return self._to_sandbox_info(stored_sandbox, runtime)
+ except Exception:
+ _logger.exception(
+ f'Error getting runtime for sandbox {stored_sandbox.id}',
+ stack_info=True,
+ )
+ return self._to_sandbox_info(stored_sandbox, None)
async def start_sandbox(
self, sandbox_spec_id: str | None = None, sandbox_id: str | None = None
diff --git a/tests/unit/app_server/test_remote_sandbox_service.py b/tests/unit/app_server/test_remote_sandbox_service.py
index 9bbdaac444..f316559e19 100644
--- a/tests/unit/app_server/test_remote_sandbox_service.py
+++ b/tests/unit/app_server/test_remote_sandbox_service.py
@@ -1023,132 +1023,18 @@ class TestGetSandboxBySessionApiKey:
async def test_get_sandbox_by_session_api_key_not_found(
self, remote_sandbox_service
):
- """Test finding sandbox when no matching hash exists and legacy fallback fails."""
- # Setup - no hash match
- mock_result_no_hash = MagicMock()
- mock_result_no_hash.scalar_one_or_none.return_value = None
-
- # Setup - legacy fallback: /list API fails, then no stored sandboxes
- mock_response = MagicMock()
- mock_response.raise_for_status.side_effect = Exception('API error')
- remote_sandbox_service.httpx_client.request = AsyncMock(
- return_value=mock_response
- )
-
- mock_result_legacy = MagicMock()
- mock_result_legacy.scalars.return_value.all.return_value = []
-
- remote_sandbox_service.db_session.execute = AsyncMock(
- side_effect=[mock_result_no_hash, mock_result_legacy]
- )
+ """Test that None is returned when no sandbox matches the session API key hash."""
+ mock_result = MagicMock()
+ mock_result.scalar_one_or_none.return_value = None
+ remote_sandbox_service.db_session.execute = AsyncMock(return_value=mock_result)
remote_sandbox_service.user_context.get_user_id.return_value = 'test-user-123'
- # Execute
result = await remote_sandbox_service.get_sandbox_by_session_api_key(
'unknown-key'
)
- # Verify
assert result is None
- @pytest.mark.asyncio
- async def test_get_sandbox_by_session_api_key_legacy_via_list_api(
- self, remote_sandbox_service
- ):
- """Test legacy fallback finding sandbox via /list API and backfilling hash."""
- from openhands.app_server.sandbox.remote_sandbox_service import (
- _hash_session_api_key,
- )
-
- # Setup
- session_api_key = 'test-session-key'
- stored_sandbox = create_stored_sandbox(
- session_api_key_hash=None
- ) # Legacy sandbox
- runtime_data = create_runtime_data(session_api_key=session_api_key)
-
- # First call returns None (no hash match)
- mock_result_no_match = MagicMock()
- mock_result_no_match.scalar_one_or_none.return_value = None
-
- # Legacy fallback: /list API returns the runtime
- mock_response = MagicMock()
- mock_response.raise_for_status.return_value = None
- mock_response.json.return_value = {'runtimes': [runtime_data]}
- remote_sandbox_service.httpx_client.request = AsyncMock(
- return_value=mock_response
- )
-
- # Query for sandbox by session_id returns the stored sandbox
- mock_result_sandbox = MagicMock()
- mock_result_sandbox.scalar_one_or_none.return_value = stored_sandbox
-
- remote_sandbox_service.db_session.execute = AsyncMock(
- side_effect=[mock_result_no_match, mock_result_sandbox]
- )
- remote_sandbox_service.user_context.get_user_id.return_value = 'test-user-123'
-
- # Execute
- result = await remote_sandbox_service.get_sandbox_by_session_api_key(
- session_api_key
- )
-
- # Verify
- assert result is not None
- assert result.id == 'test-sandbox-123'
- # Verify the hash was backfilled
- expected_hash = _hash_session_api_key(session_api_key)
- assert stored_sandbox.session_api_key_hash == expected_hash
-
- @pytest.mark.asyncio
- async def test_get_sandbox_by_session_api_key_legacy_via_runtime_check(
- self, remote_sandbox_service
- ):
- """Test legacy fallback checking each sandbox's runtime when /list API fails."""
- from openhands.app_server.sandbox.remote_sandbox_service import (
- _hash_session_api_key,
- )
-
- # Setup
- session_api_key = 'test-session-key'
- stored_sandbox = create_stored_sandbox(
- session_api_key_hash=None
- ) # Legacy sandbox
- runtime_data = create_runtime_data(session_api_key=session_api_key)
-
- # First call returns None (no hash match)
- mock_result_no_match = MagicMock()
- mock_result_no_match.scalar_one_or_none.return_value = None
-
- # Legacy fallback: /list API fails
- mock_response = MagicMock()
- mock_response.raise_for_status.side_effect = Exception('API error')
- remote_sandbox_service.httpx_client.request = AsyncMock(
- return_value=mock_response
- )
-
- # Get all stored sandboxes returns the legacy sandbox
- mock_result_all = MagicMock()
- mock_result_all.scalars.return_value.all.return_value = [stored_sandbox]
-
- remote_sandbox_service.db_session.execute = AsyncMock(
- side_effect=[mock_result_no_match, mock_result_all]
- )
- remote_sandbox_service._get_runtime = AsyncMock(return_value=runtime_data)
- remote_sandbox_service.user_context.get_user_id.return_value = 'test-user-123'
-
- # Execute
- result = await remote_sandbox_service.get_sandbox_by_session_api_key(
- session_api_key
- )
-
- # Verify
- assert result is not None
- assert result.id == 'test-sandbox-123'
- # Verify the hash was backfilled
- expected_hash = _hash_session_api_key(session_api_key)
- assert stored_sandbox.session_api_key_hash == expected_hash
-
@pytest.mark.asyncio
async def test_get_sandbox_by_session_api_key_runtime_error(
self, remote_sandbox_service