Skip to content

Repeated synchronous streaming connect calls allocate unowned sockets or silently drop audio #321

Backlog

Description

@codebanditssss

Reproduced on 0ba094c.

Observed behavior

The synchronous client creates its read/write threads once, but accepts another connect call and opens a WebSocket before trying to restart those threads.

  • connect → connect allocates two sockets, then raises RuntimeError: threads can only be started once. The overwritten first socket remains open even after two public disconnect calls.
  • connect → disconnect → connect opens a new socket before raising the same error.
  • A failed initial handshake followed by connect can return normally with stopped threads; stream sends no audio.

Expected: reject unsupported client reuse before a new handshake, matching the existing asynchronous single-use contract, or fully implement reconnect. A single-use guard is the smaller fix. This reproduction proves socket ownership/audio-delivery behavior, not live billing.

Source: assemblyai/streaming/v3/client.py.

Reproduction evidence

Python 3.12; install the SDK's dependencies, save the script below in the repository root, then run python reproduce.py. It was run under Pydantic 1.10.26 and 2.12.5, with websockets 15.0.1 and httpx 0.28.1.

No credentials, real service connections, or billable API calls are used. These scripts assert baseline observations and controls, not fixed behavior.

Offline reproduction script
"""Transport-boundary repro; real SDK threads/tasks, no network or credentials."""
import asyncio
import json
import queue
import sys
import os
from unittest.mock import patch

sys.dont_write_bytecode = True
sys.path.insert(0, os.environ.get("AAI_SDK_ROOT", os.getcwd()))
import pydantic
import websockets
from assemblyai.streaming.v3 import (
    RealTimeTranscriber, AsyncRealTimeTranscriber, RealTimeTranscriberOptions,
    RealTimeParameters, RealTimeEvents,
)

PARAMS = RealTimeParameters(sample_rate=16000, speech_model="assemblyai-stt-3-7-realtime-agent")
OPTIONS = RealTimeTranscriberOptions(api_key="unused-offline", max_connection_retries=0)
BEGIN = json.dumps({"type": "Begin", "id": "offline-session", "expires_at": "2030-01-01T00:00:00Z"})

class Socket:
    def __init__(self):
        self.closed = False
        self.close_calls = 0
        self.sent = []
        self.incoming = queue.Queue()
        self.incoming.put(BEGIN)
    def recv(self, timeout=1):
        try:
            return self.incoming.get(timeout=min(timeout, 0.05))
        except queue.Empty:
            raise TimeoutError
    def send(self, data):
        assert not self.closed
        self.sent.append(data)
    def close(self):
        self.close_calls += 1
        self.closed = True

class Transport:
    def __init__(self, fail_first=False):
        self.calls = 0
        self.sockets = []
        self.fail_first = fail_first
    def connect(self, *args, **kwargs):
        self.calls += 1
        if self.fail_first and self.calls == 1:
            raise TimeoutError("offline handshake failure")
        socket = Socket()
        self.sockets.append(socket)
        return socket
    def state(self):
        return {"handshake_calls": self.calls, "allocations": len(self.sockets),
                "closed": [s.closed for s in self.sockets],
                "close_calls": [s.close_calls for s in self.sockets]}

def sync_case(disconnect_first):
    transport = Transport()
    client = RealTimeTranscriber(OPTIONS)
    seen = __import__("threading").Event()
    client.on(RealTimeEvents.Begin, lambda c, e: seen.set())
    with patch("assemblyai.streaming.v3.client.websocket_connect", transport.connect):
        try:
            client.connect(PARAMS)
            assert seen.wait(2), "first session did not dispatch Begin"
            if disconnect_first:
                client.disconnect()
                client.disconnect()  # idempotency control
            try:
                client.connect(PARAMS)
                raise AssertionError("expected already-started thread error")
            except RuntimeError as exc:
                assert str(exc) == "threads can only be started once"
                print(json.dumps({"case": "sync_after_disconnect" if disconnect_first else "sync_while_connected",
                                  "exception": repr(exc), "at_exception": transport.state()}))
            assert len(transport.sockets) == 2
            assert not transport.sockets[-1].closed
            client.disconnect()
            client.disconnect()
            print(json.dumps({"case": "sync_cleanup", "disconnect_first": disconnect_first,
                              "after_public_disconnect_twice": transport.state()}))
            assert transport.sockets[0].closed == disconnect_first
            assert transport.sockets[1].closed
        finally:
            client.disconnect()
            for s in transport.sockets:
                s.close()  # harness closes any overwritten socket, after evidence
            client._client._http_client.close()
    assert not client._read_thread.is_alive() and not client._write_thread.is_alive()
    print("sync harness cleanup: all sockets closed, SDK threads stopped")

