Skip to content

Quickly sandbox your AI agent.

Python

fix(quicksand-core): demultiplex virtio-serial agent responses by id

cheng04c75a7ee7d8
diff --git a/packages/quicksand-core/quicksand_core/host/virtio_serial_agent_client.py b/packages/quicksand-core/quicksand_core/host/virtio_serial_agent_client.py
index 70eedd9..2e51af2 100644
--- a/packages/quicksand-core/quicksand_core/host/virtio_serial_agent_client.py
+++ b/packages/quicksand-core/quicksand_core/host/virtio_serial_agent_client.py
@@ -1,7 +1,9 @@
"""Async client for quicksand guest agent over virtio-serial (Unix/TCP socket).
-Uses length-prefixed JSON framing over a QEMU chardev socket, bypassing
-the guest networking stack entirely.
+Uses length-prefixed JSON framing over a QEMU chardev socket. A background
+reader task demultiplexes incoming frames by ``id`` into per-request futures
+(or per-stream queues), so caller timeouts and concurrent calls cannot corrupt
+each other's reads.
Frame format:
┌──────────┬─────────────────────┐
@@ -32,13 +34,11 @@ _MAX_FRAME_SIZE = 64 * 1024 * 1024 # 64 MB sanity limit
def _encode_frame(msg: dict) -> bytes:
- """Encode a message as a length-prefixed JSON frame."""
payload = json.dumps(msg, separators=(",", ":")).encode("utf-8")
return struct.pack(_HEADER_FMT, len(payload)) + payload
async def _read_frame(reader: asyncio.StreamReader) -> dict:
- """Read one length-prefixed JSON frame from the stream."""
header = await reader.readexactly(_HEADER_SIZE)
(length,) = struct.unpack(_HEADER_FMT, header)
if length > _MAX_FRAME_SIZE:
@@ -51,8 +51,11 @@ class VirtioSerialAgentClient:
"""Async client for the quicksand guest agent over virtio-serial.
Communicates via QEMU's chardev Unix domain socket (or TCP on Windows)
- using length-prefixed JSON framing. Provides the same interface as
- QuicksandGuestAgentClient.
+ using length-prefixed JSON framing. After authentication, a background
+ reader task demultiplexes responses by ``id``: one-shot calls register
+ a future, streaming calls register a queue. Late frames whose ``id`` has
+ no waiter (e.g. response to a request whose caller already timed out)
+ are dropped at the reader.
"""
def __init__(self, socket_path: str | Path, token: str):
@@ -60,12 +63,15 @@ class VirtioSerialAgentClient:
self._token = token
self._reader: asyncio.StreamReader | None = None
self._writer: asyncio.StreamWriter | None = None
- self._lock: asyncio.Lock | None = None
+ self._writer_lock: asyncio.Lock | None = None
+ self._reader_task: asyncio.Task[None] | None = None
+ self._pending: dict[int, asyncio.Future[dict]] = {}
+ self._pending_streams: dict[int, asyncio.Queue[dict]] = {}
self._request_id = 0
@property
def is_connected(self) -> bool:
- return self._writer is not None
+ return self._writer is not None and self._reader_task is not None
def _next_id(self) -> int:
self._request_id += 1
@@ -78,8 +84,10 @@ class VirtioSerialAgentClient:
) -> None:
"""Connect to the agent via the chardev socket and authenticate.
- Retries until the socket is ready (QEMU creates it at launch) and
- the guest agent sends a valid authentication response.
+ Auth is content-keyed (the agent's authenticated reply has no ``id``),
+ so it runs synchronously on the bare reader. Once auth succeeds the
+ demux reader task takes ownership of ``self._reader`` and all later
+ request/response routing goes through it.
Once connected to the QEMU chardev socket, the connection is kept
open across auth retries. Disconnecting causes QEMU to stop
@@ -145,6 +153,11 @@ class VirtioSerialAgentClient:
logger.debug("Drained %d stale auth responses", drained)
# Reset request ID so future requests start fresh
self._request_id = 0
+ # Spawn the demux reader. From here on, only this task
+ # touches ``self._reader``; callers wait on per-id futures
+ # or queues registered in ``_pending`` / ``_pending_streams``.
+ self._writer_lock = asyncio.Lock()
+ self._reader_task = asyncio.create_task(self._read_loop())
return
raise RuntimeError("Authentication rejected by agent")
@@ -173,6 +186,52 @@ class VirtioSerialAgentClient:
f"Last error: {last_error}"
)
+ async def _read_loop(self) -> None:
+ """Background task: demultiplex incoming frames by ``id``.
+
+ Stream requests register an ``asyncio.Queue`` (frames pushed in order,
+ terminated by an ``exit`` or ``error`` frame). One-shot requests
+ register an ``asyncio.Future`` (resolved by the first matching frame).
+ Frames whose ``id`` has no waiter are dropped.
+ """
+ assert self._reader is not None
+ try:
+ while True:
+ frame = await _read_frame(self._reader)
+ frame_id = frame.get("id")
+ if not isinstance(frame_id, int):
+ logger.debug("Dropping frame without integer id: %r", frame)
+ continue
+ queue = self._pending_streams.get(frame_id)
+ if queue is not None:
+ queue.put_nowait(frame)
+ continue
+ fut = self._pending.pop(frame_id, None)
+ if fut is not None and not fut.done():
+ fut.set_result(frame)
+ else:
+ logger.debug("Dropping frame with no waiter id=%d", frame_id)
+ except asyncio.IncompleteReadError:
+ self._fail_pending(ConnectionResetError("agent connection closed"))
+ except (ConnectionResetError, OSError) as e:
+ self._fail_pending(e)
+ except asyncio.CancelledError:
+ self._fail_pending(ConnectionResetError("client closed"))
+ raise
+ except Exception as e: # pragma: no cover — unexpected
+ logger.exception("Unexpected error in agent reader loop")
+ self._fail_pending(e)
+
+ def _fail_pending(self, exc: BaseException) -> None:
+ """Wake every outstanding caller with a connection error."""
+ for fut in self._pending.values():
+ if not fut.done():
+ fut.set_exception(exc)
+ self._pending.clear()
+ for queue in self._pending_streams.values():
+ queue.put_nowait({"error": {"message": f"Connection error: {exc}"}})
+ self._pending_streams.clear()
+
def _close_transport(self) -> None:
if self._writer:
with contextlib.suppress(Exception):
@@ -181,6 +240,11 @@ class VirtioSerialAgentClient:
self._writer = None
async def close(self) -> None:
+ if self._reader_task is not None:
+ self._reader_task.cancel()
+ with contextlib.suppress(BaseException):
+ await self._reader_task
+ self._reader_task = None
self._close_transport()
async def send_request(
@@ -189,46 +253,47 @@ class VirtioSerialAgentClient:
params: dict[str, Any],
timeout: float = Timeouts.GUEST_AGENT_REQUEST,
) -> dict[str, Any]:
- if self._writer is None or self._reader is None:
+ if self._writer is None or self._reader_task is None or self._writer_lock is None:
raise RuntimeError("Not connected to agent")
- if self._lock is None:
- self._lock = asyncio.Lock()
- async with self._lock:
- method_map = {
- QuicksandGuestAgentMethod.EXECUTE: "execute",
- QuicksandGuestAgentMethod.PING: "ping",
- }
- method_name = method_map.get(method)
- if method_name is None:
- return {"error": {"message": f"Unknown method: {method}"}}
+ method_map = {
+ QuicksandGuestAgentMethod.EXECUTE: "execute",
+ QuicksandGuestAgentMethod.PING: "ping",
+ }
+ method_name = method_map.get(method)
+ if method_name is None:
+ return {"error": {"message": f"Unknown method: {method}"}}
- msg = {"id": self._next_id(), "method": method_name, "params": params}
+ request_id = self._next_id()
+ loop = asyncio.get_event_loop()
+ future: asyncio.Future[dict] = loop.create_future()
+ # Register BEFORE writing so a fast reply can't arrive before we have
+ # a slot in ``_pending``.
+ self._pending[request_id] = future
- try:
+ msg = {"id": request_id, "method": method_name, "params": params}
+
+ try:
+ async with self._writer_lock:
self._writer.write(_encode_frame(msg))
await self._writer.drain()
-
- response = await asyncio.wait_for(_read_frame(self._reader), timeout=timeout)
-
- resp_id = response.get("id")
- if resp_id != msg["id"]:
- return {
- "error": {
- "message": (
- f"Response ID mismatch: expected {msg['id']}, got {resp_id}"
- )
- }
- }
-
- if "error" in response:
- return {"error": response["error"]}
- return {"result": response.get("result", response)}
-
- except TimeoutError:
- return {"error": {"message": f"Request timed out after {timeout}s"}}
- except (ConnectionResetError, BrokenPipeError, OSError) as e:
- return {"error": {"message": f"Connection error: {e}"}}
+ except (ConnectionResetError, BrokenPipeError, OSError) as e:
+ self._pending.pop(request_id, None)
+ return {"error": {"message": f"Connection error: {e}"}}
+
+ try:
+ response = await asyncio.wait_for(future, timeout=timeout)
+ except TimeoutError:
+ # Caller gives up: pop our slot so a late reply is dropped at
+ # the reader instead of poisoning the next call's read.
+ self._pending.pop(request_id, None)
+ return {"error": {"message": f"Request timed out after {timeout}s"}}
+ except (ConnectionResetError, OSError) as e:
+ return {"error": {"message": f"Connection error: {e}"}}
+
+ if "error" in response:
+ return {"error": response["error"]}
+ return {"result": response.get("result", response)}
async def send_stream_request(
self,
@@ -237,66 +302,63 @@ class VirtioSerialAgentClient:
on_stdout: Callable[[str], None] | None = None,
on_stderr: Callable[[str], None] | None = None,
) -> dict[str, Any]:
- if self._writer is None or self._reader is None:
+ if self._writer is None or self._reader_task is None or self._writer_lock is None:
raise RuntimeError("Not connected to agent")
- if self._lock is None:
- self._lock = asyncio.Lock()
- async with self._lock:
- msg = {"id": self._next_id(), "method": "execute_stream", "params": params}
- stdout_parts: list[str] = []
- stderr_parts: list[str] = []
- exit_code = -1
+ request_id = self._next_id()
+ queue: asyncio.Queue[dict] = asyncio.Queue()
+ self._pending_streams[request_id] = queue
- try:
+ msg = {"id": request_id, "method": "execute_stream", "params": params}
+
+ try:
+ async with self._writer_lock:
self._writer.write(_encode_frame(msg))
await self._writer.drain()
-
- deadline = asyncio.get_event_loop().time() + timeout
- while True:
- remaining = deadline - asyncio.get_event_loop().time()
- if remaining <= 0:
- return {"error": {"message": f"Stream timed out after {timeout}s"}}
-
- frame = await asyncio.wait_for(_read_frame(self._reader), timeout=remaining)
-
- frame_id = frame.get("id")
- if frame_id != msg["id"]:
- return {
- "error": {
- "message": (
- f"Stream response ID mismatch: expected {msg['id']}, "
- f"got {frame_id}"
- )
- }
- }
-
- stream = frame.get("stream")
- if stream == "stdout":
- data = frame.get("data", "")
- stdout_parts.append(data)
- if on_stdout:
- on_stdout(data)
- elif stream == "stderr":
- data = frame.get("data", "")
- stderr_parts.append(data)
- if on_stderr:
- on_stderr(data)
- elif stream == "exit":
- exit_code = frame.get("exit_code", -1)
- break
- elif "error" in frame:
- return {"error": frame["error"]}
-
+ except (ConnectionResetError, BrokenPipeError, OSError) as e:
+ self._pending_streams.pop(request_id, None)
+ return {"error": {"message": f"Stream connection error: {e}"}}
+
+ try:
+ return await asyncio.wait_for(
+ self._consume_stream(queue, on_stdout, on_stderr),
+ timeout=timeout,
+ )
+ except TimeoutError:
+ return {"error": {"message": f"Stream timed out after {timeout}s"}}
+ finally:
+ # Drop any further frames for this id (the reader will log+skip
+ # them once we're no longer registered).
+ self._pending_streams.pop(request_id, None)
+
+ async def _consume_stream(
+ self,
+ queue: asyncio.Queue[dict],
+ on_stdout: Callable[[str], None] | None,
+ on_stderr: Callable[[str], None] | None,
+ ) -> dict[str, Any]:
+ stdout_parts: list[str] = []
+ stderr_parts: list[str] = []
+ while True:
+ frame = await queue.get()
+ if "error" in frame:
+ return {"error": frame["error"]}
+ stream = frame.get("stream")
+ if stream == "stdout":
+ data = frame.get("data", "")
+ stdout_parts.append(data)
+ if on_stdout:
+ on_stdout(data)
+ elif stream == "stderr":
+ data = frame.get("data", "")
+ stderr_parts.append(data)
+ if on_stderr:
+ on_stderr(data)
+ elif stream == "exit":
return {
"result": {
"stdout": "".join(stdout_parts),
"stderr": "".join(stderr_parts),
- "exit_code": exit_code,
+ "exit_code": frame.get("exit_code", -1),
}
}
-
- except TimeoutError:
- return {"error": {"message": f"Stream timed out after {timeout}s"}}
- except (ConnectionResetError, BrokenPipeError, OSError) as e:
- return {"error": {"message": f"Stream connection error: {e}"}}
diff --git a/tests/unit/test_virtio_serial_agent_client.py b/tests/unit/test_virtio_serial_agent_client.py
new file mode 100644
index 0000000..c92f3d7
--- /dev/null
+++ b/tests/unit/test_virtio_serial_agent_client.py
@@ -0,0 +1,295 @@
+"""Unit tests for VirtioSerialAgentClient framing/demux behavior."""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import json
+import struct
+from collections.abc import Awaitable, Callable
+from pathlib import Path
+
+import pytest
+from quicksand_core._types import QuicksandGuestAgentMethod
+from quicksand_core.host.virtio_serial_agent_client import VirtioSerialAgentClient
+
+_HEADER_FMT = "!I"
+_HEADER_SIZE = struct.calcsize(_HEADER_FMT)
+_TEST_TOKEN = "test-token"
+
+
+def _encode_frame(msg: dict) -> bytes:
+ payload = json.dumps(msg).encode()
+ return struct.pack(_HEADER_FMT, len(payload)) + payload
+
+
+async def _read_frame(reader: asyncio.StreamReader) -> dict:
+ header = await reader.readexactly(_HEADER_SIZE)
+ (length,) = struct.unpack(_HEADER_FMT, header)
+ payload = await reader.readexactly(length)
+ return json.loads(payload)
+
+
+def _ok(request_id: int, stdout: str = "") -> dict:
+ return {
+ "id": request_id,
+ "result": {"stdout": stdout, "stderr": "", "exit_code": 0},
+ }
+
+
+# Handler signature: receives a non-auth request frame, returns reply frames.
+Handler = Callable[[dict], Awaitable[list[dict]]]
+
+
+class FakeAgent:
+ """Server speaking the agent wire protocol on a Unix socket.
+
+ Auto-replies to ``authenticate`` with an id-less authenticated frame.
+ Dispatches every other request frame to ``handler`` and writes the
+ returned frames back to the same connection.
+ """
+
+ def __init__(self, sock_path: Path, handler: Handler):
+ self._sock_path = sock_path
+ self._handler = handler
+ self._server: asyncio.AbstractServer | None = None
+ self._writers: list[asyncio.StreamWriter] = []
+ self._handler_tasks: list[asyncio.Task] = []
+ self.received_requests: list[dict] = []
+
+ async def __aenter__(self) -> FakeAgent:
+ self._server = await asyncio.start_unix_server(self._on_connect, path=str(self._sock_path))
+ return self
+
+ async def __aexit__(self, *_exc_info) -> None:
+ for task in self._handler_tasks:
+ task.cancel()
+ for task in self._handler_tasks:
+ with contextlib.suppress(BaseException):
+ await task
+ for writer in self._writers:
+ with contextlib.suppress(Exception):
+ writer.close()
+ for writer in self._writers:
+ with contextlib.suppress(Exception):
+ await writer.wait_closed()
+ if self._server is not None:
+ self._server.close()
+ await self._server.wait_closed()
+
+ async def disconnect_all(self) -> None:
+ """Close every active server-side connection."""
+ for writer in list(self._writers):
+ with contextlib.suppress(Exception):
+ writer.close()
+
+ async def _on_connect(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
+ self._writers.append(writer)
+ try:
+ while True:
+ msg = await _read_frame(reader)
+ self.received_requests.append(msg)
+ if msg.get("method") == "authenticate":
+ writer.write(_encode_frame({"result": {"authenticated": True}}))
+ await writer.drain()
+ continue
+ self._handler_tasks.append(asyncio.create_task(self._handle(msg, writer)))
+ except (asyncio.IncompleteReadError, ConnectionResetError, OSError):
+ pass
+
+ async def _handle(self, msg: dict, writer: asyncio.StreamWriter) -> None:
+ try:
+ replies = await self._handler(msg)
+ except asyncio.CancelledError:
+ return
+ for reply in replies:
+ try:
+ writer.write(_encode_frame(reply))
+ await writer.drain()
+ except (ConnectionResetError, BrokenPipeError):
+ return
+
+
+def sock_path(tmp_path: Path) -> Path:
+ return tmp_path / "agent.sock"
+
+
+async def _connected_client(sock_path: Path) -> VirtioSerialAgentClient:
+ client = VirtioSerialAgentClient(sock_path, token=_TEST_TOKEN)
+ await client.connect(timeout=5.0)
+ return client
+
+
+# ---------------------------------------------------------------------------
+# Tests
+# ---------------------------------------------------------------------------
+
+
+async def test_wrong_id_frame_does_not_raise_mismatch(tmp_path: Path) -> None:
+ """A frame whose id matches no outstanding request is dropped at the
+ reader; the caller times out without surfacing 'Response ID mismatch'."""
+
+ async def fake_agent(_reader, writer):
+ for msg in [
+ {"result": {"authenticated": True}},
+ {"id": 99, "result": {"stdout": "", "stderr": "", "exit_code": 0}},
+ ]:
+ b = json.dumps(msg).encode()
+ writer.write(struct.pack("!I", len(b)) + b)
+ await writer.drain()
+
+ sock = tmp_path / "agent.sock"
+ server = await asyncio.start_unix_server(fake_agent, path=str(sock))
+ client = VirtioSerialAgentClient(sock, token=_TEST_TOKEN)
+ try:
+ await client.connect(timeout=5.0)
+ result = await client.send_request(
+ QuicksandGuestAgentMethod.EXECUTE,
+ {"command": "x"},
+ timeout=0.5,
+ )
+ assert "error" in result
+ assert "Response ID mismatch" not in result["error"]["message"], result
+ finally:
+ await client.close()
+ server.close()
+
+
+async def test_concurrent_calls_each_get_their_own_response(sock_path: Path) -> None:
+ """Five concurrent calls; the agent replies in reverse-id order so wire
+ order is the opposite of call order. Each caller receives its own
+ response, routed by id."""
+
+ num_requests = 5
+
+ async def handler(msg: dict) -> list[dict]:
+ # Higher ids reply first — wire order is reversed from call order.
+ delay = (num_requests + 1 - msg["id"]) * 0.02
+ await asyncio.sleep(delay)
+ return [_ok(msg["id"], stdout=f"id={msg['id']}")]
+
+ async with FakeAgent(sock_path, handler):
+ client = await _connected_client(sock_path)
+ try:
+ results = await asyncio.gather(
+ *[
+ client.send_request(
+ QuicksandGuestAgentMethod.EXECUTE,
+ {"command": f"req-{i}"},
+ timeout=2.0,
+ )
+ for i in range(num_requests)
+ ]
+ )
+ finally:
+ await client.close()
+
+ for i, r in enumerate(results, start=1):
+ assert "result" in r, r
+ assert r["result"]["stdout"] == f"id={i}"
+
+
+async def test_timeout_does_not_poison_subsequent_calls(sock_path: Path) -> None:
+ """Request A times out on the host; its late reply is dropped at the
+ reader. Request B's reply is delivered correctly."""
+
+ async def handler(msg: dict) -> list[dict]:
+ if msg["id"] == 1:
+ await asyncio.sleep(0.5)
+ return [_ok(msg["id"], stdout=f"id={msg['id']}")]
+
+ async with FakeAgent(sock_path, handler):
+ client = await _connected_client(sock_path)
+ try:
+ r1 = await client.send_request(
+ QuicksandGuestAgentMethod.EXECUTE,
+ {"command": "first"},
+ timeout=0.1,
+ )
+ r2 = await client.send_request(
+ QuicksandGuestAgentMethod.EXECUTE,
+ {"command": "second"},
+ timeout=2.0,
+ )
+ finally:
+ await client.close()
+
+ assert "error" in r1
+ assert "timed out" in r1["error"]["message"].lower()
+ assert "result" in r2, r2
+ assert r2["result"]["stdout"] == "id=2"
+
+
+async def test_connection_drop_fails_pending_callers_fast(sock_path: Path) -> None:
+ """When the agent disconnects mid-request, the pending caller wakes up
+ with a connection error well before the request timeout would fire."""
+
+ async def handler(msg: dict) -> list[dict]:
+ await asyncio.sleep(10)
+ return [_ok(msg["id"])]
+
+ async with FakeAgent(sock_path, handler) as agent:
+ client = await _connected_client(sock_path)
+ try:
+
+ async def disconnect_after_delay():
+ await asyncio.sleep(0.1)
+ await agent.disconnect_all()
+
+ disconnect_task = asyncio.create_task(disconnect_after_delay())
+ try:
+ start = asyncio.get_event_loop().time()
+ result = await client.send_request(
+ QuicksandGuestAgentMethod.EXECUTE,
+ {"command": "x"},
+ timeout=10.0,
+ )
+ elapsed = asyncio.get_event_loop().time() - start
+ finally:
+ await disconnect_task
+ finally:
+ await client.close()
+
+ assert "error" in result
+ assert "Connection error" in result["error"]["message"]
+ assert elapsed < 1.0, f"Caller waited {elapsed:.2f}s; should fail fast"
+
+
+async def test_stream_request_accumulates_multi_frame_output(sock_path: Path) -> None:
+ """A streaming request emits multiple frames sharing one id; the client
+ accumulates stdout/stderr across frames, invokes per-chunk callbacks,
+ and terminates on the exit frame."""
+
+ chunks_seen: list[tuple[str, str]] = []
+
+ async def handler(msg: dict) -> list[dict]:
+ rid = msg["id"]
+ return [
+ {"id": rid, "stream": "stdout", "data": "hello "},
+ {"id": rid, "stream": "stdout", "data": "world\n"},
+ {"id": rid, "stream": "stderr", "data": "warn\n"},
+ {"id": rid, "stream": "exit", "exit_code": 0},
+ ]
+
+ async with FakeAgent(sock_path, handler):
+ client = await _connected_client(sock_path)
+ try:
+ result = await client.send_stream_request(
+ {"command": "x"},
+ timeout=2.0,
+ on_stdout=lambda d: chunks_seen.append(("out", d)),
+ on_stderr=lambda d: chunks_seen.append(("err", d)),
+ )
+ finally:
+ await client.close()
+
+ assert "result" in result, result
+ assert result["result"]["stdout"] == "hello world\n"
+ assert result["result"]["stderr"] == "warn\n"
+ assert result["result"]["exit_code"] == 0
+ assert chunks_seen == [
+ ("out", "hello "),
+ ("out", "world\n"),
+ ("err", "warn\n"),
+ ]