Skip to content

Build and run agents you can see, understand and trust.

fix(realtime): release streams when local transport start fails (#3659)

Kiko0301475008336b4d
diff --git a/src/agentscope/realtime/_transport/_local.py b/src/agentscope/realtime/_transport/_local.py
index 5d1db8500..5b5b1151f 100644
--- a/src/agentscope/realtime/_transport/_local.py
+++ b/src/agentscope/realtime/_transport/_local.py
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
"""The local sound-card transport."""
import asyncio
+import contextlib
import threading
import time
from typing import Any, AsyncIterator
@@ -79,23 +80,39 @@ class LocalAudioTransport(TransportBase):
# not leak into this one.
self._in_queue = asyncio.Queue()
self._loop = asyncio.get_running_loop()
- self._in_stream = sd.InputStream(
- samplerate=self.input_sample_rate,
- channels=1,
- dtype="int16",
- blocksize=self._chunk_frames,
- device=self._input_device,
- callback=self._on_input,
- )
- self._out_stream = sd.OutputStream(
- samplerate=self.output_sample_rate,
- channels=1,
- dtype="int16",
- device=self._output_device,
- callback=self._on_output,
- )
- self._in_stream.start()
- self._out_stream.start()
+ self._in_stream = None
+ self._out_stream = None
+ try:
+ self._in_stream = sd.InputStream(
+ samplerate=self.input_sample_rate,
+ channels=1,
+ dtype="int16",
+ blocksize=self._chunk_frames,
+ device=self._input_device,
+ callback=self._on_input,
+ )
+ self._out_stream = sd.OutputStream(
+ samplerate=self.output_sample_rate,
+ channels=1,
+ dtype="int16",
+ device=self._output_device,
+ callback=self._on_output,
+ )
+ self._in_stream.start()
+ self._out_stream.start()
+ except BaseException:
+ # If start() fails, async with does not call __aexit__().
+ # Release partially acquired streams here to avoid leaks.
+ self._loop = None
+ for stream in (self._in_stream, self._out_stream):
+ if stream is None:
+ continue
+ with contextlib.suppress(Exception):
+ stream.stop()
+ with contextlib.suppress(Exception):
+ stream.close()
+ self._in_stream = self._out_stream = None
+ raise
async def close(self) -> None:
"""Stop both streams and end :meth:`incoming`."""
diff --git a/tests/realtime_local_transport_test.py b/tests/realtime_local_transport_test.py
index 2761ee2ae..154f79b81 100644
--- a/tests/realtime_local_transport_test.py
+++ b/tests/realtime_local_transport_test.py
@@ -162,6 +162,38 @@ class LocalAudioTransportTest(IsolatedAsyncioTestCase):
await incoming.aclose()
await transport.close()
+ async def test_start_failure_releases_open_streams(self) -> None:
+ """Failed entry releases streams and preserves the original error."""
+ sd = MagicMock()
+ in_stream = MagicMock(name="in_stream")
+ out_stream = MagicMock(name="out_stream")
+ sd.InputStream.return_value = in_stream
+ sd.OutputStream.return_value = out_stream
+ error = RuntimeError("device busy")
+ out_stream.start.side_effect = error
+
+ transport = LocalAudioTransport()
+
+ with patch.dict(sys.modules, {"sounddevice": sd}):
+ with self.assertRaises(RuntimeError) as raised:
+ async with transport:
+ self.fail("__aenter__ must not succeed")
+
+ self.assertIs(raised.exception, error)
+ in_stream.start.assert_called_once_with()
+ in_stream.stop.assert_called_once_with()
+ in_stream.close.assert_called_once_with()
+ out_stream.stop.assert_called_once_with()
+ out_stream.close.assert_called_once_with()
+ self.assertEqual(
+ (
+ transport._in_stream,
+ transport._out_stream,
+ transport._loop,
+ ),
+ (None, None, None),
+ )
+
async def test_playout_position_shape(self) -> None:
"""The position is a plain value object."""
self.assertEqual(