def sync_failed_first():
    transport = Transport(fail_first=True)
    client = RealTimeTranscriber(OPTIONS)
    errors = []
    client.on(RealTimeEvents.Error, lambda c, e: errors.append(str(e)))
    with patch("assemblyai.streaming.v3.client.websocket_connect", transport.connect):
        try:
            client.connect(PARAMS)
            assert errors and not transport.sockets
            client.connect(PARAMS)
            client._read_thread.join(2)
            client._write_thread.join(2)
            assert not client._read_thread.is_alive() and not client._write_thread.is_alive()
            client.stream(b"\0" * 3200)
            assert not transport.sockets[0].sent
            print(json.dumps({"case": "sync_after_failed_handshake", "second_connect": "returned normally",
                              "stop_set": client._stop_event.is_set(), "threads_alive": False,
                              "sent_audio_frames": len(transport.sockets[0].sent),
                              "at_return": transport.state(), "errors": errors}))
        finally:
            client.disconnect()
            client.disconnect()
            for s in transport.sockets:
                s.close()
            client._client._http_client.close()

class AsyncSocket(Socket):
    async def recv(self):
        if not self.incoming.empty():
            return self.incoming.get_nowait()
        await asyncio.Future()
    async def send(self, data):
        super().send(data)
    async def close(self):
        super().close()

async def async_case(mode):
    transport = Transport()
    async def connect(*args, **kwargs):
        transport.calls += 1
        if mode == "failed_handshake" and transport.calls == 1:
            raise TimeoutError("offline handshake failure")
        s = AsyncSocket()
        transport.sockets.append(s)
        return s
    client = AsyncRealTimeTranscriber(OPTIONS)
    with patch("assemblyai.streaming.v3.async_client.websocket_connect_async", connect):
        try:
            await client.connect(PARAMS)
            if mode == "disconnected":
                await client.disconnect()
                await client.disconnect()
            before = transport.calls
            try:
                await client.connect(PARAMS)
                raise AssertionError("expected single-use rejection")
            except RuntimeError as exc:
                assert transport.calls == before
                print(json.dumps({"case": "async_" + mode, "exception": str(exc),
                                  "second_handshake_calls": transport.calls - before, "state": transport.state()}))
        finally:
            await client.disconnect()
            await client.disconnect()
    assert all(s.closed for s in transport.sockets)

if __name__ == "__main__":
    print(f"Python {sys.version.split()[0]}, pydantic {pydantic.__version__}, websockets {websockets.__version__}")
    sync_case(False)
    sync_case(True)
    sync_failed_first()
    for mode in ("connected", "disconnected", "failed_handshake"):
        asyncio.run(asyncio.wait_for(async_case(mode), 5))
Observed output
Python 3.12.13, pydantic 2.12.5, websockets 15.0.1
{"case": "sync_while_connected", "exception": "RuntimeError('threads can only be started once')", "at_exception": {"handshake_calls": 2, "allocations": 2, "closed": [false, false], "close_calls": [0, 0]}}
{"case": "sync_cleanup", "disconnect_first": false, "after_public_disconnect_twice": {"handshake_calls": 2, "allocations": 2, "closed": [false, true], "close_calls": [0, 2]}}
sync harness cleanup: all sockets closed, SDK threads stopped
{"case": "sync_after_disconnect", "exception": "RuntimeError('threads can only be started once')", "at_exception": {"handshake_calls": 2, "allocations": 2, "closed": [true, false], "close_calls": [2, 0]}}
{"case": "sync_cleanup", "disconnect_first": true, "after_public_disconnect_twice": {"handshake_calls": 2, "allocations": 2, "closed": [true, true], "close_calls": [2, 2]}}
sync harness cleanup: all sockets closed, SDK threads stopped
Connection failed: Connection failed: offline handshake failure (code=None)
{"case": "sync_after_failed_handshake", "second_connect": "returned normally", "stop_set": true, "threads_alive": false, "sent_audio_frames": 0, "at_return": {"handshake_calls": 2, "allocations": 1, "closed": [false], "close_calls": [0]}, "errors": ["Connection failed: offline handshake failure"]}
{"case": "async_connected", "exception": "AsyncRealTimeTranscriber has already been connected; create a new instance for a new connection.", "second_handshake_calls": 0, "state": {"handshake_calls": 1, "allocations": 1, "closed": [false], "close_calls": [0]}}
{"case": "async_disconnected", "exception": "AsyncRealTimeTranscriber has already been connected; create a new instance for a new connection.", "second_handshake_calls": 0, "state": {"handshake_calls": 1, "allocations": 1, "closed": [true], "close_calls": [2]}}
Connection failed: Connection failed: offline handshake failure (code=None)
{"case": "async_failed_handshake", "exception": "AsyncRealTimeTranscriber has already been connected; create a new instance for a new connection.", "second_handshake_calls": 0, "state": {"handshake_calls": 1, "allocations": 0, "closed": [], "close_calls": []}}

Controls and scope

Normal first-session Begin dispatch, repeated disconnect, and the async equivalents were checked. Async reuse makes zero additional handshake calls. All mock sockets and real SDK threads/tasks were cleaned up.

All six Python executions (three reproductions under both Pydantic versions) exited 0.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions