Skip to content

fix(core): raise ApiError when a sync websocket handshake is rejected - #832

Open
mayankbohradev wants to merge 2 commits into
deepgram:mainfrom
mayankbohradev:fix/sync-websocket-handshake-api-error
Open

mayankbohradev wants to merge 2 commits into
deepgram:mainfrom
mayankbohradev:fix/sync-websocket-handshake-api-error

Conversation

@mayankbohradev

Copy link
Copy Markdown
Contributor

What

Sync WebSocket clients now raise ApiError when the server rejects the handshake, the same as the async clients. Before this change they raised a raw websockets.exceptions.InvalidStatus.

Why

except ApiError in sync code does not catch a rejected handshake (HTTP 401 for a bad key, 429 for a rate limit). This runs against the live API with an invalid key on deepgram-sdk==7.19.0:

import asyncio
from deepgram import AsyncDeepgramClient, DeepgramClient

async def async_connect():
    async with AsyncDeepgramClient(api_key="invalid-key").listen.v1.connect(model="nova-3"):
        pass

def sync_connect():
    with DeepgramClient(api_key="invalid-key").listen.v1.connect(model="nova-3"):
        pass
async: ApiError(status_code=401)
sync:  websockets.exceptions.InvalidStatus: server rejected WebSocket connection: HTTP 401

Cause: websockets has two exception classes for a rejected handshake.

  • The legacy asyncio client raises InvalidStatusCode (exc.status_code).
  • websockets.sync.client raises InvalidStatus (exc.response.status_code).

core/websocket_compat.py imports InvalidStatusCode first and uses InvalidStatus only on ImportError. The legacy name still imports on every supported websockets version, so InvalidWebSocketStatus was always the legacy class. The async connect() methods use the legacy client, so they matched. The sync connect() methods use websockets.sync.client, so they never matched.

The result is the same on websockets 12.0, 13.1, 16.1.1 and 17.4. It depends on sync or async, not on the websockets version. v5.0.0 already caught only InvalidStatusCode around the sync connect call, so this is not a regression.

How

  • InvalidWebSocketStatus is now a tuple of both classes. The 20 generated except InvalidWebSocketStatus as exc call sites (sync and async, in client.py and raw_client.py for Listen V1/V2, Speak V1/V2 and Agent V1) do not change.
  • get_status_code reads exc.status_code when it exists, else exc.response.status_code.
  • core/websocket_compat.py is Fern output, so the patch is recorded as temporarily frozen in .fernignore and AGENTS.md, with the unfreeze condition: remove it when the generated shim matches both classes.
  • Two existing test helpers built the exception with InvalidWebSocketStatus.__new__(InvalidWebSocketStatus). They now take the class from the tuple.

Testing

  • New tests/custom/test_websocket_handshake_rejection.py, registered in .fernignore and AGENTS.md. It starts a real local websockets server that rejects the handshake with 401 and 429, and checks every sync and async connect(), high-level and with_raw_response. The existing mapping tests raise a hand-built exception from a patched connect, so they passed while the real sync client raised a different class.
  • Without the fix, 12 of the 22 new tests fail: the 10 sync cases and the 2 shim tests. The 10 async cases pass before and after.
  • The CI test command, poetry run pytest -rP --cov=deepgram --cov-branch ., with the WireMock container: 1197 passed, 4 skipped, 1 xfailed; coverage 95.11%. The full suite also passes on Python 3.10, 3.11, 3.12 and 3.13.
  • The new test plus the streaming, Speak V2 and transport tests pass on websockets 12.0, 13.1, 16.1.1 and 17.4.
  • mypy src/ and mypy tests/typecheck pass on Python 3.10 and 3.13. ruff check passes on the changed files.
  • poetry build passes. The built wheel, installed into clean environments on Python 3.10 to 3.14, raises ApiError for a rejected handshake (401 and 429) on sync and async, high-level and with_raw_response.
  • With the fix, the script above prints ApiError(status_code=401) for both clients.

Notes for reviewers

  • InvalidWebSocketStatus changes from a class to a tuple of classes. It is re-exported from deepgram.core. except and isinstance work as before. Code that instantiates it or uses it as a type annotation would need a change; in src/ and examples/ it is used only in the except clauses.
  • The durable fix belongs in the generator. I can open the Fern issue if that helps.
  • examples/17-transcription-live-reconnect.py catches (ApiError, InvalidStatus) for this case. I kept the clause so the example still works with older SDK releases, and corrected its comment, which said the type depends on the websockets version.
  • On websockets 14 and later, the InvalidStatusCode import emits a DeprecationWarning. That was already the case and this PR does not change it.

websockets raises InvalidStatusCode from the legacy asyncio client and
InvalidStatus from websockets.sync.client. The compat shim bound only
InvalidStatusCode, so the sync connect() methods raised a raw InvalidStatus
for a rejected handshake (401, 429) while the async methods raised ApiError.

Match both classes and read the status code from either layout. The
generated except clauses stay unchanged.

Add regression coverage that uses a real local server, and freeze the
patched shim in .fernignore with an AGENTS.md entry.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant