diff --git a/CHANGELOG.md b/CHANGELOG.md index 040c47c..aaede59 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,24 @@ All notable changes to `ojin-client` are documented here. The format follows ## Unreleased +## 0.12.2 - 2026-10-15 + +### Added +- `STVEvent.SESSION_STARTING` (args `phase`, `elapsed_ms`): the service's startup + status, emitted in direct-WebRTC mode for each `sessionPing` it sends while + the session is still starting. `OjinSessionReadyPing` now carries `phase` and + `elapsed_ms`; a ping whose fields have unexpected types parses with them unset + and can never end the session. +- `WebRTCSettings.startup_inactivity_timeout_s` (default 20 s). + +### Changed +- The direct-WebRTC start is no longer bounded by a blind total once the service + reports progress. From the first `sessionPing` the fixed `webrtc_join_timeout_s` + timer is replaced by a watchdog that fails (`WEBRTC_JOIN_TIMEOUT`, naming the + last phase reported) only after `startup_inactivity_timeout_s` of silence; the + service's own deadlines bound the total. A service that sends no status is + handled as before. + ## 0.12.1 - 2026-10-01 ### Changed diff --git a/README.md b/README.md index b359f5c..4e75271 100644 --- a/README.md +++ b/README.md @@ -202,6 +202,7 @@ Register handlers with `@client.on(STVEvent.X)` or `client.add_listener(STVEvent | Event | Fires when | Handler kwargs | |---|---|---| +| `SESSION_STARTING` | Direct WebRTC only: the service is still starting the session and reported its progress (every few seconds until `SESSION_READY`) | `phase: str \| None`, `elapsed_ms: int \| None` | | `SESSION_READY` | The session is live and ready for audio | `session_data: dict \| None` | | `WEBRTC_CONNECTED` | Direct WebRTC only: the avatar has joined your room | `participant_id: str \| None` | | `FIRST_FRAME` | The avatar's first video frame is out (emitted to your output, or published to the room) | `frame_type: int` | @@ -380,7 +381,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 90 s — it covers the model's cold start too, which alone can take more than 30 s) | +| `WEBRTC_JOIN_TIMEOUT` | The session wasn't ready in time: within `webrtc_join_timeout_s` (default 90 s) on a service that sends no startup status, or after `startup_inactivity_timeout_s` (default 20 s) of silence from one that does | | `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 +413,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 `90.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`), `webrtc_join_timeout_s` (default `90.0`) and `startup_inactivity_timeout_s` (default `20.0`); the playback fields above don't apply because the media goes to the room. --- @@ -491,7 +492,7 @@ 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` (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. +- **`WEBRTC_JOIN_TIMEOUT`** — the session didn't become ready in time. A service that reports its startup progress (`SESSION_STARTING` events) bounds the start itself, and the client fails only after `startup_inactivity_timeout_s` (default 20 s) without a report; the message names the last phase reported. On a service that sends no reports, `webrtc_join_timeout_s` (default 90 s) applies; 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/pyproject.toml b/pyproject.toml index 2d1bf1f..e57bf8d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "ojin-client" -version = "0.12.1" +version = "0.12.2" description = "Ojin platform services" readme = "README.md" requires-python = ">=3.10" diff --git a/skills/ojin-stv-integration/SKILL.md b/skills/ojin-stv-integration/SKILL.md index 8fdaaa2..889637f 100644 --- a/skills/ojin-stv-integration/SKILL.md +++ b/skills/ojin-stv-integration/SKILL.md @@ -133,6 +133,7 @@ Handlers may be sync or async; one failing handler never breaks the loops. | Event | Fires when | Kwargs | |---|---|---| +| `SESSION_STARTING` | direct WebRTC only: the service reported startup progress (every few seconds until ready) | `phase`, `elapsed_ms` | | `SESSION_READY` | session is live (safe to send audio) | `session_data` | | `WEBRTC_CONNECTED` | direct WebRTC only: the avatar joined your room | `participant_id` | | `FIRST_FRAME` | the avatar's first video frame is out (to your output, or into the room) | `frame_type` | @@ -205,8 +206,9 @@ 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 90 s, - includes cold start — don't lower it below ~60 s) or an unsupporting server is a fatal +- **No fallback.** A failed join, a startup that times out (`webrtc_join_timeout_s`, default + 90 s, on a service that sends no startup status; `startup_inactivity_timeout_s` + of silence, default 20 s, on one that does) 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 a33d5be..16db80b 100644 --- a/src/ojin/ojin_client.py +++ b/src/ojin/ojin_client.py @@ -118,6 +118,27 @@ def _read_tcp_info(sock: socket.socket) -> dict[str, int]: return {} +def _parse_session_ping(data: dict) -> OjinSessionReadyPing: + """Read the startup status out of a ``sessionPing`` (bare on older services). + + Never raises: a status message must not be able to end the session, so a + field of the wrong type is simply left unset. + """ + payload = data.get("payload") + if not isinstance(payload, dict): + return OjinSessionReadyPing() + phase = payload.get("phase") + elapsed = payload.get("elapsed_ms") + elapsed_ms: int | None = None + if isinstance(elapsed, (int, float)) and not isinstance(elapsed, bool): + # json.loads admits NaN and Infinity, which int() refuses. + with contextlib.suppress(ValueError, OverflowError): + elapsed_ms = int(elapsed) + return OjinSessionReadyPing( + phase=phase if isinstance(phase, str) else None, elapsed_ms=elapsed_ms + ) + + class OjinClient(IOjinClient): """WebSocket client for communicating with the OJIN STV service. @@ -507,16 +528,17 @@ async def _handle_server_message(self, message: str | bytes) -> None: await self._available_response_messages_queue.put(session_ready) return - msg = msg_class(**data) + msg = ( + _parse_session_ping(data) + if msg_type == "sessionPing" + else msg_class(**data) + ) 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): - # Discard session pings - pass else: logger.warning("Unknown message type: %s", msg_type) diff --git a/src/ojin/ojin_client_messages.py b/src/ojin/ojin_client_messages.py index 7abf246..bf5f729 100644 --- a/src/ojin/ojin_client_messages.py +++ b/src/ojin/ojin_client_messages.py @@ -68,7 +68,17 @@ class OjinSessionReadyMessage(OjinMessage): class OjinSessionReadyPing(OjinMessage): - """Ping message used to check session readiness with the Ojin backend.""" + """Startup status from the service while the session is still starting. + + Sent every few seconds before ``sessionReady`` by a service that bounds + the start itself. ``phase`` names what it is waiting on (for example + ``waiting_for_container`` or ``setting_up_session``) and ``elapsed_ms`` + is the time since the start was requested; both are absent on an older + service, which sends the bare ping. + """ + + phase: str | None = None + elapsed_ms: int | None = None class OjinInteractionResponseMessage(OjinMessage): diff --git a/src/ojin/stv/config.py b/src/ojin/stv/config.py index bec9d9f..e0a6a57 100644 --- a/src/ojin/stv/config.py +++ b/src/ojin/stv/config.py @@ -46,8 +46,11 @@ 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, 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. + than 30 s — on a service that sends no startup status. A service that + reports its startup progress (``sessionPing`` messages every few seconds) + bounds the start itself; from the first such message the client waits as + long as the reports keep coming and fails only after + ``startup_inactivity_timeout_s`` of silence instead. The settings are declared in the WebSocket **upgrade request** (DR-006 as amended 2026-07-24): the non-secret fields ride ``webrtc_*`` query params @@ -58,7 +61,8 @@ class WebRTCSettings: the ``sessionSetup`` it authors. ``token`` is excluded from ``repr``, must never be logged, and never - appears in a URL. ``webrtc_join_timeout_s`` is client-local and is never + appears in a URL. ``webrtc_join_timeout_s`` and + ``startup_inactivity_timeout_s`` are client-local and are never serialized. """ @@ -67,6 +71,7 @@ class WebRTCSettings: provider: WebRTCProvider | str = WebRTCProvider.DAILY audio_sample_rate: int = 16000 webrtc_join_timeout_s: float = 90.0 + startup_inactivity_timeout_s: float = 20.0 version: int = 2 def to_connect_query_params(self) -> dict: @@ -74,8 +79,9 @@ def to_connect_query_params(self) -> dict: Values are strings ready for URL-encoding. The ``token`` is deliberately absent — a URL lands in access logs; the token travels - via :meth:`to_connect_headers` instead. ``webrtc_join_timeout_s`` is - likewise absent (client-local, never serialized). + via :meth:`to_connect_headers` instead. ``webrtc_join_timeout_s`` and + ``startup_inactivity_timeout_s`` are likewise absent (client-local, + never serialized). """ return { "webrtc_version": str(self.version), @@ -114,6 +120,11 @@ def __post_init__(self) -> None: raise ValueError( f"webrtc_join_timeout_s must be > 0, got {self.webrtc_join_timeout_s}" ) + if self.startup_inactivity_timeout_s <= 0: + raise ValueError( + "startup_inactivity_timeout_s must be > 0, got " + f"{self.startup_inactivity_timeout_s}" + ) rate = self.audio_sample_rate if not _MIN_AUDIO_SAMPLE_RATE <= rate <= _MAX_AUDIO_SAMPLE_RATE or ( rate % _FRAMES_PER_SECOND diff --git a/src/ojin/stv/events.py b/src/ojin/stv/events.py index f3db62a..71ec57b 100644 --- a/src/ojin/stv/events.py +++ b/src/ojin/stv/events.py @@ -22,6 +22,7 @@ class STVEvent(Enum): """Lifecycle/state events emitted by :class:`OjinSTVClient`.""" + SESSION_STARTING = "session_starting" # args: phase, elapsed_ms SESSION_READY = "session_ready" # args: session_data WEBRTC_CONNECTED = "webrtc_connected" # args: participant_id FIRST_FRAME = "first_frame" # args: frame_type diff --git a/src/ojin/stv/ojin_stv_webrtc_client.py b/src/ojin/stv/ojin_stv_webrtc_client.py index 0bac31c..88ec3ef 100644 --- a/src/ojin/stv/ojin_stv_webrtc_client.py +++ b/src/ojin/stv/ojin_stv_webrtc_client.py @@ -61,6 +61,7 @@ OjinCancelInteractionMessage, OjinInteractionResponseMessage, OjinSessionReadyMessage, + OjinSessionReadyPing, OjinWebRTCStatusMessage, ) from ojin.stv._outbound_feed import OutboundFeedMixin @@ -77,6 +78,7 @@ _MS_PER_METADATA_FRAME = 40.0 # metadata frames are paced at 25/s _METADATA_WATCHDOG_S = 5.0 _WATCHDOG_POLL_S = 1.0 +_STARTUP_WATCHDOG_POLL_S = 0.5 _SPEECH_TYPES = (int(FrameType.SPEECH), int(FrameType.START_OF_SPEECH)) _SILENCE_TYPES = (int(FrameType.IDLE), int(FrameType.FADE_OUT)) @@ -180,6 +182,10 @@ def __init__( # noqa: PLR0913 — injectable deps + flat field init self._closed = False self._close_task: Optional[asyncio.Task] = None self._request_sent_at = 0.0 + # Startup status from the service: once it reports progress, the + # fixed join timer gives way to a silence watchdog. + self._last_startup_status_at: Optional[float] = None + self._last_startup_phase: Optional[str] = None self._last_metadata_at = 0.0 self._first_frame_pending = False self._last_frame_type: Optional[int] = None @@ -284,7 +290,9 @@ async def start(self) -> None: The webrtc request rides the connect exchange itself (declared on the transport at construction), so once the connection is up the negotiation is already in flight: the join timer armed here governs - the whole ``sessionReady`` wait (``webrtc_join_timeout_s``). + the ``sessionReady`` wait (``webrtc_join_timeout_s``) until the + service's first startup status report hands it to the silence + watchdog (see :meth:`_on_startup_status`). """ self._tr_session_start = self._tracer.mark() self._tr_connect_start = self._tr_session_start @@ -324,7 +332,8 @@ async def close(self) -> None: was_initialized = self._initialized self._initialized = False self._preinit_inputs.clear() - self._cancel_join_timer() + join_timer, self._join_timer_task = self._join_timer_task, None + await self._cancel_task(join_timer) await self._cancel_task(self._watchdog_task) self._watchdog_task = None if was_initialized: @@ -478,6 +487,8 @@ async def _handle_message(self, message: BaseModel) -> None: """Route one server message (session ready / interaction / error).""" if isinstance(message, OjinSessionReadyMessage): await self._on_session_ready(message) + elif isinstance(message, OjinSessionReadyPing): + await self._on_startup_status(message) elif isinstance(message, OjinInteractionResponseMessage): was_interrupting = self._interruption_ongoing await self._on_interaction_response(message) @@ -493,6 +504,9 @@ async def _handle_message(self, message: BaseModel) -> None: self._tracer.instant( "lifecycle", "server_error", args={"code": code, "message": text} ) + # The server's verdict ends the start; no startup timer may add a + # second ERROR behind it. + self._cancel_join_timer() await self._events.emit(STVEvent.ERROR, message=text, code=code, fatal=True) self._schedule_close() @@ -658,11 +672,66 @@ async def _join_timer(self) -> None: await asyncio.sleep(self._webrtc_settings.webrtc_join_timeout_s) await self._handle_join_timeout() + async def _on_startup_status(self, ping: OjinSessionReadyPing) -> None: + """Note that the service is still starting the session. + + The service sends these while it waits on its own bounded steps, so + from the first one the total is its responsibility, not ours: the + fixed join timer is replaced by a watchdog that fails only when the + reports stop. + """ + if self._state is not _DirectState.PENDING or self._initialized or self._closed: + return + first = self._last_startup_status_at is None + self._last_startup_status_at = self._clock() + self._last_startup_phase = ping.phase + self._tracer.instant( + "webrtc", + "startup_status", + args={"phase": ping.phase or "", "elapsed_ms": ping.elapsed_ms or 0}, + ) + if first: + self._cancel_join_timer() + self._join_timer_task = asyncio.create_task(self._startup_watchdog()) + await self._events.emit( + STVEvent.SESSION_STARTING, phase=ping.phase, elapsed_ms=ping.elapsed_ms + ) + + async def _startup_watchdog(self) -> None: + """Fail the start once the service's status reports fall silent. + + Polled every ``_STARTUP_WATCHDOG_POLL_S``, so the failure lands up to + that much after ``startup_inactivity_timeout_s`` of silence, never + before it. + """ + limit = self._webrtc_settings.startup_inactivity_timeout_s + while True: + await asyncio.sleep(_STARTUP_WATCHDOG_POLL_S) + last = self._last_startup_status_at + if last is None or self._clock() - last < limit: + continue + if ( + self._state is not _DirectState.PENDING + or self._initialized + or self._closed + ): + return + self._tracer.instant("webrtc", "startup_stalled") + phase = self._last_startup_phase or "unknown" + await self._fail( + WEBRTC_JOIN_TIMEOUT, + "Timed out: the service stopped reporting progress for " + f"{limit:g} s while the session was starting (last phase: {phase})", + {"outcome": "timeout", "last_phase": phase}, + ) + return + async def _handle_join_timeout(self) -> None: """Fail the session if no sessionReady arrived within the join timeout. In v2 the server joins the room during setup, so - ``webrtc_join_timeout_s`` governs the whole ``sessionReady`` wait. + ``webrtc_join_timeout_s`` governs the ``sessionReady`` wait on a + service that sends no startup status. """ if self._state is not _DirectState.PENDING or self._initialized: return diff --git a/tests/stv/test_frames_config.py b/tests/stv/test_frames_config.py index c812a3e..af1d2cf 100644 --- a/tests/stv/test_frames_config.py +++ b/tests/stv/test_frames_config.py @@ -86,6 +86,8 @@ def test_webrtc_provider_str_is_wire_value() -> None: {"token": ""}, {"webrtc_join_timeout_s": 0}, {"webrtc_join_timeout_s": -1.0}, + {"startup_inactivity_timeout_s": 0}, + {"startup_inactivity_timeout_s": -5.0}, ], ) def test_webrtc_settings_rejects_invalid_fields(overrides: dict) -> None: diff --git a/tests/stv/test_stv_client_webrtc_mode.py b/tests/stv/test_stv_client_webrtc_mode.py index 8afcfa8..1312b59 100644 --- a/tests/stv/test_stv_client_webrtc_mode.py +++ b/tests/stv/test_stv_client_webrtc_mode.py @@ -15,6 +15,8 @@ FrameType, OjinAudioInputMessage, OjinCancelInteractionMessage, + OjinSessionReadyMessage, + OjinSessionReadyPing, ) from ojin.stv.config import STVConfig, WebRTCProvider, WebRTCSettings from ojin.stv.events import STVEvent @@ -243,6 +245,191 @@ async def test_join_timeout_is_reported_and_closes() -> None: assert closed == [{}] +def _startup_client(join_timeout_s: float, inactivity_s: float): + """Build a WebRTC-mode client whose transport never delivers sessionReady itself.""" + fake_client = _NeverReadyClient() + client = OjinSTVClient( + webrtc=WebRTCSettings( + room_url=ROOM_URL, + token=TOKEN, + provider="livekit", + audio_sample_rate=RATE, + webrtc_join_timeout_s=join_timeout_s, + startup_inactivity_timeout_s=inactivity_s, + ), + client=fake_client, + tracer=RecordingTracer(), + config=STVConfig( + loop_stall_watchdog_ms=0, + stall_probe_ms=0, + server_feed_batching_enabled=False, + ), + ) + return client, fake_client + + +async def test_startup_status_replaces_the_fixed_join_timeout() -> None: + """While the service keeps reporting progress, the client keeps waiting.""" + client, fake_client = _startup_client(join_timeout_s=0.05, inactivity_s=0.6) + errors = _record(client, STVEvent.ERROR) + starting = _record(client, STVEvent.SESSION_STARTING) + ready = _record(client, STVEvent.SESSION_READY) + await client.start() + + # Four reports over 0.4 s: well past the 0.05 s join timeout. + for i in range(4): + await fake_client.push( + OjinSessionReadyPing(phase="waiting_for_container", elapsed_ms=i * 100) + ) + await asyncio.sleep(0.1) + await fake_client.push( + OjinSessionReadyMessage(parameters=READY_CONNECTED_PARAMETERS) + ) + await asyncio.sleep(0.05) + + assert errors == [] + assert [s["phase"] for s in starting] == ["waiting_for_container"] * 4 + assert starting[-1]["elapsed_ms"] == 300 + assert len(ready) == 1 + assert client.is_connected is True + await client.close() + + +async def test_startup_status_going_silent_fails_the_start() -> None: + """Once the service has reported progress, only its silence ends the wait.""" + client, fake_client = _startup_client(join_timeout_s=5.0, inactivity_s=0.2) + errors = _record(client, STVEvent.ERROR) + closed = _record(client, STVEvent.CLOSED) + await client.start() + + await fake_client.push( + OjinSessionReadyPing(phase="setting_up_session", elapsed_ms=40_000) + ) + await asyncio.sleep(0.8) + + assert [(e["code"], e["fatal"]) for e in errors] == [("WEBRTC_JOIN_TIMEOUT", True)] + assert "stopped reporting progress for 0.2 s" in errors[0]["message"] + assert "last phase: setting_up_session" in errors[0]["message"] + assert closed == [{}] + + +async def test_a_second_report_reuses_the_watchdog_and_a_late_one_is_ignored() -> None: + """One watchdog per start; reports after the session is ready change nothing.""" + client, fake_client = _startup_client(join_timeout_s=5.0, inactivity_s=5.0) + starting = _record(client, STVEvent.SESSION_STARTING) + errors = _record(client, STVEvent.ERROR) + await client.start() + + await fake_client.push(OjinSessionReadyPing(phase="waiting_for_container")) + await asyncio.sleep(0.02) + first_watchdog = client._webrtc._join_timer_task + await fake_client.push(OjinSessionReadyPing(phase="setting_up_session")) + await asyncio.sleep(0.02) + assert client._webrtc._join_timer_task is first_watchdog + assert [s["phase"] for s in starting] == [ + "waiting_for_container", + "setting_up_session", + ] + + await fake_client.push( + OjinSessionReadyMessage(parameters=READY_CONNECTED_PARAMETERS) + ) + await asyncio.sleep(0.02) + await fake_client.push(OjinSessionReadyPing(phase="setting_up_session")) + await asyncio.sleep(0.02) + + assert len(starting) == 2 # the late report was ignored + assert first_watchdog.cancelled() or first_watchdog.done() + assert client.is_connected is True + await client.close() + assert errors == [] + + +class _SlowClosingClient(_NeverReadyClient): + """A transport whose close takes a while, as a real WebSocket handshake does.""" + + async def close(self) -> None: + """Hold the close open so messages can still arrive meanwhile.""" + await asyncio.sleep(0.05) + await super().close() + + +async def test_a_first_report_during_close_cannot_revive_the_start() -> None: + """A status report landing while close() runs arms nothing and reports nothing.""" + fake_client = _SlowClosingClient() + client = OjinSTVClient( + webrtc=WebRTCSettings( + room_url=ROOM_URL, + token=TOKEN, + provider="livekit", + audio_sample_rate=RATE, + webrtc_join_timeout_s=5.0, + startup_inactivity_timeout_s=0.2, + ), + client=fake_client, + tracer=RecordingTracer(), + config=STVConfig( + loop_stall_watchdog_ms=0, + stall_probe_ms=0, + server_feed_batching_enabled=False, + ), + ) + events: list[str] = [] + for event in (STVEvent.SESSION_STARTING, STVEvent.ERROR, STVEvent.CLOSED): + client.add_listener( + event, lambda _event=event, **_: events.append(_event.value) + ) + await client.start() + + closing = asyncio.create_task(client.close()) + await asyncio.sleep(0.01) # close() is inside the transport's slow close + await fake_client.push(OjinSessionReadyPing(phase="waiting_for_container")) + await closing + await asyncio.sleep(0.8) # past the inactivity limit and the watchdog poll + + assert events == ["closed"] + assert client._webrtc._join_timer_task is None + + +async def test_a_server_error_leaves_no_startup_timer_to_add_a_second_error() -> None: + """The server's verdict is the only ERROR, even if its listener runs long.""" + fake_client = _NeverReadyClient() + client, _ = make_client(fake=fake_client, join_timeout_s=0.1) + timeline: list[tuple[str, object]] = [] + + async def _slow_error_listener(code: str | None = None, **_: object) -> None: + timeline.append(("error", code)) + await asyncio.sleep(0.5) # outlasts the fixed join timer + + client.add_listener(STVEvent.ERROR, _slow_error_listener) + client.add_listener(STVEvent.CLOSED, lambda **_: timeline.append(("closed", None))) + await client.start() + + await fake_client.push( + ErrorResponseMessage( + payload=ErrorResponse(code="BOOM", message="boom", timestamp=1789000000000) + ) + ) + await asyncio.sleep(1.0) + + assert timeline == [("error", "BOOM"), ("closed", None)] + + +async def test_bare_ping_from_an_older_service_still_counts_as_progress() -> None: + """A ping without phase or elapsed time still says the service is working.""" + client, fake_client = _startup_client(join_timeout_s=0.05, inactivity_s=0.3) + errors = _record(client, STVEvent.ERROR) + starting = _record(client, STVEvent.SESSION_STARTING) + await client.start() + + await fake_client.push(OjinSessionReadyPing()) + await asyncio.sleep(0.15) + + assert errors == [] + assert starting == [{"phase": None, "elapsed_ms": None}] + await client.close() + + 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() diff --git a/tests/test_ojin_client.py b/tests/test_ojin_client.py index c5e28da..95d5047 100644 --- a/tests/test_ojin_client.py +++ b/tests/test_ojin_client.py @@ -18,6 +18,7 @@ OjinCancelInteractionMessage, OjinInteractionResponseMessage, OjinSessionReadyMessage, + OjinSessionReadyPing, OjinWebRTCStatusMessage, ) @@ -729,3 +730,52 @@ async def test_close_after_session_ready_queues_no_error() -> None: queued = await _run_receive_loop([json.dumps(ready)], 1000, "") assert [type(m) for m in queued] == [OjinSessionReadyMessage] + + +async def test_session_ping_carries_the_startup_status() -> None: + """A sessionPing with a payload is parsed into phase and elapsed time.""" + client = _client() + ping = { + "type": "sessionPing", + "payload": { + "phase": "waiting_for_container", + "elapsed_ms": 12000, + "timestamp": 1, + }, + } + await client._handle_server_message(json.dumps(ping)) + msg = client._available_response_messages_queue.get_nowait() + assert isinstance(msg, OjinSessionReadyPing) + assert (msg.phase, msg.elapsed_ms) == ("waiting_for_container", 12000) + + +@pytest.mark.parametrize( + "payload", + [ + {"phase": 5, "elapsed_ms": "abc"}, + {"phase": None, "elapsed_ms": 12.5}, + {"phase": ["x"], "elapsed_ms": True}, + {"elapsed_ms": float("nan")}, # json.dumps emits the NaN literal + {"elapsed_ms": float("inf")}, + "not an object", + ], +) +async def test_malformed_session_ping_never_ends_the_session(payload: object) -> None: + """A status message with odd field types parses loosely and the session goes on.""" + bad_ping = json.dumps({"type": "sessionPing", "payload": payload}) + ready = json.dumps({"type": "sessionReady", "payload": {"parameters": {}}}) + queued = await _run_receive_loop([bad_ping, ready], 1000, "") + + assert [type(m) for m in queued] == [OjinSessionReadyPing, OjinSessionReadyMessage] + ping = queued[0] + assert ping.phase is None or isinstance(ping.phase, str) + assert ping.elapsed_ms is None or isinstance(ping.elapsed_ms, int) + + +async def test_bare_session_ping_is_still_a_ping() -> None: + """An older service's payload-less ping parses with empty status fields.""" + client = _client() + await client._handle_server_message(json.dumps({"type": "sessionPing"})) + msg = client._available_response_messages_queue.get_nowait() + assert isinstance(msg, OjinSessionReadyPing) + assert (msg.phase, msg.elapsed_ms) == (None, None) diff --git a/uv.lock b/uv.lock index 20ce050..61e8799 100644 --- a/uv.lock +++ b/uv.lock @@ -825,7 +825,7 @@ wheels = [ [[package]] name = "ojin-client" -version = "0.12.1" +version = "0.12.2" source = { editable = "." } dependencies = [ { name = "async-lru" },