Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(sandbox): drain MCP responses before cancellation teardown (#3696)

Francesco Bonacci07e36a3f05d8
diff --git a/libs/python/cua-sandbox/cua_sandbox/interfaces/driver.py b/libs/python/cua-sandbox/cua_sandbox/interfaces/driver.py
index c788deca90..68beb5df5a 100644
--- a/libs/python/cua-sandbox/cua_sandbox/interfaces/driver.py
+++ b/libs/python/cua-sandbox/cua_sandbox/interfaces/driver.py
@@ -29,14 +29,15 @@ def _consume_result(done: asyncio.Future) -> None:
done.exception()
-async def _bounded_cleanup(awaitable: Any) -> bool:
+async def _bounded_cleanup(awaitable: Any, *, cancel_on_timeout: bool = True) -> bool:
"""Bound best-effort cleanup, including callbacks that ignore cancellation."""
task = asyncio.ensure_future(awaitable)
task.add_done_callback(_consume_result)
done, _ = await asyncio.wait({task}, timeout=_CLEANUP_TIMEOUT)
if task not in done:
- task.cancel()
+ if cancel_on_timeout:
+ task.cancel()
logger.warning("Driver cleanup timed out; remote session cleanup is unconfirmed")
return False
if task.cancelled() or task.exception() is not None:
@@ -209,6 +210,7 @@ def _channel(
self.cleanup_confirmed = False
self._close_task = None
self.cancelled: set[str] = set()
+ self._exchanges: dict[str, asyncio.Task] = {}
self.carrier = McpCarrier(transport, service) if mode == "mcp" else None
def fail(self, reason: str):
@@ -342,7 +344,15 @@ def _channel(
timeout = min(deadline - int(time.time() * 1000), 120000) / 1000
if timeout <= 0:
raise self.fail("Driver request deadline has expired")
- exchange = asyncio.create_task(self.request("POST", "/exchange", body, timeout=timeout))
+ # The caller's deadline still bounds the operation. MCP gets a
+ # small HTTP grace period to receive its cancellation response;
+ # aborting that stream before teardown can strand a stdio bridge.
+ http_timeout = timeout + 2 * _CLEANUP_TIMEOUT if self.carrier else timeout
+ exchange = asyncio.create_task(
+ self.request("POST", "/exchange", body, timeout=http_timeout)
+ )
+ self._exchanges[request.request_id] = exchange
+ exchange.add_done_callback(lambda done: self._exchanges.pop(request.request_id, None))
exchange.add_done_callback(_consume_result)
try:
done, _ = await asyncio.wait({exchange}, timeout=timeout)
@@ -350,7 +360,8 @@ def _channel(
raise TimeoutError("Driver request deadline has expired; completion is unknown")
return await self.decode_response(request, exchange.result())
except BaseException:
- exchange.cancel()
+ if self.carrier is None:
+ exchange.cancel()
await self.cancel(request.request_id)
await self.close()
raise
@@ -399,6 +410,11 @@ def _channel(
async def cancel(self, request_id):
self.cancelled.add(request_id)
+ if self.carrier is not None:
+ # A native future can cancel its callback and invoke cancel()
+ # concurrently. One shielded close task owns wire teardown.
+ await self.close()
+ return
if not self.closed:
self.closed = True
try:
@@ -418,11 +434,47 @@ def _channel(
if self._close_task is None:
async def cleanup():
+ if self.carrier is not None:
+ pending = dict(self._exchanges)
+ ids = self.cancelled | set(pending)
+ if ids:
+ cancellation_finished = await _bounded_cleanup(
+ asyncio.gather(
+ *(
+ self.request("POST", "/cancel", {"request_id": request_id})
+ for request_id in ids
+ ),
+ return_exceptions=True,
+ ),
+ cancel_on_timeout=False,
+ )
+ if not cancellation_finished:
+ return
+ if pending:
+ _, undrained = await asyncio.wait(
+ set(pending.values()), timeout=_CLEANUP_TIMEOUT
+ )
+ if undrained:
+ # Do not abort a live response or destroy its
+ # HTTP session. Cleanup remains unconfirmed;
+ # request timeouts still bound the HTTP work.
+ logger.warning(
+ "Driver response drain timed out; remote session cleanup "
+ "is unconfirmed"
+ )
+ return
receiver_closed = self.connection_id is None
if self.connection_id is not None:
- receiver_closed = await _bounded_cleanup(self.request("DELETE"))
+ receiver_close = asyncio.create_task(self.request("DELETE"))
+ receiver_closed = await _bounded_cleanup(
+ receiver_close, cancel_on_timeout=self.carrier is None
+ )
+ if self.carrier is not None and not receiver_close.done():
+ return
if self.carrier is not None:
- session_closed = await _bounded_cleanup(self.carrier.close_session())
+ session_closed = await _bounded_cleanup(
+ self.carrier.close_session(), cancel_on_timeout=False
+ )
self.cleanup_confirmed = receiver_closed and session_closed
else:
self.cleanup_confirmed = receiver_closed
diff --git a/libs/python/cua-sandbox/tests/test_driver_mcp.py b/libs/python/cua-sandbox/tests/test_driver_mcp.py
index 6896c5ea3a..a3f35d5a47 100644
--- a/libs/python/cua-sandbox/tests/test_driver_mcp.py
+++ b/libs/python/cua-sandbox/tests/test_driver_mcp.py
@@ -27,6 +27,10 @@ class McpTransport(Transport):
self.fail_exchange = False
self.exchange_started = asyncio.Event()
self.exchange_wait = None
+ self.cancel_releases_exchange = True
+ self.exchange_aborted = False
+ self.exchange_finished = asyncio.Event()
+ self.cancel_received = asyncio.Event()
async def request_service(
self, name, *, method, path, json_body=None, headers=None, timeout=None
@@ -69,13 +73,22 @@ class McpTransport(Transport):
if rpc == "cua/driver/v1/exchange":
self.exchange_started.set()
if self.exchange_wait is not None:
- await self.exchange_wait.wait()
+ try:
+ await self.exchange_wait.wait()
+ except asyncio.CancelledError:
+ self.exchange_aborted = True
+ raise
if self.fail_exchange:
raise RuntimeError("sensitive transport diagnostic")
request = json_body["params"]["envelope"]
result = dict(self.response_data, request_id=request["request_id"])
+ self.exchange_finished.set()
else:
assert rpc in ("cua/driver/v1/cancel", "cua/driver/v1/close")
+ if rpc == "cua/driver/v1/cancel":
+ self.cancel_received.set()
+ if self.cancel_releases_exchange and self.exchange_wait is not None:
+ self.exchange_wait.set()
result = {"ok": True}
response = {"jsonrpc": "2.0", "id": json_body["id"], "result": result}
if self.mutate:
@@ -219,6 +232,67 @@ async def test_cancel_can_overtake_exchange_and_prevents_late_result(native):
await sb.disconnect()
[email protected]("finish", ["cancel", "close", "callback-cancel"])
+async def test_mcp_teardown_drains_pending_response_before_closing_session(native, finish):
+ transport = McpTransport()
+ transport.exchange_wait = asyncio.Event()
+ transport.cancel_releases_exchange = False
+ sb = await sandbox(transport)
+ async with sb.driver.connect(service="mcp", transport="mcp") as driver:
+ channel = driver.channel
+ task = asyncio.create_task(channel.exchange(envelope()))
+ await transport.exchange_started.wait()
+ if finish == "callback-cancel":
+ task.cancel()
+ closing = task
+ else:
+ closing = asyncio.create_task(
+ channel.cancel("request-1") if finish == "cancel" else channel.close()
+ )
+ await asyncio.wait_for(transport.cancel_received.wait(), 1)
+ await asyncio.sleep(0)
+ assert not closing.done()
+ assert not transport.exchange_aborted
+ assert transport.sessions
+ assert not any(
+ (event[3] or {}).get("method") == "cua/driver/v1/close" for event in transport.events
+ )
+ transport.exchange_wait.set()
+ if finish == "callback-cancel":
+ with pytest.raises(asyncio.CancelledError):
+ await closing
+ else:
+ await closing
+ with pytest.raises(ChannelError, match="after close or cancellation"):
+ await task
+ assert transport.exchange_finished.is_set()
+ assert not transport.exchange_aborted
+ assert channel.cleanup_confirmed
+ assert not transport.sessions
+ await sb.disconnect()
+
+
+async def test_mcp_drain_timeout_is_bounded_unconfirmed_and_does_not_abort(native, monkeypatch):
+ monkeypatch.setattr("cua_sandbox.interfaces.driver._CLEANUP_TIMEOUT", 0.02)
+ transport = McpTransport()
+ transport.exchange_wait = asyncio.Event()
+ transport.cancel_releases_exchange = False
+ sb = await sandbox(transport)
+ async with sb.driver.connect(service="mcp", transport="mcp") as driver:
+ channel = driver.channel
+ task = asyncio.create_task(channel.exchange(envelope()))
+ await transport.exchange_started.wait()
+ await asyncio.wait_for(channel.cancel("request-1"), 0.5)
+ assert channel.closed and not channel.cleanup_confirmed
+ assert not transport.exchange_aborted
+ assert transport.sessions
+ assert transport.events[-1][3]["method"] == "cua/driver/v1/cancel"
+ transport.exchange_wait.set()
+ with pytest.raises(ChannelError, match="after close or cancellation"):
+ await task
+ await sb.disconnect()
+
+
@pytest.mark.parametrize(
"body,media",
[
diff --git a/libs/python/cua-sandbox/tests/test_driver_mcp_native.py b/libs/python/cua-sandbox/tests/test_driver_mcp_native.py
index 9b0ee74f9d..b68b269403 100644
--- a/libs/python/cua-sandbox/tests/test_driver_mcp_native.py
+++ b/libs/python/cua-sandbox/tests/test_driver_mcp_native.py
@@ -111,6 +111,8 @@ async def test_actual_native_future_cancellation_reaches_mcp_receiver(sdk):
await asyncio.wait_for(cancellation_received(), 2)
assert not transport.sessions
+ assert not transport.exchange_aborted
+ assert transport.exchange_finished.is_set()
finally:
transport.exchange_wait.set()
await sb.disconnect()