From c2f2bd1cf89cb73e4df0c4090a44aaad59cb53a7 Mon Sep 17 00:00:00 2001 From: sqrt-negativeone Date: Thu, 1 Oct 2026 14:14:08 +0000 Subject: [PATCH 1/2] fix(stv): report connection closes before sessionReady and raise join timeout default A direct-WebRTC session failed to wait long enough for sessionReady. The ``webrtc_join_timeout_s`` default of 10 s covered only the room join; the model's cold start alone can exceed 30 s, so most first sessions timed out. The default is now 90 s, and the README, example, and skill docs are updated. When the server closes the WebSocket before sending sessionReady without an errorResponse (e.g. a failed entitlement check), the client now queues a CONNECTION_CLOSED error with the WebSocket close code and reason instead of waiting silent until timeout. Co-Authored-By: Claude Fable 5.1 --- CHANGELOG.md | 16 ++++++ README.md | 7 +-- examples/03-direct-webrtc/main.py | 3 -- skills/ojin-stv-integration/SKILL.md | 4 +- src/ojin/ojin_client.py | 39 +++++++++++++++ src/ojin/stv/config.py | 6 ++- src/ojin/stv/ojin_stv_webrtc_client.py | 6 +-- tests/stv/test_stv_client_webrtc_mode.py | 25 +++++++++ tests/stv/test_webrtc_client.py | 2 +- tests/stv/test_webrtc_negotiation.py | 3 +- tests/test_ojin_client.py | 64 ++++++++++++++++++++++++ 11 files changed, 160 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 92dd0a0..438b85a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,22 @@ All notable changes to `ojin-client` are documented here. The format follows ## Unreleased +### Changed +- `WebRTCSettings.webrtc_join_timeout_s` now defaults to **90 s** (was 10 s). The + wait covers the model's cold start as well as the room join, and a cold start + alone can take more than 30 s, so the old default failed sessions the server + was about to start. An explicit value still wins; anything under ~60 s will + trip on cold starts. +- The `WEBRTC_JOIN_TIMEOUT` message now starts with `Timed out:`. + +### Fixed +- A connection that the server closes before `sessionReady` without sending an + `errorResponse` (for example a failed entitlement check) is now reported at + once as a fatal `ERROR` with code `CONNECTION_CLOSED` and the WebSocket close + code and reason in the message. Previously nothing was reported: the WebSocket + client waited forever and the WebRTC client waited out the whole join timeout, + then blamed a timeout. + ## 0.12.0 - 2026-09-29 ### Added diff --git a/README.md b/README.md index dd62b6e..b359f5c 100644 --- a/README.md +++ b/README.md @@ -380,7 +380,7 @@ avatar_token = ( | `WEBRTC_AUTH_FAILED` | The room rejected the avatar's token | | `WEBRTC_NETWORK_FAILED` | Ojin couldn't reach the room | | `WEBRTC_INVALID_SETTINGS` | The room URL or provider was unusable | -| `WEBRTC_JOIN_TIMEOUT` | The session wasn't ready within `webrtc_join_timeout_s` (default 10 s — it covers the model's cold start too, so leave headroom) | +| `WEBRTC_JOIN_TIMEOUT` | The session wasn't ready within `webrtc_join_timeout_s` (default 90 s — it covers the model's cold start too, which alone can take more than 30 s) | | `WEBRTC_ROOM_LOST` | The avatar dropped out of the room mid-session | | `WEBRTC_NOT_SUPPORTED` | The server returned no room result for this session | | `WEBRTC_JOIN_FAILED` | Fallback: the join failed with a code this SDK doesn't recognise | @@ -412,7 +412,7 @@ avatar_token = ( Video frames are emitted at the server's native resolution — read `STVVideoFrame.width`/`height` per frame rather than configuring an output size. Set `OJIN_MODE=dev` in the environment to attach the dev-mode query flag when connecting with the default transport. -For direct WebRTC, `WebRTCSettings` takes `provider`, `room_url`, `token`, `audio_sample_rate` (default `16000`) and `webrtc_join_timeout_s` (default `10.0`); the playback fields above don't apply because the media goes to the room. +For direct WebRTC, `WebRTCSettings` takes `provider`, `room_url`, `token`, `audio_sample_rate` (default `16000`) and `webrtc_join_timeout_s` (default `90.0`); the playback fields above don't apply because the media goes to the room. --- @@ -491,7 +491,8 @@ async def main(pcm_16k_mono: bytes) -> None: - **Choppy playback** — keep the event loop free; the SDK already decodes JPEG off-loop, but heavy synchronous work in your frame handlers will stall the 40 ms tick. Enable `STVConfig(lipsync_trace_enabled=True)` to inspect per-tick timing. - **Latency higher than expected** — the WebSocket transport is built for **server-to-server** use over a stable connection. Run the client on a backend (not an end-user device), ideally in **US East**, close to Ojin's inference; deliver the final media to end users over a realtime transport such as WebRTC — or publish straight into their room with [direct WebRTC](#direct-webrtc-livekit--daily). The client keeps a small video buffer (`initial_buffer_frames`) to absorb network jitter, since the server delivers at realtime 25 fps. - **`WEBRTC_AUTH_FAILED`** — the token doesn't grant the avatar access to that room. On LiveKit, check the token's identity is exactly `ojin-avatar` and it allows publishing; on Daily, check the meeting token is for the same room as `room_url`. -- **`WEBRTC_JOIN_TIMEOUT`** — the session didn't become ready within `webrtc_join_timeout_s`. It covers the model's cold start as well as the room join, so raise it (e.g. `30.0`) if it trips on first sessions. +- **`WEBRTC_JOIN_TIMEOUT`** — the session didn't become ready within `webrtc_join_timeout_s` (default 90 s). It covers the model's cold start as well as the room join, and a cold start alone can take more than 30 s, so don't lower it below that. Retrying usually succeeds: the server keeps starting after the client gives up. +- **`CONNECTION_CLOSED`** — the connection ended before the session was ready and the server sent no error of its own. The message carries the WebSocket close code and reason (for example `1008: Insufficient funds`). - **Your bot hears the avatar** — it's subscribed to the `ojin-avatar` participant's microphone. Detect it with `is_avatar_participant()` / `is_avatar_identity()` and unsubscribe. --- diff --git a/examples/03-direct-webrtc/main.py b/examples/03-direct-webrtc/main.py index f025d55..f49a546 100644 --- a/examples/03-direct-webrtc/main.py +++ b/examples/03-direct-webrtc/main.py @@ -23,8 +23,6 @@ from ojin import Credentials, MissingCredentialsError, load_env, resolve_credentials from ojin.stv import OjinSTVClient, STVEvent, WebRTCSettings -JOIN_TIMEOUT_S = 30.0 # covers the room join AND a model cold start - def read_mono_wav(path: pathlib.Path) -> tuple[bytes, int]: """Read a mono 16-bit PCM WAV as (pcm_bytes, sample_rate), or exit with a hint.""" @@ -60,7 +58,6 @@ def webrtc_settings_from_env(sample_rate: int) -> WebRTCSettings: room_url=room_url, token=token, audio_sample_rate=sample_rate, # publish at the clip's own rate - webrtc_join_timeout_s=JOIN_TIMEOUT_S, ) except ValueError as exc: sys.exit(f"\n Invalid WebRTC settings: {exc}\n") diff --git a/skills/ojin-stv-integration/SKILL.md b/skills/ojin-stv-integration/SKILL.md index 70ebe28..8fdaaa2 100644 --- a/skills/ojin-stv-integration/SKILL.md +++ b/skills/ojin-stv-integration/SKILL.md @@ -205,8 +205,8 @@ client = OjinSTVClient( ends at close. Don't build a render path in this mode. - `WEBRTC_CONNECTED` fires when the avatar is in the room; `FIRST_FRAME` and the speaking events still fire. -- **No fallback.** A failed join, a `webrtc_join_timeout_s` expiry (default 10 s, - includes cold start — use ~30 s in production) or an unsupporting server is a fatal +- **No fallback.** A failed join, a `webrtc_join_timeout_s` expiry (default 90 s, + includes cold start — don't lower it below ~60 s) or an unsupporting server is a fatal `ERROR` naming the cause (`WEBRTC_AUTH_FAILED`, `WEBRTC_NETWORK_FAILED`, `WEBRTC_INVALID_SETTINGS`, `WEBRTC_JOIN_TIMEOUT`, `WEBRTC_ROOM_LOST` or `WEBRTC_NOT_SUPPORTED`) and the session closes. diff --git a/src/ojin/ojin_client.py b/src/ojin/ojin_client.py index c1543f0..a33d5be 100644 --- a/src/ojin/ojin_client.py +++ b/src/ojin/ojin_client.py @@ -177,6 +177,9 @@ def __init__( # noqa: PLR0913 # tracer derives an ingress-bandwidth lane from its slope. self._ingress_bytes_total: int = 0 self._inference_server_ready: bool = False + # Set once an error has been queued for the consumer, so a close that + # follows it is not reported as a second, vaguer error. + self._error_reported: bool = False self._cancelled: bool = False self._outbound_generation: int = 0 self._active_interaction_id: str | None = None @@ -270,6 +273,7 @@ async def connect(self) -> None: # Enable TCP_NODELAY to reduce latency for real-time frames _configure_tcp_nodelay(self._ws) self._running = True + self._error_reported = False self._receive_task = asyncio.create_task( self._receive_server_messages() ) @@ -352,8 +356,40 @@ async def _receive_server_messages(self) -> None: except Exception as e: logger.exception("Error in WebSocket receive loop: %s", e) finally: + if self._running: # the server ended it, not our own close() + await self._report_closed_before_ready() await self.close() + async def _report_closed_before_ready(self) -> None: + """Queue an error when the connection ends before ``sessionReady``. + + Consumers block on :meth:`receive_message`, so a proxy that closes + without an ``errorResponse`` (a failed entitlement check, a dropped + connection) would otherwise look like a session that is still starting + until the caller's own timeout expires. + """ + if self._inference_server_ready or self._error_reported: + return + close_code = getattr(self._ws, "close_code", None) + close_reason = getattr(self._ws, "close_reason", None) + detail = "" + if close_code is not None: + detail = f" (close code {close_code}" + detail += f": {close_reason})" if close_reason else ")" + self._error_reported = True + await self._available_response_messages_queue.put( + ErrorResponseMessage( + payload=ErrorResponse( + interaction_id=None, + code="CONNECTION_CLOSED", + message="The connection closed before the session was ready" + + detail, + timestamp=int(time.time() * 1000), + details=None, + ) + ) + ) + async def _handle_server_message(self, message: str | bytes) -> None: """Handle an incoming WebSocket message. @@ -401,6 +437,7 @@ async def _handle_server_message(self, message: str | bytes) -> None: "active_interaction_id": self._active_interaction_id, }, ) + self._error_reported = True await self._available_response_messages_queue.put( ErrorResponseMessage( payload=ErrorResponse( @@ -431,6 +468,7 @@ async def _handle_server_message(self, message: str | bytes) -> None: "active_interaction_id": self._active_interaction_id, }, ) + self._error_reported = True await self._available_response_messages_queue.put( ErrorResponseMessage( payload=ErrorResponse( @@ -473,6 +511,7 @@ async def _handle_server_message(self, message: str | bytes) -> None: await self._available_response_messages_queue.put(msg) if isinstance(msg, ErrorResponseMessage): + self._error_reported = True raise RuntimeError(f"Error in Inference Server received: {msg}") if isinstance(msg, OjinSessionReadyPing): diff --git a/src/ojin/stv/config.py b/src/ojin/stv/config.py index d13f19e..bec9d9f 100644 --- a/src/ojin/stv/config.py +++ b/src/ojin/stv/config.py @@ -45,7 +45,9 @@ class WebRTCSettings: Set ``audio_sample_rate`` to the rate your TTS emits to avoid resampling. ``webrtc_join_timeout_s`` bounds the whole wait for the session to become - ready — the room join *and* a model cold start — so leave headroom. + ready — the room join *and* a model cold start, which alone can take more + than 30 s. It is a backstop: a start the service itself gives up on is + reported sooner, as the server's own error. The settings are declared in the WebSocket **upgrade request** (DR-006 as amended 2026-07-24): the non-secret fields ride ``webrtc_*`` query params @@ -64,7 +66,7 @@ class WebRTCSettings: token: str = field(repr=False) provider: WebRTCProvider | str = WebRTCProvider.DAILY audio_sample_rate: int = 16000 - webrtc_join_timeout_s: float = 10.0 + webrtc_join_timeout_s: float = 90.0 version: int = 2 def to_connect_query_params(self) -> dict: diff --git a/src/ojin/stv/ojin_stv_webrtc_client.py b/src/ojin/stv/ojin_stv_webrtc_client.py index 2fb41f0..0bac31c 100644 --- a/src/ojin/stv/ojin_stv_webrtc_client.py +++ b/src/ojin/stv/ojin_stv_webrtc_client.py @@ -669,9 +669,9 @@ async def _handle_join_timeout(self) -> None: self._tracer.instant("webrtc", "join_timeout") await self._fail( WEBRTC_JOIN_TIMEOUT, - "The session was not ready within " - f"{self._webrtc_settings.webrtc_join_timeout_s} s (the wait covers the " - "room join and the model's cold start)", + "Timed out: the session was not ready within " + f"{self._webrtc_settings.webrtc_join_timeout_s:g} s (the wait covers " + "the room join and the model's cold start)", {"outcome": "timeout"}, ) diff --git a/tests/stv/test_stv_client_webrtc_mode.py b/tests/stv/test_stv_client_webrtc_mode.py index 2938f4e..8afcfa8 100644 --- a/tests/stv/test_stv_client_webrtc_mode.py +++ b/tests/stv/test_stv_client_webrtc_mode.py @@ -10,6 +10,7 @@ import pytest +from ojin.entities.interaction_messages import ErrorResponse, ErrorResponseMessage from ojin.ojin_client_messages import ( FrameType, OjinAudioInputMessage, @@ -242,6 +243,30 @@ async def test_join_timeout_is_reported_and_closes() -> None: assert closed == [{}] +async def test_error_before_session_ready_fails_without_waiting_for_timeout() -> None: + """A start the server gives up on ends at once, under the server's own code.""" + fake_client = _NeverReadyClient() + client, _ = make_client(fake=fake_client, join_timeout_s=60.0) + errors = _record(client, STVEvent.ERROR) + closed = _record(client, STVEvent.CLOSED) + await client.start() + + await fake_client.push( + ErrorResponseMessage( + payload=ErrorResponse( + code="BACKEND_UNAVAILABLE", + message="No GPU became available", + timestamp=1789000000000, + ) + ) + ) + await asyncio.sleep(0.05) + + assert [(e["code"], e["fatal"]) for e in errors] == [("BACKEND_UNAVAILABLE", True)] + assert errors[0]["message"] == "No GPU became available" + assert closed == [{}] + + async def test_mid_session_room_loss_is_reported_and_closes() -> None: """A post-connect webrtcStatus failed(REJOIN_FAILED) ends the session.""" client, fake_client = make_client() diff --git a/tests/stv/test_webrtc_client.py b/tests/stv/test_webrtc_client.py index e343ae7..138beaf 100644 --- a/tests/stv/test_webrtc_client.py +++ b/tests/stv/test_webrtc_client.py @@ -375,7 +375,7 @@ def test_webrtc_settings_repr_hides_token_and_pins_defaults() -> None: assert settings.version == 2 # protocol v2 (DR-006) # Client-local; in v2 it governs the whole sessionReady wait and must not # appear in the connect declaration. - assert settings.webrtc_join_timeout_s == 10.0 + assert settings.webrtc_join_timeout_s == 90.0 assert "webrtc_join_timeout_s" not in settings.to_connect_query_params() assert settings.to_connect_query_params()["webrtc_version"] == "2" # The token travels only in the header — never in a query param. diff --git a/tests/stv/test_webrtc_negotiation.py b/tests/stv/test_webrtc_negotiation.py index db9bc87..01f2b4b 100644 --- a/tests/stv/test_webrtc_negotiation.py +++ b/tests/stv/test_webrtc_negotiation.py @@ -265,7 +265,8 @@ async def test_no_session_ready_within_timeout_is_fatal_and_closes() -> None: assert len(errors) == 1 assert errors[0]["code"] == "WEBRTC_JOIN_TIMEOUT" assert errors[0]["fatal"] is True - assert "not ready within" in errors[0]["message"] + assert errors[0]["message"].startswith("Timed out: ") + assert "not ready within 90 s" in errors[0]["message"] assert client._preinit_inputs == [] # held input discarded on timeout assert _audio_messages(fake_client) == [] assert closed == [{}] diff --git a/tests/test_ojin_client.py b/tests/test_ojin_client.py index 3be9ca3..c5e28da 100644 --- a/tests/test_ojin_client.py +++ b/tests/test_ojin_client.py @@ -665,3 +665,67 @@ def on_status(status: OjinWebRTCStatusMessage) -> None: # The seeded interaction response was drained by the cancel; the status, # delivered via the callback, was never at risk. assert client._available_response_messages_queue.empty() + + +class _ClosingWS: + """Delivers ``messages`` and then ends, as a socket the server closed does.""" + + def __init__(self, messages: list, close_code: int, close_reason: str) -> None: + self._messages = list(messages) + self.close_code = close_code + self.close_reason = close_reason + + def __aiter__(self) -> "_ClosingWS": + return self + + async def __anext__(self): + if not self._messages: + raise StopAsyncIteration + return self._messages.pop(0) + + async def close(self) -> None: + """Nothing to release.""" + + +async def _run_receive_loop(messages: list, code: int, reason: str) -> list: + """Run the receive loop over a server-closed socket; return what it queued.""" + client = _client() + client._ws = _ClosingWS(messages, code, reason) + client._running = True + await client._receive_server_messages() + queue = client._available_response_messages_queue + return [queue.get_nowait() for _ in range(queue.qsize())] + + +async def test_close_before_session_ready_is_reported_with_the_close_reason() -> None: + """A proxy close with no errorResponse must not look like a slow start.""" + queued = await _run_receive_loop([], 1008, "Insufficient funds") + + assert len(queued) == 1 + assert isinstance(queued[0], ErrorResponseMessage) + assert queued[0].payload.code == "CONNECTION_CLOSED" + assert "before the session was ready" in queued[0].payload.message + assert "1008: Insufficient funds" in queued[0].payload.message + + +async def test_close_after_server_error_reports_only_the_server_error() -> None: + """The server's own errorResponse is the cause; the close adds no second one.""" + error = { + "type": "errorResponse", + "payload": { + "code": "BACKEND_UNAVAILABLE", + "message": "No GPU became available", + "timestamp": 1789000000000, + }, + } + queued = await _run_receive_loop([json.dumps(error)], 1013, "") + + assert [m.payload.code for m in queued] == ["BACKEND_UNAVAILABLE"] + + +async def test_close_after_session_ready_queues_no_error() -> None: + """Only the pre-ready wait is covered; a later close stays as it was.""" + ready = {"type": "sessionReady", "payload": {"parameters": {"persona": "x"}}} + queued = await _run_receive_loop([json.dumps(ready)], 1000, "") + + assert [type(m) for m in queued] == [OjinSessionReadyMessage] From 589ed4389350c24cd10f6f8b38fba7df8dc409a2 Mon Sep 17 00:00:00 2001 From: sqrt-negativeone Date: Thu, 1 Oct 2026 15:10:28 +0000 Subject: [PATCH 2/2] chore: bump ojin-client version to 0.12.1 The WebRTC join timeout default (90s) and connection-close-before-sessionReady reporting fix the integration in fix/webrtc-session-ready-wait. Automated publishing requires a version bump to deploy these changes to production. Co-Authored-By: Claude Fable 5.1 --- CHANGELOG.md | 2 ++ pyproject.toml | 2 +- uv.lock | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 438b85a..040c47c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to `ojin-client` are documented here. The format follows ## Unreleased +## 0.12.1 - 2026-10-01 + ### Changed - `WebRTCSettings.webrtc_join_timeout_s` now defaults to **90 s** (was 10 s). The wait covers the model's cold start as well as the room join, and a cold start diff --git a/pyproject.toml b/pyproject.toml index bda8a93..2d1bf1f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "ojin-client" -version = "0.12.0" +version = "0.12.1" description = "Ojin platform services" readme = "README.md" requires-python = ">=3.10" diff --git a/uv.lock b/uv.lock index f4ce1bc..20ce050 100644 --- a/uv.lock +++ b/uv.lock @@ -825,7 +825,7 @@ wheels = [ [[package]] name = "ojin-client" -version = "0.12.0" +version = "0.12.1" source = { editable = "." } dependencies = [ { name = "async-lru" },