diff --git a/ai_agents/.env.example b/ai_agents/.env.example index a03f841ea7..ba88c1de95 100644 --- a/ai_agents/.env.example +++ b/ai_agents/.env.example @@ -34,6 +34,11 @@ NEXT_PUBLIC_EDIT_GRAPH_MODE=true AGORA_APP_ID= AGORA_APP_CERTIFICATE= +# Extension: spatialreal_avatar_python (SpatialReal API key, avatar id, optional app id) +SPATIALREAL_API_KEY= +SPATIALREAL_AVATAR_ID= +SPATIALREAL_APP_ID= + # ------------------------------ # LLM # ------------------------------ diff --git a/ai_agents/agents/examples/voice-assistant-advanced/tenapp/manifest.json b/ai_agents/agents/examples/voice-assistant-advanced/tenapp/manifest.json index 5af5d80ce9..75cc854190 100644 --- a/ai_agents/agents/examples/voice-assistant-advanced/tenapp/manifest.json +++ b/ai_agents/agents/examples/voice-assistant-advanced/tenapp/manifest.json @@ -153,6 +153,9 @@ { "path": "../../../ten_packages/extension/anam_avatar_python" }, + { + "path": "../../../ten_packages/extension/spatialreal_avatar_python" + }, { "path": "../../../ten_packages/extension/cartesia_tts" } diff --git a/ai_agents/agents/examples/voice-assistant-advanced/tenapp/property.json b/ai_agents/agents/examples/voice-assistant-advanced/tenapp/property.json index a62df58e20..fbe39baebe 100644 --- a/ai_agents/agents/examples/voice-assistant-advanced/tenapp/property.json +++ b/ai_agents/agents/examples/voice-assistant-advanced/tenapp/property.json @@ -1556,6 +1556,286 @@ } ] } + }, + { + "name": "voice_assistant_spatialreal", + "auto_start": false, + "graph": { + "nodes": [ + { + "type": "extension", + "name": "agora_rtc", + "addon": "agora_rtc", + "extension_group": "default", + "property": { + "app_id": "${env:AGORA_APP_ID}", + "app_certificate": "${env:AGORA_APP_CERTIFICATE|}", + "channel": "", + "stream_id": 0, + "remote_stream_id": 182837, + "subscribe_audio": true, + "publish_audio": true, + "publish_data": true, + "enable_agora_asr": false + } + }, + { + "type": "extension", + "name": "stt", + "addon": "deepgram_ws_asr_python", + "extension_group": "stt", + "property": { + "params": { + "api_key": "${env:DEEPGRAM_API_KEY}", + "url": "wss://api.deepgram.com/v1/listen", + "model": "nova-3", + "language": "en-US", + "interim_results": true, + "endpointing": 100, + "utterance_end_ms": 1000 + } + } + }, + { + "type": "extension", + "name": "llm", + "addon": "openai_llm2_python", + "extension_group": "chatgpt", + "property": { + "base_url": "https://api.groq.com/openai/v1/", + "api_key": "${env:GROQ_API_KEY}", + "frequency_penalty": 0.9, + "model": "llama-3.3-70b-versatile", + "max_tokens": 512, + "prompt": "You are a voice assistant. Your responses will be heard, not read. Keep every response between 10-20 words.", + "proxy_url": "${env:OPENAI_PROXY_URL|}", + "greeting": "TEN Agent connected. How can I help you today?", + "max_memory_length": 10 + } + }, + { + "type": "extension", + "name": "tts", + "addon": "cartesia_tts", + "extension_group": "tts", + "property": { + "dump": false, + "dump_path": "./", + "params": { + "api_key": "${env:CARTESIA_TTS_KEY}", + "model_id": "sonic-3", + "voice": { + "mode": "id", + "id": "71a7ad14-091c-4e8e-a314-022ece01c121" + }, + "generation_config": { + "speed": 1 + }, + "output_format": { + "container": "raw", + "sample_rate": 44100 + }, + "language": "en" + } + } + }, + { + "type": "extension", + "name": "main_control", + "addon": "main_python", + "extension_group": "control", + "property": { + "greeting": "TEN Agent connected. How can I help you today?" + } + }, + { + "type": "extension", + "name": "message_collector", + "addon": "message_collector2", + "extension_group": "transcriber", + "property": {} + }, + { + "type": "extension", + "name": "streamid_adapter", + "addon": "streamid_adapter", + "property": {} + }, + { + "type": "extension", + "name": "avatar", + "addon": "spatialreal_avatar_python", + "extension_group": "default", + "property": { + "channel": "", + "params": { + "spatialreal_api_key": "${env:SPATIALREAL_API_KEY|}", + "spatialreal_avatar_id": "${env:SPATIALREAL_AVATAR_ID|}", + "spatialreal_app_id": "${env:SPATIALREAL_APP_ID|}", + "environment": "us-west", + "console_endpoint_url": "", + "ingress_endpoint_url": "", + "sample_rate": 24000, + "egress_idle_reconnect_ms": 1080000, + "agora_uid": "12345", + "agora_token": "", + "agora_appid": "${env:AGORA_APP_ID|}", + "agora_appcert": "${env:AGORA_APP_CERTIFICATE|}", + "agora_channel": "" + } + } + } + ], + "connections": [ + { + "extension": "main_control", + "cmd": [ + { + "names": [ + "on_user_joined", + "on_user_left" + ], + "source": [ + { + "extension": "agora_rtc" + } + ] + }, + { + "name": "flush", + "source": [ + { + "extension": "stt" + } + ] + }, + { + "name": "flush", + "dest": [ + { + "extension": "avatar" + } + ] + } + ], + "data": [ + { + "name": "asr_result", + "source": [ + { + "extension": "stt" + } + ] + } + ] + }, + { + "extension": "agora_rtc", + "audio_frame": [ + { + "name": "pcm_frame", + "dest": [ + { + "extension": "streamid_adapter" + } + ] + } + ], + "data": [ + { + "name": "data", + "source": [ + { + "extension": "message_collector" + } + ] + } + ] + }, + { + "extension": "streamid_adapter", + "audio_frame": [ + { + "name": "pcm_frame", + "dest": [ + { + "extension": "stt" + } + ] + } + ] + }, + { + "extension": "stt", + "cmd": [ + { + "name": "flush", + "dest": [ + { + "extension": "main_control" + } + ] + } + ] + }, + { + "extension": "llm", + "cmd": [ + { + "names": [ + "flush" + ], + "source": [ + { + "extension": "main_control" + } + ] + } + ], + "data": [ + { + "name": "text_data", + "source": [ + { + "extension": "main_control" + } + ] + } + ] + }, + { + "extension": "tts", + "data": [ + { + "name": "text_data", + "source": [ + { + "extension": "llm" + } + ] + }, + { + "name": "tts_audio_end", + "dest": [ + { + "extension": "avatar" + } + ] + } + ], + "audio_frame": [ + { + "name": "pcm_frame", + "dest": [ + { + "extension": "avatar" + } + ] + } + ] + } + ] + } } ] } diff --git a/ai_agents/agents/examples/voice-assistant-advanced/tenapp/rebuild_property.py b/ai_agents/agents/examples/voice-assistant-advanced/tenapp/rebuild_property.py index 037178a3ee..56a3525374 100644 --- a/ai_agents/agents/examples/voice-assistant-advanced/tenapp/rebuild_property.py +++ b/ai_agents/agents/examples/voice-assistant-advanced/tenapp/rebuild_property.py @@ -489,6 +489,33 @@ }, } +# SpatialReal avatar: audio plus animation (SEI) into the channel, no video. +# `channel` stays empty on purpose: the server fills it in per call. +spatialreal_avatar = { + "type": "extension", + "name": "avatar", + "addon": "spatialreal_avatar_python", + "extension_group": "default", + "property": { + "channel": "", + "params": { + "spatialreal_api_key": "${env:SPATIALREAL_API_KEY|}", + "spatialreal_avatar_id": "${env:SPATIALREAL_AVATAR_ID|}", + "spatialreal_app_id": "${env:SPATIALREAL_APP_ID|}", + "environment": "us-west", + "console_endpoint_url": "", + "ingress_endpoint_url": "", + "sample_rate": 24000, + "egress_idle_reconnect_ms": 1080000, + "agora_uid": "12345", + "agora_token": "", + "agora_appid": "${env:AGORA_APP_ID|}", + "agora_appcert": "${env:AGORA_APP_CERTIFICATE|}", + "agora_channel": "", + }, + }, +} + thymia_analyzer = { "type": "extension", "name": "thymia_analyzer", @@ -581,10 +608,12 @@ def create_basic_voice_assistant( connections = copy.deepcopy(basic_connections) - if has_avatar and avatar_type in ["heygen", "anam"]: + if has_avatar and avatar_type in ["heygen", "anam", "spatialreal"]: # Add appropriate avatar node if avatar_type == "heygen": nodes.append(copy.deepcopy(heygen_avatar)) + elif avatar_type == "spatialreal": + nodes.append(copy.deepcopy(spatialreal_avatar)) else: # anam nodes.append(copy.deepcopy(anam_avatar)) @@ -969,6 +998,17 @@ def create_apollo_graph( ) ) +# Group 6: SpatialReal avatar (basic voice assistant, no tools) +print("Creating SpatialReal avatar graph...") + +new_graphs.append( + create_basic_voice_assistant( + "voice_assistant_spatialreal", + has_avatar=True, + avatar_type="spatialreal", + ) +) + # Build final structure new_data = {"ten": {"log": log_config, "predefined_graphs": new_graphs}} diff --git a/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/README.md b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/README.md new file mode 100644 index 0000000000..c141ad589c --- /dev/null +++ b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/README.md @@ -0,0 +1,257 @@ +# spatialreal_avatar_python + +Drives a [SpatialReal](https://spatialreal.ai) avatar into the Agora channel +from a TEN graph's TTS audio. + +## What it does + +The extension takes the `pcm_frame` audio the TTS node produces, resamples it +to the SpatialReal session rate and streams it into a SpatialReal session +configured for Agora egress. SpatialReal's egress joins the channel as its own +user (`params.agora_uid`) and publishes two things: the TTS audio and the +avatar's facial and pose animation as an SEI track riding on a placeholder +video track. **There are no rendered video frames.** The 3D Gaussian Splatting +avatar is rendered on the viewer's side, so the viewing client must use the +SpatialReal web SDK in Agora mode; a plain Agora player shows audio and a +black 64x64 picture. Nothing flows back into the graph: the extension emits +no audio or video frames, only `flush` (forwarded downstream) and `error`. + +One SpatialReal request is opened per TTS request: the first `pcm_frame` after +idle opens it and data `tts_audio_end` or `finalize` closes it. End signals are queued in +order behind the audio that preceded them, so a request is closed only after +all of its audio has been sent. A `flush` command drops the queued audio and +end signals, interrupts the avatar and continues downstream. + +Preserve `metadata.session_id` and `metadata.turn_id` on both PCM and end +messages. TEN's TTS PCM carries this metadata, not a standard `request_id`. +Turn IDs must increase within each session, as in TEN's main controller; +the sender rejects an older turn even when its first PCM arrives late. +Different sessions have independent turn counters. +The sender rejects audio and ends from flushed or superseded turns, and an +end for another identified turn cannot close the current one. A matching +`INTERRUPTED` end closes the current request even after an earlier flush. +The `request_id` on end messages suppresses duplicate ends; completing one +TTS request does not discard other requests in the same turn. A new identified +turn closes an unfinished predecessor before its own audio is sent. + +Unidentified PCM/end messages remain supported in arrival order. Without a +shared turn identity, stale events cannot be distinguished: the legacy guard +ignores `INTERRUPTED` after a flush until an end closes a request. A `finalize` +without metadata applies to the current request. PCM from two requests in the +same turn cannot be distinguished by metadata alone; keep each request's PCM +before its own end and do not interleave those requests. +If a flush arrives before any identity for the cancelled turn, and that turn's +first PCM arrives before a newer turn is known, the unscoped flush alone cannot +identify that PCM as stale. The producer must stop cancelled output. + +Within a request +audio is sent as fast as it arrives; a small amount of silence is inserted when +the sentence gap would otherwise let the server's playout buffer run dry (see +Limits). Errors are reported as `ten_ai_base.message.ModuleError` on data +`error`: `-1012` for a configuration problem, `-1` when the session is gone for +good (credits exhausted, authentication refused, reconnection given up), +`1001` while the extension is reconnecting or degraded. `vendor_info.vendor` +is `spatialreal` and `vendor_info.code` carries the server's WebSocket close +code (for example `4001`), the HTTP status of a failed session-token exchange +(`401` or `403` for a refused API key, reported once as `-1`) or the exception +class name. A session start the server does not confirm within 20 s is closed +and retried like a transport failure (`1001`, code `TimeoutError`). + +## Configuration + +Two top-level properties: `channel`, which the TEN server owns, and `params`, +which holds everything the operator sets. Defaults are the package +`property.json`; `${env:NAME|}` reads the variable and falls back to empty. + +| Property | Env | Default | Range / notes | +|---|---|---|---| +| `channel` | — | `""` | Agora channel. Filled in by the TEN server per `/start` call; must be present (empty) in the graph node's `property`. | +| `params.spatialreal_api_key` | `SPATIALREAL_API_KEY` | `""` | **Required.** SpatialReal API key. | +| `params.spatialreal_avatar_id` | `SPATIALREAL_AVATAR_ID` | `""` | **Required.** Avatar id from the SpatialReal console. | +| `params.spatialreal_app_id` | `SPATIALREAL_APP_ID` | `""` | Optional; sent as `X-App-ID` when set. | +| `params.environment` | — | `us-west` | SDK named environment. | +| `params.console_endpoint_url` | — | `""` | Overrides the environment's console URL, for a non-default SpatialReal deployment. | +| `params.ingress_endpoint_url` | — | `""` | Overrides the environment's ingress URL, for a non-default SpatialReal deployment. | +| `params.sample_rate` | — | `24000` | One of 8000, 16000, 22050, 24000, 32000, 44100, 48000. | +| `params.source_timeline_only` | — | `true` | Source-timeline-only playback. `false` selects compatibility mode for viewers that play the egress's native audio (see below). | +| `params.source_playback_profile` | — | `1` with source-only, otherwise `0` | Normally omit. `1` requests `BOUNDED_BURST_V1`; `0` keeps the earlier source-only profile. | +| `params.egress_idle_reconnect_ms` | — | `1080000` | Idle time after which the session is reconnected so the avatar stays in the channel; must stay below the server's inactivity timeout (20 min today). | +| `params.agora_uid` | — | `""` | **Required.** Avatar uid in the channel; must parse as a non-zero integer. | +| `params.agora_token` | — | `""` | Used verbatim when set; otherwise a token is minted per connect. | +| `params.agora_appid` | `AGORA_APP_ID` | `""` | Required unless `agora_token` is set. | +| `params.agora_appcert` | `AGORA_APP_CERTIFICATE` | `""` | Empty for a project without a certificate (the App ID is then used as the token). | +| `params.agora_channel` | — | `""` | Explicit channel; overrides `channel` when set. | + +`params.sample_rate` is the SpatialReal **session** rate, not the rate of the +incoming TTS audio. The TTS rate is read from each `AudioFrame` and frames at +another rate are resampled, so a 44.1 kHz TTS feeding a 24 kHz session is +fine; 24000 matches what most TTS extensions emit and is then pass-through. + +A missing or invalid value is reported once at start as a `-1012` error whose +message names the key (`params.`) and the extension stays idle; the +configuration is logged with the secrets masked. + +### Viewer requirement and playback mode + +By default the extension publishes in source-timeline-only mode with the +bounded burst playback profile (`BOUNDED_BURST_V1`), which it negotiates with +the SpatialReal backend at session start. This needs the SpatialReal Python +SDK 0.4.0 or newer, the release in which these are the SDK defaults. + +Viewers must use `@spatialreal/web-sdk` 1.0.0-beta.7 or newer, which detects +the published profile automatically, or 1.0.0-beta.6 with +`agora.sourcePlaybackProfile: 'bounded-burst-v1'` set in its configuration. +The publisher cannot see which viewers are in the channel; older viewers need +compatibility mode. + +The backend must confirm both capabilities, `agora_source_timeline_only` and +`agora_source_burst_v1`, when it confirms the session. If it does not, the +session is closed and a `-1012` configuration error is reported: the +extension does not retry and does not fall back silently. Every reconnect +checks again; ordinary transport failures keep the retry policy. + +Compatibility mode, for viewers that play the egress's native audio: set +`params.source_timeline_only: false` and omit `params.source_playback_profile` +(it then defaults to `0`). To keep source-only playback without the burst +profile, leave `source_timeline_only` at `true` and set +`source_playback_profile: 0`. Booleans, strings and profile values other than +`0` and `1` are configuration errors, as is profile `1` without source-only. + +## Graph + +A complete avatar node. `channel` is left empty on purpose: the TEN server +overwrites it from the start request's `channel_name`, and only for nodes +whose `property` already has the key. + +```json +{ + "type": "extension", + "name": "avatar", + "addon": "spatialreal_avatar_python", + "extension_group": "default", + "property": { + "channel": "", + "params": { + "spatialreal_api_key": "${env:SPATIALREAL_API_KEY|}", + "spatialreal_avatar_id": "${env:SPATIALREAL_AVATAR_ID|}", + "spatialreal_app_id": "${env:SPATIALREAL_APP_ID|}", + "environment": "us-west", + "console_endpoint_url": "", + "ingress_endpoint_url": "", + "sample_rate": 24000, + "egress_idle_reconnect_ms": 1080000, + "agora_uid": "12345", + "agora_token": "", + "agora_appid": "${env:AGORA_APP_ID|}", + "agora_appcert": "${env:AGORA_APP_CERTIFICATE|}", + "agora_channel": "" + } + } +} +``` + +Three edges wire it in, the same shape the HeyGen graph uses in +`voice-assistant-advanced/tenapp/rebuild_property.py`: `flush` from +`main_control`, and `pcm_frame` plus `tts_audio_end` from `tts`. The TTS +`pcm_frame` destination moves from `agora_rtc` to `avatar`, and the matching +`pcm_frame` source entry is removed from the `agora_rtc` connection, because +the avatar's audio reaches the channel through SpatialReal's egress, not +through `agora_rtc`. + +```json +[ + { + "extension": "main_control", + "cmd": [ + { "name": "flush", "dest": [{ "extension": "avatar" }] } + ] + }, + { + "extension": "tts", + "audio_frame": [ + { "name": "pcm_frame", "dest": [{ "extension": "avatar" }] } + ], + "data": [ + { "name": "tts_audio_end", "dest": [{ "extension": "avatar" }] } + ] + } +] +``` + +A TTS that signals the end of a request with data `finalize` instead of +`tts_audio_end` works as well; route `finalize` to `avatar` the same way. The +`voice_assistant_spatialreal` graph in +`ai_agents/agents/examples/voice-assistant-advanced` is the full example; set +`SPATIALREAL_API_KEY`, `SPATIALREAL_AVATAR_ID` (and optionally +`SPATIALREAL_APP_ID`) in `ai_agents/.env`. + +## Development + +Unit tests for the pure modules (`pacer`, `audio`, `agora_token`, `config`, +`session_client`) run on any laptop; `tests/runtime/` needs the TEN runtime +and is skipped without it: + +```bash +cd ai_agents/agents/ten_packages/extension/spatialreal_avatar_python +pip install -r requirements.txt pytest pytest-asyncio +pytest tests/ +``` + +Everything, including the runtime tests, runs inside the `ten_agent_dev` +container from `ai_agents/`: + +```bash +task test-extension EXTENSION=agents/ten_packages/extension/spatialreal_avatar_python +task build-agent-deps # once, installs every extension's requirements +task lint-extension EXTENSION=spatialreal_avatar_python +task check # black, line length 80 +``` + +## Limits + +- `params.agora_uid` must be an integer; Agora projects that use string user + accounts are not supported, because the egress identity is an integer uid. +- There is no "avatar finished speaking" signal in Agora mode. Playback + progress is not reported, and back-to-back requests are spaced by a fixed + gate (`GATE_MS`, 2000 ms in `pacer.py`) rather than by a server event, so + two requests that arrive faster than real time see up to that much delay + between them. +- Concurrency is counted per SpatialReal API key owner. A refused slot (close + code `4003`) is reported as `1001` and retried on a slow schedule (30, 60, + 120, 300 s, ten attempts) before the extension gives up with `-1`. +- Padding: the server auto-ends a request after 400 ms of empty playout + buffer, so the extension keeps a virtual playhead and inserts 100 ms + silence chunks only after the sent audio drains (`PAD_FLOOR_MS`, 0 ms). + It leaves positive lead alone: filling a reserve there would splice + silence between speech chunks that arrive in time. Silence costs the same + inference time as speech, which is why it is bounded: `PAD_MAX_MS` + (3000 ms of contiguous padding) closes the request, and `TURN_STALL_MS` + (15 s after real audio drains) is the outer backstop. These are constants + in `pacer.py`. +- Pending input is preserved in RAM within three hard limits: 120 s of PCM, + 16 MiB of PCM bytes, and 4096 audio/end items, including the item waiting + for a connection or the previous request's gate. A 26 s TTS response can + therefore survive a slow initial connection without a missing middle. + These are retained-input limits, not a wall-clock reconnect deadline or + a bound on total process RSS; resampling and transport also use buffers. +- Admission beyond any input limit cancels buffered speech and emits a + nonfatal avatar error with vendor category `InputQueueOverflow`. It never + discards old PCM and then reports a normally completed shortened answer. + Identified failed turns stay retired; fresh turns can proceed after the + interrupt completes. Older graphs without turn metadata discard that + failed request until its ordered End or a stop/reset. If that End has a + `request_id`, duplicates cannot close a following request; an unidentified + End without any request ID cannot be distinguished from a new boundary. + No input PCM is spilled to disk. +- A session is billed on connection time and holds one concurrency slot for as + long as the extension runs, idle reconnects included. +- Interruption before the first frame: if a `flush` reaches the avatar before + the interrupted turn has delivered any PCM, the avatar cannot tell that + turn from a legitimate successor (the `flush` from `main_python` carries + no turn identity, and both arrive with the same next turn id). PCM the TTS + emitted before it handled its own `tts_flush` can then play after the + interrupt. The window is bounded: once the TTS handles `tts_flush` its + frames carry no turn, and the replayed request is closed by the TTS's + `INTERRUPTED` `tts_audio_end` for that turn or by the successor's first + frame, whichever arrives first. Closing it completely needs the cancelled + turn id on the `flush` cmd sent to the avatar. diff --git a/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/__init__.py b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/__init__.py new file mode 100644 index 0000000000..72593ab225 --- /dev/null +++ b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/__init__.py @@ -0,0 +1,6 @@ +# +# This file is part of TEN Framework, an open source project. +# Licensed under the Apache License, Version 2.0. +# See the LICENSE file for more information. +# +from . import addon diff --git a/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/addon.py b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/addon.py new file mode 100644 index 0000000000..c01ba16ca7 --- /dev/null +++ b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/addon.py @@ -0,0 +1,20 @@ +# +# This file is part of TEN Framework, an open source project. +# Licensed under the Apache License, Version 2.0. +# See the LICENSE file for more information. +# +from ten_runtime import ( # pylint: disable=import-error + Addon, + register_addon_as_extension, + TenEnv, +) +from .extension import SpatialRealAvatarExtension + + +@register_addon_as_extension("spatialreal_avatar_python") +class SpatialRealAvatarExtensionAddon(Addon): + def on_create_instance(self, ten_env: TenEnv, name: str, context) -> None: + ten_env.log_info("on_create_instance") + ten_env.on_create_instance_done( + SpatialRealAvatarExtension(name), context + ) diff --git a/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/agora_token.py b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/agora_token.py new file mode 100644 index 0000000000..9eecd9d664 --- /dev/null +++ b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/agora_token.py @@ -0,0 +1,49 @@ +# +# This file is part of TEN Framework, an open source project. +# Licensed under the Apache License, Version 2.0. +# See the LICENSE file for more information. +# +"""The Agora token rule for the avatar's egress identity. + +Pure: no TEN or SpatialReal imports. The session client calls this on every +connect so a reconnect always joins the channel with a fresh token. + +Token rule: + +1. an explicit ``agora_token`` is used verbatim; +2. otherwise, with an App Certificate, a publisher token is signed for the + channel and uid, valid for ``ttl_s`` (24 h by default); +3. otherwise (project without certificate) the App ID itself is the token. + +Nothing to return from is a configuration error, raised as ``ValueError``. +""" + +import time + +from agora_token_builder import RtcTokenBuilder + +ROLE_PUBLISHER = 1 +DEFAULT_TTL_S = 24 * 3600 + + +def build_agora_token( + app_id: str, + app_cert: str, + channel: str, + uid: int, + explicit_token: str = "", + ttl_s: int = DEFAULT_TTL_S, + now_s: int | None = None, +) -> str: + """Return the token the avatar joins ``channel`` with as ``uid``.""" + if explicit_token: + return explicit_token + if not app_id: + raise ValueError("agora_appid is required unless agora_token is set") + if not app_cert: + return app_id + if now_s is None: + now_s = int(time.time()) + return RtcTokenBuilder.buildTokenWithUid( + app_id, app_cert, channel, uid, ROLE_PUBLISHER, now_s + ttl_s + ) diff --git a/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/audio.py b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/audio.py new file mode 100644 index 0000000000..e733be9248 --- /dev/null +++ b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/audio.py @@ -0,0 +1,85 @@ +# +# This file is part of TEN Framework, an open source project. +# Licensed under the Apache License, Version 2.0. +# See the LICENSE file for more information. +# +"""PCM helpers: resampling to the session rate and silence generation. + +Pure: no TEN or SpatialReal imports. Everything is 16-bit little-endian +mono, the only format the graph's TTS extensions emit and the only one +``SessionConfig.sample_rate`` describes. + +Frames arrive at ``AudioFrame.get_sample_rate()`` and are converted to the +session rate with ``audioop.ratecv``; the filter state is kept across chunks +of one request and reset at close or flush so a request that arrives in +20 ms pieces converts like one that arrives whole. A trailing odd byte (half +a sample) is dropped first: ``ratecv`` raises on it, and a raise in the +frame handler would take the whole extension down. + +Silence is generated in whole samples at the session rate so the virtual +playhead's ``sent_ms`` stays exact. +""" + +import audioop # pylint: disable=deprecated-module + +ACCEPTED_RATES: tuple[int, ...] = ( + 8000, + 16000, + 22050, + 24000, + 32000, + 44100, + 48000, +) + +SAMPLE_WIDTH = 2 +CHANNELS = 1 + + +class Resampler: + """Streaming int16 mono resampler from ``src_rate`` to ``dst_rate``. + + ``convert`` may be called once per chunk; ``reset`` forgets the filter + state so the next chunk is treated as the start of a new request. + """ + + def __init__(self, src_rate: int, dst_rate: int): + if src_rate <= 0 or dst_rate <= 0: + raise ValueError("sample rates must be positive") + self.src_rate = src_rate + self.dst_rate = dst_rate + self._state = None + + def convert(self, pcm: bytes) -> bytes: + """Return ``pcm`` resampled to ``dst_rate``; never raises on length.""" + if len(pcm) % SAMPLE_WIDTH: + pcm = pcm[: len(pcm) - len(pcm) % SAMPLE_WIDTH] + if self.src_rate == self.dst_rate or not pcm: + return pcm + out, self._state = audioop.ratecv( + pcm, + SAMPLE_WIDTH, + CHANNELS, + self.src_rate, + self.dst_rate, + self._state, + ) + return out + + def reset(self) -> None: + """Forget the filter state (request closed or flushed).""" + self._state = None + + +def silence(ms: int, rate: int) -> bytes: + """Return ``ms`` of int16 zero at ``rate``; must be whole samples.""" + if rate * ms % 1000: + raise ValueError( + f"{ms} ms at {rate} Hz is not a whole number of samples" + ) + return bytes(rate * ms // 1000 * SAMPLE_WIDTH) + + +def duration_ms(pcm: bytes, rate: int) -> float: + """Playout time of ``pcm`` at ``rate``; an odd trailing byte is ignored.""" + return len(pcm) // SAMPLE_WIDTH * 1000.0 / rate diff --git a/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/config.py b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/config.py new file mode 100644 index 0000000000..2497b59099 --- /dev/null +++ b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/config.py @@ -0,0 +1,171 @@ +# +# This file is part of TEN Framework, an open source project. +# Licensed under the Apache License, Version 2.0. +# See the LICENSE file for more information. +# +"""Property resolution and validation. + +Pure: no TEN or SpatialReal imports, so the rules are unit-tested on any +laptop. The extension reads two top-level properties, ``channel`` (owned by +the TEN server, which injects the per-call channel into the graph node) and +the ``params`` object (everything the operator sets), and hands them here. + +Every failure is a ``ValueError`` whose message names the offending key the +way it appears in the node property (``params.``), so the ``-1012`` +ModuleError the glue emits tells the operator what to fix. +""" + +from dataclasses import dataclass +from typing import Any, Mapping + +from .audio import ACCEPTED_RATES + +DEFAULT_ENVIRONMENT = "us-west" +DEFAULT_SAMPLE_RATE = 24000 +DEFAULT_EGRESS_IDLE_RECONNECT_MS = 1_080_000 + +CHANNEL_HINT = ( + 'channel is empty: add "channel": "" to the avatar node\'s property so ' + "the TEN server can inject it, or set params.agora_channel" +) + + +@dataclass +class ResolvedConfig: + """Validated settings; the glue maps them 1:1 onto ``SessionSettings``.""" + + api_key: str + avatar_id: str + app_id: str + environment: str + console_endpoint_url: str + ingress_endpoint_url: str + sample_rate: int + channel: str + uid: int + agora_appid: str + agora_appcert: str + agora_token: str + egress_idle_reconnect_ms: int + source_timeline_only: bool + source_playback_profile: int + + +def _string(params: Mapping[str, Any], key: str, default: str = "") -> str: + """A string property; missing or null means ``default``.""" + value = params.get(key) + if value is None: + return default + if not isinstance(value, str): + raise ValueError( + f"params.{key} must be a string, got {type(value).__name__}" + ) + return value + + +def _required(params: Mapping[str, Any], key: str) -> str: + value = _string(params, key).strip() + if not value: + raise ValueError(f"params.{key} is required") + return value + + +def _integer(params: Mapping[str, Any], key: str, default: int) -> int: + """An integer property given as an int or a decimal string.""" + value = params.get(key) + if value is None or value == "": + return default + if isinstance(value, bool): + raise ValueError(f"params.{key} must be an integer, got a boolean") + if isinstance(value, int): + return value + if isinstance(value, str): + try: + return int(value.strip(), 10) + except ValueError: + pass + raise ValueError(f"params.{key} must be an integer, got {value!r}") + + +def _boolean(params: Mapping[str, Any], key: str, default: bool) -> bool: + value = params.get(key, default) + if not isinstance(value, bool): + raise ValueError(f"params.{key} must be a boolean") + return value + + +def resolve_config(channel: str, params: Mapping[str, Any]) -> ResolvedConfig: + """Validate the node properties and return the session settings. + + Raises ``ValueError`` naming the first invalid key. Order: the two + SpatialReal keys, the channel, the uid, the sample rate, the Agora + credentials, then the optional knobs. + """ + api_key = _required(params, "spatialreal_api_key") + avatar_id = _required(params, "spatialreal_avatar_id") + + explicit_channel = _string(params, "agora_channel").strip() + channel = explicit_channel or (channel or "").strip() + if not channel: + raise ValueError(CHANNEL_HINT) + + uid_raw = params.get("agora_uid") + try: + uid = _integer(params, "agora_uid", 0) + except ValueError: + uid = 0 + if uid == 0: + raise ValueError( + f"params.agora_uid must be a non-zero integer, got {uid_raw!r}" + ) + + rate_raw = params.get("sample_rate") + try: + sample_rate = _integer(params, "sample_rate", DEFAULT_SAMPLE_RATE) + except ValueError: + sample_rate = 0 + if sample_rate not in ACCEPTED_RATES: + accepted = ", ".join(str(r) for r in ACCEPTED_RATES) + raise ValueError( + f"params.sample_rate must be one of {accepted}, got {rate_raw!r}" + ) + + agora_token = _string(params, "agora_token").strip() + agora_appid = _string(params, "agora_appid").strip() + if not agora_appid and not agora_token: + raise ValueError( + "params.agora_appid is required unless params.agora_token is set" + ) + + idle_ms = _integer( + params, "egress_idle_reconnect_ms", DEFAULT_EGRESS_IDLE_RECONNECT_MS + ) + source_only = _boolean(params, "source_timeline_only", True) + profile = params.get("source_playback_profile", 1 if source_only else 0) + # The SDK's RtcSourcePlaybackProfile: zero is compatibility, one is + # BOUNDED_BURST_V1. SessionClient also checks the installed SDK's enum. + if type(profile) is not int or profile not in (0, 1): + raise ValueError("params.source_playback_profile must be 0 or 1") + if profile and not source_only: + raise ValueError( + "params.source_playback_profile requires source_timeline_only" + ) + + return ResolvedConfig( + api_key=api_key, + avatar_id=avatar_id, + app_id=_string(params, "spatialreal_app_id").strip(), + environment=_string(params, "environment", DEFAULT_ENVIRONMENT).strip() + or DEFAULT_ENVIRONMENT, + console_endpoint_url=_string(params, "console_endpoint_url").strip(), + ingress_endpoint_url=_string(params, "ingress_endpoint_url").strip(), + sample_rate=sample_rate, + channel=channel, + uid=uid, + agora_appid=agora_appid, + agora_appcert=_string(params, "agora_appcert").strip(), + agora_token=agora_token, + egress_idle_reconnect_ms=idle_ms, + source_timeline_only=source_only, + source_playback_profile=profile, + ) diff --git a/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/extension.py b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/extension.py new file mode 100644 index 0000000000..577d6bcd85 --- /dev/null +++ b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/extension.py @@ -0,0 +1,398 @@ +# +# This file is part of TEN Framework, an open source project. +# Licensed under the Apache License, Version 2.0. +# See the LICENSE file for more information. +# +"""TEN glue for the SpatialReal avatar. + +Everything TEN-specific lives here: the property dataclass, the hook +dispatch (audio frames, ``tts_audio_end``/``finalize`` data, the ``flush`` +command) and ``ModuleError`` emission. The work is delegated to the pure +modules: ``config`` validates the properties, ``sender`` queues frames and +end markers in order and resamples to the session rate, ``pacer`` owns +request boundaries and padding, and ``session_client`` keeps the SpatialReal +session up. + +Nothing raises out of a hook (an uncaught exception ends the TEN process): +a configuration failure is reported as a ``-1012`` error and the extension +stays idle; a session failure is reported by the client and the audio path +simply has nowhere to send until it reconnects. +""" + +import asyncio +import json +import traceback +from dataclasses import asdict, dataclass, field +from typing import Any, Mapping, Optional + +from ten_runtime import ( # pylint: disable=import-error + AsyncExtension, + AsyncTenEnv, + AudioFrame, + Cmd, + CmdResult, + Data, + StatusCode, +) +from ten_ai_base.config import BaseConfig # pylint: disable=import-error +from ten_ai_base.message import ( # pylint: disable=import-error + ModuleError, + ModuleErrorVendorInfo, + ModuleType, +) +from ten_ai_base.utils import encrypt # pylint: disable=import-error + +from .config import ResolvedConfig, resolve_config +from .pacer import Pacer +from .sender import AudioSender, End, QueueCapacityError, Turn +from .session_client import ( + CODE_CONFIG, + CODE_FATAL, + CODE_NON_FATAL, + ErrorReport, + SessionClient, + SessionSettings, +) + +VENDOR = "spatialreal" +# Property keys whose values are secrets; redacted wherever config is logged. +SECRET_KEYS = frozenset({"spatialreal_api_key", "agora_token", "agora_appcert"}) +# ``ResolvedConfig`` fields whose name differs from their property key. +_PROPERTY_KEY_OF_FIELD = {"api_key": "spatialreal_api_key"} + + +@dataclass +class SpatialRealAvatarConfig(BaseConfig): + """The two top-level properties: the server-owned channel and the + operator's ``params`` object. Every other key lives inside ``params``.""" + + channel: str = "" + params: dict = field(default_factory=dict) + + +def _masked(values: Mapping[str, Any], property_key_of=None) -> dict: + """``values`` with every ``SECRET_KEYS`` entry replaced by its mask.""" + property_key_of = property_key_of or (lambda name: name) + return { + name: ( + encrypt(str(value)) + if property_key_of(name) in SECRET_KEYS + else value + ) + for name, value in values.items() + } + + +def redacted(cfg: ResolvedConfig) -> dict: + """The resolved config as a loggable dict; secrets masked.""" + return _masked( + asdict(cfg), lambda name: _PROPERTY_KEY_OF_FIELD.get(name, name) + ) + + +def redacted_params(channel: str, params: dict) -> dict: + """The raw properties as a loggable dict, for the validation-failed log.""" + return {"channel": channel, "params": _masked(params or {})} + + +class SpatialRealAvatarExtension(AsyncExtension): + """Drives one SpatialReal avatar into the Agora channel from TTS audio.""" + + def __init__(self, name: str): + super().__init__(name) + self.ten_env: Optional[AsyncTenEnv] = None + self.config: Optional[ResolvedConfig] = None + self.client: Optional[SessionClient] = None + self.pacer: Optional[Pacer] = None + self.sender: Optional[AudioSender] = None + self._tasks: set[asyncio.Task] = set() + self._sender_task: Optional[asyncio.Task] = None + self._ticker_task: Optional[asyncio.Task] = None + self._turn_id = 0 + self._stopping = False + + # -- lifecycle ---------------------------------------------------------- + + async def on_init(self, ten_env: AsyncTenEnv) -> None: + ten_env.log_debug("on_init") + self.ten_env = ten_env + + async def on_start(self, ten_env: AsyncTenEnv) -> None: + ten_env.log_debug("on_start") + self.ten_env = ten_env + try: + raw = await SpatialRealAvatarConfig.create_async(ten_env) + except Exception as exc: + ten_env.log_error(f"config: load failed: {traceback.format_exc()}") + await self._send_error( + CODE_CONFIG, type(exc).__name__, f"failed to load: {exc}" + ) + return + params = raw.params if isinstance(raw.params, dict) else {} + try: + self.config = resolve_config(raw.channel, params) + except ValueError as exc: + ten_env.log_error( + f"config: invalid: {exc}; " + f"config: {redacted_params(raw.channel, params)}" + ) + await self._send_error(CODE_CONFIG, "ValueError", str(exc)) + return + ten_env.log_info(f"config: {redacted(self.config)}") + + try: + self._start_session(self.config) + except Exception as exc: + ten_env.log_error(f"session start failed: {traceback.format_exc()}") + await self._send_error(CODE_FATAL, type(exc).__name__, str(exc)) + + def _start_session(self, cfg: ResolvedConfig) -> None: + # ResolvedConfig and SessionSettings share their field names 1:1. + settings = SessionSettings(**asdict(cfg)) + self.client = SessionClient( + settings, + on_report=self._on_report, + on_connected=self._on_connected, + on_disconnected=self._on_disconnected, + ) + self.pacer = Pacer( + sink=self.client, + sample_rate=cfg.sample_rate, + on_request_state=self.client.note_request_state, + ) + self.sender = AudioSender( + self.pacer, + cfg.sample_rate, + self.ten_env, + on_request_state=self.client.note_request_state, + ) + self._sender_task = self._spawn(self.sender.run()) + self._ticker_task = self._spawn(self.pacer.run()) + self._spawn(self.client.start()) + + async def on_stop(self, ten_env: AsyncTenEnv) -> None: + ten_env.log_debug("on_stop") + self._stopping = True + for task in (self._sender_task, self._ticker_task): + if task is not None: + task.cancel() + self._sender_task = None + self._ticker_task = None + if self.client is not None: + try: + await self.client.stop() + except Exception: + ten_env.log_error(f"client stop: {traceback.format_exc()}") + for task in list(self._tasks): + task.cancel() + if self.sender is not None: + self.sender.clear() + + async def on_deinit(self, ten_env: AsyncTenEnv) -> None: + ten_env.log_debug("on_deinit") + + # -- dispatch ----------------------------------------------------------- + + async def on_cmd(self, ten_env: AsyncTenEnv, cmd: Cmd) -> None: + cmd_name = cmd.get_name() + ten_env.log_debug(f"on_cmd name={cmd_name}") + if cmd_name == "flush": + try: + if self.sender is not None: + await self.sender.flush() + except Exception: + ten_env.log_error(f"flush: {traceback.format_exc()}") + # The flush continues downstream. + await ten_env.send_cmd(Cmd.create("flush")) + await ten_env.return_result(CmdResult.create(StatusCode.OK, cmd)) + + async def on_data(self, ten_env: AsyncTenEnv, data: Data) -> None: + data_name = data.get_name() + ten_env.log_debug(f"on_data name={data_name}") + if self.sender is None: + return + try: + if data_name == "tts_audio_end": + self._on_tts_audio_end(ten_env, data) + elif data_name == "finalize": + payload = _payload(data) + self.sender.put_end( + End( + "finalize", + turn=Turn.from_metadata(payload.get("metadata")), + request_id=_request_id(payload), + ) + ) + except QueueCapacityError as exc: + await self._handle_queue_capacity(exc) + except Exception: + ten_env.log_error(f"on_data {data_name}: {traceback.format_exc()}") + + async def on_audio_frame( + self, ten_env: AsyncTenEnv, audio_frame: AudioFrame + ) -> None: + if self.sender is None or self._stopping: + return + try: + buf = audio_frame.get_buf() + rate = audio_frame.get_sample_rate() + turn = Turn.from_metadata(_payload(audio_frame, "metadata")) + except Exception: + ten_env.log_error(f"audio frame: {traceback.format_exc()}") + return + if not buf: + return + if rate <= 0 and self.config is not None: + rate = self.config.sample_rate + try: + self.sender.put_audio(bytes(buf), rate, turn) + except QueueCapacityError as exc: + await self._handle_queue_capacity(exc) + + async def _handle_queue_capacity(self, error: QueueCapacityError) -> None: + """Fail closed before yielding; never acknowledge a shortened turn.""" + turn = error.turn + try: + try: + if self.sender is not None: + # flush retires and clears synchronously before its first + # await, so subsequent hooks cannot race old PCM/end past it. + await self.sender.flush() + except Exception: + self.ten_env.log_error("input queue overflow: interrupt failed") + if not self._stopping: + await self._send_error( + CODE_NON_FATAL, + "InputQueueOverflow", + f"{error}; buffered speech cancelled", + session_id=turn.session_id if turn is not None else None, + turn_id=turn.turn_id if turn is not None else None, + ) + except asyncio.CancelledError: + # TEN treats an uncaught BaseException in a hook as process fatal. + # Cancellation already retired the old turn; stopping must neither + # kill the worker nor manufacture a successful normal end. + return + + # -- request signals ---------------------------------------------------- + + def _on_tts_audio_end(self, ten_env: AsyncTenEnv, data: Data) -> None: + """Queue the end as a marker behind the audio already queued. + + The pacer applies its reason rules when the marker is reached; + the turn id is taken at once because it only labels error reports. + """ + payload = _payload(data) + reason = payload.get("reason") + if not isinstance(reason, int) or isinstance(reason, bool): + # The pacer treats an unknown reason as "close"; keep what came + # in out of the arithmetic and log it as such. + reason = -1 + request_id = _request_id(payload) + turn = Turn.from_metadata(payload.get("metadata")) + if turn is not None: + self._turn_id = turn.turn_id + label = f"tts_audio_end request_id={request_id} reason={reason}" + ten_env.log_debug(f"queued end: {label}") + self.sender.put_end(End(label, reason, turn, request_id)) + + # -- session callbacks -------------------------------------------------- + + def _on_connected(self, connection_id: str) -> None: + self.ten_env.log_info(f"session connected: {connection_id}") + if self.sender is not None: + self.sender.session_up() + + def _on_disconnected(self) -> None: + self.ten_env.log_info("session disconnected") + if self.sender is not None: + self.sender.session_down() + + def _on_report(self, report: ErrorReport) -> None: + # The report carries the id of the session it is about; by the time + # the spawned task runs, the client may already have cleared its own. + self._spawn( + self._send_error( + report.code, + report.vendor_code, + report.message, + session_id=report.session_id, + ) + ) + + # -- errors ------------------------------------------------------------- + + async def _send_error( + self, + code: int, + vendor_code: str, + message: str, + session_id: Optional[str] = None, + turn_id: Optional[int] = None, + ) -> None: + """Emit a ``ModuleError`` on data ``error``. + + ``session_id`` defaults to the client's current connection id; a + report from the client names the session it is about instead. + """ + if self.ten_env is None: + return + if session_id is None: + session_id = self.client.connection_id if self.client else "" + error = ModuleError( + id=str(turn_id if turn_id is not None else self._turn_id or 0), + module=ModuleType.AVATAR.value, + code=code, + message=message, + vendor_info=ModuleErrorVendorInfo( + vendor=VENDOR, code=vendor_code, message=message + ), + metadata={ + "session_id": session_id, + "vendor_metadata": self._vendor_metadata(), + }, + ) + try: + data = Data.create("error") + data.set_property_from_json(None, error.model_dump_json()) + line = f"error: code={code} vendor_code={vendor_code} {message}" + if code == CODE_NON_FATAL: + self.ten_env.log_warn(line) + else: + self.ten_env.log_error(line) + await self.ten_env.send_data(data) + except Exception: + self.ten_env.log_error(f"send error: {traceback.format_exc()}") + + def _vendor_metadata(self) -> dict[str, Any]: + """Identifiers only: never a URL, key or token; no empty values.""" + values: dict[str, Any] = {"name": VENDOR} + if self.config is not None: + values["avatar_id"] = self.config.avatar_id + values["environment"] = self.config.environment + values["agora_uid"] = self.config.uid + return {k: v for k, v in values.items() if v not in ("", None, 0)} + + # -- tasks -------------------------------------------------------------- + + def _spawn(self, coro) -> asyncio.Task: + task = asyncio.ensure_future(coro) + self._tasks.add(task) + task.add_done_callback(self._tasks.discard) + return task + + +def _request_id(payload: dict) -> str: + value = payload.get("request_id", "") + return value if isinstance(value, str) else "" + + +def _payload(data, path=None) -> dict: + json_str, _ = data.get_property_to_json(path) + if not json_str: + return {} + try: + payload = json.loads(json_str) + except ValueError: + return {} + return payload if isinstance(payload, dict) else {} diff --git a/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/manifest.json b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/manifest.json new file mode 100644 index 0000000000..ec01d136cf --- /dev/null +++ b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/manifest.json @@ -0,0 +1,117 @@ +{ + "type": "extension", + "name": "spatialreal_avatar_python", + "version": "0.1.0", + "dependencies": [ + { + "type": "system", + "name": "ten_runtime_python", + "version": "0.11" + }, + { + "type": "system", + "name": "ten_ai_base", + "version": "0.7" + } + ], + "package": { + "include": [ + "manifest.json", + "property.json", + "**.py", + "README.md", + "pyproject.toml", + "requirements.txt" + ] + }, + "api": { + "property": { + "properties": { + "channel": { + "type": "string" + }, + "params": { + "type": "object", + "properties": { + "spatialreal_api_key": { + "type": "string" + }, + "spatialreal_avatar_id": { + "type": "string" + }, + "spatialreal_app_id": { + "type": "string" + }, + "environment": { + "type": "string" + }, + "console_endpoint_url": { + "type": "string" + }, + "ingress_endpoint_url": { + "type": "string" + }, + "sample_rate": { + "type": "int64" + }, + "source_timeline_only": { + "type": "bool" + }, + "source_playback_profile": { + "type": "int64" + }, + "egress_idle_reconnect_ms": { + "type": "int64" + }, + "agora_uid": { + "type": "string" + }, + "agora_token": { + "type": "string" + }, + "agora_appid": { + "type": "string" + }, + "agora_appcert": { + "type": "string" + }, + "agora_channel": { + "type": "string" + } + } + } + } + }, + "audio_frame_in": [ + { + "name": "pcm_frame" + } + ], + "data_in": [ + { + "name": "tts_audio_end" + }, + { + "name": "finalize" + } + ], + "cmd_in": [ + { + "name": "flush" + } + ], + "cmd_out": [ + { + "name": "flush" + } + ], + "data_out": [ + { + "name": "error" + } + ] + }, + "scripts": { + "test": "tests/bin/start" + } +} diff --git a/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/pacer.py b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/pacer.py new file mode 100644 index 0000000000..9b97541fd1 --- /dev/null +++ b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/pacer.py @@ -0,0 +1,374 @@ +# +# This file is part of TEN Framework, an open source project. +# Licensed under the Apache License, Version 2.0. +# See the LICENSE file for more information. +# +"""Request pacer: request boundaries, silence padding and gating. + +Pure: no TEN or SpatialReal imports. The pacer talks to the session through +the ``PacerSink`` protocol and takes its clock and sleep from the caller so +the tests drive time by hand. + +One avatar request per TTS request. The first audio after idle opens a +request; the first of ``tts_audio_end`` (reasons 1, 3, unknown, and 2 unless +a flush has been processed), ``finalize``, the padding bound or the stall +backstop closes it with ``send_audio(b"", end=True)``. Closing is +idempotent. + +Padding keeps egress's playout buffer from running dry inside a request: +the virtual playhead is ``ahead_ms = sent_ms - (now - first_send)`` and a +tick sends enough 100 ms silence chunks to return it to ``pad_floor_ms`` +(zero by default) only after it dips below. Positive lead is left alone so +the next speech chunk can follow without inserted silence. +``pad_max_ms`` of contiguous padding with no new real audio closes the +request; ``turn_stall_ms`` after the real audio drained is the outer backstop. +While a real chunk's send is in flight the ticker does none of this: that +chunk is not on the playhead yet, so it would see a drain that is not there +and pad, or close the request, ahead of speech that has already arrived. + +A new request whose predecessor is still less than ``gate_ms`` past drained +waits before its first chunk so the predecessor's tail is not cut by the new +server-side session. ``flush`` cancels that wait and the frame that was +waiting (``push_audio`` returns ``PushResult.CANCELLED`` without sending), +closes the open request locally without ``end=True``, interrupts the sink +and waives the gate for the next request. + +The sink reports whether a send went out. A send that did not (the session +dropped between the sender's readiness check and the send, possibly after a +long gate wait) is not counted: ``push_audio`` returns +``PushResult.NOT_SENT`` and forgets the request it may just have opened, so +the caller can hold the chunk for the replacement session. +""" + +import asyncio +import math +import time +from enum import Enum +from typing import Awaitable, Callable, Optional, Protocol + +from .audio import duration_ms, silence + +# Refill only after the virtual playhead drains. A positive reserve inserts +# silence between speech chunks even when the next chunk arrives in time. +PAD_FLOOR_MS = 0 +PAD_TICK_MS = 100 +PAD_MAX_MS = 3000 +TURN_STALL_MS = 15000 +GATE_MS = 2000 + +_EPS_MS = 1e-3 + + +class PushResult(Enum): + """What became of a ``push_audio`` call.""" + + SENT = "sent" + # A flush landed while the chunk waited at the gate: it belonged to the + # cancelled turn and was not sent. + CANCELLED = "cancelled" + # The sink could not send (session gone): the chunk is still owed. + NOT_SENT = "not_sent" + + +class PacerSink(Protocol): + """What the pacer needs from the session: audio out and interrupt. + + ``send_audio`` returns False when nothing went out because the session + is not connected or the send failed; by then the session has told the + extension it is down (``on_session_reset``) or is about to. + """ + + async def send_audio(self, pcm: bytes, end: bool = False) -> bool: ... + + async def interrupt(self) -> bool: ... + + +class Pacer: + """Owns request boundaries and the virtual playhead for one session. + + All methods run on one asyncio loop; ``push_audio`` is called by a + single sender, ``tick``/``run`` by the ticker, ``flush`` and the end + signals by the extension's handlers. State is re-read after every + ``await`` so an end or flush that lands mid-send stops the padding. + ``on_request_state(False)`` is called whenever a request is closed with + ``end=True``, including the ticker's pad-max and stall closures. + """ + + def __init__( + self, + sink: PacerSink, + sample_rate: int, + *, + clock: Callable[[], float] = time.monotonic, + sleep: Callable[[float], Awaitable[None]] = asyncio.sleep, + pad_floor_ms: int = PAD_FLOOR_MS, + pad_tick_ms: int = PAD_TICK_MS, + pad_max_ms: int = PAD_MAX_MS, + turn_stall_ms: int = TURN_STALL_MS, + gate_ms: int = GATE_MS, + on_request_state: Callable[[bool], None] = lambda open_: None, + ) -> None: + if sample_rate <= 0: + raise ValueError("sample_rate must be positive") + if pad_tick_ms <= 0: + raise ValueError("pad_tick_ms must be positive") + self._sink = sink + self._rate = sample_rate + self._clock = clock + self._sleep = sleep + self._pad_floor_ms = pad_floor_ms + self._pad_tick_ms = pad_tick_ms + self._pad_max_ms = pad_max_ms + self._turn_stall_ms = turn_stall_ms + self._gate_ms = gate_ms + self._on_request_state = on_request_state + # Raises ValueError for a tick that is not whole samples at this rate. + self._pad_chunk = silence(pad_tick_ms, sample_rate) + + self._req_open = False + self._first_send: Optional[float] = None + self._sent_ms = 0.0 + self._real_sent_ms = 0.0 + self._padded_ms_contiguous = 0.0 + self._last_real_audio_at: Optional[float] = None + self._flush_seen = False + self._gate_waiver = False + self._gate_abort = asyncio.Event() + # Bumped by every flush; a gate wait that started under an older + # value was cancelled by it. + self._cancel_gen = 0 + # An awaited send may finish after end, flush or reconnect and after + # a new request has opened. Its accounting belongs only to its epoch. + self._request_gen = 0 + # Real sends awaiting the sink; the ticker stands still meanwhile. + self._real_sends_in_flight = 0 + + # -- observable state --------------------------------------------------- + + @property + def request_open(self) -> bool: + return self._req_open + + @property + def ahead_ms(self) -> float: + """Lead of the current or last request's playhead over wall time. + + Negative once the sent audio has drained; ``-inf`` when nothing has + been sent since construction or the last session reset. + """ + if self._first_send is None: + return -math.inf + return self._sent_ms - (self._clock() - self._first_send) * 1000.0 + + # -- audio in ----------------------------------------------------------- + + async def push_audio(self, pcm: bytes) -> PushResult: + """Send one chunk at the session rate, opening a request if idle. + + An empty chunk is a no-op reported as sent. A chunk that a flush + cancels while it waits at the gate is not sent. A chunk the sink + could not send is ``NOT_SENT``: nothing is counted, and a request + opened for it is forgotten so the next chunk opens a fresh one. A + send that completes after a flush, end or reset is not counted + toward the request that boundary closed. + """ + if not pcm: + return PushResult.SENT + opened = False + if not self._req_open: + if not await self._wait_for_gate(): + return PushResult.CANCELLED + self._open() + opened = True + gen = self._request_gen + self._real_sends_in_flight += 1 + try: + sent = await self._sink.send_audio(pcm, end=False) + finally: + self._real_sends_in_flight -= 1 + if gen != self._request_gen: + # A flush, end or reset closed this request during the send. + return PushResult.SENT if sent else PushResult.NOT_SENT + if not sent: + if opened: + self._forget_request() + return PushResult.NOT_SENT + now = self._clock() + ms = duration_ms(pcm, self._rate) + self._sent_ms += ms + self._real_sent_ms += ms + self._padded_ms_contiguous = 0.0 + self._last_real_audio_at = now + return PushResult.SENT + + def _open(self) -> None: + now = self._clock() + self._request_gen += 1 + self._req_open = True + self._first_send = now + self._sent_ms = 0.0 + self._real_sent_ms = 0.0 + self._padded_ms_contiguous = 0.0 + self._last_real_audio_at = now + self._gate_waiver = False + + async def _wait_for_gate(self) -> bool: + """Block while the previous request may still be playing out. + + The wait is a race between the injected ``sleep`` and the abort + event ``flush`` and ``on_session_reset`` set; whichever finishes + first, the loop re-reads the waiver and the playhead, so an early + wake never sends too soon. Returns False when a flush landed during + the wait: the chunk belongs to the cancelled turn. The waiver the + flush set stays for the next request's first chunk. + """ + gen = self._cancel_gen + self._gate_abort.clear() + while not self._gate_waiver: + remaining_ms = self.ahead_ms + self._gate_ms + if remaining_ms <= 0: + return True + sleeper = asyncio.ensure_future(self._sleep(remaining_ms / 1000.0)) + aborter = asyncio.ensure_future(self._gate_abort.wait()) + try: + await asyncio.wait( + {sleeper, aborter}, return_when=asyncio.FIRST_COMPLETED + ) + finally: + sleeper.cancel() + aborter.cancel() + if gen != self._cancel_gen: + return False + return True + + # -- request end -------------------------------------------------------- + + async def end_request(self, reason: str) -> bool: + """Close the open request with ``end=True``; a no-op when idle. + + Returns True when this call closed the request, so the caller can + log the end signal once with its reason. ``reason`` is for that log + line only. + """ + del reason # the caller logs it; the pacer keeps no history + if not self._req_open: + return False + self._request_gen += 1 + self._req_open = False + self._padded_ms_contiguous = 0.0 + # The ticker closes requests too (pad max, stall), outside the + # sender that otherwise reports the state after each operation. + self._on_request_state(False) + # An end signal closes the window in which a late reason 2 could + # belong to a pre-flush request. + self._flush_seen = False + await self._sink.send_audio(b"", end=True) + return True + + async def on_tts_audio_end(self, reason: int) -> bool: + """Apply the end-of-request rules for data ``tts_audio_end``. + + Reasons 1 (REQUEST_END), 3 (ERROR) and anything unknown close the + request. Reason 2 (INTERRUPTED) closes it only when no flush has been + processed since the last end signal: after a flush it may belong to + the pre-flush request and arrive after the new turn's first frame. + """ + if reason == 2 and self._flush_seen: + return False + return await self.end_request(f"tts_audio_end reason={reason}") + + async def flush(self) -> None: + """Drop the open request locally, interrupt, waive the gate. + + A chunk waiting at the gate is cancelled rather than released. + """ + self._flush_seen = True + self._gate_waiver = True + self._cancel_gen += 1 + self._request_gen += 1 + self._gate_abort.set() + if self._req_open: + self._req_open = False + self._padded_ms_contiguous = 0.0 + await self._sink.interrupt() + + # -- ticker ------------------------------------------------------------- + + async def tick(self) -> None: + """One padding/stall step; ``run`` calls it every ``pad_tick_ms``. + + A no-op while a real send is in flight: the playhead does not hold + that chunk yet, so neither padding nor a padding or stall closure + may overtake it. The next tick after it completes reads the updated + playhead. ``flush`` is not held back by an in-flight send. + """ + if not self._req_open or self._real_sends_in_flight: + return + gen = self._request_gen + now = self._clock() + if self._stalled(now): + await self.end_request("turn stall") + return + while ( + self._req_open + and gen == self._request_gen + and not self._real_sends_in_flight + ): + # Real audio can arrive during an awaited padding send. Recheck + # its lead before each chunk instead of sending a stale batch. + # The tolerance avoids an extra chunk from float clock drift. + deficit_ms = self._pad_floor_ms - self.ahead_ms - _EPS_MS + if deficit_ms <= 0: + return + if not await self._sink.send_audio(self._pad_chunk, end=False): + # Session gone; the reset that follows forgets the request. + return + if gen != self._request_gen: + return + self._sent_ms += self._pad_tick_ms + self._padded_ms_contiguous += self._pad_tick_ms + if self._real_sends_in_flight: + # Real audio started during this padding send; once it is + # counted the contiguous padding restarts from zero. + return + if self._padded_ms_contiguous >= self._pad_max_ms: + await self.end_request("pad max") + return + + def _stalled(self, now: float) -> bool: + """True when real audio ran out ``turn_stall_ms`` ago and the request + is still open; padding normally closes it long before this.""" + if self._first_send is None or self._last_real_audio_at is None: + return False + real_drained_at = self._first_send + self._real_sent_ms / 1000.0 + idle_since = max(real_drained_at, self._last_real_audio_at) + return (now - idle_since) * 1000.0 >= self._turn_stall_ms + + async def run(self) -> None: + """Tick every ``pad_tick_ms`` until cancelled.""" + while True: + await self._sleep(self._pad_tick_ms / 1000.0) + await self.tick() + + # -- session ------------------------------------------------------------ + + def on_session_reset(self) -> None: + """After a reconnect: the server has no request, forget the playhead. + + A sender waiting at the gate for the old request's tail is woken: + with no playhead left there is nothing to wait for. + """ + self._forget_request() + self._gate_abort.set() + + def _forget_request(self) -> None: + """No request and no playhead: the server-side state is gone.""" + self._request_gen += 1 + self._req_open = False + self._first_send = None + self._sent_ms = 0.0 + self._real_sent_ms = 0.0 + self._padded_ms_contiguous = 0.0 + self._last_real_audio_at = None + self._flush_seen = False + self._gate_waiver = False diff --git a/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/property.json b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/property.json new file mode 100644 index 0000000000..c301b57096 --- /dev/null +++ b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/property.json @@ -0,0 +1,18 @@ +{ + "channel": "", + "params": { + "spatialreal_api_key": "${env:SPATIALREAL_API_KEY|}", + "spatialreal_avatar_id": "${env:SPATIALREAL_AVATAR_ID|}", + "spatialreal_app_id": "${env:SPATIALREAL_APP_ID|}", + "environment": "us-west", + "console_endpoint_url": "", + "ingress_endpoint_url": "", + "sample_rate": 24000, + "egress_idle_reconnect_ms": 1080000, + "agora_uid": "", + "agora_token": "", + "agora_appid": "${env:AGORA_APP_ID|}", + "agora_appcert": "${env:AGORA_APP_CERTIFICATE|}", + "agora_channel": "" + } +} diff --git a/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/pyproject.toml b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/pyproject.toml new file mode 100644 index 0000000000..d79095e539 --- /dev/null +++ b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/pyproject.toml @@ -0,0 +1,17 @@ +[project] +name = "spatialreal-avatar-python" +version = "0.1.0" +requires-python = ">=3.10" +dependencies = [ + "spatialreal>=0.4.0,<0.5", + "agora-token-builder>=1.0.0", + "audioop-lts>=0.2.1; python_version >= \"3.13\"", +] + +[tool.pytest.ini_options] +# `pytest tests/` from this directory: stop conftest lookup at tests/ so the +# package __init__ (which needs ten_runtime) is not imported on a laptop +# without the TEN runtime. The extension directory is deliberately not on +# sys.path: the modules import each other relatively, as the TEN addon loader +# requires, and tests/conftest.py exposes them as a package. +addopts = "--confcutdir=tests" diff --git a/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/requirements.txt b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/requirements.txt new file mode 100644 index 0000000000..14394dee39 --- /dev/null +++ b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/requirements.txt @@ -0,0 +1,3 @@ +spatialreal>=0.4.0,<0.5 +agora-token-builder>=1.0.0 +audioop-lts>=0.2.1; python_version >= "3.13" diff --git a/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/sender.py b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/sender.py new file mode 100644 index 0000000000..750da70f61 --- /dev/null +++ b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/sender.py @@ -0,0 +1,525 @@ +# +# This file is part of TEN Framework, an open source project. +# Licensed under the Apache License, Version 2.0. +# See the LICENSE file for more information. +# +"""Audio sender: the ordered queue between the TEN hooks and the pacer. + +Pure: no TEN or SpatialReal imports. The extension's hooks only append to +the queue; one sender task drains it in order, resamples each frame to the +session rate and pushes it through the ``Pacer``. + +The queue carries two kinds of item. A ``Frame`` is PCM at the rate it +arrived with. An ``End`` is the end-of-request signal (``tts_audio_end`` or +``finalize``) as an ordered marker: it is applied only after every frame +queued before it has been sent, so ``end=True`` can never overtake its own +audio while the sender is behind, waiting for the session or waiting at the +previous request's gate. ``flush`` acts at once instead: it clears the +queue, markers included, because everything queued belongs to the cancelled +turn. + +Frames and ordered end markers are preserved within explicit duration, byte +and item budgets. Admission beyond a budget raises ``QueueCapacityError``; +the extension cancels the buffered turn instead of playing truncated speech. +""" + +import asyncio +import traceback +from collections import deque +from dataclasses import dataclass +from typing import Callable, Optional, Protocol, Union + +from .audio import Resampler, duration_ms +from .pacer import Pacer, PushResult + +INPUT_QUEUE_MAX_MS = 120_000 +INPUT_QUEUE_MAX_BYTES = 16 * 1024 * 1024 +INPUT_QUEUE_MAX_ITEMS = 4096 + + +class QueueCapacityError(RuntimeError): + """An atomic admission failed; its caller must cancel buffered speech.""" + + def __init__(self, duration: float, byte_count: int, item_count: int): + self.turn: Optional["Turn"] = None + super().__init__( + "input queue capacity exceeded: " + f"duration_ms={duration:.3f} bytes={byte_count} items={item_count}" + ) + + +class SenderLog(Protocol): + """The four log levels the sender uses; ``AsyncTenEnv`` satisfies it.""" + + def log_debug(self, msg: str) -> None: ... + + def log_info(self, msg: str) -> None: ... + + def log_warn(self, msg: str) -> None: ... + + def log_error(self, msg: str) -> None: ... + + +@dataclass(frozen=True) +class Turn: + """The identity carried by TEN TTS PCM and end metadata. + + PCM has no standard request_id. A turn may contain multiple TTS + requests, so normal request completion does not retire the turn. + """ + + session_id: str + turn_id: int + + @classmethod + def from_metadata(cls, metadata) -> Optional["Turn"]: + """Accept the actual metadata fields, including turn zero.""" + if not isinstance(metadata, dict): + return None + session_id = metadata.get("session_id", "") + turn_id = metadata.get("turn_id") + if ( + not isinstance(session_id, str) + or not isinstance(turn_id, int) + or isinstance(turn_id, bool) + ): + return None + return cls(session_id, turn_id) + + +@dataclass(frozen=True) +class Frame: + """One audio frame as it arrived: PCM int16 mono at ``rate``.""" + + pcm: bytes + rate: int + turn: Optional[Turn] = None + + +@dataclass(frozen=True) +class End: + """An end-of-request marker, applied after every frame queued before it. + + ``label`` is for the log line only. ``tts_reason`` is the + ``tts_audio_end`` reason, so the pacer can apply its reason rules; + ``None`` is an unconditional end (``finalize``). + """ + + label: str + tts_reason: Optional[int] = None + turn: Optional[Turn] = None + request_id: str = "" + + +QueueItem = Union[Frame, End] + + +class InputQueue: + """Frames and end markers waiting for the sender, in arrival order. + + No admission removes older PCM or moves an end marker. The caller must + handle a capacity error as cancellation, never as a normally ended tail. + """ + + def __init__( + self, + max_ms: int = INPUT_QUEUE_MAX_MS, + max_bytes: int = INPUT_QUEUE_MAX_BYTES, + max_items: int = INPUT_QUEUE_MAX_ITEMS, + ) -> None: + self._max_ms = max_ms + self._max_bytes = max_bytes + self._max_items = max_items + self._items: deque[QueueItem] = deque() + self._frames = 0 + self._queued_ms = 0.0 + self._queued_bytes = 0 + self._ready = asyncio.Event() + + def __len__(self) -> int: + return len(self._items) + + @property + def queued_ms(self) -> float: + return self._queued_ms + + def check_capacity( + self, duration: float, byte_count: int, item_count: int + ) -> None: + """Check additional retained data before mutating the FIFO.""" + duration += self._queued_ms + byte_count += self._queued_bytes + item_count += len(self._items) + if ( + duration > self._max_ms + or byte_count > self._max_bytes + or item_count > self._max_items + ): + raise QueueCapacityError(duration, byte_count, item_count) + + @property + def turns(self) -> set[Turn]: + """Identified turns still queued, including end-only requests.""" + return {item.turn for item in self._items if item.turn is not None} + + @property + def has_unidentified(self) -> bool: + """Whether cancellation would include items without turn metadata.""" + return any(item.turn is None for item in self._items) + + def put_audio( + self, pcm: bytes, rate: int, turn: Optional[Turn] = None + ) -> bool: + """Queue a frame without discarding any earlier item.""" + self.check_capacity(duration_ms(pcm, rate), len(pcm), 1) + self._items.append(Frame(pcm, rate, turn)) + self._frames += 1 + self._queued_ms += duration_ms(pcm, rate) + self._queued_bytes += len(pcm) + self._ready.set() + return False + + def put_end(self, end: End) -> None: + self.check_capacity(0.0, 0, 1) + self._items.append(end) + self._ready.set() + + async def get(self) -> QueueItem: + while not self._items: + self._ready.clear() + await self._ready.wait() + item = self._items.popleft() + if isinstance(item, Frame): + self._frames -= 1 + self._queued_ms -= duration_ms(item.pcm, item.rate) + self._queued_bytes -= len(item.pcm) + if self._frames == 0: + self._queued_ms = 0.0 + return item + + def clear(self) -> int: + """Drop everything; returns how many items were dropped.""" + count = len(self._items) + self._items.clear() + self._frames = 0 + self._queued_ms = 0.0 + self._queued_bytes = 0 + self._ready.clear() + return count + + +class AudioSender: + """Drains the input queue into the pacer, in order. + + All methods run on one asyncio loop. The hooks call ``put_audio``, + ``put_end`` and ``flush``; the session callbacks call ``session_up`` and + ``session_down``; ``run`` is the sender task. ``on_request_state`` is + told the pacer's request state after every operation that may change + it, so the session's idle timer knows when a request is open. + """ + + def __init__( + self, + pacer: Pacer, + sample_rate: int, + log: SenderLog, + *, + on_request_state: Callable[[bool], None] = lambda open_: None, + max_queue_ms: int = INPUT_QUEUE_MAX_MS, + max_queue_bytes: int = INPUT_QUEUE_MAX_BYTES, + max_queue_items: int = INPUT_QUEUE_MAX_ITEMS, + ) -> None: + self._pacer = pacer + self._rate = sample_rate + self._log = log + self._on_request_state = on_request_state + self._queue = InputQueue(max_queue_ms, max_queue_bytes, max_queue_items) + self._connected = asyncio.Event() + self._resampler: Optional[Resampler] = None + self._flush_gen = 0 + self._active_turn: Optional[Turn] = None + self._inflight_turn: Optional[Turn] = None + self._inflight_item: Optional[QueueItem] = None + self._legacy_overflowed = False + self._retired_turns: set[Turn] = set() + self._latest_turn_ids: dict[str, int] = {} + self._ended_requests: set[tuple[Optional[Turn], str]] = set() + self._flushing = 0 + self._flush_done = asyncio.Event() + self._flush_done.set() + + # -- observable state --------------------------------------------------- + + @property + def request_open(self) -> bool: + return self._pacer.request_open + + @property + def queued(self) -> int: + """Items still waiting for the sender.""" + return len(self._queue) + + # -- hooks -------------------------------------------------------------- + + def put_audio( + self, pcm: bytes, rate: int, turn: Optional[Turn] = None + ) -> None: + if not pcm: + return + if turn is None and self._legacy_overflowed: + return + if turn is not None and turn in self._retired_turns: + self._log.log_debug("audio ignored: retired turn") + return + self._check_admission(duration_ms(pcm, rate), len(pcm), turn) + self._queue.put_audio(pcm, rate, turn) + + def put_end(self, end: End) -> None: + if end.turn is None and self._legacy_overflowed: + # Without shared metadata, only this ordered request boundary + # proves that later unidentified PCM can belong to a new request. + key = (end.turn, end.request_id) + if end.request_id and key in self._ended_requests: + return + if end.request_id: + self._ended_requests.add(key) + self._legacy_overflowed = False + return + if end.turn is not None and end.turn in self._retired_turns: + return + try: + self._check_admission(0.0, 0, end.turn) + except QueueCapacityError: + if end.turn is None: + # The boundary that hit the item budget still terminates + # the unidentified failed request; never send it as EOF. + self._legacy_overflowed = False + if end.request_id: + self._ended_requests.add((end.turn, end.request_id)) + raise + self._queue.put_end(end) + + def _check_admission( + self, duration: float, byte_count: int, turn: Optional[Turn] + ) -> None: + held = self._inflight_item + if isinstance(held, Frame): + duration += duration_ms(held.pcm, held.rate) + byte_count += len(held.pcm) + try: + self._queue.check_capacity( + duration, byte_count, 1 + int(held is not None) + ) + except QueueCapacityError as error: + # This must precede the extension's awaited cancellation: late + # failed-turn PCM/end cannot become a normal shortened request. + if ( + turn is None + or self._queue.has_unidentified + or (held is not None and held.turn is None) + or (self._active_turn is None and self._pacer.request_open) + ): + self._legacy_overflowed = True + if turn is not None: + self._retired_turns.add(turn) + error.turn = turn + raise + + async def flush(self) -> None: + """Drop everything queued, cancel the turn, interrupt the avatar.""" + self._flush_gen += 1 + self._flushing += 1 + self._flush_done.clear() + self._retired_turns.update(self._queue.turns) + for turn in (self._active_turn, self._inflight_turn): + if turn is not None: + self._retired_turns.add(turn) + self._active_turn = None + dropped = self._queue.clear() + if dropped: + self._log.log_debug(f"flush: dropped {dropped} queued items") + self._reset_resampler() + try: + await self._pacer.flush() + finally: + self._note_request_state() + self._flushing -= 1 + if not self._flushing: + self._flush_done.set() + + def clear(self) -> None: + """Drop the queue without touching the pacer (used at stop).""" + self._flush_gen += 1 + self._queue.clear() + self._legacy_overflowed = False + self._active_turn = None + self._inflight_turn = None + self._inflight_item = None + self._reset_resampler() + self._retired_turns.clear() + self._latest_turn_ids.clear() + self._ended_requests.clear() + + # -- session ------------------------------------------------------------ + + def session_up(self) -> None: + self._pacer.on_session_reset() + self._reset_resampler() + self._note_request_state() + self._connected.set() + + def session_down(self) -> None: + self._connected.clear() + self._pacer.on_session_reset() + self._reset_resampler() + self._note_request_state() + + # -- sender task -------------------------------------------------------- + + async def run(self) -> None: + """Drain the queue until cancelled. + + A frame waits for the session before it is sent, so audio queued + during a reconnect goes out (bounded by the queue) instead of being + lost; a flush that lands during that wait, or while the frame waits + at the pacer's gate, drops it. A frame the session could not take + (it dropped during the gate wait) is held for the next session. A + marker never waits: every frame queued before it has already been + sent or dropped by the time it is dequeued. + """ + while True: + item = await self._queue.get() + self._inflight_item = item + self._inflight_turn = item.turn + try: + if isinstance(item, End): + await self._apply_end(item) + else: + await self._send_frame(item) + except Exception: + # CancelledError derives from BaseException, so cancelling + # the sender task still propagates past this handler. + self._log.log_error(f"sender: {traceback.format_exc()}") + finally: + self._inflight_turn = None + self._inflight_item = None + + async def _send_frame(self, frame: Frame) -> None: + gen = self._flush_gen + # New audio must follow the actual interrupt send. Otherwise an + # awaited old interrupt could reach the sink after the new audio. + await self._flush_done.wait() + if gen != self._flush_gen: + return + if frame.turn is not None: + latest = self._latest_turn_ids.get(frame.turn.session_id) + if frame.turn in self._retired_turns or ( + latest is not None and frame.turn.turn_id < latest + ): + self._log.log_debug("audio ignored: retired turn") + return + # TEN's controller increments turn_id within a session. A + # cancelled turn's first PCM can arrive only after its successor + # starts, so it need not appear in the retired set yet. Update + # on dequeue, not admission: already-queued earlier audio is valid. + self._latest_turn_ids[frame.turn.session_id] = frame.turn.turn_id + if ( + self._active_turn is not None + and frame.turn != self._active_turn + ): + # The next identified turn is an actual boundary, even if + # its predecessor's end was delayed or never delivered. + self._retired_turns.add(self._active_turn) + await self._pacer.end_request("turn changed") + if gen != self._flush_gen: + return + self._reset_resampler() + self._active_turn = frame.turn + converted: Optional[bytes] = None + while True: + await self._connected.wait() + if gen != self._flush_gen or ( + frame.turn is not None and frame.turn in self._retired_turns + ): + # A flush landed while this frame waited for the session: it + # belongs to the cancelled turn. + return + if converted is None: + converted = self._resample(frame.pcm, frame.rate) + if not converted: + return + result = await self._pacer.push_audio(converted) + self._note_request_state() + if result is PushResult.SENT: + return + if result is PushResult.CANCELLED: + self._log.log_debug( + "flush: dropped the frame waiting at the gate" + ) + return + if self._connected.is_set(): + # Refused while the session is still up: a send failure, + # not an outage. There is no reconnect to wait for. + self._log.log_warn( + "send failed while the session is up: dropping the frame" + ) + return + # The session went down between the readiness check and the + # send (a gate wait can last seconds); the frame waits for the + # next session. + self._log.log_debug("send failed: holding the frame for reconnect") + + async def _apply_end(self, end: End) -> None: + gen = self._flush_gen + await self._flush_done.wait() + if gen != self._flush_gen: + return + if end.turn is not None and ( + end.turn in self._retired_turns + or (self._active_turn is not None and end.turn != self._active_turn) + ): + self._log.log_debug(f"end ignored: stale turn; {end.label}") + return + key = (end.turn, end.request_id) + if end.request_id and key in self._ended_requests: + self._log.log_debug(f"end ignored: duplicate request; {end.label}") + return + if end.request_id: + self._ended_requests.add(key) + # A matching identified end belongs to this turn, including reason + # 2 after a prior flush. Keep the legacy reason guard only when no + # common turn identity is available. + if end.tts_reason is None or ( + end.turn is not None and end.turn == self._active_turn + ): + closed = await self._pacer.end_request(end.label) + else: + closed = await self._pacer.on_tts_audio_end(end.tts_reason) + self._note_request_state() + if closed: + self._reset_resampler() + self._log.log_info(f"request closed: {end.label}") + else: + self._log.log_debug( + f"end ignored: {end.label} " + f"request_open={self._pacer.request_open}" + ) + + # -- helpers ------------------------------------------------------------ + + def _resample(self, pcm: bytes, rate: int) -> bytes: + if self._resampler is None or self._resampler.src_rate != rate: + if self._resampler is not None: + self._log.log_info( + f"input sample rate changed " + f"{self._resampler.src_rate} -> {rate}" + ) + self._resampler = Resampler(rate, self._rate) + return self._resampler.convert(pcm) + + def _reset_resampler(self) -> None: + if self._resampler is not None: + self._resampler.reset() + + def _note_request_state(self) -> None: + self._on_request_state(self._pacer.request_open) diff --git a/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/session_client.py b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/session_client.py new file mode 100644 index 0000000000..28ef017c6c --- /dev/null +++ b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/session_client.py @@ -0,0 +1,757 @@ +# +# This file is part of TEN Framework, an open source project. +# Licensed under the Apache License, Version 2.0. +# See the LICENSE file for more information. +# +"""SpatialReal session wrapper: one SDK session at a time, plus reconnects. + +Imports ``spatialreal`` only; no TEN. The extension glue owns config, +``ModuleError`` emission and logging, and talks to this module through +``SessionClient``: ``send_audio``/``interrupt`` for the pacer, three +callbacks for state and error reports. + +Every connect is a new SDK session with a fresh session token (``expire_at`` +now + 1 h) and a fresh Agora token. The reconnect decision follows the +observable event: + +* ``start()`` refused: 4001/4010 are fatal, 4003 takes the slow schedule + (30, 60, 120, 300… s, ten attempts, then fatal), 4503 and transport + failures the fast schedule (1, 2, 4, 8, 15, 30… s while running); +* ``start()`` and its capability check not finished within + ``START_TIMEOUT_S`` (the server never confirmed the session): the session + is closed and the fast schedule applies; +* ``init()`` refused with HTTP 400: configuration error, stop; HTTP 401 or + 403 (the API key is invalid or revoked): fatal, stop; other token + failures (5xx, network) take the fast schedule; +* ``on_error`` mid-session: retryable codes and errors with no close code + take the fast schedule; a 4010 relayed as a server error while the + session continues is reported without a reconnect; anything else + non-retryable is fatal; +* ``on_close`` with no preceding error (drain), ``ValueError`` from + ``send_audio`` (connection gone) and ``transport_frames`` (animation over + the WebSocket: egress lost the channel) take the fast schedule; +* idle for ``egress_idle_reconnect_ms`` with no request open: reconnect at + once, before egress's own inactivity timeout drops the channel. + +An outage reports ``1001`` once when it begins and ``-1`` if the client +gives up; a planned idle reconnect reports nothing. SDK callbacks are +marshalled onto the loop with ``call_soon_threadsafe`` and bound to the +session that registered them, so a callback that arrives after that session +was torn down is dropped. One that arrives after the server confirmed the +session but before the connection is published is held and resolved then: a +close or retryable error makes it a failed connect on the fast schedule, a +fatal error stops without ever reporting the session connected. +""" + +import asyncio +import logging +import time +from dataclasses import dataclass +from datetime import datetime, timedelta, timezone +from enum import Enum +from typing import Awaitable, Callable, Optional, Sequence + +import spatialreal +from spatialreal import ( + AgoraEgressConfig, + AvatarSDKError, + SessionTokenError, + new_avatar_session, +) + +from .agora_token import build_agora_token + +logger = logging.getLogger(__name__) + +FAST_BACKOFF_S: Sequence[float] = (1, 2, 4, 8, 15, 30) +SLOW_BACKOFF_S: Sequence[float] = (30, 60, 120, 300) +SLOW_MAX_ATTEMPTS = 10 +SESSION_TOKEN_TTL_S = 3600 +# Deadline for the handshake: endpoint lookup, WebSocket upgrade, the +# ServerConfirmSession frame (which the SDK awaits with no timeout of its own) +# and the capability check that follows it. +START_TIMEOUT_S = 20.0 +EGRESS_IDLE_RECONNECT_MS = 1_080_000 +# How often the idle timer re-checks while a request is still open. +IDLE_RECHECK_S = 1.0 + +CODE_CONFIG = -1012 +CODE_FATAL = -1 +CODE_NON_FATAL = 1001 + +_CLOSE_CREDITS = 4001 +_CLOSE_CONCURRENCY = 4003 +_CLOSE_AUTH = 4010 +# Token exchange (console API) statuses that retrying cannot change. +_TOKEN_BAD_REQUEST = 400 +_TOKEN_REFUSED = (401, 403) + + +@dataclass +class SessionSettings: + """Everything a connect needs; validated by the glue before it gets here.""" + + api_key: str + avatar_id: str + app_id: str = "" + environment: str = "us-west" + console_endpoint_url: str = "" + ingress_endpoint_url: str = "" + sample_rate: int = 24000 + channel: str = "" + uid: int = 0 + agora_appid: str = "" + agora_appcert: str = "" + agora_token: str = "" + egress_idle_reconnect_ms: int = EGRESS_IDLE_RECONNECT_MS + source_timeline_only: bool = True + source_playback_profile: Optional[int] = None + + def __post_init__(self) -> None: + if self.source_playback_profile is None: + self.source_playback_profile = 1 if self.source_timeline_only else 0 + + +@dataclass +class ErrorReport: + """What the glue turns into a ``ModuleError``.""" + + code: int # CODE_FATAL | CODE_NON_FATAL | CODE_CONFIG + # WS close code or token-exchange HTTP status as a string, or the + # exception class name. + vendor_code: str + message: str + session_id: str = "" + + +class Decision(Enum): + FAST = "fast" + SLOW = "slow" + STOP = "stop" + REPORT_ONLY = "report_only" + CONFIG = "config" + + +def _vendor_code(exc: Exception) -> str: + close_code = getattr(exc, "close_code", None) + if close_code is not None: + return str(close_code) + if isinstance(exc, SessionTokenError) and exc.http_status is not None: + return str(exc.http_status) + return type(exc).__name__ + + +def classify_start_error( + exc: Exception, *, source_timeline_only: bool = False +) -> tuple[Decision, int, str]: + """Decide on an exception from ``init()`` or ``start()``.""" + vendor = _vendor_code(exc) + unsupported_config = getattr( + spatialreal, "UnsupportedConfigurationError", None + ) + if ( + source_timeline_only + and unsupported_config is not None + and isinstance(exc, unsupported_config) + ): + return Decision.CONFIG, CODE_CONFIG, vendor + if isinstance(exc, SessionTokenError): + if exc.http_status == _TOKEN_BAD_REQUEST: + return Decision.CONFIG, CODE_CONFIG, vendor + if exc.http_status in _TOKEN_REFUSED: + # The console refused the API key: no session will ever be + # minted with it, so the 4010 handling downstream never runs. + return Decision.STOP, CODE_FATAL, vendor + return Decision.FAST, CODE_NON_FATAL, vendor + if isinstance(exc, AvatarSDKError): + if exc.close_code is None: + # No close code: transport failure, a frame that did not parse, + # or a ServerError with no session-fate code: fast schedule. + return Decision.FAST, CODE_NON_FATAL, vendor + if exc.close_code in (_CLOSE_CREDITS, _CLOSE_AUTH): + return Decision.STOP, CODE_FATAL, vendor + if exc.close_code == _CLOSE_CONCURRENCY: + return Decision.SLOW, CODE_NON_FATAL, vendor + if exc.retryable: + return Decision.FAST, CODE_NON_FATAL, vendor + return Decision.STOP, CODE_FATAL, vendor + if isinstance(exc, ValueError): + # The SDK raises ValueError for a request it cannot build (missing + # key, bad endpoint scheme): retrying changes nothing. + return Decision.CONFIG, CODE_CONFIG, vendor + return Decision.FAST, CODE_NON_FATAL, vendor + + +def classify_runtime_error(exc: Exception) -> tuple[Decision, int, str]: + """Decide on an exception from ``on_error`` or a send.""" + vendor = _vendor_code(exc) + if isinstance(exc, AvatarSDKError): + if exc.close_code is None or exc.retryable: + # Retryable codes and the absence of a close code (a failed + # inference call relayed as ServerError{code: 0}, a frame that + # did not parse, a transport drop) both take the fast schedule. + return Decision.FAST, CODE_NON_FATAL, vendor + if exc.close_code == _CLOSE_AUTH and exc.server_code: + # A server error frame, not a close: inference auth failed but + # the session continues. + return Decision.REPORT_ONLY, CODE_NON_FATAL, vendor + return Decision.STOP, CODE_FATAL, vendor + return Decision.FAST, CODE_NON_FATAL, vendor + + +class SessionClient: + """Keeps one SpatialReal session up for the lifetime of the extension. + + All methods run on one asyncio loop. ``start()`` spawns the connect + loop and returns; ``stop()`` ends everything. ``connected`` and + ``connection_id`` are readable at any time. + """ + + def __init__( + self, + settings: SessionSettings, + *, + on_report: Callable[[ErrorReport], None], + on_connected: Callable[[str], None], + on_disconnected: Callable[[], None], + session_factory: Callable[..., object] = new_avatar_session, + clock: Callable[[], float] = time.monotonic, + sleep: Callable[[float], Awaitable[None]] = asyncio.sleep, + fast_backoff: Sequence[float] = FAST_BACKOFF_S, + slow_backoff: Sequence[float] = SLOW_BACKOFF_S, + slow_max_attempts: int = SLOW_MAX_ATTEMPTS, + start_timeout_s: float = START_TIMEOUT_S, + ) -> None: + self._settings = settings + self._on_report = on_report + self._on_connected = on_connected + self._on_disconnected = on_disconnected + self._factory = session_factory + self._clock = clock + self._sleep = sleep + self._fast_backoff = tuple(fast_backoff) + self._slow_backoff = tuple(slow_backoff) + self._slow_max_attempts = slow_max_attempts + self._start_timeout_s = start_timeout_s + + self.connected = False + self.connection_id = "" + + self._loop: Optional[asyncio.AbstractEventLoop] = None + self._run_task: Optional[asyncio.Task] = None + self._idle_task: Optional[asyncio.Task] = None + self._session = None + # Incremented per connect attempt and again at teardown; callbacks + # carry the value they were registered with. + self._gen = 0 + self._closing = False + self._stopped = False + self._wake = asyncio.Event() + self._pending: Optional[tuple[Decision, bool]] = None + # The attempt whose handshake is in progress, and the first decisive + # callback it received before the connection was published: the SDK + # starts its read loop inside ``start()``, so the server can close or + # fail the session before ``_connect_once()`` resumes. + self._startup_gen = 0 + self._startup_failure: Optional[tuple[Decision, int, str, str]] = None + self._last_vendor_code = "" + self._outage_reported = False + self._fast_index = 0 + self._slow_attempts = 0 + self._last_rpc_at = clock() + self._request_open = False + + # -- lifecycle ---------------------------------------------------------- + + async def start(self) -> None: + """Spawn the connect loop; returns immediately.""" + if self._run_task is not None or self._stopped: + return + self._loop = asyncio.get_running_loop() + self._run_task = self._loop.create_task(self._run()) + + async def stop(self) -> None: + """End reconnection, cancel the loop and timer, close the session.""" + self._stopped = True + self._closing = True + task, self._run_task = self._run_task, None + if task is not None and task is not asyncio.current_task(): + task.cancel() + try: + await task + except asyncio.CancelledError: + pass + self._cancel_idle_timer() + session, self._session = self._session, None + self._mark_disconnected() + if session is not None: + await self._close_quietly(session) + + def note_request_state(self, open_: bool) -> None: + """The idle timer only reconnects while no request is open.""" + self._request_open = open_ + + # -- audio -------------------------------------------------------------- + + async def send_audio(self, pcm: bytes, end: bool = False) -> bool: + """Forward one chunk; False when not connected or the send failed.""" + session = self._session + if not self.connected or session is None: + return False + try: + await session.send_audio(pcm, end=end) + except ValueError as exc: + # The SDK's "connection is not established": the socket is gone + # and no callback may have told us yet. + self._request_reconnect(Decision.FAST, _vendor_code(exc), str(exc)) + return False + except AvatarSDKError as exc: + self._handle_runtime_exception(exc) + return False + self._last_rpc_at = self._clock() + return True + + async def interrupt(self) -> bool: + """Interrupt the last request; False when there was none to cut.""" + session = self._session + if not self.connected or session is None: + return False + try: + await session.interrupt() + except ValueError: + # "no request to interrupt" is benign; a lost connection also + # raises ValueError here but surfaces through on_close or the + # next send, so it is not treated as a drop. + return False + except AvatarSDKError as exc: + self._handle_runtime_exception(exc) + return False + self._last_rpc_at = self._clock() + return True + + # -- connect loop ------------------------------------------------------- + + async def _run(self) -> None: + while not self._stopped: + self._wake.clear() + connected = await self._connect_once() + if connected: + await self._wake.wait() + await self._teardown() + if self._stopped: + return + decision, immediate = self._pending or (Decision.FAST, False) + self._pending = None + delay = 0.0 if immediate else self._next_delay(decision) + if delay is None: + self._report( + CODE_FATAL, + self._last_vendor_code, + "gave up after %d reconnect attempts" + % self._slow_max_attempts, + ) + self._stopped = True + return + if delay > 0: + await self._sleep(delay) + + async def _connect_once(self) -> bool: + s = self._settings + self._gen += 1 + gen = self._gen + self._startup_gen = gen + self._startup_failure = None + loop = self._loop + session = None + try: + expire_at = datetime.now(timezone.utc) + timedelta( + seconds=SESSION_TOKEN_TTL_S + ) + egress_options = {} + sdk_fields = getattr(AgoraEgressConfig, "__dataclass_fields__", {}) + # Preserve explicit compatibility even when the SDK itself now + # defaults to burst. Old SDKs must not receive unknown keywords. + if "source_timeline_only" in sdk_fields: + egress_options["source_timeline_only"] = s.source_timeline_only + if "source_playback_profile" in sdk_fields: + egress_options["source_playback_profile"] = ( + s.source_playback_profile + ) + if s.source_timeline_only: + has_source_field = "source_timeline_only" in getattr( + AgoraEgressConfig, "__dataclass_fields__", {} + ) + has_ack_check = ( + getattr(spatialreal, "UnsupportedConfigurationError", None) + is not None + ) + if not (has_source_field and has_ack_check): + raise ValueError( + "params.source_timeline_only requires a SpatialReal " + "SDK with source-timeline-only handshake support" + ) + egress_options["source_timeline_only"] = True + if s.source_playback_profile: + profile_type = getattr( + spatialreal, "RtcSourcePlaybackProfile", None + ) + has_profile_field = "source_playback_profile" in getattr( + AgoraEgressConfig, "__dataclass_fields__", {} + ) + if not ( + s.source_timeline_only + and has_profile_field + and profile_type is not None + ): + raise ValueError( + "params.source_playback_profile requires source-only " + "mode and a SpatialReal SDK with burst profile support" + ) + egress_options["source_playback_profile"] = profile_type( + s.source_playback_profile + ) + egress = AgoraEgressConfig( + channel_name=s.channel, + token=build_agora_token( + s.agora_appid, + s.agora_appcert, + s.channel, + s.uid, + explicit_token=s.agora_token, + ), + uid=s.uid, + **egress_options, + ) + kwargs = { + "api_key": s.api_key, + "avatar_id": s.avatar_id, + "expire_at": expire_at, + "sample_rate": s.sample_rate, + "environment": s.environment, + "agora_egress": egress, + "on_error": lambda exc: loop.call_soon_threadsafe( + self._handle_error, gen, exc + ), + "on_close": lambda: loop.call_soon_threadsafe( + self._handle_close, gen + ), + "transport_frames": lambda payload, end: ( + loop.call_soon_threadsafe( + self._handle_transport_frames, gen + ) + ), + } + if s.app_id: + kwargs["app_id"] = s.app_id + if s.console_endpoint_url: + kwargs["console_endpoint_url"] = s.console_endpoint_url + if s.ingress_endpoint_url: + kwargs["ingress_endpoint_url"] = s.ingress_endpoint_url + session = self._factory(**kwargs) + self._session = session + await session.init() + connection_id = await self._start_with_deadline(session) + except Exception as exc: + self._startup_gen = 0 + decision, code, vendor = classify_start_error( + exc, source_timeline_only=s.source_timeline_only + ) + await self._abandon_attempt( + session, decision, code, vendor, str(exc) + ) + return False + + self._startup_gen = 0 + failure, self._startup_failure = self._startup_failure, None + if failure is not None: + # The session confirmed, then closed or failed before it was + # published: a failed connect, never a connected one. + await self._abandon_attempt(session, *failure) + return False + + self.connected = True + self.connection_id = connection_id or "" + self._fast_index = 0 + self._slow_attempts = 0 + self._outage_reported = False + self._last_rpc_at = self._clock() + self._start_idle_timer(gen) + self._on_connected(self.connection_id) + return True + + async def _abandon_attempt( + self, + session, + decision: Decision, + code: int, + vendor: str, + message: str, + ) -> None: + """Close a connect attempt that did not produce a live session, then + stop or schedule the retry its decision calls for.""" + if session is not None: + # start() may have joined before the capability check failed, + # and a timed-out start() was cancelled, which skips the SDK's + # own cleanup of the half-open socket. Invalidate callbacks + # before the (idempotent) close, and retain ownership until + # that close has completed. + self._gen += 1 + await self._close_quietly(session) + self._session = None + logger.warning( + "spatialreal connect failed (%s, %s): %s", + vendor, + decision.value, + message, + ) + self._last_vendor_code = vendor + if decision in (Decision.STOP, Decision.CONFIG): + self._report(code, vendor, message) + self._stopped = True + else: + self._pending = (decision, False) + self._report_outage(vendor, message) + + async def _start_with_deadline(self, session) -> str: + """The whole handshake, or ``TimeoutError`` after the deadline. + + The deadline covers ``session.start()`` and the capability + confirmation that follows it. On a timeout (or cancellation) the + pending handshake is cancelled; the caller then closes the session. + """ + starter = asyncio.ensure_future(self._start_and_confirm(session)) + timer = asyncio.ensure_future(self._sleep(self._start_timeout_s)) + try: + await asyncio.wait( + {starter, timer}, return_when=asyncio.FIRST_COMPLETED + ) + finally: + timer.cancel() + if not starter.done(): + starter.cancel() + if not starter.done() or starter.cancelled(): + raise TimeoutError( + "session start not confirmed within %.0f s" + % self._start_timeout_s + ) + return starter.result() + + async def _start_and_confirm(self, session) -> str: + """``session.start()``, then the capability check for the requested + source playback profile.""" + connection_id = await session.start() + if self._settings.source_playback_profile: + capabilities = getattr(session, "capabilities", ()) + if not isinstance(capabilities, tuple) or not all( + capability in capabilities + for capability in ( + "agora_source_timeline_only", + "agora_source_burst_v1", + ) + ): + raise spatialreal.UnsupportedConfigurationError( + "Server did not confirm the requested source profile", + connection_id=connection_id, + ) + return connection_id + + def _next_delay(self, decision: Decision) -> Optional[float]: + if decision is Decision.SLOW: + self._slow_attempts += 1 + if self._slow_attempts > self._slow_max_attempts: + return None + index = min(self._slow_attempts - 1, len(self._slow_backoff) - 1) + return self._slow_backoff[index] + index = min(self._fast_index, len(self._fast_backoff) - 1) + self._fast_index += 1 + return self._fast_backoff[index] + + async def _teardown(self) -> None: + """Close the current session; stale callbacks are dropped afterwards.""" + self._cancel_idle_timer() + session = self._session + if session is None: + return + self._closing = True + try: + await self._close_quietly(session) + finally: + self._closing = False + self._gen += 1 + if self._session is session: + self._session = None + + @staticmethod + async def _close_quietly(session) -> None: + try: + await session.close() + except Exception: + logger.exception("spatialreal session close raised") + + # -- events ------------------------------------------------------------- + + def _stale(self, gen: int) -> bool: + return ( + gen != self._gen + or self._closing + or self._stopped + or self._session is None + ) + + def _starting(self, gen: int) -> bool: + return gen == self._startup_gen and not self._stale(gen) + + def _record_startup_failure( + self, decision: Decision, code: int, vendor: str, message: str + ) -> None: + """Keep the first event of the handshake window; a fatal one + replaces an earlier retryable one, as it would once connected.""" + if self._startup_failure is None or ( + decision is Decision.STOP + and self._startup_failure[0] is not Decision.STOP + ): + self._startup_failure = (decision, code, vendor, message) + + def _handle_error(self, gen: int, exc: Exception) -> None: + if self._stale(gen): + return + if self._starting(gen): + decision, code, vendor = classify_runtime_error(exc) + if decision is not Decision.REPORT_ONLY: + self._record_startup_failure(decision, code, vendor, str(exc)) + return + self._handle_runtime_exception(exc) + + def _handle_runtime_exception(self, exc: Exception) -> None: + decision, code, vendor = classify_runtime_error(exc) + logger.warning( + "spatialreal session error (%s, %s): %s", + vendor, + decision.value, + exc, + ) + if decision is Decision.REPORT_ONLY: + self._report(code, vendor, str(exc)) + elif decision is Decision.STOP: + self._fail_fatally(vendor, str(exc)) + else: + self._request_reconnect(Decision.FAST, vendor, str(exc)) + + def _handle_close(self, gen: int) -> None: + if self._stale(gen): + return + if self._starting(gen): + self._record_startup_failure( + Decision.FAST, + CODE_NON_FATAL, + "on_close", + "session closed by the server", + ) + return + self._request_reconnect( + Decision.FAST, "on_close", "session closed by the server" + ) + + def _handle_transport_frames(self, gen: int) -> None: + if self._stale(gen): + return + if self._starting(gen): + self._record_startup_failure( + Decision.FAST, + CODE_NON_FATAL, + "transport_frames", + "animation arrived over the WebSocket: egress left the channel", + ) + return + self._request_reconnect( + Decision.FAST, + "transport_frames", + "animation arrived over the WebSocket: egress left the channel", + ) + + def _request_reconnect( + self, + decision: Decision, + vendor_code: str, + message: str, + *, + immediate: bool = False, + report: bool = True, + ) -> None: + """Tear down and reconnect; a no-op unless currently connected, so + the first event of an outage wins and the rest are ignored.""" + if self._stopped or not self.connected: + return + self._pending = (decision, immediate) + self._last_vendor_code = vendor_code + if report: + self._report_outage(vendor_code, message) + self._mark_disconnected() + self._wake.set() + + def _fail_fatally(self, vendor_code: str, message: str) -> None: + if self._stopped: + return + self._report(CODE_FATAL, vendor_code, message) + self._stopped = True + self._pending = (Decision.STOP, False) + self._mark_disconnected() + self._wake.set() + + def _mark_disconnected(self) -> None: + if not self.connected: + return + self.connected = False + self.connection_id = "" + self._on_disconnected() + + # -- reports ------------------------------------------------------------ + + def _report(self, code: int, vendor_code: str, message: str) -> None: + self._on_report( + ErrorReport(code, vendor_code, message, self.connection_id) + ) + + def _report_outage(self, vendor_code: str, message: str) -> None: + """Report 1001 once per outage; later attempts stay quiet.""" + if self._outage_reported: + return + self._outage_reported = True + self._report(CODE_NON_FATAL, vendor_code, message) + + # -- idle timer --------------------------------------------------------- + + def _start_idle_timer(self, gen: int) -> None: + self._cancel_idle_timer() + if self._settings.egress_idle_reconnect_ms <= 0 or self._loop is None: + return + self._idle_task = self._loop.create_task(self._idle_loop(gen)) + + def _cancel_idle_timer(self) -> None: + task, self._idle_task = self._idle_task, None + if task is not None and task is not asyncio.current_task(): + task.cancel() + + async def _idle_loop(self, gen: int) -> None: + idle_s = self._settings.egress_idle_reconnect_ms / 1000.0 + while not self._stale(gen): + remaining = idle_s - (self._clock() - self._last_rpc_at) + if remaining > 0: + await self._sleep(remaining) + continue + if self._request_open: + await self._sleep(IDLE_RECHECK_S) + continue + logger.info( + "spatialreal session idle for %.0f s: reconnecting before " + "egress drops the channel", + idle_s, + ) + self._request_reconnect( + Decision.FAST, + "idle", + "planned idle reconnect", + immediate=True, + report=False, + ) + return diff --git a/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/bin/start b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/bin/start new file mode 100755 index 0000000000..41da3fdb45 --- /dev/null +++ b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/bin/start @@ -0,0 +1,21 @@ +#!/bin/bash + +set -e + +cd "$(dirname "${BASH_SOURCE[0]}")/../.." + +export PYTHONPATH=.ten/app:.ten/app/ten_packages/system/ten_runtime_python/lib:.ten/app/ten_packages/system/ten_runtime_python/interface:.ten/app/ten_packages/system/ten_ai_base/interface:$PYTHONPATH + +# If the Python app imports some modules that are compiled with a different +# version of libstdc++ (ex: PyTorch), the Python app may encounter confusing +# errors. To solve this problem, we can preload the correct version of +# libstdc++. +# +# export LD_PRELOAD=/lib/x86_64-linux-gnu/libstdc++.so.6 +# +# Another solution is to make sure the module 'ten_runtime_python' is imported +# _after_ the module that requires another version of libstdc++ is imported. +# +# Refer to https://github.com/pytorch/pytorch/issues/102360?from_wecom=1#issuecomment-1708989096 + +pytest tests/ "$@" diff --git a/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/conftest.py b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/conftest.py new file mode 100644 index 0000000000..70f6861036 --- /dev/null +++ b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/conftest.py @@ -0,0 +1,81 @@ +# +# This file is part of TEN Framework, an open source project. +# Licensed under the Apache License, Version 2.0. +# See the LICENSE file for more information. +# +"""Pure fixtures shared by the unit tests. + +Nothing here imports ``ten_runtime``, ``ten_ai_base`` or ``spatialreal`` so +these tests run on any laptop with pytest. Runtime tests that need the TEN +runtime live under ``tests/runtime/`` behind an ``importorskip`` guard. + +The pure modules import their siblings relatively (``from .audio import``), +the way the TEN addon loader imports the extension as a package. The tests +reach them as ``spatialreal_avatar_python.`` through a stub package +whose ``__path__`` is the extension directory, so the real ``__init__`` +(which imports ``ten_runtime``) never runs here. + +The coroutine tests (``@pytest.mark.asyncio``) run under pytest-asyncio when +it is installed. The TEN CI image has pytest without pytest-asyncio, where +pytest 8 skips coroutine tests and pytest 9 fails them, so without the plugin +``pytest_pyfunc_call`` below runs each coroutine on a fresh event loop. All +fixtures are synchronous, which is what keeps this fallback small. +""" + +import asyncio +import inspect +import pathlib +import sys +import types + +import pytest + +_pkg = types.ModuleType("spatialreal_avatar_python") +_pkg.__path__ = [str(pathlib.Path(__file__).resolve().parents[1])] +sys.modules.setdefault("spatialreal_avatar_python", _pkg) + + +def _has_pytest_asyncio(config: pytest.Config) -> bool: + return config.pluginmanager.hasplugin("asyncio") + + +def pytest_configure(config: pytest.Config) -> None: + if not _has_pytest_asyncio(config): + config.addinivalue_line( + "markers", + "asyncio: coroutine test, run on a fresh event loop when " + "pytest-asyncio is not installed", + ) + + +@pytest.hookimpl(tryfirst=True) +def pytest_pyfunc_call(pyfuncitem: pytest.Function): + if _has_pytest_asyncio(pyfuncitem.config): + return None + func = pyfuncitem.obj + if not inspect.iscoroutinefunction(func): + return None + names = inspect.signature(func).parameters + kwargs = { + n: pyfuncitem.funcargs[n] for n in names if n in pyfuncitem.funcargs + } + asyncio.run(func(**kwargs)) + return True + + +class FakeClock: + """A clock the test advances by hand; ``now()`` is in seconds.""" + + def __init__(self, start_s: float = 1000.0): + self._now_s = start_s + + def now(self) -> float: + return self._now_s + + def advance(self, ms: float) -> None: + self._now_s += ms / 1000.0 + + +@pytest.fixture +def clock() -> FakeClock: + return FakeClock() diff --git a/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/runtime/conftest.py b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/runtime/conftest.py new file mode 100644 index 0000000000..f3ed5e3840 --- /dev/null +++ b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/runtime/conftest.py @@ -0,0 +1,102 @@ +# +# This file is part of TEN Framework, an open source project. +# Licensed under the Apache License, Version 2.0. +# See the LICENSE file for more information. +# +import pytest + +pytest.importorskip("ten_runtime") + +import json +import threading +from typing_extensions import override +from ten_runtime import ( + App, + TenEnv, +) + + +class FakeApp(App): + def __init__(self): + super().__init__() + self.event: threading.Event | None = None + + # In the case of a fake app, we use `on_init` to allow the blocked testing + # fixture to continue execution, rather than using `on_configure`. The + # reason is that in the TEN runtime C core, the relationship between the + # addon manager and the (fake) app is bound after `on_configure_done` is + # called. So we only need to let the testing fixture continue execution + # after this action in the TEN runtime C core, and at the upper layer + # timing, the earliest point is within the `on_init()` function of the upper + # TEN app. Therefore, we release the testing fixture lock within the user + # layer's `on_init()` of the TEN app. + @override + def on_init(self, ten_env: TenEnv) -> None: + assert self.event + self.event.set() + + ten_env.on_init_done() + + @override + def on_configure(self, ten_env: TenEnv) -> None: + ten_env.init_property_from_json( + json.dumps( + { + "ten": { + "log": { + "handlers": [ + { + "matchers": [{"level": "debug"}], + "formatter": { + "type": "plain", + "colored": True, + }, + "emitter": { + "type": "console", + "config": {"stream": "stdout"}, + }, + } + ] + } + } + } + ), + ) + + ten_env.on_configure_done() + + +class FakeAppCtx: + def __init__(self, event: threading.Event): + self.fake_app: FakeApp | None = None + self.event = event + + +def run_fake_app(fake_app_ctx: FakeAppCtx): + app = FakeApp() + app.event = fake_app_ctx.event + fake_app_ctx.fake_app = app + app.run(False) + + +@pytest.fixture(scope="session", autouse=True) +def global_setup_and_teardown(): + event = threading.Event() + fake_app_ctx = FakeAppCtx(event) + + fake_app_thread = threading.Thread( + target=run_fake_app, args=(fake_app_ctx,) + ) + fake_app_thread.start() + + event.wait() + + assert fake_app_ctx.fake_app is not None + + # Yield control to the test; after the test execution is complete, continue + # with the teardown process. + yield + + # Teardown part. + fake_app_ctx.fake_app.close() + fake_app_thread.join() diff --git a/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/runtime/test_basic.py b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/runtime/test_basic.py new file mode 100644 index 0000000000..a45006436b --- /dev/null +++ b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/runtime/test_basic.py @@ -0,0 +1,118 @@ +# +# This file is part of TEN Framework, an open source project. +# Licensed under the Apache License, Version 2.0. +# See the LICENSE file for more information. +# +import json +from typing import Optional +from ten_runtime import ( + AsyncExtensionTester, + AsyncTenEnvTester, + Cmd, + CmdResult, + Data, + ExtensionTester, + StatusCode, + TenEnvTester, + TenError, +) + + +class ExtensionTesterBasic(ExtensionTester): + def check_hello( + self, + ten_env: TenEnvTester, + result: Optional[CmdResult], + error: Optional[TenError], + ): + if error is not None: + assert False, error.error_message() + + assert result is not None + + statusCode = result.get_status_code() + ten_env.log_debug(f"receive hello_world, status: {statusCode}") + + if statusCode == StatusCode.OK: + ten_env.stop_test() + + def on_start(self, ten_env: TenEnvTester) -> None: + new_cmd = Cmd.create("hello_world") + + ten_env.log_debug("send hello_world") + ten_env.send_cmd( + new_cmd, + lambda ten_env, result, error: self.check_hello( + ten_env, result, error + ), + ) + + ten_env.log_debug("tester on_start_done") + ten_env.on_start_done() + + +def test_basic(): + tester = ExtensionTesterBasic() + tester.set_test_mode_single("spatialreal_avatar_python") + tester.run() + + +class ExtensionTesterConfigError(AsyncExtensionTester): + """Starts the extension with invalid params and waits for data ``error``.""" + + def __init__(self): + super().__init__() + self.error: Optional[dict] = None + + async def on_start(self, ten_env: AsyncTenEnvTester) -> None: + ten_env.log_debug("tester on_start: waiting for the config error") + + async def on_data(self, ten_env: AsyncTenEnvTester, data: Data) -> None: + if data.get_name() != "error": + return + json_str, _ = data.get_property_to_json(None) + self.error = json.loads(json_str) + ten_env.log_debug(f"received error: {self.error}") + ten_env.stop_test() + + +def test_config_error_uses_module_error(): + # The SpatialReal keys and the channel are set, so validation gets past + # the first checks and fails on ``agora_uid``. An empty ``params`` dict + # would fail on ``spatialreal_api_key`` instead, so a message naming + # ``agora_uid`` proves the ``params`` object reached ``resolve_config`` + # as a dict. on_start reports the -1012 configuration error and + # leaves the extension idle; it must not raise and must not connect. + invalid_params = { + "channel": "test-channel", + "params": { + "spatialreal_api_key": "test-api-key-not-real", + "spatialreal_avatar_id": "test-avatar-id", + "agora_appid": "test-appid", + "agora_uid": "abc", + }, + } + tester = ExtensionTesterConfigError() + tester.set_test_mode_single( + "spatialreal_avatar_python", json.dumps(invalid_params) + ) + error = tester.run() + assert error is None, error.error_message() + + assert tester.error is not None + assert tester.error["module"] == "avatar" + assert tester.error["code"] == -1012 + assert "agora_uid" in tester.error["message"] + assert "spatialreal_api_key" not in tester.error["message"] + vendor_info = tester.error["vendor_info"] + assert vendor_info["vendor"] == "spatialreal" + assert vendor_info["code"] == "ValueError" + metadata = tester.error["metadata"] + assert metadata["session_id"] == "" + vendor_metadata = metadata["vendor_metadata"] + assert vendor_metadata["name"] == "spatialreal" + for key in vendor_metadata: + assert "key" not in key + assert "url" not in key + # No empty values travel in vendor_metadata. + assert all(value not in ("", None) for value in vendor_metadata.values()) diff --git a/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/runtime/test_queue_capacity.py b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/runtime/test_queue_capacity.py new file mode 100644 index 0000000000..6939515216 --- /dev/null +++ b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/runtime/test_queue_capacity.py @@ -0,0 +1,294 @@ +# +# This file is part of TEN Framework, an open source project. +# Licensed under the Apache License, Version 2.0. +# See the LICENSE file for more information. +# +"""Native callbacks preserve a startup burst or explicitly cancel overflow. + +The shared FakeApp fixture and addon registration come from the runtime +suite. Production hooks, sender, resampler and pacer remain unchanged; +only the external session, clock and test queue limits are substituted. +""" + +import asyncio +from array import array +import hashlib +import json +import sys + +import pytest +from ten_runtime import AudioFrame, AudioFrameDataFmt, Data + +from test_request_lifecycle import ( + LifecycleTester, + META_A, + META_B, + PCM_A, + RecordingSession, + extension, +) + + +class BlockedSession(RecordingSession): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.release_connection = None + self.release_interrupt = None + self.interrupt_started = False + self.overflow_task = None + self.cancel_hook_on_stop = False + self.cancelled_hook_finished = False + self.stopped = False + self.instance = None + + async def start(self): + self.loop = asyncio.get_running_loop() + self.release_connection = asyncio.Event() + self.release_interrupt = asyncio.Event() + await self.release_connection.wait() + self.callbacks["on_connected"](self.connection_id) + + async def interrupt(self): + self.calls.append(("interrupt", b"")) + self.interrupt_started = True + await self.release_interrupt.wait() + return True + + async def stop(self): + self.stopped = True + if self.cancel_hook_on_stop and self.overflow_task is not None: + # Simulate shutdown cancelling an in-flight external operation. + # A CancelledError escaping the production hook makes the real + # TEN wrapper exit the process, so pytest cannot falsely pass. + assert self.instance._stopping + assert not self.overflow_task.done() + self.overflow_task.cancel() + await self.overflow_task + self.cancelled_hook_finished = True + + +class CapacityTester(LifecycleTester): + def __init__(self, case): + super().__init__(case) + self.module_errors = [] + self.report = {} + + async def on_data(self, _ten_env, data): + if data.get_name() == "error": + raw, error = data.get_property_to_json(None) + assert error is None + self.module_errors.append(json.loads(raw)) + + async def control(self, callback): + async def execute(): + result = callback() + for _ in range(15): + await asyncio.sleep(0) + return result + + future = asyncio.run_coroutine_threadsafe(execute(), self.sink.loop) + return await asyncio.wrap_future(future) + + async def wait_until(self, predicate): + for _ in range(500): + if await self.control(predicate): + return + await asyncio.sleep(0.005) + raise AssertionError("native queue test condition did not settle") + + async def enqueue_audio(self, pcm, metadata, rate=24000): + frame = AudioFrame.create("pcm_frame") + frame.set_sample_rate(rate) + frame.set_bytes_per_sample(2) + frame.set_number_of_channels(1) + frame.set_samples_per_channel(len(pcm) // 2) + frame.set_data_fmt(AudioFrameDataFmt.INTERLEAVE) + frame.set_timestamp(0) + frame.set_property_from_json("metadata", json.dumps(metadata)) + frame.alloc_buf(len(pcm)) + buffer = frame.lock_buf() + buffer[:] = pcm + frame.unlock_buf(buffer) + assert await self.env.send_audio_frame(frame) is None + + async def enqueue_end(self, request, metadata): + data = Data.create("tts_audio_end") + data.set_property_from_json( + None, + json.dumps( + {"request_id": request, "reason": 1, "metadata": metadata} + ), + ) + assert await self.env.send_data(data) is None + + async def hook_completions(self, count): + for _ in range(count): + await asyncio.wait_for(self.acks.get(), 5) + + async def run_case(self): + if self.case == "startup_burst": + samples = array( + "h", ((i * 137) % 60001 - 30000 for i in range(44100 * 26)) + ) + if sys.byteorder != "little": + samples.byteswap() + pcm = samples.tobytes() + chunks = [pcm[i : i + 8820] for i in range(0, len(pcm), 8820)] + # No hook ACK, snapshot or scheduling barrier between frames or + # End: exercise the real independent TEN callback dispatch. + for chunk in chunks: + await self.enqueue_audio(chunk, META_A, rate=44100) + await self.enqueue_end("startup-A", META_A) + await self.hook_completions(len(chunks) + 1) + assert not self.sink.calls + assert not self.module_errors + await self.snapshot(advance_ms=41000) + assert not self.sink.calls, "virtual time must not imply readiness" + await self.control(self.sink.release_connection.set) + await self.wait_until( + lambda: bool(self.sink.calls) + and self.sink.calls[-1][0] == "end" + ) + calls, opened = await self.snapshot() + from ten_packages.extension.spatialreal_avatar_python.audio import ( + Resampler, + ) + + expected = Resampler(44100, 24000).convert(pcm) + actual = b"".join(data for kind, data in calls if kind == "audio") + assert actual == expected + assert calls[-1] == ("end", b"") + assert sum(kind == "end" for kind, _ in calls) == 1 + assert not opened + assert not self.module_errors + self.report = { + "input_samples_44100": len(pcm) // 2, + "input_chunks": len(chunks), + "virtual_wait_ms": 41000, + "output_samples_24000": len(actual) // 2, + "sha256": hashlib.sha256(actual).hexdigest(), + "end_last": True, + } + return + + # The held first frame counts toward a deliberately small budget. + await self.enqueue_audio(PCM_A, META_A) + await self.enqueue_end("old-A", META_A) + await self.hook_completions(2) + await self.enqueue_audio(PCM_A, META_B) + await self.wait_until(lambda: self.sink.interrupt_started) + assert self.sink.calls == [("interrupt", b"")] + + if self.case == "overflow_stop_cancel": + self.sink.cancel_hook_on_stop = True + # The inherited tester calls stop_test after this returns. + # Production on_stop -> fake stop cancels the waiting hook. + return + + # A later end can change the extension's current turn while the + # overflow hook is awaiting interrupt. Error identity must stay B. + meta_c = {**META_A, "turn_id": 3} + await self.enqueue_end("concurrent-C", meta_c) + await self.hook_completions(1) + await self.control(self.sink.release_interrupt.set) + await self.hook_completions(1) + await self.wait_until(lambda: len(self.module_errors) == 1) + error = self.module_errors[0] + assert error["code"] == extension.CODE_NON_FATAL + assert error["vendor_info"]["code"] == "InputQueueOverflow" + assert error["id"] == str(META_B["turn_id"]) + assert error["metadata"]["session_id"] == META_B["session_id"] + assert not any(kind == "end" for kind, _ in self.sink.calls) + await self.control(self.sink.release_connection.set) + await self.wait_until( + lambda: self.sink.instance.sender._inflight_item is None + ) + fresh = {**META_A, "turn_id": 4} + await self.enqueue_audio(PCM_A, fresh) + await self.enqueue_end("fresh-D", fresh) + await self.hook_completions(2) + await self.wait_until(lambda: self.sink.calls[-1][0] == "end") + assert self.sink.calls == [ + ("interrupt", b""), + ("audio", PCM_A), + ("end", b""), + ] + self.report = {"overflow_turn": 2, "fresh_turn_recovered": True} + + +@pytest.mark.parametrize( + "case", ["startup_burst", "overflow_recovery", "overflow_stop_cancel"] +) +def test_queue_capacity_through_native_callbacks(monkeypatch, request, case): + RecordingSession.instances.clear() + tester = CapacityTester(case) + real_pacer = extension.Pacer + real_sender = extension.AudioSender + + def make_pacer(*args, **kwargs): + sink = kwargs.get("sink", args[0] if args else None) + kwargs.update(clock=sink.clock.now, sleep=sink.clock.sleep) + return real_pacer(*args, **kwargs) + + def make_sender(*args, **kwargs): + if case != "startup_burst": + kwargs["max_queue_ms"] = 150 + sender = real_sender(*args, **kwargs) + return sender + + monkeypatch.setattr(extension, "SessionClient", BlockedSession) + monkeypatch.setattr(extension, "Pacer", make_pacer) + monkeypatch.setattr(extension, "AudioSender", make_sender) + cls = extension.SpatialRealAvatarExtension + original_audio = cls.on_audio_frame + original_data = cls.on_data + original_start = cls.on_start + + async def observed_start(self, ten_env): + await original_start(self, ten_env) + if self.client is not None: + self.client.instance = self + + async def observed_audio(self, ten_env, frame): + raw, error = frame.get_property_to_json("metadata") + metadata = json.loads(raw) if raw and error is None else None + if metadata == META_B: + self.client.overflow_task = asyncio.current_task() + await original_audio(self, ten_env, frame) + tester.loop.call_soon_threadsafe( + tester.acks.put_nowait, ("audio", metadata) + ) + + async def observed_data(self, ten_env, data): + await original_data(self, ten_env, data) + tester.loop.call_soon_threadsafe(tester.acks.put_nowait, ("data", None)) + + monkeypatch.setattr(cls, "on_start", observed_start) + monkeypatch.setattr(cls, "on_audio_frame", observed_audio) + monkeypatch.setattr(cls, "on_data", observed_data) + tester.set_test_mode_single( + "spatialreal_avatar_python", + json.dumps( + { + "channel": "synthetic-channel", + "params": { + "spatialreal_api_key": "synthetic-not-a-real-key", + "spatialreal_avatar_id": "synthetic-avatar", + "agora_appid": "synthetic-app", + "agora_uid": "1001", + }, + } + ), + ) + error = tester.run() + assert error is None, error.error_message() + if tester.failure is not None: + raise tester.failure + assert tester.sink.stopped + if case == "overflow_stop_cancel": + assert tester.sink.cancelled_hook_finished + assert not tester.module_errors + assert tester.sink.calls == [("interrupt", b"")] + tester.report = {"cancelled_hook_finished": True, "normal_ends": 0} + for key, value in tester.report.items(): + request.node.user_properties.append((key, value)) diff --git a/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/runtime/test_request_lifecycle.py b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/runtime/test_request_lifecycle.py new file mode 100644 index 0000000000..d10f644a68 --- /dev/null +++ b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/runtime/test_request_lifecycle.py @@ -0,0 +1,317 @@ +# +# This file is part of TEN Framework, an open source project. +# Licensed under the Apache License, Version 2.0. +# See the LICENSE file for more information. +# +"""Native TEN routes -> production hooks/sender/pacer, without network calls. + +The session-scoped FakeApp fixture is shared with the other runtime tests. +Only the external session and clock are replaced. Hook spies delegate to the +production methods and acknowledge completion across the two asyncio loops. +""" + +import asyncio +import importlib +import json +import struct + +import pytest +from ten_runtime import ( + AsyncExtensionTester, + AudioFrame, + AudioFrameDataFmt, + Cmd, + CmdResult, + Data, + StatusCode, +) + + +# Import through the normal addon namespace, not the pure tests' stub package. +# The decorator registers the existing addon once; no test addon is introduced. +extension = importlib.import_module( + "ten_packages.extension.spatialreal_avatar_python.extension" +) + +RATE = 24000 +META_A = {"session_id": "synthetic-session", "turn_id": 1} +META_B = {"session_id": "synthetic-session", "turn_id": 2} +PCM_A = struct.pack(" NOW_S + + +def test_no_cert_returns_app_id(): + assert build_agora_token(APP_ID, "", CHANNEL, UID, now_s=NOW_S) == APP_ID + + +def test_nothing_raises(): + with pytest.raises(ValueError): + build_agora_token("", "", CHANNEL, UID, now_s=NOW_S) + with pytest.raises(ValueError): + build_agora_token("", "c", CHANNEL, UID, now_s=NOW_S) diff --git a/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/test_audio.py b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/test_audio.py new file mode 100644 index 0000000000..237d847fd0 --- /dev/null +++ b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/test_audio.py @@ -0,0 +1,121 @@ +# +# This file is part of TEN Framework, an open source project. +# Licensed under the Apache License, Version 2.0. +# See the LICENSE file for more information. +# +"""Unit tests for the audio helpers: resampling and silence padding. + +Resampling keeps ``audioop.ratecv`` state across chunks so a request that +arrives in 20 ms pieces converts like one that arrives whole; a trailing odd +byte is dropped instead of raising; silence is generated in whole samples. +""" + +import struct + +import pytest + +from spatialreal_avatar_python.audio import ( + ACCEPTED_RATES, + Resampler, + duration_ms, + silence, +) + + +def _tone(rate: int, ms: int, step: int = 7) -> bytes: + """Deterministic non-silent int16 PCM (a sawtooth) of ``ms`` at ``rate``.""" + frames = rate * ms // 1000 + return b"".join( + struct.pack(" dict: + """A complete, valid params object; tests override one key at a time.""" + base = { + "spatialreal_api_key": "k", + "spatialreal_avatar_id": "av", + "agora_uid": "12345", + "agora_appid": APP_ID, + } + base.update(overrides) + return base + + +def test_minimal_valid_config_resolves_with_defaults(): + cfg = resolve_config("room", params()) + assert isinstance(cfg, ResolvedConfig) + assert cfg.api_key == "k" + assert cfg.avatar_id == "av" + assert cfg.channel == "room" + assert cfg.uid == 12345 + assert cfg.agora_appid == APP_ID + assert cfg.agora_appcert == "" + assert cfg.agora_token == "" + assert cfg.app_id == "" + assert cfg.environment == "us-west" + assert cfg.console_endpoint_url == "" + assert cfg.ingress_endpoint_url == "" + assert cfg.sample_rate == 24000 + assert cfg.egress_idle_reconnect_ms == 1_080_000 + assert cfg.source_timeline_only is True + + +@pytest.mark.parametrize("enabled", [False, True]) +def test_source_timeline_only_boolean_passes_through(enabled): + cfg = resolve_config("room", params(source_timeline_only=enabled)) + assert cfg.source_timeline_only is enabled + + +@pytest.mark.parametrize("invalid", [None, 0, 1, "true", "false", {}, []]) +def test_source_timeline_only_rejects_non_boolean(invalid): + with pytest.raises(ValueError, match="params.source_timeline_only"): + resolve_config("room", params(source_timeline_only=invalid)) + + +def test_source_profile_defaults_burst_and_resolves_legacy_override(): + assert resolve_config("room", params()).source_playback_profile == 1 + assert ( + resolve_config( + "room", params(source_timeline_only=False) + ).source_playback_profile + == 0 + ) + cfg = resolve_config( + "room", params(source_timeline_only=True, source_playback_profile=1) + ) + assert cfg.source_playback_profile == 1 + assert SessionSettings(**asdict(cfg)).source_playback_profile == 1 + + +@pytest.mark.parametrize("invalid", [True, False, None, "1", 1.0, -1, 2, 999]) +def test_source_profile_rejects_invalid_values(invalid): + with pytest.raises(ValueError, match="params.source_playback_profile"): + resolve_config( + "room", + params(source_timeline_only=True, source_playback_profile=invalid), + ) + + +def test_source_profile_requires_source_only(): + with pytest.raises(ValueError, match="source_timeline_only"): + resolve_config( + "room", + params(source_timeline_only=False, source_playback_profile=1), + ) + + +def test_agora_channel_in_params_overrides_channel(): + cfg = resolve_config("injected", params(agora_channel="explicit")) + assert cfg.channel == "explicit" + + +def test_uid_string_and_int_parse(): + # Hosted graphs carry the uid as a string, self-hosted graphs as an int + # (Review Focus 5); both must resolve to the same integer. + assert resolve_config("room", params(agora_uid="12345")).uid == 12345 + assert resolve_config("room", params(agora_uid=12345)).uid == 12345 + assert resolve_config("room", params(agora_uid=" 7 ")).uid == 7 + + +@pytest.mark.parametrize("bad", ["abc", "", "0", 0, "1.5", None, "-0"]) +def test_uid_invalid_is_config_error(bad): + with pytest.raises(ValueError) as exc_info: + resolve_config("room", params(agora_uid=bad)) + assert "agora_uid" in str(exc_info.value) + + +def test_channel_precedence_and_hint_message(): + # Top-level channel is used when params.agora_channel is empty ... + assert resolve_config("room", params()).channel == "room" + assert resolve_config("room", params(agora_channel="")).channel == "room" + # ... and when both are empty the message tells the operator how the + # TEN server injects the channel, and names the explicit alternative. + with pytest.raises(ValueError) as exc_info: + resolve_config("", params()) + message = str(exc_info.value) + assert '"channel": ""' in message + assert "agora_channel" in message + + +@pytest.mark.parametrize( + "rate", [8000, 16000, 22050, 24000, 32000, 44100, 48000, "16000"] +) +def test_sample_rate_accepted_values(rate): + assert resolve_config("room", params(sample_rate=rate)).sample_rate == int( + rate + ) + + +@pytest.mark.parametrize("rate", [11025, 0, -1, "fast", "1.5", True]) +def test_sample_rate_must_be_accepted(rate): + with pytest.raises(ValueError) as exc_info: + resolve_config("room", params(sample_rate=rate)) + assert "sample_rate" in str(exc_info.value) + + +def test_appid_required_unless_token(): + with pytest.raises(ValueError) as exc_info: + resolve_config("room", params(agora_appid="")) + message = str(exc_info.value) + assert "agora_appid" in message + assert "agora_token" in message + # An explicit token makes the App ID optional. + cfg = resolve_config("room", params(agora_appid="", agora_token="tok")) + assert cfg.agora_token == "tok" + assert cfg.agora_appid == "" + + +def test_missing_api_key_message_names_key(): + with pytest.raises(ValueError) as exc_info: + resolve_config("room", params(spatialreal_api_key="")) + assert "spatialreal_api_key" in str(exc_info.value) + with pytest.raises(ValueError) as exc_info: + resolve_config( + "room", {k: v for k, v in params().items() if "key" not in k} + ) + assert "spatialreal_api_key" in str(exc_info.value) + + +def test_missing_avatar_id_message_names_key(): + with pytest.raises(ValueError) as exc_info: + resolve_config("room", params(spatialreal_avatar_id="")) + assert "spatialreal_avatar_id" in str(exc_info.value) + + +def test_optional_strings_and_idle_ms_pass_through(): + cfg = resolve_config( + "room", + params( + spatialreal_app_id="app", + agora_appcert="cert", + environment="test", + console_endpoint_url="https://console.example", + ingress_endpoint_url="wss://ingress.example/v2", + egress_idle_reconnect_ms="600000", + ), + ) + assert cfg.app_id == "app" + assert cfg.agora_appcert == "cert" + assert cfg.environment == "test" + assert cfg.console_endpoint_url == "https://console.example" + assert cfg.ingress_endpoint_url == "wss://ingress.example/v2" + assert cfg.egress_idle_reconnect_ms == 600_000 + + +@pytest.mark.parametrize("bad", ["soon", "1.5", False]) +def test_idle_ms_invalid_is_config_error(bad): + with pytest.raises(ValueError) as exc_info: + resolve_config("room", params(egress_idle_reconnect_ms=bad)) + assert "egress_idle_reconnect_ms" in str(exc_info.value) + + +@pytest.mark.parametrize("empty", ["", None]) +def test_integer_knobs_fall_back_to_defaults_when_unset(empty): + # A JSON null or an empty string where an integer belongs is "not set": + # the package defaults apply rather than a config error. + cfg = resolve_config( + "room", params(sample_rate=empty, egress_idle_reconnect_ms=empty) + ) + assert cfg.sample_rate == 24000 + assert cfg.egress_idle_reconnect_ms == 1_080_000 + + +def test_non_string_values_are_rejected_not_coerced(): + # A nested object where a string belongs is a graph authoring error, + # not something to str() silently. + with pytest.raises(ValueError) as exc_info: + resolve_config("room", params(spatialreal_api_key={"k": 1})) + assert "spatialreal_api_key" in str(exc_info.value) + + +def test_resolved_config_maps_onto_session_settings_field_for_field(): + # The glue builds ``SessionSettings(**asdict(cfg))``: the two dataclasses + # must keep the same field names or a connect loses a setting silently. + assert [f.name for f in fields(ResolvedConfig)] == [ + f.name for f in fields(SessionSettings) + ] + cfg = resolve_config("room", params(agora_token="t", environment="dev")) + assert asdict(SessionSettings(**asdict(cfg))) == asdict(cfg) diff --git a/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/test_pacer.py b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/test_pacer.py new file mode 100644 index 0000000000..aef09f4cb4 --- /dev/null +++ b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/test_pacer.py @@ -0,0 +1,857 @@ +# +# This file is part of TEN Framework, an open source project. +# Licensed under the Apache License, Version 2.0. +# See the LICENSE file for more information. +# +"""Unit tests for the request pacer: request boundaries, padding, flush. + +Time never passes for real: the pacer gets the ``FakeClock`` and a fake +``sleep`` that records what was asked and advances the clock, and the +tests call ``tick()`` by hand instead of running the ticker loop. +""" + +import asyncio +import math + +import pytest + +from spatialreal_avatar_python.audio import duration_ms +from spatialreal_avatar_python.pacer import Pacer, PushResult + +pytestmark = pytest.mark.asyncio + +RATE = 24000 + + +class FakeSink: + """Records every call the pacer makes, in order. + + ``connected`` is what ``send_audio`` returns, as the session client + answers False once the session is gone. + """ + + def __init__(self): + self.calls: list[tuple] = [] + self.connected = True + + async def send_audio(self, pcm: bytes, end: bool = False) -> bool: + self.calls.append(("audio", pcm, end)) + return self.connected + + async def interrupt(self) -> bool: + self.calls.append(("interrupt",)) + return self.connected + + @property + def ends(self) -> int: + return sum(1 for c in self.calls if c[0] == "audio" and c[2]) + + @property + def interrupts(self) -> int: + return sum(1 for c in self.calls if c[0] == "interrupt") + + def audio_ms(self, *, silent: bool | None = None) -> float: + """Milliseconds of audio sent; ``silent`` filters zeros / non-zeros.""" + total = 0.0 + for call in self.calls: + if call[0] != "audio" or call[2]: + continue + is_silent = not call[1].strip(b"\x00") + if silent is None or is_silent == silent: + total += duration_ms(call[1], RATE) + return total + + def silence_chunks(self) -> list[bytes]: + return [ + c[1] + for c in self.calls + if c[0] == "audio" and not c[2] and not c[1].strip(b"\x00") + ] + + +class PausingPaddingSink(FakeSink): + """Let another pacer operation run during the first padding send.""" + + def __init__(self): + super().__init__() + self.padding_started = asyncio.Event() + self.release_padding = asyncio.Event() + + async def send_audio(self, pcm: bytes, end: bool = False) -> bool: + result = await super().send_audio(pcm, end=end) + if pcm and not pcm.strip(b"\x00"): + if not self.padding_started.is_set(): + self.padding_started.set() + await self.release_padding.wait() + return result + + +class HoldingRealSink(PausingPaddingSink): + """Hold every real (non-silent) send open until ``release_real`` is set. + + Stands in for a WebSocket send that yields under backpressure. + ``real_started`` is set once such a send has been recorded. + """ + + def __init__(self): + super().__init__() + self.release_padding.set() + self.real_started = asyncio.Event() + self.release_real = asyncio.Event() + self.hold = False + + async def send_audio(self, pcm: bytes, end: bool = False) -> bool: + if self.hold and pcm and pcm.strip(b"\x00"): + self.calls.append(("audio", pcm, end)) + self.real_started.set() + await self.release_real.wait() + return self.connected + return await super().send_audio(pcm, end=end) + + +class FakeSleep: + """Records each requested sleep and advances the clock by it. + + It yields to the event loop once, as a real sleep would, so a loop + built on it (``Pacer.run``) can be cancelled from the test. + """ + + def __init__(self, clock): + self.clock = clock + self.calls: list[float] = [] + + async def __call__(self, seconds: float) -> None: + self.calls.append(seconds) + self.clock.advance(seconds * 1000) + await asyncio.sleep(0) + + +class HangingSleep: + """Records the request and never returns until cancelled.""" + + def __init__(self): + self.calls: list[float] = [] + + async def __call__(self, seconds: float) -> None: + self.calls.append(seconds) + await asyncio.Event().wait() + + +def _speech(ms: int, rate: int = RATE) -> bytes: + """Non-silent int16 PCM of ``ms`` (every sample is 0x0101).""" + return b"\x01\x01" * (rate * ms // 1000) + + +def _pacer(clock, sink, sleep=None, **kw) -> Pacer: + return Pacer( + sink, + RATE, + clock=clock.now, + sleep=sleep or FakeSleep(clock), + **kw, + ) + + +async def test_first_audio_opens_request_and_sends(clock): + sink = FakeSink() + pacer = _pacer(clock, sink) + assert not pacer.request_open + assert pacer.ahead_ms == -math.inf + + pcm = _speech(200) + assert await pacer.push_audio(pcm) is PushResult.SENT + + assert pacer.request_open + assert sink.calls == [("audio", pcm, False)] + assert pacer.ahead_ms == 200.0 + + # More audio within the request is sent as it arrives: no gate, no pad. + await pacer.push_audio(_speech(100)) + assert len(sink.calls) == 2 + assert pacer.ahead_ms == 300.0 + + +async def test_empty_audio_does_not_open_a_request(clock): + sink = FakeSink() + pacer = _pacer(clock, sink) + await pacer.push_audio(b"") + assert not pacer.request_open + assert sink.calls == [] + + +async def test_ahead_goes_negative_once_drained(clock): + sink = FakeSink() + pacer = _pacer(clock, sink) + await pacer.push_audio(_speech(200)) + clock.advance(500) + assert pacer.ahead_ms == pytest.approx(-300.0) + + +@pytest.mark.parametrize( + "first_ms,tick_ms,next_chunk_at_ms", + [(139, 62, 66), (139, 37, 65), (325, 28, 77)], +) +async def test_tick_preserves_speech_when_next_chunk_arrives_before_drain( + clock, first_ms, tick_ms, next_chunk_at_ms +): + """A ticker must not splice silence into speech that has not run out.""" + sink = FakeSink() + pacer = _pacer(clock, sink) + first = _speech(first_ms) + second = _speech(200) + await pacer.push_audio(first) + + clock.advance(tick_ms) + assert pacer.ahead_ms > 0 + await pacer.tick() + assert sink.calls == [("audio", first, False)] + + clock.advance(next_chunk_at_ms - tick_ms) + assert pacer.ahead_ms > 0 + await pacer.push_audio(second) + await pacer.end_request("tts_audio_end") + assert sink.calls == [ + ("audio", first, False), + ("audio", second, False), + ("audio", b"", True), + ] + + +async def test_padding_rechecks_lead_after_real_audio_arrives_during_send( + clock, +): + sink = PausingPaddingSink() + pacer = _pacer(clock, sink) + first, second, third = _speech(20), _speech(1000), _speech(100) + await pacer.push_audio(first) + clock.advance(270) + assert pacer.ahead_ms == pytest.approx(-250) + + ticker = asyncio.create_task(pacer.tick()) + try: + await asyncio.wait_for(sink.padding_started.wait(), timeout=1) + await pacer.push_audio(second) + assert pacer.ahead_ms > 0 + finally: + sink.release_padding.set() + await asyncio.wait_for(ticker, timeout=1) + + await pacer.push_audio(third) + await pacer.end_request("tts_audio_end") + assert sink.calls == [ + ("audio", first, False), + ("audio", bytes(RATE // 10 * 2), False), + ("audio", second, False), + ("audio", third, False), + ("audio", b"", True), + ] + + +async def test_end_during_padding_send_stops_padding_after_that_send(clock): + sink = PausingPaddingSink() + pacer = _pacer(clock, sink) + first = _speech(20) + await pacer.push_audio(first) + clock.advance(270) + + ticker = asyncio.create_task(pacer.tick()) + try: + await asyncio.wait_for(sink.padding_started.wait(), timeout=1) + assert await pacer.end_request("tts_audio_end") is True + assert await pacer.end_request("finalize") is False + finally: + sink.release_padding.set() + await asyncio.wait_for(ticker, timeout=1) + + assert not pacer.request_open + assert sink.calls == [ + ("audio", first, False), + ("audio", bytes(RATE // 10 * 2), False), + ("audio", b"", True), + ] + + +async def test_padding_when_ahead_below_floor(clock): + sink = FakeSink() + pacer = _pacer(clock, sink) + await pacer.push_audio(_speech(200)) + clock.advance(400) + assert pacer.ahead_ms == pytest.approx(-200.0) + + await pacer.tick() + + # Catch up the actual deficit, without creating a reserve inside speech. + assert sink.audio_ms(silent=True) == 200.0 + assert len(sink.silence_chunks()) == 2 + assert pacer.ahead_ms == pytest.approx(0.0, abs=1e-6) + assert pacer.request_open + assert sink.ends == 0 + + +async def test_no_padding_when_ahead_above_floor(clock): + sink = FakeSink() + pacer = _pacer(clock, sink) + await pacer.push_audio(_speech(2000)) + clock.advance(400) + await pacer.tick() + assert sink.audio_ms(silent=True) == 0.0 + assert len(sink.calls) == 1 + + +async def test_no_padding_without_open_request(clock): + sink = FakeSink() + pacer = _pacer(clock, sink) + await pacer.tick() + assert sink.calls == [] + + +async def test_pad_max_closes_request(clock): + sink = FakeSink() + pacer = _pacer(clock, sink) + await pacer.push_audio(_speech(200)) + + ticks = 0 + while pacer.request_open and ticks < 100: + clock.advance(100) + await pacer.tick() + ticks += 1 + + assert not pacer.request_open + assert sink.ends == 1 + assert sink.audio_ms(silent=True) == 3000.0 + assert sink.calls[-1] == ("audio", b"", True) + + # Closed means closed: later ticks neither pad nor end again. + before = len(sink.calls) + clock.advance(100) + await pacer.tick() + assert len(sink.calls) == before + + +async def test_padding_resumes_after_real_audio(clock): + """Real audio resets the contiguous-padding counter.""" + sink = FakeSink() + pacer = _pacer(clock, sink) + await pacer.push_audio(_speech(200)) + for _ in range(25): # 200 ms of speech, then 2.3 s of bounded padding + clock.advance(100) + await pacer.tick() + assert pacer.request_open + assert sink.audio_ms(silent=True) == 2300.0 + + await pacer.push_audio(_speech(100)) + for _ in range(25): + clock.advance(100) + await pacer.tick() + assert pacer.request_open + assert sink.ends == 0 + + +async def test_turn_stall_closes_request(clock): + sink = FakeSink() + pacer = _pacer(clock, sink) + await pacer.push_audio(_speech(200)) + + clock.advance(15_200) + await pacer.tick() + + assert not pacer.request_open + assert sink.ends == 1 + # The stall backstop closes before any padding is attempted. + assert sink.audio_ms(silent=True) == 0.0 + + +@pytest.mark.parametrize("reason", [1, 3, 99]) +async def test_tts_audio_end_reason_1_and_3_and_unknown_close(clock, reason): + sink = FakeSink() + pacer = _pacer(clock, sink) + await pacer.push_audio(_speech(200)) + + assert await pacer.on_tts_audio_end(reason) is True + + assert not pacer.request_open + assert sink.ends == 1 + assert sink.calls[-1] == ("audio", b"", True) + + +async def test_reason_2_closes_without_flush_and_is_ignored_after_flush( + clock, +): + sink = FakeSink() + pacer = _pacer(clock, sink) + + # No flush since open: INTERRUPTED comes from a request_id preemption + # and closes the request. + await pacer.push_audio(_speech(200)) + assert await pacer.on_tts_audio_end(2) is True + assert not pacer.request_open + assert sink.ends == 1 + + # A flush, then the new turn's first frame, then a late reason 2 that + # belongs to the pre-flush request: the new request stays open. + await pacer.push_audio(_speech(200)) + await pacer.flush() + assert not pacer.request_open + assert sink.ends == 1 # flush closes locally, no end=True + await pacer.push_audio(_speech(200)) + assert pacer.request_open + assert await pacer.on_tts_audio_end(2) is False + assert pacer.request_open + assert sink.ends == 1 + + # The real end of the new request closes it and re-arms reason 2. + assert await pacer.on_tts_audio_end(1) is True + assert sink.ends == 2 + await pacer.push_audio(_speech(200)) + assert await pacer.on_tts_audio_end(2) is True + assert sink.ends == 3 + + +async def test_end_request_idempotent(clock): + """Review Focus 2: finalize then tts_audio_end sends one end=True.""" + sink = FakeSink() + pacer = _pacer(clock, sink) + await pacer.push_audio(_speech(200)) + + assert await pacer.end_request("finalize") is True + assert await pacer.on_tts_audio_end(1) is False + assert await pacer.end_request("finalize") is False + + assert sink.ends == 1 + assert not pacer.request_open + + +async def test_end_request_without_open_request_is_noop(clock): + sink = FakeSink() + pacer = _pacer(clock, sink) + assert await pacer.end_request("finalize") is False + assert await pacer.on_tts_audio_end(1) is False + assert sink.calls == [] + + +async def test_gate_waits_until_drained(clock): + sink = FakeSink() + sleep = FakeSleep(clock) + pacer = _pacer(clock, sink, sleep) + + await pacer.push_audio(_speech(2000)) + await pacer.end_request("tts_audio_end") + assert pacer.ahead_ms == pytest.approx(2000.0) + + pcm_b = _speech(300) + await pacer.push_audio(pcm_b) + + # Request A is 2000 ms ahead; B may start once A is 2000 ms drained. + assert len(sleep.calls) == 1 + assert sleep.calls[0] == pytest.approx(4.0) + assert sink.calls[-1] == ("audio", pcm_b, False) + assert pacer.request_open + # B's playhead starts fresh. + assert pacer.ahead_ms == pytest.approx(300.0) + + +async def test_gate_rechecks_after_partial_sleep(clock): + """A sleep that wakes early just loops; it never sends ahead of time.""" + + class ShortSleep(FakeSleep): + async def __call__(self, seconds: float) -> None: + await super().__call__(min(seconds, 1.0)) + + sink = FakeSink() + sleep = ShortSleep(clock) + pacer = _pacer(clock, sink, sleep) + await pacer.push_audio(_speech(2000)) + await pacer.end_request("tts_audio_end") + + await pacer.push_audio(_speech(100)) + assert len(sleep.calls) == 4 + assert sink.calls[-1][2] is False + assert len(sink.calls) == 3 + + +async def test_no_gate_when_predecessor_drained(clock): + sink = FakeSink() + sleep = FakeSleep(clock) + pacer = _pacer(clock, sink, sleep) + await pacer.push_audio(_speech(500)) + await pacer.end_request("tts_audio_end") + clock.advance(2600) # 500 ms played, then 2100 ms > GATE_MS idle + assert pacer.ahead_ms < -2000 + + await pacer.push_audio(_speech(100)) + assert sleep.calls == [] + assert pacer.request_open + + +async def test_flush_cancels_the_chunk_waiting_at_the_gate(clock): + """Flush during the gate wait: the wait ends, the sink is interrupted, + and the chunk that was waiting is dropped, not sent (it belongs to the + turn the flush cancelled). The next turn's first chunk skips the gate.""" + sink = FakeSink() + sleep = HangingSleep() + pacer = _pacer(clock, sink, sleep) + + await pacer.push_audio(_speech(2000)) + await pacer.end_request("tts_audio_end") + + pcm_b = _speech(300) + sender = asyncio.create_task(pacer.push_audio(pcm_b)) + for _ in range(10): + await asyncio.sleep(0) + if sleep.calls: + break + assert sleep.calls == [pytest.approx(4.0)] + assert not sender.done() + + await pacer.flush() + assert await asyncio.wait_for(sender, timeout=1.0) is PushResult.CANCELLED + + assert sink.interrupts == 1 + assert ("audio", pcm_b, False) not in sink.calls + assert sink.ends == 1 # only A's; flush never sends end=True + assert not pacer.request_open + assert len(sleep.calls) == 1 + + # The new turn's first chunk opens a request at once (waiver). + pcm_c = _speech(100) + assert await pacer.push_audio(pcm_c) is PushResult.SENT + assert sink.calls[-1] == ("audio", pcm_c, False) + assert pacer.request_open + assert len(sleep.calls) == 1 + + +async def test_flush_closes_open_request_locally(clock): + sink = FakeSink() + sleep = FakeSleep(clock) + pacer = _pacer(clock, sink, sleep) + await pacer.push_audio(_speech(2000)) + + await pacer.flush() + + assert not pacer.request_open + assert sink.ends == 0 + assert sink.interrupts == 1 + + # The next request skips the gate exactly once. + await pacer.push_audio(_speech(100)) + assert sleep.calls == [] + assert pacer.request_open + await pacer.end_request("tts_audio_end") + await pacer.push_audio(_speech(100)) + assert len(sleep.calls) == 1 + + # A closed request does not pad after the flush. + pacer2 = _pacer(clock, FakeSink()) + await pacer2.flush() + await pacer2.tick() + + +async def test_flush_when_idle_still_interrupts(clock): + sink = FakeSink() + pacer = _pacer(clock, sink) + await pacer.flush() + assert sink.calls == [("interrupt",)] + assert not pacer.request_open + + +async def test_padding_is_whole_samples(clock): + rate = 22050 + sink = FakeSink() + pacer = Pacer(sink, rate, clock=clock.now, sleep=FakeSleep(clock)) + await pacer.push_audio(_speech(100, rate)) + clock.advance(300) + await pacer.tick() + + chunks = [ + c[1] + for c in sink.calls + if c[0] == "audio" and not c[2] and not c[1].strip(b"\x00") + ] + assert chunks + chunk_bytes = rate * 100 // 1000 * 2 + for chunk in chunks: + assert len(chunk) % 2 == 0 + assert len(chunk) == chunk_bytes + + +async def test_fractional_tick_is_rejected_at_construction(clock): + # 44100 Hz * 1 ms is 44.1 samples: not representable. + with pytest.raises(ValueError): + Pacer(FakeSink(), 44100, clock=clock.now, pad_tick_ms=1) + + +async def test_session_reset_clears_playhead(clock): + sink = FakeSink() + sleep = FakeSleep(clock) + pacer = _pacer(clock, sink, sleep) + await pacer.push_audio(_speech(2000)) + assert pacer.request_open + + pacer.on_session_reset() + + assert not pacer.request_open + assert pacer.ahead_ms == -math.inf + # Nothing is sent for the abandoned request: no end=True, no padding. + await pacer.tick() + assert sink.ends == 0 + assert len(sink.calls) == 1 + + # The next audio opens a request without waiting on the old playhead. + await pacer.push_audio(_speech(100)) + assert sleep.calls == [] + assert pacer.request_open + + +async def test_session_reset_wakes_sender_waiting_at_gate(clock): + """A reconnect while a sender waits at the gate: the old request's tail + is gone with the old session, so the pending audio goes out at once.""" + sink = FakeSink() + sleep = HangingSleep() + pacer = _pacer(clock, sink, sleep) + + await pacer.push_audio(_speech(2000)) + await pacer.end_request("tts_audio_end") + + pcm_b = _speech(300) + sender = asyncio.create_task(pacer.push_audio(pcm_b)) + for _ in range(10): + await asyncio.sleep(0) + if sleep.calls: + break + assert sleep.calls == [pytest.approx(4.0)] + assert not sender.done() + + pacer.on_session_reset() + await asyncio.wait_for(sender, timeout=1.0) + + assert sink.calls[-1] == ("audio", pcm_b, False) + assert sink.interrupts == 0 + assert pacer.request_open + assert pacer.ahead_ms == pytest.approx(300.0) + # Woken by the reset, not by a second sleep. + assert len(sleep.calls) == 1 + + +async def test_failed_send_is_not_counted_and_forgets_the_request(clock): + """A send the sink refuses (session gone) leaves no request open and no + playhead, so the chunk can be retried on the next session without a + gate wait; a refused padding chunk is not counted either.""" + sink = FakeSink() + sleep = FakeSleep(clock) + pacer = _pacer(clock, sink, sleep) + sink.connected = False + + pcm = _speech(300) + assert await pacer.push_audio(pcm) is PushResult.NOT_SENT + assert sink.calls == [("audio", pcm, False)] + assert not pacer.request_open + assert pacer.ahead_ms == -math.inf + + sink.connected = True + assert await pacer.push_audio(pcm) is PushResult.SENT + assert sleep.calls == [] + assert pacer.request_open + assert pacer.ahead_ms == pytest.approx(300.0) + + # Padding that the sink refuses does not move the playhead. + sink.connected = False + clock.advance(500) + await pacer.tick() + assert pacer.ahead_ms == pytest.approx(-200.0) + assert len(sink.silence_chunks()) == 1 + + +async def test_run_ticks_every_pad_tick(clock): + sink = FakeSink() + sleep = FakeSleep(clock) + pacer = _pacer(clock, sink, sleep) + await pacer.push_audio(_speech(200)) + + task = asyncio.create_task(pacer.run()) + for _ in range(50): + await asyncio.sleep(0) + if sink.ends: + break + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + + assert all(s == pytest.approx(0.1) for s in sleep.calls) + assert sink.ends == 1 + assert sink.audio_ms(silent=True) == 3000.0 + + +@pytest.mark.parametrize("boundary", ["end", "flush", "session_reset"]) +async def test_old_padding_completion_cannot_advance_new_request( + clock, boundary +): + sink = PausingPaddingSink() + pacer = _pacer(clock, sink) + await pacer.push_audio(_speech(100)) + clock.advance(200) + tick = asyncio.create_task(pacer.tick()) + await asyncio.wait_for(sink.padding_started.wait(), timeout=1) + try: + if boundary == "end": + await pacer.end_request("A end") + elif boundary == "flush": + await pacer.flush() + else: + pacer.on_session_reset() + await pacer.push_audio(_speech(100)) + assert pacer.ahead_ms == pytest.approx(100) + finally: + sink.release_padding.set() + await asyncio.wait_for(tick, timeout=1) + assert pacer.request_open + assert pacer.ahead_ms == pytest.approx(100) + + +async def _start_held_send(pacer, sink, pcm): + sink.hold = True + task = asyncio.create_task(pacer.push_audio(pcm)) + await asyncio.wait_for(sink.real_started.wait(), timeout=1) + return task + + +@pytest.mark.parametrize("opening", [True, False]) +async def test_ticker_neither_pads_nor_ends_during_a_held_real_send( + clock, opening +): + """A real send held across more than pad-max and turn-stall worth of + ticks: no silence and no end=True go out until it completes.""" + sink = HoldingRealSink() + pacer = _pacer(clock, sink) + real_ms = 200.0 + if not opening: + await pacer.push_audio(_speech(200)) + clock.advance(150) + real_ms += 200 + started_at = clock.now() + held = await _start_held_send(pacer, sink, _speech(200)) + + for _ in range(170): # 17 s: past PAD_MAX_MS and TURN_STALL_MS + clock.advance(100) + await pacer.tick() + assert not held.done() + assert sink.silence_chunks() == [] + assert sink.ends == 0 + assert pacer.request_open + + sink.release_real.set() + assert await asyncio.wait_for(held, timeout=1) is PushResult.SENT + assert pacer.request_open + assert sink.ends == 0 + if opening: + first_send = started_at + else: + first_send = started_at - 0.150 + elapsed_ms = (clock.now() - first_send) * 1000 + assert pacer.ahead_ms == pytest.approx(real_ms - elapsed_ms) + + +async def test_padding_resumes_from_the_playhead_after_a_held_send(clock): + sink = HoldingRealSink() + pacer = _pacer(clock, sink) + await pacer.push_audio(_speech(200)) + clock.advance(150) + held = await _start_held_send(pacer, sink, _speech(1000)) + for _ in range(5): # the first 200 ms drain at 200 ms + clock.advance(100) + await pacer.tick() + assert sink.silence_chunks() == [] + + sink.release_real.set() + assert await asyncio.wait_for(held, timeout=1) is PushResult.SENT + # Elapsed 650 ms against 1200 ms of real audio. + assert pacer.ahead_ms == pytest.approx(550) + await pacer.tick() + assert sink.silence_chunks() == [] + + clock.advance(600) + assert pacer.ahead_ms == pytest.approx(-50) + await pacer.tick() + assert sink.audio_ms(silent=True) == 100.0 + assert pacer.ahead_ms == pytest.approx(50) + assert pacer.request_open + assert sink.ends == 0 + + +async def test_flush_during_a_held_send_acts_at_once_and_stays_closed(clock): + sink = HoldingRealSink() + sleep = FakeSleep(clock) + pacer = _pacer(clock, sink, sleep) + await pacer.push_audio(_speech(200)) + clock.advance(150) + held = await _start_held_send(pacer, sink, _speech(1000)) + for _ in range(3): + clock.advance(100) + await pacer.tick() + + await pacer.flush() + assert not held.done() + assert sink.calls[-1] == ("interrupt",) + assert not pacer.request_open + playhead = pacer.ahead_ms + + sink.release_real.set() + assert await asyncio.wait_for(held, timeout=1) is PushResult.SENT + assert not pacer.request_open + assert pacer.ahead_ms == pytest.approx(playhead) + for _ in range(40): + clock.advance(100) + await pacer.tick() + assert sink.silence_chunks() == [] + assert sink.ends == 0 + + # The next turn opens a fresh request without a gate wait. + sink.hold = False + assert await pacer.push_audio(_speech(100)) is PushResult.SENT + assert sleep.calls == [] + assert pacer.request_open + assert pacer.ahead_ms == pytest.approx(100) + + +async def test_refused_held_opening_send_is_forgotten_without_padding(clock): + sink = HoldingRealSink() + sleep = FakeSleep(clock) + pacer = _pacer(clock, sink, sleep) + held = await _start_held_send(pacer, sink, _speech(200)) + for _ in range(40): + clock.advance(100) + await pacer.tick() + assert sink.silence_chunks() == [] + + sink.connected = False + sink.release_real.set() + assert await asyncio.wait_for(held, timeout=1) is PushResult.NOT_SENT + assert not pacer.request_open + assert pacer.ahead_ms == -math.inf + await pacer.tick() + assert sink.silence_chunks() == [] + assert sink.ends == 0 + + +async def test_pad_max_does_not_close_while_a_real_send_is_in_flight(clock): + """Real audio arrives during the padding send that reaches pad max: the + request is not closed ahead of it.""" + sink = HoldingRealSink() + sink.release_padding.clear() + pacer = _pacer(clock, sink, pad_max_ms=100) + await pacer.push_audio(_speech(20)) + clock.advance(270) + tick = asyncio.create_task(pacer.tick()) + await asyncio.wait_for(sink.padding_started.wait(), timeout=1) + held = await _start_held_send(pacer, sink, _speech(1000)) + + sink.release_padding.set() + await asyncio.wait_for(tick, timeout=1) + assert sink.ends == 0 + assert pacer.request_open + + sink.release_real.set() + assert await asyncio.wait_for(held, timeout=1) is PushResult.SENT + await pacer.tick() + assert sink.ends == 0 + assert pacer.request_open + assert len(sink.silence_chunks()) == 1 diff --git a/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/test_sender.py b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/test_sender.py new file mode 100644 index 0000000000..51d883531f --- /dev/null +++ b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/test_sender.py @@ -0,0 +1,975 @@ +# +# This file is part of TEN Framework, an open source project. +# Licensed under the Apache License, Version 2.0. +# See the LICENSE file for more information. +# +"""Unit tests for the audio sender: queue ordering, flush and session state. + +The sender runs against the real ``Pacer`` and a recording sink, with the +``FakeClock`` and a sleep the test releases by hand, so the gate wait is +held open for as long as a test needs to queue more behind it. +""" + +import asyncio +import hashlib + +import pytest + +from spatialreal_avatar_python.pacer import Pacer +from spatialreal_avatar_python.sender import ( + INPUT_QUEUE_MAX_MS, + AudioSender, + End, + InputQueue, + Turn, +) + +pytestmark = pytest.mark.asyncio + +RATE = 24000 + + +async def settle(rounds: int = 50) -> None: + """Let every ready task step run.""" + for _ in range(rounds): + await asyncio.sleep(0) + + +class FakeSink: + """Records every call the pacer makes, in order.""" + + def __init__(self): + self.calls: list[tuple] = [] + + async def send_audio(self, pcm: bytes, end: bool = False) -> bool: + self.calls.append(("audio", pcm, end)) + return True + + async def interrupt(self) -> bool: + self.calls.append(("interrupt",)) + return True + + @property + def ends(self) -> int: + return sum(1 for c in self.calls if c[0] == "audio" and c[2]) + + @property + def interrupts(self) -> int: + return sum(1 for c in self.calls if c[0] == "interrupt") + + def audio(self) -> list[bytes]: + """Non-end PCM payloads, in order.""" + return [c[1] for c in self.calls if c[0] == "audio" and not c[2]] + + +class FakeLog: + def __init__(self): + self.lines: list[tuple[str, str]] = [] + + def log_debug(self, msg: str) -> None: + self.lines.append(("debug", msg)) + + def log_info(self, msg: str) -> None: + self.lines.append(("info", msg)) + + def log_warn(self, msg: str) -> None: + self.lines.append(("warn", msg)) + + def log_error(self, msg: str) -> None: + self.lines.append(("error", msg)) + + def level(self, name: str) -> list[str]: + return [msg for lvl, msg in self.lines if lvl == name] + + +class ControlledSleep: + """Parks every sleep until the test releases it. + + ``release`` wakes the oldest sleeper and advances the clock by what it + asked for, so the pacer's gate re-check sees the time as elapsed. + """ + + def __init__(self, clock): + self.clock = clock + self.calls: list[float] = [] + self._pending: list[tuple[float, asyncio.Future]] = [] + + async def __call__(self, seconds: float) -> None: + self.calls.append(seconds) + fut = asyncio.get_running_loop().create_future() + entry = (seconds, fut) + self._pending.append(entry) + try: + await fut + finally: + if entry in self._pending: + self._pending.remove(entry) + + def release(self) -> None: + seconds, fut = self._pending.pop(0) + self.clock.advance(seconds * 1000) + if not fut.done(): + fut.set_result(None) + + +def _speech(ms: int, rate: int = RATE) -> bytes: + """Non-silent int16 PCM of ``ms`` (every sample is 0x0101).""" + return b"\x01\x01" * (rate * ms // 1000) + + +class FakeClient: + """A session client whose sessions the test opens and drops by hand. + + ``send_audio`` answers False once the session is gone, as the real + client does; what each session received is kept per connection id. + """ + + def __init__(self): + self.connected = False + self.refuse_sends = False + self.sessions: dict[str, list[tuple[bytes, bool]]] = {} + self.interrupts = 0 + self._current = "" + + def connect(self, connection_id: str) -> None: + self.connected = True + self._current = connection_id + self.sessions[connection_id] = [] + + def disconnect(self) -> None: + self.connected = False + self._current = "" + + async def send_audio(self, pcm: bytes, end: bool = False) -> bool: + if not self.connected or self.refuse_sends: + return False + self.sessions[self._current].append((pcm, end)) + return True + + async def interrupt(self) -> bool: + if not self.connected: + return False + self.interrupts += 1 + return True + + +class Harness: + """A sender over the real pacer, with the sender task running.""" + + def __init__(self, clock, *, sink=None, sleep=None, max_queue_ms=10_000): + self.sink = sink or FakeSink() + self.log = FakeLog() + self.sleep = sleep or ControlledSleep(clock) + self.states: list[bool] = [] + self.pacer = Pacer(self.sink, RATE, clock=clock.now, sleep=self.sleep) + self.sender = AudioSender( + self.pacer, + RATE, + self.log, + on_request_state=self.states.append, + max_queue_ms=max_queue_ms, + ) + self.task: asyncio.Task | None = None + + async def __aenter__(self) -> "Harness": + self.task = asyncio.create_task(self.sender.run()) + return self + + async def __aexit__(self, *exc) -> None: + self.task.cancel() + try: + await self.task + except asyncio.CancelledError: + pass + + +# -- ordering ----------------------------------------------------------------- + + +async def test_end_follows_its_own_audio_behind_the_gate(clock): + """Regression: a second request plus its end queued while the first + request's gate holds the sender. The end must not overtake the PCM.""" + async with Harness(clock) as h: + h.sender.session_up() + pcm_a = _speech(2000) + h.sender.put_audio(pcm_a, RATE) + h.sender.put_end(End("tts_audio_end reason=1", tts_reason=1)) + await settle() + assert h.sink.calls == [("audio", pcm_a, False), ("audio", b"", True)] + assert not h.sender.request_open + + # Request B arrives complete while A is still less than GATE_MS + # past drained: its first frame waits at the gate. + pcm_b1, pcm_b2 = _speech(300), _speech(200) + h.sender.put_audio(pcm_b1, RATE) + h.sender.put_audio(pcm_b2, RATE) + h.sender.put_end(End("finalize")) + await settle() + assert h.sleep.calls == [pytest.approx(4.0)] + # Nothing of B has gone out, and its end is still behind its audio. + assert h.sink.ends == 1 + assert len(h.sink.calls) == 2 + assert h.sender.queued == 2 + + h.sleep.release() + await settle() + + assert h.sink.calls[2:] == [ + ("audio", pcm_b1, False), + ("audio", pcm_b2, False), + ("audio", b"", True), + ] + assert not h.sender.request_open + assert h.states[-1] is False + assert "request closed: finalize" in h.log.level("info") + + +async def test_over_10s_queued_behind_an_active_gate_all_reach_the_sink(clock): + """A connected session waiting at the gate keeps every queued frame: a + second request longer than 10 s, queued while the first request's tail + plays, reaches the sink whole and in order, its end last.""" + async with Harness(clock, max_queue_ms=INPUT_QUEUE_MAX_MS) as h: + h.sender.session_up() + pcm_a = _speech(2000) + h.sender.put_audio(pcm_a, RATE) + h.sender.put_end(End("finalize")) + await settle() + assert h.sink.calls == [("audio", pcm_a, False), ("audio", b"", True)] + + # 12 s of distinct 100 ms frames for request B, all queued while + # the sender is parked at A's gate. + frames = [ + (index + 1).to_bytes(2, "little") * (RATE // 10) + for index in range(120) + ] + for pcm in frames: + h.sender.put_audio(pcm, RATE) + h.sender.put_end(End("finalize")) + await settle() + assert h.sleep.calls == [pytest.approx(4.0)] + assert len(h.sink.calls) == 2 + # The first frame is in flight at the gate; the rest wait behind it. + assert h.sender.queued == len(frames) + + h.sleep.release() + await settle() + + assert h.sink.audio() == [pcm_a, *frames] + assert h.sink.calls[-1] == ("audio", b"", True) + assert h.sink.ends == 2 + assert not h.log.level("warn") + assert not h.log.level("error") + + +async def test_end_waits_for_audio_queued_before_the_session_is_up(clock): + async with Harness(clock) as h: + pcm = _speech(500) + h.sender.put_audio(pcm, RATE) + h.sender.put_end(End("finalize")) + await settle() + # The frame is parked on the session; the marker waits behind it. + assert h.sink.calls == [] + assert h.sender.queued == 1 + + h.sender.session_up() + await settle() + + assert h.sink.calls == [("audio", pcm, False), ("audio", b"", True)] + assert not h.sender.request_open + + +async def test_delayed_initial_session_preserves_26s_source_before_normal_end( + clock, +): + """A transport startup retry must not turn a full response into its tail.""" + sink, log = FakeSink(), FakeLog() + pacer = Pacer(sink, RATE, clock=clock.now) + sender = AudioSender(pacer, RATE, log) + turn = Turn("startup", 0) + chunks = [ + (index + 1).to_bytes(2, "little") * (RATE // 10) for index in range(260) + ] + task = asyncio.create_task(sender.run()) + try: + sender.put_audio(chunks[0], RATE, turn) + await settle() + for pcm in chunks[1:]: + sender.put_audio(pcm, RATE, turn) + sender.put_end(End("tts_audio_end", 1, turn, "tts-request-0")) + clock.advance(41_000) + await settle() + assert sink.calls == [] + + sender.session_up() + await settle() + received = b"".join(sink.audio()) + expected = b"".join(chunks) + assert len(received) == len(expected) + assert ( + hashlib.sha256(received).digest() + == hashlib.sha256(expected).digest() + ) + assert sink.ends == 1 + assert sink.calls[-1] == ("audio", b"", True) + assert not log.level("warn") + finally: + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + + +async def test_tts_audio_end_marker_applies_the_reason_rules(clock): + async with Harness(clock) as h: + h.sender.session_up() + h.sender.put_audio(_speech(100), RATE) + await settle() + assert h.sender.request_open + + # A flush, then the new turn, then the late reason 2 that belongs to + # the pre-flush request: the marker is reached and ignored. + await h.sender.flush() + h.sender.put_audio(_speech(100), RATE) + h.sender.put_end(End("tts_audio_end reason=2", tts_reason=2)) + await settle() + assert h.sender.request_open + assert h.sink.ends == 0 + assert any( + msg.startswith("end ignored: tts_audio_end reason=2") + for msg in h.log.level("debug") + ) + + h.sender.put_end(End("tts_audio_end reason=1", tts_reason=1)) + await settle() + assert not h.sender.request_open + assert h.sink.ends == 1 + + +async def test_end_with_nothing_open_is_a_noop(clock): + async with Harness(clock) as h: + h.sender.session_up() + h.sender.put_end(End("finalize")) + await settle() + assert h.sink.calls == [] + # session_up and the marker each report the state; never "open". + assert h.states == [False, False] + + +# -- flush ---------------------------------------------------------------------- + + +@pytest.mark.parametrize("reason", [1, 2, 3, -1, None]) +async def test_old_turn_end_cannot_close_the_turn_after_flush(clock, reason): + async with Harness(clock) as h: + h.sender.session_up() + a, b = Turn("session", 1), Turn("session", 2) + h.sender.put_audio(_speech(100), RATE, a) + await settle() + await h.sender.flush() + h.sender.put_audio(_speech(100), RATE, b) + h.sender.put_end(End("late A", reason, a, "request-a")) + await settle() + assert h.sender.request_open + assert h.sink.ends == 0 + h.sender.put_end(End("B", 1, b, "request-b")) + await settle() + assert not h.sender.request_open + assert h.sink.ends == 1 + + +async def test_identified_interrupted_end_closes_the_current_turn(clock): + async with Harness(clock) as h: + h.sender.session_up() + await h.sender.flush() + b = Turn("session", 2) + h.sender.put_audio(_speech(100), RATE, b) + h.sender.put_end(End("B interrupted", 2, b, "request-b")) + await settle() + assert not h.sender.request_open + assert h.sink.ends == 1 + + +async def test_late_cancelled_pcm_cannot_restart_or_contaminate_next_turn( + clock, +): + async with Harness(clock) as h: + h.sender.session_up() + a, b = Turn("session", 1), Turn("session", 2) + first, cancelled, second = _speech(100), _speech(200), _speech(300) + h.sender.put_audio(first, RATE, a) + await settle() + await h.sender.flush() + h.sender.put_audio(cancelled, RATE, a) + h.sender.put_audio(second, RATE, b) + h.sender.put_audio(cancelled, RATE, a) + h.sender.put_end(End("B", 1, b, "request-b")) + await settle() + assert h.sink.audio() == [first, second] + assert h.sink.ends == 1 + + +async def test_duplicate_end_does_not_close_another_request_in_the_same_turn( + clock, +): + async with Harness(clock) as h: + h.sender.session_up() + turn = Turn("session", 1) + h.sender.put_audio(_speech(100), RATE, turn) + h.sender.put_end(End("A", 1, turn, "request-a")) + await settle() + h.sender.put_audio(_speech(200), RATE, turn) + h.sender.put_end(End("A duplicate", 1, turn, "request-a")) + await settle() + h.sleep.release() + await settle() + assert h.sender.request_open + assert h.sink.ends == 1 + h.sender.put_end(End("B", 1, turn, "request-b")) + await settle() + assert h.sink.ends == 2 + + +async def test_flush_retires_queued_and_inflight_turns(clock): + async with Harness(clock) as h: + a, b = Turn("session", 1), Turn("session", 2) + h.sender.put_audio(_speech(100), RATE, a) + h.sender.put_audio(_speech(100), RATE, b) + await settle() + await h.sender.flush() + h.sender.session_up() + h.sender.put_audio(_speech(100), RATE, a) + h.sender.put_audio(_speech(100), RATE, b) + h.sender.put_audio(_speech(300), RATE, Turn("session", 3)) + await settle() + assert h.sink.audio() == [_speech(300)] + + +async def test_new_turn_closes_predecessor_and_ignores_its_late_events(clock): + async with Harness(clock) as h: + h.sender.session_up() + a, b = Turn("session", 1), Turn("session", 2) + first, second = _speech(100), _speech(200) + h.sender.put_audio(first, RATE, a) + h.sender.put_audio(second, RATE, b) + h.sender.put_audio(_speech(300), RATE, a) + h.sender.put_end(End("late A", 1, a, "request-a")) + await settle() + assert h.sink.calls == [("audio", first, False), ("audio", b"", True)] + h.sleep.release() + await settle() + assert h.sink.audio() == [first, second] + assert h.sender.request_open + assert h.sink.ends == 1 + h.sender.put_end(End("B", 1, b, "request-b")) + await settle() + assert h.sink.ends == 2 + + +async def test_turn_zero_in_another_session_survives_flush(clock): + async with Harness(clock) as h: + h.sender.session_up() + a, b = Turn("old-session", 0), Turn("new-session", 0) + h.sender.put_audio(_speech(100), RATE, a) + h.sender.put_end(End("A", 1, a, "request-0")) + await settle() + await h.sender.flush() + h.sender.put_audio(_speech(200), RATE, b) + h.sender.put_end(End("B", 1, b, "request-0")) + await settle() + assert h.sink.audio() == [_speech(100), _speech(200)] + assert h.sink.ends == 2 + + +async def test_new_turn_waits_until_the_old_interrupt_has_been_sent(clock): + class SlowInterrupt(FakeSink): + def __init__(self): + super().__init__() + self.started = asyncio.Event() + self.release = asyncio.Event() + + async def interrupt(self): + self.started.set() + await self.release.wait() + return await super().interrupt() + + sink = SlowInterrupt() + async with Harness(clock, sink=sink) as h: + h.sender.session_up() + a, b = Turn("session", 1), Turn("session", 2) + first, second = _speech(100), _speech(200) + h.sender.put_audio(first, RATE, a) + await settle() + flushing = asyncio.create_task(h.sender.flush()) + await asyncio.wait_for(sink.started.wait(), timeout=1) + try: + h.sender.put_audio(second, RATE, b) + h.sender.put_end(End("B", 1, b, "request-b")) + await settle() + assert sink.audio() == [first] + finally: + sink.release.set() + await asyncio.wait_for(flushing, timeout=1) + await settle() + assert sink.calls == [ + ("audio", first, False), + ("interrupt",), + ("audio", second, False), + ("audio", b"", True), + ] + + +async def test_unseen_old_turn_first_pcm_cannot_supersede_new_turn(clock): + async with Harness(clock) as h: + h.sender.session_up() + await h.sender.flush() # A has not delivered its first PCM yet. + a, b = Turn("session", 1), Turn("session", 2) + first, second = _speech(100), _speech(300) + h.sender.put_audio(first, RATE, b) + # Queue A before B has been processed, to exercise dequeue checks. + h.sender.put_audio(_speech(200), RATE, a) + h.sender.put_audio(second, RATE, b) + h.sender.put_end(End("B", 1, b, "request-b")) + await settle() + assert h.sink.audio() == [first, second] + assert h.sink.ends == 1 + assert not h.sender.request_open + + +async def test_turn_order_check_preserves_earlier_audio_already_in_queue(clock): + async with Harness(clock) as h: + h.sender.session_up() + a, b = Turn("session", 1), Turn("session", 2) + first, second = _speech(100), _speech(200) + h.sender.put_audio(first, RATE, a) + h.sender.put_end(End("A", 1, a, "request-a")) + h.sender.put_audio(second, RATE, b) + h.sender.put_end(End("B", 1, b, "request-b")) + await settle() + assert h.sink.audio() == [first] + h.sleep.release() + await settle() + assert h.sink.audio() == [first, second] + assert h.sink.ends == 2 + + +@pytest.mark.parametrize( + "metadata", [None, [], {}, {"turn_id": True}, {"turn_id": "1"}] +) +def test_invalid_turn_metadata_is_unscoped(metadata): + assert Turn.from_metadata(metadata) is None + + +def test_turn_zero_and_session_identity_are_preserved(): + assert Turn.from_metadata({"session_id": "s", "turn_id": 0}) == Turn("s", 0) + assert Turn("s", 0) != Turn("another-session", 0) + + +async def test_flush_drops_queued_audio_and_markers(clock): + async with Harness(clock) as h: + h.sender.put_audio(_speech(500), RATE) + h.sender.put_audio(_speech(500), RATE) + h.sender.put_end(End("finalize")) + await settle() + + await h.sender.flush() + assert h.sender.queued == 0 + assert h.sink.calls == [("interrupt",)] + + # The frame that was already parked on the session is dropped too. + h.sender.session_up() + await settle() + assert h.sink.calls == [("interrupt",)] + assert not h.sender.request_open + + +# -- queue bound ---------------------------------------------------------------- + + +async def test_queue_capacity_rejects_atomically_without_truncating_audio(): + queue = InputQueue(max_ms=1000) + first, second = _speech(600), _speech(600) + assert queue.put_audio(first, RATE) is False + queue.put_end(End("finalize")) + with pytest.raises(RuntimeError, match="input queue capacity"): + queue.put_audio(second, RATE) + assert queue.queued_ms == pytest.approx(600.0) + + item = await queue.get() + assert item.pcm == first + assert await queue.get() == End("finalize") + assert len(queue) == 0 + assert queue.queued_ms == 0.0 + + +async def test_queue_byte_and_marker_item_bounds_are_atomic(): + queue = InputQueue(max_bytes=4, max_items=2) + with pytest.raises(RuntimeError, match="input queue capacity"): + queue.put_audio(b"\x01\x00" * 3, RATE) + assert len(queue) == 0 + queue.put_end(End("first")) + queue.put_end(End("second")) + with pytest.raises(RuntimeError, match="input queue capacity"): + queue.put_end(End("excess")) + assert len(queue) == 2 + assert await queue.get() == End("first") + assert await queue.get() == End("second") + + +async def test_sender_capacity_includes_inflight_and_cancels_failed_turn(clock): + turn, following = Turn("capacity", 1), Turn("capacity", 2) + async with Harness(clock, max_queue_ms=1000) as h: + h.sender.put_audio(_speech(600), RATE, turn) + await settle() + # The first frame is no longer in the FIFO, but still owns memory. + with pytest.raises(RuntimeError, match="input queue capacity") as error: + h.sender.put_audio(_speech(600), RATE, turn) + assert getattr(error.value, "turn", None) == turn + await h.sender.flush() + h.sender.put_audio(_speech(200), RATE, turn) + h.sender.put_end(End("tts_audio_end", 1, turn, "failed-request")) + h.sender.session_up() + await settle() + assert not h.sink.audio() + assert h.sink.ends == 0 + + pcm = _speech(200) + h.sender.put_audio(pcm, RATE, following) + h.sender.put_end(End("tts_audio_end", 1, following, "next-request")) + await settle() + assert h.sink.audio() == [pcm] + assert h.sink.ends == 1 + + +async def test_unknown_failed_request_stays_blocked_until_end(clock): + async with Harness(clock, max_queue_ms=1000) as h: + h.sender.put_audio(_speech(600), RATE) + await settle() + with pytest.raises(RuntimeError, match="input queue capacity"): + h.sender.put_audio(_speech(600), RATE) + await h.sender.flush() + h.sender.put_audio(_speech(200), RATE) + h.sender.session_up() + await settle() + assert not h.sink.audio() + assert h.sink.ends == 0 + h.sender.put_end(End("tts_audio_end", 1, request_id="failed")) + await settle() + assert h.sink.ends == 0 + pcm = _speech(200) + h.sender.put_audio(pcm, RATE) + await settle() + h.sender.put_end(End("tts_audio_end", 1, request_id="failed")) + await settle() + assert h.sink.ends == 0 + h.sender.put_end(End("tts_audio_end", 1, request_id="next")) + await settle() + assert h.sink.audio() == [pcm] + assert h.sink.ends == 1 + + +async def test_unknown_capacity_failure_can_be_reset_at_stop(clock): + async with Harness(clock, max_queue_ms=1000) as h: + with pytest.raises(RuntimeError, match="input queue capacity"): + h.sender.put_audio(_speech(1200), RATE) + await h.sender.flush() + h.sender.clear() + h.sender.session_up() + pcm = _speech(200) + h.sender.put_audio(pcm, RATE) + h.sender.put_end(End("tts_audio_end", 1)) + await settle() + assert h.sink.audio() == [pcm] + assert h.sink.ends == 1 + + +async def test_byte_and_item_limits_include_the_inflight_frame(clock): + for limits, following in ( + ({"max_queue_bytes": 8}, "audio"), + ({"max_queue_items": 1}, "end"), + ): + sink, log = FakeSink(), FakeLog() + sender = AudioSender( + Pacer(sink, RATE, clock=clock.now), RATE, log, **limits + ) + turn = Turn("inflight", 1) + task = asyncio.create_task(sender.run()) + try: + sender.put_audio(b"\x01\x00" * 2, RATE, turn) + await settle() + with pytest.raises(RuntimeError, match="input queue capacity"): + if following == "audio": + sender.put_audio(b"\x02\x00" * 3, RATE, turn) + else: + sender.put_end(End("tts_audio_end", 1, turn, "failed")) + await sender.flush() + sender.session_up() + await settle() + assert not sink.audio() + assert sink.ends == 0 + finally: + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + + +async def test_clear_releases_cancelled_inflight_admission_budget(clock): + sink, log = FakeSink(), FakeLog() + sender = AudioSender( + Pacer(sink, RATE, clock=clock.now), RATE, log, max_queue_bytes=4 + ) + task = asyncio.create_task(sender.run()) + try: + sender.put_audio(b"\x01\x00" * 2, RATE, Turn("reset", 1)) + await settle() + sender.clear() + pcm = b"\x02\x00" * 2 + sender.put_audio(pcm, RATE, Turn("reset", 2)) + sender.session_up() + await settle() + assert sink.audio() == [pcm] + finally: + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + + +async def test_legacy_end_capacity_failure_is_itself_a_request_boundary(clock): + sink, log = FakeSink(), FakeLog() + sender = AudioSender( + Pacer(sink, RATE, clock=clock.now), RATE, log, max_queue_items=1 + ) + task = asyncio.create_task(sender.run()) + try: + sender.put_audio(b"\x01\x00", RATE) + await settle() + with pytest.raises(RuntimeError, match="input queue capacity"): + sender.put_end(End("tts_audio_end", 1, request_id="failed")) + await sender.flush() + sender.session_up() + await settle() + pcm = b"\x02\x00" + sender.put_audio(pcm, RATE) + await settle() + sender.put_end(End("tts_audio_end", 1, request_id="next")) + await settle() + assert sink.audio() == [pcm] + assert sink.ends == 1 + finally: + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + + +@pytest.mark.parametrize("phase", ["queued", "inflight", "active"]) +async def test_mixed_overflow_blocks_cancelled_unknown_audio(clock, phase): + async with Harness(clock, max_queue_ms=1000) as h: + pcm = _speech(600) + if phase == "active": + h.sender.session_up() + h.sender.put_audio(pcm, RATE) + if phase != "queued": + await settle() + with pytest.raises(RuntimeError, match="input queue capacity"): + h.sender.put_audio( + _speech(1200 if phase == "active" else 600), + RATE, + Turn("mixed", 1), + ) + await h.sender.flush() + h.sender.put_audio(_speech(200), RATE) + h.sender.session_up() + await settle() + assert h.sink.audio() == ([pcm] if phase == "active" else []) + assert h.sink.ends == 0 + following = Turn("mixed", 2) + next_pcm = _speech(100) + h.sender.put_audio(next_pcm, RATE, following) + await settle() + # The cancelled legacy boundary cannot close identified recovery. + h.sender.put_end(End("tts_audio_end", 1, request_id="legacy-failed")) + await settle() + assert h.sink.ends == 0 + h.sender.put_end(End("tts_audio_end", 1, following, "next")) + await settle() + assert h.sink.audio()[-1] == next_pcm + assert h.sink.ends == 1 + + +async def test_flush_drops_the_frame_waiting_at_the_gate(clock): + """The sender checked the flush generation before entering the pacer; a + flush that lands while the frame waits at the gate must still drop it, + so the cancelled turn does not restart after the interrupt.""" + async with Harness(clock) as h: + h.sender.session_up() + pcm_a = _speech(2000) + h.sender.put_audio(pcm_a, RATE) + h.sender.put_end(End("finalize")) + await settle() + assert h.sink.ends == 1 + + pcm_b = _speech(300) + h.sender.put_audio(pcm_b, RATE) + await settle() + assert h.sleep.calls == [pytest.approx(4.0)] + assert h.sink.audio() == [pcm_a] + + await h.sender.flush() + await settle() + assert h.sink.audio() == [pcm_a] + assert h.sink.interrupts == 1 + assert not h.sender.request_open + + # The next turn goes out at once, after the interrupt. + pcm_c = _speech(100) + h.sender.put_audio(pcm_c, RATE) + await settle() + assert h.sink.audio() == [pcm_a, pcm_c] + assert h.sink.calls.index(("interrupt",)) < h.sink.calls.index( + ("audio", pcm_c, False) + ) + assert h.sender.request_open + assert len(h.sleep.calls) == 1 + + +# -- reconnect ------------------------------------------------------------------ + + +async def test_frame_waiting_at_the_gate_survives_a_reconnect(clock): + """The session drops while a frame waits at the gate: the woken send is + refused, the frame is held, and the replacement session receives it.""" + client = FakeClient() + async with Harness(clock, sink=client) as h: + client.connect("conn-0") + h.sender.session_up() + pcm_a = _speech(2000) + h.sender.put_audio(pcm_a, RATE) + h.sender.put_end(End("finalize")) + await settle() + assert client.sessions["conn-0"] == [(pcm_a, False), (b"", True)] + + pcm_b = _speech(300) + h.sender.put_audio(pcm_b, RATE) + await settle() + assert h.sleep.calls == [pytest.approx(4.0)] + + # The reset wakes the gate; the send that follows is refused because + # the session is gone. Nothing is counted and the frame is held. + client.disconnect() + h.sender.session_down() + await settle() + assert client.sessions["conn-0"] == [(pcm_a, False), (b"", True)] + assert not h.sender.request_open + assert h.sender.queued == 0 + + client.connect("conn-1") + h.sender.session_up() + await settle() + assert client.sessions["conn-1"] == [(pcm_b, False)] + assert h.sender.request_open + assert h.pacer.ahead_ms == pytest.approx(300.0) + assert len(h.sleep.calls) == 1 + + +async def test_frame_held_for_reconnect_is_dropped_by_a_flush(clock): + client = FakeClient() + async with Harness(clock, sink=client) as h: + client.connect("conn-0") + h.sender.session_up() + h.sender.put_audio(_speech(2000), RATE) + h.sender.put_end(End("finalize")) + await settle() + h.sender.put_audio(_speech(300), RATE) + await settle() + assert len(h.sleep.calls) == 1 + + client.disconnect() + h.sender.session_down() + await settle() + await h.sender.flush() + + client.connect("conn-1") + h.sender.session_up() + await settle() + assert client.sessions["conn-1"] == [] + assert not h.sender.request_open + + +class BlockingClient(FakeClient): + """A ``FakeClient`` whose next send parks until the test releases it. + + The released send re-reads the connection, so a session that dropped + meanwhile refuses it, as the real client does. + """ + + def __init__(self): + super().__init__() + self.block_next = False + self._parked: asyncio.Future | None = None + + @property + def parked(self) -> bool: + return self._parked is not None and not self._parked.done() + + async def send_audio(self, pcm: bytes, end: bool = False) -> bool: + if self.block_next: + self.block_next = False + self._parked = asyncio.get_running_loop().create_future() + await self._parked + return await super().send_audio(pcm, end) + + def release(self) -> None: + self._parked.set_result(None) + + +async def test_inflight_send_failed_after_a_flush_is_not_replayed(clock): + """A flush lands while a frame's send is in flight; the send then fails + because the session dropped. The frame belongs to the cancelled turn + and must not reach the replacement session.""" + client = BlockingClient() + async with Harness(clock, sink=client) as h: + client.connect("conn-0") + h.sender.session_up() + client.block_next = True + h.sender.put_audio(_speech(300), RATE) + await settle() + assert client.parked + + await h.sender.flush() + client.disconnect() + h.sender.session_down() + client.release() + await settle() + assert client.sessions["conn-0"] == [] + + client.connect("conn-1") + h.sender.session_up() + await settle() + assert client.sessions["conn-1"] == [] + assert not h.sender.request_open + + # The next turn still goes out on the replacement session. + pcm = _speech(100) + h.sender.put_audio(pcm, RATE) + await settle() + assert client.sessions["conn-1"] == [(pcm, False)] + + +async def test_frame_refused_while_the_session_is_up_is_dropped(clock): + """A send that fails without the session going down is not retried: the + frame is dropped with a warning and the sender moves on.""" + client = FakeClient() + async with Harness(clock, sink=client) as h: + client.connect("conn-0") + h.sender.session_up() + client.refuse_sends = True + h.sender.put_audio(_speech(300), RATE) + await settle() + assert client.sessions["conn-0"] == [] + assert not h.sender.request_open + assert len(h.log.level("warn")) == 1 + + client.refuse_sends = False + pcm = _speech(100) + h.sender.put_audio(pcm, RATE) + await settle() + assert client.sessions["conn-0"] == [(pcm, False)] + assert h.sender.request_open diff --git a/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/test_session_client.py b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/test_session_client.py new file mode 100644 index 0000000000..51bd5f89bb --- /dev/null +++ b/ai_agents/agents/ten_packages/extension/spatialreal_avatar_python/tests/test_session_client.py @@ -0,0 +1,1177 @@ +# +# This file is part of TEN Framework, an open source project. +# Licensed under the Apache License, Version 2.0. +# See the LICENSE file for more information. +# +"""Unit tests for the SDK session wrapper and its reconnect policy. + +The SDK is replaced by ``FakeSession`` objects a ``FakeFactory`` hands out +through ``session_factory``; each can fail ``init``/``start``, record what +was sent, and fire the SDK callbacks the way the real session does. Time is +virtual: the client's ``sleep`` parks on a future that ``VirtualTime.advance`` +resolves, so a backoff schedule is asserted by advancing exactly the delays +the schedule promises. +""" + +import asyncio +from datetime import datetime, timedelta, timezone + +import pytest +from spatialreal import AvatarSDKError, AvatarSDKErrorCode, SessionTokenError +from spatialreal import UnsupportedConfigurationError + +from spatialreal_avatar_python import session_client +from spatialreal_avatar_python.pacer import Pacer +from spatialreal_avatar_python.sender import AudioSender +from spatialreal_avatar_python.session_client import ( + CODE_CONFIG, + CODE_FATAL, + CODE_NON_FATAL, + START_TIMEOUT_S, + Decision, + ErrorReport, + SessionClient, + SessionSettings, + classify_runtime_error, + classify_start_error, +) + +# Test literals, not credentials. The App ID has the width the token builder +# expects. +APP_ID = "a" * 32 +PCM = b"\x00\x00" * 240 + + +async def settle(rounds: int = 50) -> None: + """Let every ready callback and task step run.""" + for _ in range(rounds): + await asyncio.sleep(0) + + +class VirtualTime: + """A clock plus a ``sleep`` that only returns when the test advances.""" + + def __init__(self, start_s: float = 1000.0): + self._now_s = start_s + self._sleepers: list[tuple[float, asyncio.Future]] = [] + self.requested: list[float] = [] + + def now(self) -> float: + return self._now_s + + async def sleep(self, seconds: float) -> None: + self.requested.append(seconds) + fut = asyncio.get_running_loop().create_future() + entry = (self._now_s + seconds, fut) + self._sleepers.append(entry) + try: + await fut + finally: + if entry in self._sleepers: + self._sleepers.remove(entry) + + @property + def pending(self) -> list[float]: + """Remaining time of every sleep still parked, in request order.""" + return [deadline - self._now_s for deadline, _ in self._sleepers] + + async def advance(self, seconds: float) -> None: + target = self._now_s + seconds + while True: + due = sorted( + (e for e in self._sleepers if e[0] <= target), + key=lambda e: e[0], + ) + if not due: + break + deadline, fut = due[0] + self._sleepers.remove(due[0]) + self._now_s = max(self._now_s, deadline) + if not fut.done(): + fut.set_result(None) + await settle() + self._now_s = target + await settle() + + +def sdk_error(close_code, *, server_code=None, code=None) -> AvatarSDKError: + if code is None: + code = ( + AvatarSDKErrorCode.connectionClosed + if close_code is None + else AvatarSDKErrorCode.unknown + ) + return AvatarSDKError( + code, + f"test error close_code={close_code}", + close_code=close_code, + server_code=server_code, + ) + + +class FakeSession: + """Stands in for ``spatialreal.AvatarSession``. + + ``close()`` fires ``on_close`` once, as the SDK does after our own close; + the tests fire ``on_error``/``on_close``/``transport_frames`` by hand for + everything the server would do. + """ + + def __init__(self, index: int, kwargs: dict, init_exc, start_exc): + self.index = index + self.kwargs = kwargs + self.init_exc = init_exc + self.start_exc = start_exc + self.connection_id = f"conn-{index}" + self.capabilities = ( + "agora_source_timeline_only", + "agora_source_burst_v1", + ) + self.sends: list[tuple[bytes, bool]] = [] + self.interrupts = 0 + self.closes = 0 + self.send_exc: Exception | None = None + self.interrupt_exc: Exception | None = None + # ``start()`` never returns, like a server that upgrades the socket + # but never sends ServerConfirmSession. + self.start_hangs = False + self.start_cancelled = False + # Runs as ``start()`` returns: the SDK's read loop is already up by + # then, so the server can close or fail the session at once. + self.after_start = None + self._close_notified = False + + async def init(self) -> None: + if self.init_exc is not None: + raise self.init_exc + + async def start(self) -> str: + if self.start_hangs: + try: + await asyncio.get_running_loop().create_future() + except asyncio.CancelledError: + self.start_cancelled = True + raise + if self.start_exc is not None: + raise self.start_exc + if self.after_start is not None: + self.after_start(self) + return self.connection_id + + async def send_audio(self, audio: bytes, end: bool = False) -> str: + if self.send_exc is not None: + raise self.send_exc + self.sends.append((audio, end)) + return "req" + + async def interrupt(self) -> str: + if self.interrupt_exc is not None: + raise self.interrupt_exc + self.interrupts += 1 + return "req" + + async def close(self) -> None: + self.closes += 1 + self.fire_close() + + def fire_close(self) -> None: + if not self._close_notified: + self._close_notified = True + self.kwargs["on_close"]() + + def fire_error(self, exc: Exception) -> None: + self.kwargs["on_error"](exc) + + def fire_transport_frames(self) -> None: + self.kwargs["transport_frames"](b"\x00", False) + + +class FakeFactory: + """Builds one ``FakeSession`` per connect attempt, failing on request.""" + + def __init__( + self, + *, + init_error=None, + start_error=None, + start_hangs=None, + after_start=None, + ): + self.sessions: list[FakeSession] = [] + self._init_error = init_error or (lambda i: None) + self._start_error = start_error or (lambda i: None) + self._start_hangs = start_hangs or (lambda i: False) + self._after_start = after_start or (lambda i: None) + + def __call__(self, **kwargs) -> FakeSession: + i = len(self.sessions) + session = FakeSession( + i, kwargs, self._init_error(i), self._start_error(i) + ) + session.start_hangs = self._start_hangs(i) + session.after_start = self._after_start(i) + self.sessions.append(session) + return session + + @property + def last(self) -> FakeSession: + return self.sessions[-1] + + +class Harness: + def __init__(self, factory: FakeFactory, vt: VirtualTime, **overrides): + settings = dict( + api_key="k", + avatar_id="av", + channel="room", + uid=12345, + agora_appid=APP_ID, + ) + settings.update(overrides) + self.factory = factory + self.vt = vt + self.reports: list[ErrorReport] = [] + self.connected_ids: list[str] = [] + self.disconnects = 0 + self.client = SessionClient( + SessionSettings(**settings), + on_report=self.reports.append, + on_connected=self.connected_ids.append, + on_disconnected=self._on_disconnected, + session_factory=factory, + clock=vt.now, + sleep=vt.sleep, + ) + + def _on_disconnected(self) -> None: + self.disconnects += 1 + + @property + def codes(self) -> list[tuple[int, str]]: + return [(r.code, r.vendor_code) for r in self.reports] + + +class BurstFactory(FakeFactory): + def __init__(self, capabilities, **kwargs): + super().__init__(**kwargs) + self.capabilities = capabilities + + def __call__(self, **kwargs): + session = super().__call__(**kwargs) + session.capabilities = tuple(self.capabilities(session.index)) + return session + + +@pytest.fixture +def vt() -> VirtualTime: + return VirtualTime() + + +async def connected_harness(vt: VirtualTime, **overrides) -> Harness: + h = Harness(FakeFactory(), vt, **overrides) + await h.client.start() + await settle() + assert h.client.connected + return h + + +# -- classification ----------------------------------------------------------- + + +@pytest.mark.parametrize( + "exc, expected", + [ + (sdk_error(4001), (Decision.STOP, CODE_FATAL, "4001")), + (sdk_error(4010), (Decision.STOP, CODE_FATAL, "4010")), + (sdk_error(4003), (Decision.SLOW, CODE_NON_FATAL, "4003")), + (sdk_error(4503), (Decision.FAST, CODE_NON_FATAL, "4503")), + (sdk_error(1008), (Decision.STOP, CODE_FATAL, "1008")), + (sdk_error(None), (Decision.FAST, CODE_NON_FATAL, "AvatarSDKError")), + ( + # Handshake frame that did not parse: no close code, SDK says + # not retryable, still the fast schedule. + sdk_error(None, code=AvatarSDKErrorCode.protocolError), + (Decision.FAST, CODE_NON_FATAL, "AvatarSDKError"), + ), + ( + SessionTokenError("bad request", http_status=400), + (Decision.CONFIG, CODE_CONFIG, "400"), + ), + ( + SessionTokenError("unauthorized", http_status=401), + (Decision.STOP, CODE_FATAL, "401"), + ), + ( + SessionTokenError("forbidden", http_status=403), + (Decision.STOP, CODE_FATAL, "403"), + ), + ( + SessionTokenError("unavailable", http_status=503), + (Decision.FAST, CODE_NON_FATAL, "503"), + ), + ( + SessionTokenError("unavailable", http_status=502), + (Decision.FAST, CODE_NON_FATAL, "502"), + ), + ( + SessionTokenError( + "timeout", code=AvatarSDKErrorCode.connectionFailed + ), + (Decision.FAST, CODE_NON_FATAL, "SessionTokenError"), + ), + (OSError("dns"), (Decision.FAST, CODE_NON_FATAL, "OSError")), + ], +) +def test_classify_start_errors(exc, expected): + assert classify_start_error(exc) == expected + + +@pytest.mark.parametrize( + "exc, expected", + [ + (sdk_error(4002), (Decision.FAST, CODE_NON_FATAL, "4002")), + (sdk_error(4503), (Decision.FAST, CODE_NON_FATAL, "4503")), + (sdk_error(None), (Decision.FAST, CODE_NON_FATAL, "AvatarSDKError")), + ( + # One inference call failed: ServerError{code: 0}, session + # continues; not retryable per the SDK, still the fast schedule. + sdk_error( + None, code=AvatarSDKErrorCode.serverError, server_code="0" + ), + (Decision.FAST, CODE_NON_FATAL, "AvatarSDKError"), + ), + ( + sdk_error(None, code=AvatarSDKErrorCode.protocolError), + (Decision.FAST, CODE_NON_FATAL, "AvatarSDKError"), + ), + ( + sdk_error(4010, server_code="4010"), + (Decision.REPORT_ONLY, CODE_NON_FATAL, "4010"), + ), + (sdk_error(4010), (Decision.STOP, CODE_FATAL, "4010")), + (sdk_error(4001), (Decision.STOP, CODE_FATAL, "4001")), + (RuntimeError("boom"), (Decision.FAST, CODE_NON_FATAL, "RuntimeError")), + ], +) +def test_classify_runtime_errors(exc, expected): + assert classify_runtime_error(exc) == expected + + +# -- connect ------------------------------------------------------------------ + + +@pytest.mark.asyncio +async def test_connect_success_reports_connected_and_sends(vt): + factory = FakeFactory() + h = Harness( + factory, + vt, + app_id="app", + console_endpoint_url="https://console.test", + ingress_endpoint_url="wss://ingress.test/v2", + sample_rate=16000, + ) + assert not await h.client.send_audio(PCM) + + await h.client.start() + await settle() + + assert h.client.connected + assert h.client.connection_id == "conn-0" + assert h.connected_ids == ["conn-0"] + assert h.reports == [] + kwargs = factory.last.kwargs + assert kwargs["api_key"] == "k" + assert kwargs["avatar_id"] == "av" + assert kwargs["app_id"] == "app" + assert kwargs["sample_rate"] == 16000 + assert kwargs["console_endpoint_url"] == "https://console.test" + assert kwargs["ingress_endpoint_url"] == "wss://ingress.test/v2" + egress = kwargs["agora_egress"] + assert (egress.channel_name, egress.uid) == ("room", 12345) + # No certificate: the App ID itself is the token. + assert egress.token == APP_ID + assert egress.source_timeline_only is True + assert egress.source_playback_profile == 1 + + assert await h.client.send_audio(PCM) + assert await h.client.send_audio(b"", end=True) + assert factory.last.sends == [(PCM, False), (b"", True)] + assert await h.client.interrupt() + assert factory.last.interrupts == 1 + + +@pytest.mark.asyncio +async def test_optional_settings_are_omitted_when_empty(vt): + h = await connected_harness(vt) + kwargs = h.factory.last.kwargs + assert "app_id" not in kwargs + assert "console_endpoint_url" not in kwargs + assert "ingress_endpoint_url" not in kwargs + assert kwargs["environment"] == "us-west" + + +@pytest.mark.asyncio +async def test_source_timeline_mode_survives_reconnect(vt): + h = await connected_harness(vt, source_timeline_only=True) + first = h.factory.last + assert first.kwargs["agora_egress"].source_timeline_only is True + first.fire_close() + await settle() + await vt.advance(1) + assert h.client.connected + assert len(h.factory.sessions) == 2 + assert h.factory.last.kwargs["agora_egress"].source_timeline_only is True + + +@pytest.mark.asyncio +async def test_source_timeline_missing_ack_is_config_error_without_retry(vt): + factory = FakeFactory( + start_error=lambda _: UnsupportedConfigurationError("required mode") + ) + h = Harness(factory, vt, source_timeline_only=True) + await h.client.start() + await settle() + assert h.codes == [(CODE_CONFIG, "UnsupportedConfigurationError")] + assert not h.client.connected + assert vt.pending == [] + await vt.advance(300) + assert len(factory.sessions) == 1 + + +@pytest.mark.asyncio +async def test_source_timeline_old_sdk_is_explicit_config_error( + vt, monkeypatch +): + class LegacyEgressConfig: + __dataclass_fields__ = {} + + def __init__(self, **kwargs): + self.__dict__.update(kwargs) + + monkeypatch.setattr(session_client, "AgoraEgressConfig", LegacyEgressConfig) + factory = FakeFactory() + h = Harness(factory, vt, source_timeline_only=True) + await h.client.start() + await settle() + assert h.codes == [(CODE_CONFIG, "ValueError")] + assert not h.client.connected + assert factory.sessions == [] + assert vt.pending == [] + + +@pytest.mark.asyncio +async def test_old_sdk_still_connects_when_source_mode_is_disabled( + vt, monkeypatch +): + class LegacyEgressConfig: + def __init__(self, **kwargs): + assert "source_timeline_only" not in kwargs + self.__dict__.update(kwargs) + + monkeypatch.setattr(session_client, "AgoraEgressConfig", LegacyEgressConfig) + h = await connected_harness(vt, source_timeline_only=False) + assert h.factory.last.kwargs["agora_egress"].channel_name == "room" + assert h.reports == [] + + +@pytest.mark.asyncio +async def test_source_timeline_requires_sdk_ack_support_not_just_field( + vt, monkeypatch +): + monkeypatch.delattr( + session_client.spatialreal, "UnsupportedConfigurationError" + ) + factory = FakeFactory() + h = Harness(factory, vt, source_timeline_only=True) + await h.client.start() + await settle() + assert h.codes == [(CODE_CONFIG, "ValueError")] + assert factory.sessions == [] + assert vt.pending == [] + + +BURST_CAPABILITIES = ( + "agora_source_timeline_only", + "agora_source_burst_v1", +) + + +@pytest.mark.asyncio +async def test_burst_profile_reconnect_rechecks_real_confirmation(vt): + factory = BurstFactory(lambda i: BURST_CAPABILITIES if i == 0 else ()) + h = Harness( + factory, vt, source_timeline_only=True, source_playback_profile=1 + ) + await h.client.start() + await settle() + assert h.client.connected + assert factory.last.kwargs["agora_egress"].source_playback_profile == 1 + assert await h.client.send_audio(PCM) + first = factory.last + first.fire_close() + await settle() + await vt.advance(1) + assert not h.client.connected + assert h.connected_ids == [first.connection_id] + assert len(factory.sessions) == 2 + assert factory.last.kwargs["agora_egress"].source_playback_profile == 1 + assert factory.last.closes == 1 + assert not await h.client.send_audio(PCM) + assert factory.last.sends == [] + assert vt.pending == [] + await h.client.stop() + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "capabilities", [(), BURST_CAPABILITIES[:1], BURST_CAPABILITIES[1:]] +) +async def test_burst_post_start_refusal_closes_and_invalidates_callbacks( + vt, capabilities +): + # Observe retained ownership and callback invalidation during awaited close. + # pylint: disable=protected-access + class ClosingFactory(BurstFactory): + def __call__(self, **kwargs): + session = super().__call__(**kwargs) + original_close = session.close + generation = h.client._gen + + async def close(): + assert h.client._session is session + assert h.client._stale(generation) + session.fire_error(sdk_error(4010)) + await asyncio.sleep(0) + await original_close() + + session.close = close + return session + + # Capture the generation at creation, then observe ownership while close + # yields: callbacks must already be stale before the session is cleared. + factory = ClosingFactory(lambda _: capabilities) + h = Harness( + factory, vt, source_timeline_only=True, source_playback_profile=1 + ) + await h.client.start() + await settle() + assert h.codes == [(CODE_CONFIG, "UnsupportedConfigurationError")] + assert not h.client.connected + assert h.connected_ids == [] + assert h.client._session is None + assert factory.last.closes == 1 + assert factory.last.sends == [] + factory.last.fire_error(sdk_error(4503)) + factory.last.fire_transport_frames() + await settle() + await vt.advance(300) + assert len(factory.sessions) == 1 + assert len(h.reports) == 1 + assert vt.pending == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("capabilities", [None, " ".join(BURST_CAPABILITIES)]) +async def test_burst_missing_or_malformed_capabilities_is_config_error( + vt, capabilities +): + class UnconfirmedFactory(FakeFactory): + def __call__(self, **kwargs): + session = super().__call__(**kwargs) + session.capabilities = capabilities + return session + + factory = UnconfirmedFactory() + h = Harness( + factory, vt, source_timeline_only=True, source_playback_profile=1 + ) + await h.client.start() + await settle() + assert h.codes == [(CODE_CONFIG, "UnsupportedConfigurationError")] + assert factory.last.closes == 1 + assert factory.last.sends == [] + assert vt.pending == [] + + +@pytest.mark.asyncio +async def test_burst_old_sdk_rejected_before_session_creation(vt, monkeypatch): + monkeypatch.delattr(session_client.spatialreal, "RtcSourcePlaybackProfile") + factory = FakeFactory() + h = Harness( + factory, vt, source_timeline_only=True, source_playback_profile=1 + ) + await h.client.start() + await settle() + assert h.codes == [(CODE_CONFIG, "ValueError")] + assert factory.sessions == [] + assert vt.pending == [] + + +@pytest.mark.asyncio +async def test_zero_profile_omits_new_keyword_for_old_sdk(vt, monkeypatch): + class LegacyEgressConfig: + def __init__(self, **kwargs): + assert "source_playback_profile" not in kwargs + self.__dict__.update(kwargs) + + monkeypatch.setattr(session_client, "AgoraEgressConfig", LegacyEgressConfig) + monkeypatch.delattr(session_client.spatialreal, "RtcSourcePlaybackProfile") + h = await connected_harness( + vt, source_timeline_only=False, source_playback_profile=0 + ) + assert h.reports == [] + await h.client.stop() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("close_code, retries", [(1008, False), (4503, True)]) +async def test_burst_refusal_does_not_hide_transient_failure( + vt, close_code, retries +): + factory = BurstFactory( + lambda _: BURST_CAPABILITIES, + start_error=lambda _: sdk_error(close_code), + ) + h = Harness( + factory, vt, source_timeline_only=True, source_playback_profile=1 + ) + await h.client.start() + await settle() + assert factory.last.closes == 1 + assert factory.last.sends == [] + assert vt.pending == ([1] if retries else []) + assert h.codes == [ + (CODE_NON_FATAL if retries else CODE_FATAL, str(close_code)) + ] + await h.client.stop() + + +@pytest.mark.asyncio +async def test_source_timeline_parse_failure_keeps_fast_retry(vt): + factory = FakeFactory( + start_error=lambda _: AvatarSDKError( + AvatarSDKErrorCode.protocolError, + "malformed protobuf", + phase="websocket_handshake", + ) + ) + h = Harness(factory, vt, source_timeline_only=True) + await h.client.start() + await settle() + assert h.codes == [(CODE_NON_FATAL, "AvatarSDKError")] + assert vt.pending == [1] + + +@pytest.mark.asyncio +async def test_start_4003_uses_slow_schedule_then_stops(vt): + factory = FakeFactory(start_error=lambda i: sdk_error(4003)) + h = Harness(factory, vt) + await h.client.start() + await settle() + + assert len(factory.sessions) == 1 + assert h.codes == [(CODE_NON_FATAL, "4003")] + assert not h.client.connected + + for attempt, delay in enumerate( + [30, 60, 120, 300, 300, 300, 300, 300, 300, 300], start=1 + ): + assert vt.pending == [delay], f"attempt {attempt}" + await vt.advance(delay) + assert len(factory.sessions) == attempt + 1 + + # Ten retries failed: one fatal report, and the client is stopped. + assert vt.pending == [] + assert h.codes == [(CODE_NON_FATAL, "4003"), (CODE_FATAL, "4003")] + await vt.advance(3600) + assert len(factory.sessions) == 11 + + +@pytest.mark.asyncio +async def test_start_4503_uses_fast_schedule_until_it_connects(vt): + factory = FakeFactory( + start_error=lambda i: sdk_error(4503) if i < 3 else None + ) + h = Harness(factory, vt) + await h.client.start() + await settle() + + assert h.codes == [(CODE_NON_FATAL, "4503")] + for delay in (1, 2, 4): + assert vt.pending == [delay] + await vt.advance(delay) + assert h.client.connected + assert h.connected_ids == ["conn-3"] + # One outage, one non-fatal report. + assert h.codes == [(CODE_NON_FATAL, "4503")] + + +@pytest.mark.asyncio +async def test_start_never_confirmed_times_out_closes_and_retries(vt): + """The socket is up but ServerConfirmSession never arrives: start() is + abandoned at the deadline, the half-open session is closed, the outage + is reported once and the fast schedule makes another attempt.""" + factory = FakeFactory(start_hangs=lambda i: i == 0) + h = Harness(factory, vt) + await h.client.start() + await settle() + first = factory.last + assert not h.client.connected + assert vt.pending == [START_TIMEOUT_S] + assert h.reports == [] + + await vt.advance(START_TIMEOUT_S) + assert first.start_cancelled + assert first.closes == 1 + assert h.codes == [(CODE_NON_FATAL, "TimeoutError")] + assert not h.client.connected + assert vt.pending == [1] + + await vt.advance(1) + assert len(factory.sessions) == 2 + assert h.client.connected + assert h.connected_ids == ["conn-1"] + assert h.codes == [(CODE_NON_FATAL, "TimeoutError")] + + +@pytest.mark.asyncio +async def test_init_400_is_a_config_error_and_stops(vt): + factory = FakeFactory( + init_error=lambda i: SessionTokenError("skew", http_status=400) + ) + h = Harness(factory, vt) + await h.client.start() + await settle() + + assert h.codes == [(CODE_CONFIG, "400")] + assert vt.pending == [] + await vt.advance(3600) + assert len(factory.sessions) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("status", [401, 403]) +async def test_init_401_and_403_are_fatal_and_stop(vt, status): + """An invalid or revoked API key fails the token exchange before any + session exists: one fatal report, no retry, no 4010 to wait for.""" + factory = FakeFactory( + init_error=lambda i: SessionTokenError( + "api key refused", http_status=status + ) + ) + h = Harness(factory, vt) + await h.client.start() + await settle() + + assert h.codes == [(CODE_FATAL, str(status))] + assert h.reports[0].session_id == "" + assert not h.client.connected + assert vt.pending == [] + await vt.advance(3600) + assert len(factory.sessions) == 1 + assert h.codes == [(CODE_FATAL, str(status))] + + +@pytest.mark.asyncio +async def test_init_5xx_keeps_the_fast_schedule(vt): + factory = FakeFactory( + init_error=lambda i: ( + SessionTokenError("unavailable", http_status=503) if i < 2 else None + ) + ) + h = Harness(factory, vt) + await h.client.start() + await settle() + + assert h.codes == [(CODE_NON_FATAL, "503")] + for delay in (1, 2): + assert vt.pending == [delay] + await vt.advance(delay) + assert h.client.connected + assert len(factory.sessions) == 3 + assert h.codes == [(CODE_NON_FATAL, "503")] + + +# -- events during the handshake ---------------------------------------------- + + +@pytest.mark.asyncio +async def test_close_right_after_confirmation_is_a_failed_connect(vt): + """The server closes before the connection is published: no connected + report, one outage report, and the fast retry runs.""" + factory = FakeFactory( + after_start=lambda i: FakeSession.fire_close if i == 0 else None + ) + h = Harness(factory, vt) + + await h.client.start() + await settle() + + assert not h.client.connected + assert h.connected_ids == [] + assert h.disconnects == 0 + assert h.codes == [(CODE_NON_FATAL, "on_close")] + assert factory.sessions[0].closes == 1 + assert vt.pending == [1] + + await vt.advance(1) + assert h.client.connected + assert h.connected_ids == ["conn-1"] + assert h.codes == [(CODE_NON_FATAL, "on_close")] + + +@pytest.mark.asyncio +async def test_retryable_error_right_after_confirmation_retries(vt): + factory = FakeFactory( + after_start=lambda i: ( + (lambda s: s.fire_error(sdk_error(4503))) if i == 0 else None + ) + ) + h = Harness(factory, vt) + + await h.client.start() + await settle() + + assert not h.client.connected + assert h.connected_ids == [] + assert h.codes == [(CODE_NON_FATAL, "4503")] + assert vt.pending == [1] + await vt.advance(1) + assert h.connected_ids == ["conn-1"] + + +@pytest.mark.asyncio +async def test_fatal_error_during_startup_stops_without_connecting(vt): + factory = FakeFactory( + after_start=lambda i: lambda s: s.fire_error(sdk_error(4001)) + ) + h = Harness(factory, vt) + + await h.client.start() + await settle() + + assert not h.client.connected + assert h.client.connection_id == "" + assert h.connected_ids == [] + assert h.disconnects == 0 + assert h.codes == [(CODE_FATAL, "4001")] + assert factory.sessions[0].closes == 1 + assert vt.pending == [] + await vt.advance(3600) + assert len(factory.sessions) == 1 + assert not await h.client.send_audio(PCM) + + +# -- mid-session events ------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_on_close_without_error_reconnects_fast(vt): + h = await connected_harness(vt) + first = h.factory.last + + first.fire_close() + await settle() + + assert not h.client.connected + assert h.disconnects == 1 + assert h.codes == [(CODE_NON_FATAL, "on_close")] + assert first.closes == 1 + assert vt.pending == [1] + + await vt.advance(1) + assert h.client.connected + assert h.connected_ids == ["conn-0", "conn-1"] + assert len(h.factory.sessions) == 2 + + +@pytest.mark.asyncio +async def test_on_close_after_own_close_is_ignored(vt): + """Review Focus 4: the SDK's on_close after our teardown is not a drop.""" + h = await connected_harness(vt) + first = h.factory.last + + first.fire_error(sdk_error(None)) + await settle() + # Teardown closed the session, which made the fake fire on_close once; + # a stale duplicate from the SDK's read loop can still land afterwards. + assert first.closes == 1 + first.kwargs["on_close"]() + await settle() + + assert vt.pending == [1] + await vt.advance(1) + assert h.client.connected + assert len(h.factory.sessions) == 2 + + # Nothing else was scheduled: the new session stays up. + first.kwargs["on_close"]() + await vt.advance(60) + assert h.client.connected + assert len(h.factory.sessions) == 2 + assert h.codes == [(CODE_NON_FATAL, "AvatarSDKError")] + assert h.disconnects == 1 + + +@pytest.mark.asyncio +async def test_runtime_4010_server_error_only_reports_without_reconnect(vt): + h = await connected_harness(vt) + + h.factory.last.fire_error(sdk_error(4010, server_code="4010")) + await settle() + + assert h.client.connected + assert h.codes == [(CODE_NON_FATAL, "4010")] + assert h.reports[0].session_id == "conn-0" + await vt.advance(60) + assert len(h.factory.sessions) == 1 + assert h.client.connected + + +@pytest.mark.asyncio +async def test_runtime_4001_is_fatal(vt): + h = await connected_harness(vt) + first = h.factory.last + + first.fire_error(sdk_error(4001)) + await settle() + + assert not h.client.connected + assert h.codes == [(CODE_FATAL, "4001")] + assert first.closes == 1 + assert vt.pending == [] + await vt.advance(3600) + assert len(h.factory.sessions) == 1 + + +@pytest.mark.asyncio +async def test_send_audio_value_error_schedules_reconnect(vt): + h = await connected_harness(vt) + first = h.factory.last + first.send_exc = ValueError("WebSocket connection is not established") + + assert not await h.client.send_audio(PCM) + await settle() + + assert not h.client.connected + assert h.codes == [(CODE_NON_FATAL, "ValueError")] + assert first.closes == 1 + assert vt.pending == [1] + await vt.advance(1) + assert h.client.connected + assert len(h.factory.sessions) == 2 + + +@pytest.mark.asyncio +async def test_interrupt_value_error_is_not_a_drop(vt): + h = await connected_harness(vt) + h.factory.last.interrupt_exc = ValueError("interrupt: no request") + + assert not await h.client.interrupt() + await settle() + + assert h.client.connected + assert h.reports == [] + + +@pytest.mark.asyncio +async def test_idle_timer_reconnects_only_when_no_request_open(vt): + h = await connected_harness(vt, egress_idle_reconnect_ms=10_000) + first = h.factory.last + + h.client.note_request_state(True) + await vt.advance(12) + assert h.client.connected + assert len(h.factory.sessions) == 1 + + h.client.note_request_state(False) + await vt.advance(2) + assert len(h.factory.sessions) == 2 + assert h.client.connected + assert first.closes == 1 + # A planned reconnect is not an error. + assert h.reports == [] + + # Audio keeps the timer from firing. + await vt.advance(6) + assert await h.client.send_audio(PCM) + await vt.advance(6) + assert len(h.factory.sessions) == 2 + await vt.advance(6) + assert len(h.factory.sessions) == 3 + + +class _NullLog: + def log_debug(self, msg: str) -> None: + pass + + log_info = log_warn = log_error = log_debug + + +@pytest.mark.asyncio +async def test_ticker_closed_request_lets_the_idle_reconnect_run(vt): + """A request that stops producing audio without an end marker is + closed by the pacer's ticker at the padding limit. The client must + learn that, or its idle timer keeps waiting for the request forever.""" + rate = 24000 + reports: list[ErrorReport] = [] + factory = FakeFactory() + client = SessionClient( + SessionSettings( + api_key="k", + avatar_id="av", + channel="room", + uid=12345, + agora_appid=APP_ID, + egress_idle_reconnect_ms=10_000, + ), + on_report=reports.append, + on_connected=lambda _id: sender.session_up(), + on_disconnected=lambda: sender.session_down(), + session_factory=factory, + clock=vt.now, + sleep=vt.sleep, + ) + pacer = Pacer( + client, + rate, + clock=vt.now, + sleep=vt.sleep, + on_request_state=client.note_request_state, + ) + sender = AudioSender( + pacer, rate, _NullLog(), on_request_state=client.note_request_state + ) + tasks = [ + asyncio.create_task(sender.run()), + asyncio.create_task(pacer.run()), + ] + try: + await client.start() + await settle() + assert client.connected + first = factory.last + + # 500 ms of speech and no end marker. + sender.put_audio(b"\x01\x01" * (rate // 2), rate) + await settle() + assert pacer.request_open + + # The speech drains at 0.5 s; 3 s of padding later the ticker + # closes the request with end=True. + await vt.advance(4) + assert not pacer.request_open + assert first.sends[-1] == (b"", True) + assert len(factory.sessions) == 1 + + # 10 s after that last send the planned idle reconnect runs. + await vt.advance(10) + assert len(factory.sessions) == 2 + assert first.closes == 1 + assert client.connected + assert reports == [] + finally: + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + await client.stop() + + +@pytest.mark.asyncio +async def test_transport_frames_triggers_reconnect(vt): + h = await connected_harness(vt) + first = h.factory.last + + first.fire_transport_frames() + first.fire_transport_frames() + await settle() + + assert not h.client.connected + assert h.codes == [(CODE_NON_FATAL, "transport_frames")] + assert first.closes == 1 + assert vt.pending == [1] + await vt.advance(1) + assert len(h.factory.sessions) == 2 + assert h.client.connected + + +@pytest.mark.asyncio +async def test_tokens_minted_per_connect(vt): + h = await connected_harness(vt, agora_appcert="c") + before = datetime.now(timezone.utc) + + h.factory.last.fire_close() + await settle() + await vt.advance(1) + assert len(h.factory.sessions) == 2 + + first, second = h.factory.sessions + assert first.kwargs["agora_egress"] is not second.kwargs["agora_egress"] + # A certificate signs a salted token: two mints never match. + assert ( + first.kwargs["agora_egress"].token + != second.kwargs["agora_egress"].token + ) + for session in (first, second): + expire_at = session.kwargs["expire_at"] + assert expire_at.tzinfo is not None + assert ( + timedelta(minutes=59) + < expire_at - before + < timedelta(hours=1, seconds=5) + ) + + +@pytest.mark.asyncio +async def test_stop_closes_and_silences(vt): + h = await connected_harness(vt) + first = h.factory.last + + await h.client.stop() + await settle() + + assert not h.client.connected + assert first.closes == 1 + assert h.reports == [] + assert not await h.client.send_audio(PCM) + await vt.advance(3600) + assert len(h.factory.sessions) == 1 + + +@pytest.mark.asyncio +async def test_stop_during_backoff_cancels_the_retry(vt): + factory = FakeFactory(start_error=lambda i: sdk_error(4503)) + h = Harness(factory, vt) + await h.client.start() + await settle() + assert vt.pending == [1] + + await h.client.stop() + await settle() + assert vt.pending == [] + await vt.advance(3600) + assert len(factory.sessions) == 1 + + +@pytest.mark.asyncio +async def test_explicit_legacy_passes_false_and_zero_to_new_sdk(vt): + h = await connected_harness(vt, source_timeline_only=False) + egress = h.factory.last.kwargs["agora_egress"] + assert egress.source_timeline_only is False + assert egress.source_playback_profile == 0 + await h.client.stop() + + +@pytest.mark.asyncio +async def test_default_profile_requires_actual_server_confirmation(vt): + factory = BurstFactory(lambda _: ()) + h = Harness(factory, vt) + await h.client.start() + await settle() + assert not h.client.connected + assert factory.last.closes == 1 + assert factory.last.sends == [] + assert h.codes == [(CODE_CONFIG, "UnsupportedConfigurationError")] + assert vt.pending == [] + await h.client.stop()