π OpenHands: AI-Driven Development
fix: use runtime /list API for sandbox concurrency count, not is_paused DB flag (#14834)
Tim O'Farrell4a6c74dd2b44
diff --git a/enterprise/migrations/versions/122_drop_is_paused_from_v1_remote_sandbox.py b/enterprise/migrations/versions/122_drop_is_paused_from_v1_remote_sandbox.pynew file mode 100644index 0000000000..b53fc15bc8--- /dev/null+++ b/enterprise/migrations/versions/122_drop_is_paused_from_v1_remote_sandbox.py@@ -0,0 +1,38 @@+"""Drop is_paused from v1_remote_sandbox.++The column was added in 121 to cache runtime pause state in the DB, but it is+not a reliable indicator of whether a sandbox is actually running: only+explicit app-level pause/resume calls update it, so externally terminated or+expired sandboxes remain is_paused=False forever. Concurrency counting now+uses the runtime /list endpoint as the source of truth instead.++Revision ID: 122+Revises: 121+Create Date: 2026-06-05+"""++from typing import Sequence, Union++import sqlalchemy as sa+from alembic import op++revision: str = '122'+down_revision: Union[str, None] = '121'+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ op.drop_column('v1_remote_sandbox', 'is_paused')+++def downgrade() -> None:+ op.add_column(+ 'v1_remote_sandbox',+ sa.Column(+ 'is_paused',+ sa.Boolean(),+ nullable=False,+ server_default=sa.false(),+ ),+ )diff --git a/openhands/app_server/app_lifespan/alembic/versions/012.py b/openhands/app_server/app_lifespan/alembic/versions/012.pynew file mode 100644index 0000000000..3daa8aa997--- /dev/null+++ b/openhands/app_server/app_lifespan/alembic/versions/012.py@@ -0,0 +1,41 @@+"""Drop is_paused column from v1_remote_sandbox table++Revision ID: 012+Revises: 011+Create Date: 2026-06-05 00:00:00.000000+"""++from typing import Sequence++import sqlalchemy as sa+from alembic import op++revision: str = '012'+down_revision: str | None = '011'+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def upgrade() -> None:+ """Drop the is_paused column.++ The column was added in 011 to cache runtime state in the DB, but it is+ not a reliable indicator of whether a sandbox is actually running: only+ explicit app-level pause/resume calls update it, so externally terminated+ or expired sandboxes stay is_paused=False forever. Concurrency counting+ now uses the runtime /list endpoint as the source of truth.+ """+ with op.batch_alter_table('v1_remote_sandbox') as batch_op:+ batch_op.drop_column('is_paused')+++def downgrade() -> None:+ with op.batch_alter_table('v1_remote_sandbox') as batch_op:+ batch_op.add_column(+ sa.Column(+ 'is_paused',+ sa.Boolean(),+ nullable=False,+ server_default='0',+ )+ )diff --git a/openhands/app_server/sandbox/remote_sandbox_service.py b/openhands/app_server/sandbox/remote_sandbox_service.pyindex f722dcb068..9ff8cc10b8 100644--- a/openhands/app_server/sandbox/remote_sandbox_service.py+++ b/openhands/app_server/sandbox/remote_sandbox_service.py@@ -12,7 +12,7 @@ import base62import httpxfrom fastapi import Requestfrom pydantic import Field-from sqlalchemy import Boolean, String, func, select+from sqlalchemy import String, func, selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.orm import Mapped, mapped_column@@ -93,7 +93,6 @@ class StoredRemoteSandbox(Base):created_at: Mapped[datetime] = mapped_column(UtcDateTime, server_default=func.now(), index=True)- is_paused: Mapped[bool] = mapped_column(Boolean, default=False, server_default='0')@dataclass@@ -228,20 +227,6 @@ class RemoteSandboxService(SandboxService):self.max_num_sandboxes)- async def _count_user_running_sandboxes(self) -> int:- """Count the number of running (non-paused) sandboxes for the current user.-- Queries the DB directly by created_by_user_id and is_paused, avoiding- a global runtime API call for every concurrency check.-- Returns:- int: Number of running sandboxes- """- query = await self._secure_select()- query = query.filter(StoredRemoteSandbox.is_paused == False) # noqa: E712- result = await self.db_session.execute(query)- return len(result.scalars().all())-async def _get_stored_sandbox(self, sandbox_id: str) -> StoredRemoteSandbox | None:stmt = await self._secure_select()stmt = stmt.where(StoredRemoteSandbox.id == sandbox_id)@@ -402,17 +387,40 @@ class RemoteSandboxService(SandboxService):)return self._to_sandbox_info(stored_sandbox, None)+ async def _get_user_running_sandboxes(self) -> list[StoredRemoteSandbox]:+ """Return the DB records for sandboxes that are actually running right now.++ Calls the runtime /list endpoint (which returns all running sessions across+ all users) and cross-references with the current user's DB records. This+ is the authoritative source of truth: a sandbox only counts as running if+ the runtime says it is β stale or expired DB rows are automatically excluded.+ """+ response = await self._send_runtime_api_request('GET', '/list')+ response.raise_for_status()+ running_session_ids = {+ runtime['session_id']+ for runtime in response.json().get('runtimes', [])+ if 'session_id' in runtime+ }++ query = await self._secure_select()+ query = query.filter(StoredRemoteSandbox.id.in_(running_session_ids)).order_by(+ StoredRemoteSandbox.created_at.asc()+ )+ result = await self.db_session.execute(query)+ return list(result.scalars().all())+async def check_concurrency_limit(self) -> None:"""Check if the user has reached their concurrent sandbox limit.- This check is performed synchronously before creating a task to allow- the API to return a 429 error immediately instead of failing asynchronously.+ Uses the runtime /list endpoint as the source of truth so that only+ sandboxes that are actually running count against the limit.Raises:ConcurrencyLimitError: If the user has reached their limit"""effective_limit = await self._get_user_effective_sandbox_limit()- current_count = await self._count_user_running_sandboxes()+ current_count = len(await self._get_user_running_sandboxes())if current_count >= effective_limit:_logger.info(@@ -455,15 +463,8 @@ class RemoteSandboxService(SandboxService):async def start_sandbox(self, sandbox_spec_id: str | None = None, sandbox_id: str | None = None) -> SandboxInfo:- """Start a new sandbox by creating a remote runtime.-- Uses SELECT FOR UPDATE within a nested transaction to acquire a row-level- lock, preventing race conditions (TOCTOU) when checking concurrency limits.- The lock is released after the sandbox record is inserted (before the- long-running runtime startup) to avoid blocking concurrent requests.- """+ """Start a new sandbox by creating a remote runtime."""try:- # Get sandbox spec early (before locking) to minimize lock hold timeif sandbox_spec_id is None:sandbox_spec = (await self.sandbox_spec_service.get_default_sandbox_spec()@@ -476,71 +477,23 @@ class RemoteSandboxService(SandboxService):raise ValueError('Sandbox Spec not found')sandbox_spec = sandbox_spec_maybe- # Create a unique id, use provided sandbox_id if availableif sandbox_id is None:sandbox_id = base62.encodebytes(os.urandom(16))- # Get user id for locking and record creationuser_id = await self.user_context.get_user_id()- # Use a nested transaction (savepoint) for the lock + check + insert.- # This allows us to release the row-level lock after inserting the- # sandbox record, before the long-running runtime startup begins.- # Without this, the lock would be held for the entire request duration- # (up to 120s for sandbox startup), blocking concurrent requests.- async with self.db_session.begin_nested():- # Acquire row-level lock to prevent TOCTOU race condition.- # This serializes concurrent sandbox creation requests for the same user.- # We lock the user's most recent sandbox row (if any) to coordinate access.- # If no sandbox exists, the INSERT below will still serialize due to- # unique constraint checks, and the next request will have a row to lock.- await self.db_session.execute(- select(StoredRemoteSandbox.id)- .filter(StoredRemoteSandbox.created_by_user_id == user_id)- .order_by(StoredRemoteSandbox.created_at.desc())- .limit(1)- .with_for_update()- )-- # Get user's effective limit and current count (now serialized)- effective_limit = await self._get_user_effective_sandbox_limit()- current_count = await self._count_user_running_sandboxes()-- # Check if user has reached their limit- if current_count >= effective_limit:- _logger.info(- f'User has reached sandbox limit: {current_count}/{effective_limit}'- )- raise ConcurrencyLimitError(- detail={- 'error': 'CONCURRENCY_LIMIT_REACHED',- 'message': (- f'You have reached your limit of {effective_limit} '- 'concurrent conversations. Please close an existing '- 'conversation to start a new one.'- ),- 'limit': effective_limit,- 'current': current_count,- }- )-- # Enforce sandbox limits by cleaning up old sandboxes if approaching limit- # Use effective_limit - 1 to leave room for the new sandbox- if current_count >= effective_limit - 1:- await self.pause_old_sandboxes(effective_limit - 1)-- # Store the sandbox record (this reserves the slot)- stored_sandbox = StoredRemoteSandbox(- id=sandbox_id,- created_by_user_id=user_id,- sandbox_spec_id=sandbox_spec.id,- created_at=utc_now(),- )- self.db_session.add(stored_sandbox)+ # Check concurrency limit against actual runtime state (defense in depth;+ # also checked before this call in live_status_app_conversation_service).+ await self.check_concurrency_limit()- # Nested transaction committed - lock is now released.- # The sandbox record exists, so the concurrency slot is reserved.- # Other requests can now proceed with their own concurrency checks.+ # Store the sandbox record+ stored_sandbox = StoredRemoteSandbox(+ id=sandbox_id,+ created_by_user_id=user_id,+ sandbox_spec_id=sandbox_spec.id,+ created_at=utc_now(),+ )+ self.db_session.add(stored_sandbox)# Prepare environment variablesenvironment = await self._init_environment(sandbox_spec, sandbox_id)@@ -627,7 +580,6 @@ class RemoteSandboxService(SandboxService):f'Updated session_api_key_hash for sandbox {sandbox_id} after resume')- stored_sandbox.is_paused = Falsereturn Trueexcept httpx.HTTPError as e:_logger.error(f'Error resuming sandbox {sandbox_id}: {e}')@@ -647,7 +599,6 @@ class RemoteSandboxService(SandboxService):# Security: Invalidate the session API key hash to prevent# leaked keys from being used while the sandbox is paused.stored_sandbox.session_api_key_hash = None- stored_sandbox.is_paused = Trueruntime_data = await self._get_runtime(sandbox_id)response = await self._send_runtime_api_request(@@ -691,46 +642,29 @@ class RemoteSandboxService(SandboxService):return Falseasync def pause_old_sandboxes(self, max_num_sandboxes: int) -> list[str]:- """Pause the oldest sandboxes if there are more than max_num_sandboxes running.- In a multi user environment, this will pause sandboxes only for the current user.-- Args:- max_num_sandboxes: Maximum number of sandboxes to keep running+ """Pause the oldest running sandboxes until at most max_num_sandboxes remain.- Returns:- List of sandbox IDs that were paused+ Uses _get_user_running_sandboxes (runtime /list + DB cross-reference) so+ only sandboxes that are actually running are considered."""if max_num_sandboxes <= 0:raise ValueError('max_num_sandboxes must be greater than 0')- # Query running sandboxes from DB directly using is_paused flag, avoiding- # a global runtime API call that returns all users' runtimes.- query = await self._secure_select()- query = query.filter(StoredRemoteSandbox.is_paused == False).order_by( # noqa: E712- StoredRemoteSandbox.created_at.desc()- )- running_sandboxes = list(await self.db_session.execute(query))+ running = await self._get_user_running_sandboxes()- # If we're within the limit, no cleanup needed- if len(running_sandboxes) <= max_num_sandboxes:+ if len(running) <= max_num_sandboxes:return []- # Determine how many to pause- num_to_pause = len(running_sandboxes) - max_num_sandboxes- sandboxes_to_pause = running_sandboxes[:num_to_pause]-- # Stop the oldest sandboxes- paused_sandbox_ids = []- for sandbox in sandboxes_to_pause:+ # running is sorted oldest-first; pause the oldest to make room+ num_to_pause = len(running) - max_num_sandboxes+ paused_ids: list[str] = []+ for sandbox in running[:num_to_pause]:try:- success = await self.pause_sandbox(sandbox.id)- if success:- paused_sandbox_ids.append(sandbox.id)+ if await self.pause_sandbox(sandbox.id):+ paused_ids.append(sandbox.id)except Exception:- # Continue trying to pause other sandboxes even if one failspass-- return paused_sandbox_ids+ return paused_idsasync def batch_get_sandboxes(self, sandbox_ids: list[str]diff --git a/tests/unit/app_server/test_remote_sandbox_service.py b/tests/unit/app_server/test_remote_sandbox_service.pyindex 8a01c5cd07..2d470d6e3c 100644--- a/tests/unit/app_server/test_remote_sandbox_service.py+++ b/tests/unit/app_server/test_remote_sandbox_service.py@@ -120,7 +120,6 @@ def create_stored_sandbox(spec_id: str = 'test-image:latest',created_at: datetime | None = None,session_api_key_hash: str | None = None,- is_paused: bool = False,) -> StoredRemoteSandbox:"""Helper function to create StoredRemoteSandbox for testing."""if created_at is None:@@ -132,7 +131,6 @@ def create_stored_sandbox(sandbox_spec_id=spec_id,session_api_key_hash=session_api_key_hash,created_at=created_at,- is_paused=is_paused,)@@ -397,13 +395,7 @@ class TestSandboxLifecycle:mock_response = MagicMock()mock_response.json.return_value = create_runtime_data(status='running')remote_sandbox_service.httpx_client.request.return_value = mock_response- remote_sandbox_service.pause_old_sandboxes = AsyncMock(return_value=[])-- # Mock concurrency limit methods- remote_sandbox_service._get_user_effective_sandbox_limit = AsyncMock(- return_value=10- )- remote_sandbox_service._count_user_running_sandboxes = AsyncMock(return_value=0)+ remote_sandbox_service.check_concurrency_limit = AsyncMock(return_value=None)# Mock database operationsremote_sandbox_service.db_session.add = MagicMock()@@ -428,13 +420,7 @@ class TestSandboxLifecycle:mock_response = MagicMock()mock_response.json.return_value = create_runtime_data()remote_sandbox_service.httpx_client.request.return_value = mock_response- remote_sandbox_service.pause_old_sandboxes = AsyncMock(return_value=[])-- # Mock concurrency limit methods- remote_sandbox_service._get_user_effective_sandbox_limit = AsyncMock(- return_value=10- )- remote_sandbox_service._count_user_running_sandboxes = AsyncMock(return_value=0)+ remote_sandbox_service.check_concurrency_limit = AsyncMock(return_value=None)remote_sandbox_service.db_session.add = MagicMock()remote_sandbox_service.db_session.commit = AsyncMock()@@ -455,13 +441,6 @@ class TestSandboxLifecycle:"""Test starting sandbox with non-existent spec."""# Setupmock_sandbox_spec_service.get_sandbox_spec.return_value = None- remote_sandbox_service.pause_old_sandboxes = AsyncMock(return_value=[])-- # Mock concurrency limit methods- remote_sandbox_service._get_user_effective_sandbox_limit = AsyncMock(- return_value=10- )- remote_sandbox_service._count_user_running_sandboxes = AsyncMock(return_value=0)# Execute & Verifywith pytest.raises(ValueError, match='Sandbox Spec not found'):@@ -478,13 +457,7 @@ class TestSandboxLifecycle:session_id='custom_sandbox_id')remote_sandbox_service.httpx_client.request.return_value = mock_response- remote_sandbox_service.pause_old_sandboxes = AsyncMock(return_value=[])-- # Mock concurrency limit methods- remote_sandbox_service._get_user_effective_sandbox_limit = AsyncMock(- return_value=10- )- remote_sandbox_service._count_user_running_sandboxes = AsyncMock(return_value=0)+ remote_sandbox_service.check_concurrency_limit = AsyncMock(return_value=None)# Mock database operationsremote_sandbox_service.db_session.add = MagicMock()@@ -508,13 +481,7 @@ class TestSandboxLifecycle:remote_sandbox_service.httpx_client.request.side_effect = httpx.HTTPError('API Error')- remote_sandbox_service.pause_old_sandboxes = AsyncMock(return_value=[])-- # Mock concurrency limit methods- remote_sandbox_service._get_user_effective_sandbox_limit = AsyncMock(- return_value=10- )- remote_sandbox_service._count_user_running_sandboxes = AsyncMock(return_value=0)+ remote_sandbox_service.check_concurrency_limit = AsyncMock(return_value=None)remote_sandbox_service.db_session.add = MagicMock()remote_sandbox_service.db_session.commit = AsyncMock()@@ -532,13 +499,7 @@ class TestSandboxLifecycle:mock_response = MagicMock()mock_response.json.return_value = create_runtime_data()remote_sandbox_service.httpx_client.request.return_value = mock_response- remote_sandbox_service.pause_old_sandboxes = AsyncMock(return_value=[])-- # Mock concurrency limit methods- remote_sandbox_service._get_user_effective_sandbox_limit = AsyncMock(- return_value=10- )- remote_sandbox_service._count_user_running_sandboxes = AsyncMock(return_value=0)+ remote_sandbox_service.check_concurrency_limit = AsyncMock(return_value=None)remote_sandbox_service.db_session.add = MagicMock()remote_sandbox_service.db_session.commit = AsyncMock()@@ -1198,13 +1159,28 @@ class TestConstants:class TestConcurrencyLimits:"""Test cases for sandbox concurrency limit enforcement.- Tests the _get_user_effective_sandbox_limit, _count_user_running_sandboxes,- and start_sandbox limit enforcement functionality.+ Tests _get_user_effective_sandbox_limit, _get_user_running_sandboxes,+ check_concurrency_limit, and pause_old_sandboxes.NOTE: Tests involving enterprise storage modules (UserStore, OrgMemberStore,OrgStore) are in enterprise/tests/unit/ since they require enterprise modules."""+ def _mock_list_response(self, service, session_ids: list[str]):+ """Configure the httpx mock to return the given session_ids from /list."""+ mock_response = MagicMock()+ mock_response.raise_for_status.return_value = None+ mock_response.json.return_value = {+ 'runtimes': [{'session_id': sid} for sid in session_ids]+ }+ service.httpx_client.request = AsyncMock(return_value=mock_response)++ def _mock_db_sandboxes(self, service, sandboxes: list):+ """Configure the DB mock to return the given StoredRemoteSandbox rows."""+ mock_result = MagicMock()+ mock_result.scalars.return_value.all.return_value = sandboxes+ service.db_session.execute = AsyncMock(return_value=mock_result)+@pytest.mark.asyncioasync def test_get_effective_limit_delegates_to_user_context(self, remote_sandbox_service@@ -1225,261 +1201,194 @@ class TestConcurrencyLimits:async def test_get_effective_limit_passes_max_num_sandboxes_as_default(self, remote_sandbox_service):- """Test that _get_user_effective_sandbox_limit passes max_num_sandboxes as default.-- The global fallback (max_num_sandboxes=10) is passed to UserContext,- which can use it as the default in OSS mode.- """+ """Test that max_num_sandboxes is forwarded as the OSS-mode default."""remote_sandbox_service.user_context.get_max_concurrent_sandboxes = AsyncMock(return_value=10)result = await remote_sandbox_service._get_user_effective_sandbox_limit()- assert result == 10 # global fallback (max_num_sandboxes)+ assert result == 10@pytest.mark.asyncio- async def test_count_running_sandboxes_returns_zero_when_no_db_records(+ async def test_get_user_running_sandboxes_cross_references_list_with_db(self, remote_sandbox_service):- """Test that _count_user_running_sandboxes returns 0 when user has no sandboxes."""- mock_result = MagicMock()- mock_result.scalars.return_value.all.return_value = []- remote_sandbox_service.db_session.execute = AsyncMock(return_value=mock_result)+ """_get_user_running_sandboxes uses /list to filter DB records to running ones."""+ sb1 = create_stored_sandbox(sandbox_id='running-1')+ sb2 = create_stored_sandbox(sandbox_id='running-2')+ # sb3 exists in DB but is NOT in the /list response (terminated externally)+ self._mock_list_response(remote_sandbox_service, ['running-1', 'running-2'])+ self._mock_db_sandboxes(remote_sandbox_service, [sb1, sb2])- result = await remote_sandbox_service._count_user_running_sandboxes()+ result = await remote_sandbox_service._get_user_running_sandboxes()- assert result == 0- # No runtime API call should be made- remote_sandbox_service.httpx_client.request.assert_not_called()+ assert len(result) == 2@pytest.mark.asyncio- async def test_count_running_sandboxes_excludes_paused_sandboxes(+ async def test_get_user_running_sandboxes_empty_when_none_running(self, remote_sandbox_service):- """Test that _count_user_running_sandboxes only counts non-paused sandboxes."""- # DB returns 2 running sandboxes (is_paused=False) filtered by the query;- # paused sandboxes are excluded at the query level.- mock_result = MagicMock()- mock_result.scalars.return_value.all.return_value = [- create_stored_sandbox(sandbox_id='sandbox-1', is_paused=False),- create_stored_sandbox(sandbox_id='sandbox-2', is_paused=False),- ]- remote_sandbox_service.db_session.execute = AsyncMock(return_value=mock_result)+ """Returns empty list when /list reports no running sessions for this user."""+ self._mock_list_response(remote_sandbox_service, [])+ self._mock_db_sandboxes(remote_sandbox_service, [])- result = await remote_sandbox_service._count_user_running_sandboxes()+ result = await remote_sandbox_service._get_user_running_sandboxes()- assert result == 2- # No runtime API call should be made- remote_sandbox_service.httpx_client.request.assert_not_called()+ assert result == []@pytest.mark.asyncio- async def test_start_sandbox_raises_concurrency_error_when_at_limit(+ async def test_check_concurrency_limit_raises_when_at_limit(self, remote_sandbox_service):- """Test that start_sandbox raises ConcurrencyLimitError when user is at limit."""+ """check_concurrency_limit raises ConcurrencyLimitError when at the limit."""from openhands.app_server.errors import ConcurrencyLimitErrorremote_sandbox_service._get_user_effective_sandbox_limit = AsyncMock(return_value=3)- remote_sandbox_service._count_user_running_sandboxes = AsyncMock(return_value=3)+ sandboxes = [create_stored_sandbox(f'sb-{i}') for i in range(3)]+ remote_sandbox_service._get_user_running_sandboxes = AsyncMock(+ return_value=sandboxes+ )with pytest.raises(ConcurrencyLimitError) as exc_info:- await remote_sandbox_service.start_sandbox()+ await remote_sandbox_service.check_concurrency_limit()assert exc_info.value.detail['limit'] == 3assert exc_info.value.detail['current'] == 3assert exc_info.value.status_code == 429@pytest.mark.asyncio- async def test_start_sandbox_raises_concurrency_error_when_over_limit(+ async def test_check_concurrency_limit_raises_when_over_limit(self, remote_sandbox_service):- """Test that start_sandbox raises ConcurrencyLimitError when user exceeds limit."""+ """check_concurrency_limit raises ConcurrencyLimitError when over the limit."""from openhands.app_server.errors import ConcurrencyLimitErrorremote_sandbox_service._get_user_effective_sandbox_limit = AsyncMock(return_value=5)- remote_sandbox_service._count_user_running_sandboxes = AsyncMock(return_value=7)+ sandboxes = [create_stored_sandbox(f'sb-{i}') for i in range(7)]+ remote_sandbox_service._get_user_running_sandboxes = AsyncMock(+ return_value=sandboxes+ )with pytest.raises(ConcurrencyLimitError) as exc_info:- await remote_sandbox_service.start_sandbox()+ await remote_sandbox_service.check_concurrency_limit()assert exc_info.value.detail['limit'] == 5assert exc_info.value.detail['current'] == 7@pytest.mark.asyncio- async def test_start_sandbox_allows_creation_when_under_limit(+ async def test_check_concurrency_limit_succeeds_when_under_limit(self, remote_sandbox_service):- """Test that start_sandbox succeeds when user is under their limit."""+ """check_concurrency_limit does not raise when under the limit."""remote_sandbox_service._get_user_effective_sandbox_limit = AsyncMock(return_value=5)- remote_sandbox_service._count_user_running_sandboxes = AsyncMock(return_value=2)- remote_sandbox_service.pause_old_sandboxes = AsyncMock(return_value=[])-- mock_response = MagicMock()- mock_response.raise_for_status.return_value = None- mock_response.json.return_value = {- 'session_id': 'new-sandbox-123',- 'status': 'running',- 'url': 'https://sandbox.example.com',- 'session_api_key': 'test-key',- 'runtime_id': 'runtime-456',- }- remote_sandbox_service.httpx_client.request = AsyncMock(- return_value=mock_response+ sandboxes = [create_stored_sandbox(f'sb-{i}') for i in range(2)]+ remote_sandbox_service._get_user_running_sandboxes = AsyncMock(+ return_value=sandboxes)- result = await remote_sandbox_service.start_sandbox()-- assert result is not None- assert result.id is not None+ await remote_sandbox_service.check_concurrency_limit() # should not raise@pytest.mark.asyncio- async def test_start_sandbox_pauses_old_sandboxes_when_approaching_limit(+ async def test_check_concurrency_limit_succeeds_when_no_sandboxes(self, remote_sandbox_service):- """Test that start_sandbox calls pause_old_sandboxes when approaching limit."""+ """check_concurrency_limit does not raise when the user has no running sandboxes."""remote_sandbox_service._get_user_effective_sandbox_limit = AsyncMock(- return_value=5- )- remote_sandbox_service._count_user_running_sandboxes = AsyncMock(return_value=4)- remote_sandbox_service.pause_old_sandboxes = AsyncMock(return_value=[])-- mock_response = MagicMock()- mock_response.raise_for_status.return_value = None- mock_response.json.return_value = {- 'session_id': 'new-sandbox-123',- 'status': 'running',- 'url': 'https://sandbox.example.com',- 'session_api_key': 'test-key',- 'runtime_id': 'runtime-456',- }- remote_sandbox_service.httpx_client.request = AsyncMock(- return_value=mock_response+ return_value=10)+ remote_sandbox_service._get_user_running_sandboxes = AsyncMock(return_value=[])- await remote_sandbox_service.start_sandbox()-- remote_sandbox_service.pause_old_sandboxes.assert_called_once_with(4)+ await remote_sandbox_service.check_concurrency_limit() # should not raise@pytest.mark.asyncio- async def test_start_sandbox_does_not_pause_when_well_under_limit(+ async def test_start_sandbox_raises_concurrency_error_when_at_limit(self, remote_sandbox_service):- """Test that start_sandbox does not pause sandboxes when well under limit."""+ """start_sandbox raises ConcurrencyLimitError when the user is at the limit."""+ from openhands.app_server.errors import ConcurrencyLimitError+remote_sandbox_service._get_user_effective_sandbox_limit = AsyncMock(- return_value=10+ return_value=3)- remote_sandbox_service._count_user_running_sandboxes = AsyncMock(return_value=2)- remote_sandbox_service.pause_old_sandboxes = AsyncMock(return_value=[])-- mock_response = MagicMock()- mock_response.raise_for_status.return_value = None- mock_response.json.return_value = {- 'session_id': 'new-sandbox-123',- 'status': 'running',- 'url': 'https://sandbox.example.com',- 'session_api_key': 'test-key',- 'runtime_id': 'runtime-456',- }- remote_sandbox_service.httpx_client.request = AsyncMock(- return_value=mock_response+ sandboxes = [create_stored_sandbox(f'sb-{i}') for i in range(3)]+ remote_sandbox_service._get_user_running_sandboxes = AsyncMock(+ return_value=sandboxes)- await remote_sandbox_service.start_sandbox()+ with pytest.raises(ConcurrencyLimitError) as exc_info:+ await remote_sandbox_service.start_sandbox()- remote_sandbox_service.pause_old_sandboxes.assert_not_called()+ assert exc_info.value.detail['limit'] == 3+ assert exc_info.value.detail['current'] == 3+ assert exc_info.value.status_code == 429@pytest.mark.asyncioasync def test_start_sandbox_concurrency_error_not_wrapped_in_sandbox_error(self, remote_sandbox_service):- """Test that ConcurrencyLimitError is raised directly, not wrapped in SandboxError."""+ """ConcurrencyLimitError is propagated directly, not wrapped in SandboxError."""from openhands.app_server.errors import ConcurrencyLimitErrorremote_sandbox_service._get_user_effective_sandbox_limit = AsyncMock(return_value=3)- remote_sandbox_service._count_user_running_sandboxes = AsyncMock(return_value=3)-- with pytest.raises(ConcurrencyLimitError):- await remote_sandbox_service.start_sandbox()+ sandboxes = [create_stored_sandbox(f'sb-{i}') for i in range(3)]+ remote_sandbox_service._get_user_running_sandboxes = AsyncMock(+ return_value=sandboxes+ )- # Verify it's not wrapped in SandboxErrortry:await remote_sandbox_service.start_sandbox()except ConcurrencyLimitError:- pass # Expected+ pass # expectedexcept SandboxError:pytest.fail('ConcurrencyLimitError should not be wrapped in SandboxError')@pytest.mark.asyncio- async def test_check_concurrency_limit_raises_when_at_limit(+ async def test_pause_old_sandboxes_pauses_oldest_when_over_limit(self, remote_sandbox_service):- """Test that check_concurrency_limit raises ConcurrencyLimitError when at limit."""- from openhands.app_server.errors import ConcurrencyLimitError+ """pause_old_sandboxes pauses the oldest sandboxes to reach max_num_sandboxes."""+ from datetime import timezone- remote_sandbox_service._get_user_effective_sandbox_limit = AsyncMock(- return_value=3+ old = create_stored_sandbox(+ 'old-sb', created_at=datetime(2024, 1, 1, tzinfo=timezone.utc))- remote_sandbox_service._count_user_running_sandboxes = AsyncMock(return_value=3)-- with pytest.raises(ConcurrencyLimitError) as exc_info:- await remote_sandbox_service.check_concurrency_limit()-- assert exc_info.value.detail['limit'] == 3- assert exc_info.value.detail['current'] == 3- assert exc_info.value.status_code == 429-- @pytest.mark.asyncio- async def test_check_concurrency_limit_raises_when_over_limit(- self, remote_sandbox_service- ):- """Test that check_concurrency_limit raises ConcurrencyLimitError when over limit."""- from openhands.app_server.errors import ConcurrencyLimitError-- remote_sandbox_service._get_user_effective_sandbox_limit = AsyncMock(- return_value=5+ new = create_stored_sandbox(+ 'new-sb', created_at=datetime(2024, 6, 1, tzinfo=timezone.utc)+ )+ # _get_user_running_sandboxes returns oldest first+ remote_sandbox_service._get_user_running_sandboxes = AsyncMock(+ return_value=[old, new])- remote_sandbox_service._count_user_running_sandboxes = AsyncMock(return_value=7)+ remote_sandbox_service.pause_sandbox = AsyncMock(return_value=True)- with pytest.raises(ConcurrencyLimitError) as exc_info:- await remote_sandbox_service.check_concurrency_limit()+ paused = await remote_sandbox_service.pause_old_sandboxes(max_num_sandboxes=1)- assert exc_info.value.detail['limit'] == 5- assert exc_info.value.detail['current'] == 7+ assert paused == ['old-sb']+ remote_sandbox_service.pause_sandbox.assert_called_once_with('old-sb')@pytest.mark.asyncio- async def test_check_concurrency_limit_succeeds_when_under_limit(+ async def test_pause_old_sandboxes_noop_when_within_limit(self, remote_sandbox_service):- """Test that check_concurrency_limit succeeds when under limit."""- remote_sandbox_service._get_user_effective_sandbox_limit = AsyncMock(- return_value=5+ """pause_old_sandboxes does nothing when running count is within the limit."""+ remote_sandbox_service._get_user_running_sandboxes = AsyncMock(+ return_value=[create_stored_sandbox('sb-1')])- remote_sandbox_service._count_user_running_sandboxes = AsyncMock(return_value=2)-- # Should not raise- await remote_sandbox_service.check_concurrency_limit()+ remote_sandbox_service.pause_sandbox = AsyncMock(return_value=True)- @pytest.mark.asyncio- async def test_check_concurrency_limit_succeeds_when_well_under_limit(- self, remote_sandbox_service- ):- """Test that check_concurrency_limit succeeds when well under limit."""- remote_sandbox_service._get_user_effective_sandbox_limit = AsyncMock(- return_value=10- )- remote_sandbox_service._count_user_running_sandboxes = AsyncMock(return_value=0)+ paused = await remote_sandbox_service.pause_old_sandboxes(max_num_sandboxes=3)- # Should not raise- await remote_sandbox_service.check_concurrency_limit()+ assert paused == []+ remote_sandbox_service.pause_sandbox.assert_not_called()def _async_cm_factory(value):