Skip to content

feat: add spatialreal_avatar_python avatar extension - #2387

Open
YuehengHan wants to merge 36 commits into
TEN-framework:mainfrom
SpatialReal-ai:feat/spatialreal-avatar
Open

YuehengHan wants to merge 36 commits into
TEN-framework:mainfrom
SpatialReal-ai:feat/spatialreal-avatar

Conversation

@YuehengHan

@YuehengHan YuehengHan commented Nov 4, 2026 •

Copy link
Copy Markdown

Summary

Adds spatialreal_avatar_python, an avatar extension that drives a SpatialReal avatar into the Agora channel from a TEN graph's TTS audio.

  • Sits after the TTS node like the existing avatar extensions: pcm_frame in, request end on data tts_audio_end (REQUEST_END/ERROR, INTERRUPTED without a prior flush) or data finalize, cmd flush in and forwarded, errors as ModuleError on data error (module: "avatar", vendor_info.vendor: "spatialreal", codes -1012 config / -1 fatal / 1001 non-fatal).
  • Audio goes through the spatialreal Python SDK (PyPI, >=0.4.0,<0.5) into a session configured for Agora egress; SpatialReal's egress joins the channel as params.agora_uid and publishes the TTS audio plus the avatar animation as SEI on a placeholder video track. There are no rendered video frames: the 3DGS avatar is rendered on the viewer's side with the SpatialReal web SDK in Agora mode (a plain Agora player shows audio and a black 64x64 picture). The README states this up front.
  • Playback mode: by default the egress publishes on the source audio timeline with the bounded burst profile (params.source_timeline_only, default true; params.source_playback_profile, default 1). Both are negotiated at session start: the backend must confirm the agora_source_timeline_only and agora_source_burst_v1 capabilities, otherwise the session is closed and a -1012 configuration error is reported, with no retry and no silent fallback. params.source_timeline_only: false selects compatibility mode for viewers that play the egress's native audio.
  • Viewers: @spatialreal/web-sdk 1.0.0-beta.7 or newer (detects the published profile automatically), or 1.0.0-beta.6 with agora.sourcePlaybackProfile: 'bounded-burst-v1'.
  • Properties: top-level channel (filled by the server at /start) plus a params object with the SpatialReal keys (spatialreal_api_key, spatialreal_avatar_id, optional spatialreal_app_id, environment, endpoint overrides, sample_rate, the two playback keys) and the Agora keys (agora_uid, agora_token, agora_appid, agora_appcert, agora_channel). The Agora token is used verbatim when given, otherwise minted with agora-token-builder from the app certificate, otherwise the App ID.
  • Request pacing: within a request audio is forwarded as fast as it arrives. Silence is inserted only after the sent audio has drained, so a sentence gap does not let the SpatialReal playout buffer run dry; padding is bounded to 3 s per gap, after which the request is closed. A new request waits for the previous one to finish playing so back-to-back turns do not cut each other.
  • Turn isolation and buffering: each frame and end keeps its TEN metadata.session_id/turn_id; a flush retires the active, queued and in-flight turns, and late audio or ends from a retired turn are ignored. Input is kept within 120 s of PCM, 16 MiB and 4096 items; going over cancels the buffered turn with a non-fatal InputQueueOverflow error instead of dropping audio.
  • Connection: the session handshake (start plus the capability check) has a 20 s deadline; reconnects use backoff on transport loss; credits-exhausted, auth refusals and HTTP 401/403 on the token exchange are reported and stop the reconnect loop; an idle session reconnects before the egress inactivity timeout.
  • Example: voice_assistant_spatialreal graph in voice-assistant-advanced (same wiring as the HeyGen graph with the avatar node swapped) and the three SPATIALREAL_* keys in ai_agents/.env.example.

Type of Change

  • New feature

Testing

  • task check (black, 80 cols): clean. pylint --rcfile=tools/pylint/.pylintrc on the extension: 10.00/10.
  • ghcr.io/ten-framework/ten_agent_build:0.7.14 with spatialreal 0.4.0 installed from PyPI: 227 tests pass (211 pure unit tests, 16 under the TEN runtime, none skipped). The pure tests cover the pacer, sender ordering and turn isolation, resampling, the token rule, config resolution and the session wrapper's handshake and reconnect policy; they also run with plain pytest tests/ on a laptop without the runtime.
  • End-to-end in a full TEN app: a voice-assistant graph (deepgram_asr_python → gemini_llm2_python → cartesia_tts → this extension, with main_python and agora_rtc) running in the TEN runtime against SpatialReal's backend, a real Agora channel and viewers on @spatialreal/web-sdk in desktop Chrome and Safari. Human conversations with interruptions, and scripted full-path runs that feed synthetic speech through the whole pipeline (ASR → LLM → TTS → avatar) and check that every normal reply drains to its exact final sample, with no audio scheduling gaps, and that an interruption during playback is followed by a clean reply. The same setup runs as a hosted public demo on released packages (spatialreal 0.3.0 and @spatialreal/web-sdk 1.0.0-beta.6) with both playback settings set explicitly, which is the behaviour 0.4.0 and this extension now use by default.
  • Module-level live check against SpatialReal's test environment (the extension's pacer and session client fed with recorded speech, an Agora viewer counting SEI packets, SpatialReal's egress logs): a 1.5 s sentence gap inside one request plays all audio with no frame loss; two back-to-back requests both play to the end; a 12 s gap closes the request after 3 s of padding and the next sentence starts a new one.
  • Not covered by a live session: the four commits that answer the review findings (handshake deadline, idle notification on ticker closures, and the two regression tests) — covered by unit and runtime tests.

Documentation

  • README.md for the extension: media shape, viewer requirement and playback mode, configuration table (property, env var, default, range), complete graph node, test and lint commands, limits.
  • .env.example keys; example graph in rebuild_property.py and property.json.

Breaking Changes

None. New extension and new example graph only; existing graphs are untouched.

Notes for reviewers

  • agora_uid is a string property (as the hosted engine passes it) but must parse as a non-zero integer: SpatialReal's egress publishes with an integer uid.
  • The extension never logs the API key, session token, Agora token or app certificate (redacted with ten_ai_base.utils.encrypt).
  • Changes since the first review round are summarized in the comment answering the review findings.

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown
  1. [P1] Serialize request-end signals with queued audio — extension.py:298

    Audio callbacks only enqueue PCM, but this handler immediately closes the pacer. If the sender is behind, waiting for connection, or waiting at the previous request's playback gate, tts_audio_end overtakes its own audio: it either sends end=True before the remaining frames or is discarded because the request has not opened yet. Later frames then reopen a request or merge with the following turn, breaking request boundaries and introducing extra playback gaps. Process tts_audio_end and finalize as ordered markers alongside PCM. Add an extension-level regression that queues a complete second request and its end while the first request's gate is active, asserting that each end follows all of its own PCM.

  2. [P1] Discard the waiting frame when flush cancels its turn — pacer.py:128–130

    A frame already inside _wait_for_gate() survives _flush(): the extension clears the queue and increments _flush_gen, but the sender checked that generation before entering the pacer. Pacer.flush() wakes the gate and waives the delay, so these lines reopen a request and send the cancelled frame immediately after the interrupt. A user interruption can therefore restart old speech and its silence padding. Carry a cancellation generation through the gate or cancel/discard the pending send before it reaches the sink. test_flush_bypasses_gate_and_interrupts currently asserts that the old frame is sent after interruption; change that expectation and cover the extension's flush path.

  3. [P2] Keep the dequeued frame until a connected session accepts it — extension.py:357

    The connection check precedes push_audio(), which can wait several seconds at the playback gate. If the session disconnects during that wait, _on_disconnected() resets the pacer and wakes the gate while _connected is clear. The pending send then reaches SessionClient.send_audio(), returns False, and is nevertheless counted as sent by the pacer; this dequeued PCM is permanently lost. Recheck session readiness after the gate and propagate unsuccessful sends so the frame can wait for reconnection, subject to flush cancellation. Add a test combining the sender, pacer, and client that disconnects during a gate wait and verifies the replacement session receives the pending PCM.

  4. [P2] Stop retrying permanent token-authentication failures — session_client.py:122–125

    SpatialReal SDK 0.2.3 raises SessionTokenError with http_status=401 or 403 when the token exchange rejects authentication. Both take this unconditional fast-retry branch, so an invalid or revoked API key produces only a non-fatal outage report and retries forever with unchanged credentials. The fatal handling for WebSocket close code 4010 never applies because token creation fails first. Classify HTTP 401/403 as terminal authentication errors and emit the fatal ModuleError; retain retries for transient failures. Add classification and reconnect-loop tests asserting one fatal report and no retry for both statuses.

@YuehengHan

Copy link
Copy Markdown
Author

Thanks for the review. All four findings are addressed in the commits pushed after e6e59a1 (fdc5f8b, 72f5960, 3f78a4f, d08fa42, 2f6eeb6); 133 tests pass in ten_agent_build:0.7.14, black and pylint are clean.

1. Request-end signals overtaking queued audio. Fixed in fdc5f8b. tts_audio_end and finalize are no longer applied when they arrive; they are queued as End markers in the same queue as the PCM, and the sender applies a marker only after every frame queued before it has been sent. flush still acts at once and clears frames and markers together, since everything queued belongs to the cancelled turn; the 10 s bound drops the oldest frames only, never a marker. The sender loop moved from extension.py into the pure sender.py so it runs under pytest without ten_runtime. test_end_follows_its_own_audio_behind_the_gate queues a complete second request plus its end while the first request's gate holds the sender and asserts the sink sees audio, audio, end with the request closed; further tests cover an end queued before the session is up, a flush dropping markers, and a late reason 2 after a flush.

2. Frame inside the gate surviving a flush. Fixed in 72f5960. The pacer carries a cancellation generation through _wait_for_gate(): flush() bumps it, a wait that started under an older value returns without opening a request or sending, and push_audio() reports PushResult.CANCELLED, which the sender drops. The waiver the flush set still applies to the next turn's first chunk, and on_session_reset() does not cancel, so a frame woken by a reconnect is still sent. test_flush_bypasses_gate_and_interrupts was replaced by test_flush_cancels_the_chunk_waiting_at_the_gate, which asserts the pending frame is not sent and the next turn opens immediately after the interrupt; test_flush_drops_the_frame_waiting_at_the_gate covers the sender path.

3. Send after the gate counted as sent while disconnected. Fixed in 3f78a4f and 2f6eeb6. PacerSink.send_audio declares its bool result and the pacer reads it: a refused send is PushResult.NOT_SENT, nothing is counted, and a request opened for that chunk is forgotten; refused padding is not counted either. The sender keeps the converted frame, waits for the session event again and retries on the replacement session unless a flush lands first. A refused send while the session event is still set is dropped with one warning rather than retried, to avoid a tight loop. test_frame_waiting_at_the_gate_survives_a_reconnect runs sender, pacer and a fake client that drops during the gate wait and asserts the pending PCM is delivered to the replacement session with no second gate wait; companion tests cover the flush-while-held and refused-while-up cases.

4. Permanent token-authentication failures retried forever. Fixed in d08fa42. classify_start_error treats a SessionTokenError with HTTP 401 or 403 as terminal: Decision.STOP, code -1, one fatal report, no further attempt. HTTP 400 stays a configuration error and other token failures (5xx, network) keep the fast schedule. spatialreal 0.2.3 sets http_status on every non-200 token response, so that field is the classifier's input. The vendor code for a token error that carries an HTTP status is now that status as a string, alongside the WebSocket close codes. Tests add the 401/403/502 classification cases, a reconnect-loop test per refused status asserting a single fatal report and no retry, and a 5xx test asserting the fast schedule still reconnects.

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown
  1. [P2] Preserve a frame's flush generation across send retries — sender.py:255–258

    If flush() lands while push_audio() is awaiting an SDK send and that send subsequently fails with the session down, the frame reaches the retry loop. These lines replace its original generation with the post-flush generation, so it passes the check after reconnection and replays audio from the cancelled turn. The pacer's cancellation check only covers the gate wait. Capture the frame's generation once and check it after the awaited push as well as the connection wait. Add a regression that blocks an in-flight send, flushes, lets the send fail, and verifies the replacement session never receives that frame; the existing flush test waits until the frame is already held for reconnect.

  2. [P2] Preserve connected-session audio while waiting at the playback gate — sender.py:103–104

    The 10-second eviction policy runs on every enqueue, including while connected and waiting for the preceding request to finish playing. A second request that generates more than 10 seconds of PCM during that normal gate wait loses its oldest queued frames, so the avatar skips words despite a healthy connection. The README describes this loss policy only for disconnected sessions. Preserve audio during normal connected playback, using backpressure or a separate buffering policy as needed, and add a test queuing more than 10 seconds behind an active gate that verifies all PCM reaches the sink in order.

  3. [P2] Bound the application handshake and close timed-out sessions — session_client.py:370–371

    SpatialReal SDK 0.2.3's start() awaits _await_confirm_session(), which performs an unbounded WebSocket recv(). If the socket upgrades and answers pings but never sends ServerConfirmSession, this await never finishes: the reconnect loop cannot advance, the idle timer has not started, and incoming speech is eventually evicted from the queue. Apply a finite handshake deadline and explicitly close the partially started session before retrying; cancelling this SDK call does not run its except Exception cleanup. Cover a session whose start() never returns, asserting a timeout report, session closure, and a subsequent attempt.

  4. [P2] Notify the idle timer when the ticker closes a request — pacer.py:288–289

    Padding-limit and stall closures execute in the independent pacer ticker, bypassing AudioSender._note_request_state(). After a request stops producing audio without an end marker, the pacer closes it but SessionClient._request_open remains True. With no later input to correct that flag, _idle_loop() skips the planned reconnect indefinitely, allowing egress to leave the channel after its inactivity timeout. Publish every request-state transition to the client, including ticker-initiated closure, and add a combined pacer/client test that reaches the padding limit without an end marker and then verifies the idle reconnect occurs.

Package skeleton for the SpatialReal avatar extension: manifest with the
top-level + params property shape, pcm_frame in, tts_audio_end/finalize data
in, flush cmd in/out and error data out; property.json defaults with env
references; pyproject and requirements pinning spatialreal 0.2.3,
agora-token-builder and audioop-lts on 3.13.

The extension class is a stub whose hooks log at debug and whose on_cmd
answers OK; dispatch and the session wiring come in later commits.

Tests: tests/conftest.py holds pure fixtures (FakeClock) and nothing from
TEN; tests/runtime/ carries the heygen-style FakeApp conftest and the
hello_world basic test behind pytest.importorskip("ten_runtime"), so
`pytest tests/` on a laptop runs the pure tests and skips the runtime ones.
…se in params

The TEN server injects the channel into the node property; every other setting,
including the Agora keys, lives in the params object as ten_ai_base vendor
extensions do. ten_ai_base is declared as the 0.7 range; the resolved version
must export ModuleType.AVATAR (checked at install time).
build_agora_token applies the D3 rule the session client re-runs on every connect: an
explicit agora_token is used verbatim, otherwise an App Certificate signs a publisher token
for the channel and uid (24 h by default), otherwise the App ID itself is the token. No App
ID and no token is a ValueError the glue reports as a config error.

The tests parse the minted token back and check the publisher privileges and their expiry;
byte equality is not possible because the builder salts every token.

pyproject.toml gains the pytest options that let `pytest tests/` run from this directory on
a laptop without the TEN runtime: the pure modules import from here, and collection stops
at tests/ so the package __init__ (which imports ten_runtime) is never loaded.
Pure audio module for the avatar extension (design D5): a streaming
int16 mono Resampler over audioop.ratecv that keeps filter state across
the chunks of one request and resets at close/flush, drops a trailing
odd byte instead of raising, and passes same-rate audio through; a
silence() generator in whole samples at the session rate for the pacer's
padding, and duration_ms() for the virtual playhead.

Tests cover pass-through, the odd-byte and empty-buffer guards, the
16k->24k length ratio, state continuity across 10x20 ms chunks versus a
single 200 ms conversion, reset, silence sample counts and the
fractional-sample rejection.
Pure pacer module for the avatar extension (design D5, D6). It owns the
request boundaries: the first audio after idle opens a request, and the
first of tts_audio_end (reasons 1, 3, unknown; 2 only when no flush has
been processed since the last end signal), finalize, the padding bound or
the stall backstop closes it with send_audio(b"", end=True). Closing is
idempotent and reports whether this call closed, so the glue logs each end
signal once.

A virtual playhead, ahead_ms = sent_ms - (now - first_send), drives the
padding: each tick sends enough 100 ms silence chunks (whole samples at the
session rate) to lift the playhead back to the 600 ms floor, with a
microsecond tolerance so float drift on the floor never pads a spurious
chunk. Three seconds of contiguous padding closes the request; 15 s after
the real audio drained is the outer backstop.

A new request waits while the predecessor's playhead is less than 2000 ms
past drained. The wait races the injected sleep against an abort event, so
flush cancels it, closes the open request locally without end=True, calls
interrupt and waives the gate for the next request. on_session_reset
forgets the playhead after a reconnect.

Tests drive the clock and ticks by hand with a fake sink: open and send,
padding below the floor, none above it, pad max and stall closing once,
the tts_audio_end reason table, finalize then tts_audio_end sending one
end=True, the gate wait and early-wake re-check, flush during the gate
wait (interrupt first, then the new request), whole-sample padding at
22050 Hz, session reset and the run loop.
…on loads

The TEN Python addon loader imports the extension as the package
ten_packages.extension.spatialreal_avatar_python with only the app root on
sys.path; the extension directory itself is never there. pacer.py's
`from audio import ...` therefore raised ModuleNotFoundError the moment the
package imported it, and pylint flagged it as E0401. Use `from .audio import`
like every other extension.

The laptop tests masked this through pytest's `pythonpath = ["."]`. Drop it;
tests/conftest.py now registers a stub `spatialreal_avatar_python` package
whose __path__ is the extension directory, so the tests import the pure
modules by package name without running the real __init__ (which needs
ten_runtime). The test files import through that package name.
…olicy

SessionClient keeps one spatialreal session up for the extension's lifetime and owns
reconnection (design D7). Every connect mints a fresh session token (expire_at now + 1 h) and a
fresh Agora token through the D3 rule. classify_start_error and classify_runtime_error map the
SDK's exceptions to a decision: 4001/4010 fatal, 4003 slow schedule (30, 60, 120, 300 s, ten
attempts, then fatal), 4503 and transport failures fast schedule (1, 2, 4, 8, 15, 30 s), token
HTTP 400 a config error, a 4010 server-error frame report-only. on_close without a preceding
error, ValueError from send_audio and transport_frames also reconnect on the fast schedule; an
idle timer reconnects silently after egress_idle_reconnect_ms when no request is open.

Reports (D8 codes 1001 / -1 / -1012) go to the glue as ErrorReport; an outage reports 1001 once.
SDK callbacks are marshalled with call_soon_threadsafe and bound to the session generation that
registered them, so an on_close that lands after our own teardown cannot start a second connect.

Tests drive the client against a fake session factory under virtual time and cover every
decision branch, the slow and fast schedules, the stale on_close case, the idle timer, token
re-minting per connect and stop during backoff.
…e code

classify_start_error and classify_runtime_error deferred to the SDK's
AvatarSDKError.retryable when close_code was None, and the SDK only
answers True for connectionFailed/connectionClosed/upstreamError. A
failed inference call relayed as ServerError{code: 0} (session still
up), a frame that did not parse (protocolError) and a protocolError from
the handshake therefore classified as STOP and tore the session down for
good. Design D7 says a missing close code takes the fast schedule in
both places; check close_code is None first and let retryable handle the
coded cases. Tests cover serverError(server_code="0") and protocolError
with no close code in both classifiers.

Drop the two `except asyncio.CancelledError: raise` branches: on
Python 3.8+ CancelledError is a BaseException that the following
`except Exception` never catches, so they were dead code and pylint
flagged them as W0706 (TEN CI fails on any warning). Remove the two
broad-exception-caught disables along with them; TEN's .pylintrc already
disables that check globally.
…d error reporting

Resolve the two top-level properties (channel and the params object) in a pure
config module: agora_channel overrides channel, agora_uid parses from a string or
an int and must be non-zero, sample_rate must be one of the accepted session
rates, agora_appid is required unless agora_token is set, and an empty channel
gets the hint about the TEN server injecting it. Integer knobs given as null or
an empty string fall back to the package defaults.

The extension loads the config, logs it once with secrets masked, and wires the
session client, the pacer and a per-rate resampler together: audio frames are
queued (bounded to 10 s of playout) until the session is up, tts_audio_end and
finalize close the request through the pacer, flush drops queued audio, cancels
the gate wait, interrupts and continues downstream. Every report becomes a
ModuleError on data error with module avatar, the -1012 / -1 / 1001 codes,
vendor_info spatialreal plus the close code or exception class, and a
vendor_metadata block without URLs, keys or empty values. Nothing raises out of
a hook; a config failure leaves the extension idle.

The runtime test asserts the error shape for empty params; it runs only under
the TEN runtime.
README per the design: media shape (audio plus SEI animation, no video), the
configuration table with the session-rate note, a complete avatar node with
"channel": "" and its three edges, test and lint commands, and the limits.

voice-assistant-advanced gets a voice_assistant_spatialreal graph built by the
basic voice assistant builder with the SpatialReal avatar node, the matching
path dependency in its manifest, and SPATIALREAL_* keys in .env.example next
to the Agora keys.

property.json carries only the new graph. The committed file has drifted from
rebuild_property.py (hellos prompt wording, compact "names" arrays), so a plain
rerun would also rewrite unrelated graphs; the new graph is the script's output
appended to the committed file, every other byte unchanged.
Verified in ghcr.io/ten-framework/ten_agent_build:0.7.14 (Python 3.10.12, black 25.12.0,
pylint 3.3.9): tman resolves ten_runtime_python 0.11.75 and ten_ai_base 0.7.63, which exports
ModuleType.AVATAR and ModuleErrorVendorInfo, so the manifest keeps ten_ai_base 0.7.

The CI image ships pytest without pytest-asyncio (and another extension pins pytest 8.3.4),
where pytest 8 skips coroutine tests and pytest 9 fails them. tests/conftest.py now runs each
coroutine test on a fresh event loop when the plugin is absent, so the 39 async tests run
everywhere; pytest-asyncio still owns them where it is installed.

Drop the redundant `except CancelledError: raise` in the audio sender (pylint W0706):
CancelledError derives from BaseException and already passes the `except Exception` handler.
…ams arrived as a dict

With every required key empty, an empty `params` dict and a dict of empty strings produce the
same first message ("params.spatialreal_api_key is required"), so the runtime test could not
tell whether the `params` object reached `resolve_config` at all. Give the fixture non-empty
test literals for the SpatialReal keys, the channel and the Agora app id, and `agora_uid: "abc"`:
validation now fails on `agora_uid`, which only happens when `params` was read as a dict.
…ror report names

`SessionClient` reports before it clears `connection_id`, but `_on_report` only spawns
`_send_error`, which read `self.client.connection_id` when the task ran, by which time it was
already "". Every mid-session error therefore shipped `metadata.session_id = ""`. `_send_error`
now takes `session_id`, defaulting to the client's current connection id for the config and
start-up errors, and `_on_report` passes `report.session_id`.

No committed test reaches this: extension.py imports ten_runtime, so the pure suite cannot load
it, and the runtime harness has no connected session to drop. Checked by hand with stubbed TEN
modules: a report carrying "conn-42" arrives on data `error` as `session_id` "conn-42" after
the client's own id was cleared; the default still reads the live id.
…vedConfig in one step

`ResolvedConfig` and `SessionSettings` have the same 13 fields; `_start_session` copied them one
by one and `redacted()` listed them again with its own idea of which were secret. It now does
`SessionSettings(**asdict(cfg))`, and `redacted()` and `redacted_params()` share one `_masked`
helper driven by `SECRET_KEYS`, with a one-entry map for the field whose name differs from its
property key (`api_key` -> `spatialreal_api_key`). Output is unchanged, key order included.

A pure test pins the field lists of the two dataclasses to each other so a field added to one
and not the other fails the suite instead of silently dropping a setting.
…session reset

`on_session_reset()` forgot the playhead (`ahead_ms` becomes -inf) but left the sender's gate
wait sleeping on the old remaining time, so after a reconnect the first chunk of the next
request could sit for up to `ahead_ms + gate_ms` for a tail that no longer exists. The reset
now also sets the gate-abort event; `_wait_for_gate` re-reads the playhead on wake and returns
at once. Covered by a test with a hanging sleep: the audio queued at the gate is sent as soon
as the reset lands, with no second sleep.
… queued audio

`tts_audio_end` and `finalize` closed the pacer's request the moment they arrived, while the
request's PCM could still be queued for the sender task: behind, waiting for the session, or
waiting at the previous request's gate. The `end=True` then either overtook its own audio or was
discarded because the request had not opened yet, and the frames that followed reopened a
request or merged into the next turn.

The end signals are now `End` markers in the same queue as the frames, applied by the sender
only after every frame queued before them has gone out. `flush` still acts at once: it clears the
queue, markers included, since everything queued belongs to the cancelled turn. The queue bound
drops the oldest frames only, never a marker.

The sender loop (queue, session wait, resampling, pacer calls, request-state notes) moves out
of `extension.py` into the pure `sender.py` so it runs under pytest without `ten_runtime`. The
new tests drive the real pacer with a sleep the test releases: a complete second request plus its
end queued while the first request's gate is active goes out as audio, audio, end; an end queued
before the session is up waits for its audio; a flush drops frames and markers; a late reason 2
reaches the pacer and is ignored after a flush.
…it waits at the gate

The sender compared the flush generation before it entered the pacer, so a frame already inside
`_wait_for_gate()` survived a flush: `Pacer.flush()` woke the gate and waived the delay, and the
cancelled frame was sent right after the interrupt, restarting the old speech.

The pacer now carries its own cancellation generation through the gate. `flush()` bumps it; a
wait that started under an older value returns without opening a request or sending, and
`push_audio()` reports it as `PushResult.CANCELLED` (`PushResult.SENT` otherwise). The sender
drops a cancelled frame. The waiver the flush set stays for the next turn's first chunk, as
before. `on_session_reset()` does not cancel: a frame woken by a reconnect still goes out.

`test_flush_bypasses_gate_and_interrupts` asserted the old frame was sent; it now asserts it is
not, and that the next turn's first chunk opens a request at once after the interrupt. A sender
test covers the same path end to end.
…ession refused

The sender checked the session before `push_audio()`, which can wait seconds at the gate. A
session that dropped meanwhile reset the pacer and woke the gate; the send then reached
`SessionClient.send_audio()`, which returned False, but the pacer counted the chunk as sent and
the PCM was lost.

`PacerSink.send_audio` now declares its bool result and the pacer reads it: a refused send is
`PushResult.NOT_SENT`, nothing is counted, and a request opened for that chunk is forgotten
(`_forget_request`, shared with `on_session_reset`). A refused padding chunk is not counted
either. The sender treats `NOT_SENT` as "still owed": it keeps the converted frame, waits for the
session event again and retries on the replacement session, unless a flush lands first, which
drops it as before.

Tests: a pacer test for the refused send and refused padding; sender tests over a fake client
that drops during the gate wait, asserting the pending PCM lands in the replacement session
with no second gate wait, and that a flush while the frame is held drops it.
… HTTP 401 or 403

`classify_start_error` sent every `SessionTokenError` other than HTTP 400 down the fast-retry
branch, so an invalid or revoked API key was reported once as non-fatal `1001` and retried
forever. The fatal 4010 handling never applied: with no session token there is no handshake to
be refused.

HTTP 401 and 403 from the token exchange are now terminal: `Decision.STOP`, code `-1`, one
fatal report, no further attempt. 400 stays a configuration error and everything else (5xx,
network) keeps the fast schedule. The SDK (spatialreal 0.2.3) sets `http_status` on every
non-200 token response, so that field is the classifier's input. The vendor code for a token
error that carries an HTTP status is now that status as a string ("400", "401", "403", "503"),
alongside the WebSocket close codes; the class name remains for errors without one.

Tests: classification cases for 401, 403, 502 and the updated 400/503 vendor codes; a
reconnect-loop test per refused status asserting a single fatal report and no retry over an
hour; a 5xx test asserting the fast schedule still reconnects.
…n is still up

The hold-for-reconnect path assumed every refused send meant the session had gone down. The
client can also answer False while it stays connected (a send that raised a server error the
client only reports), and the sender would then retry the same chunk in a tight loop.

A refused send is held only when the session event is clear, which is what `session_down`
does on an outage; when the event is still set the chunk is dropped with one warning and the
sender moves on. Covered by a sender test over a fake client that refuses sends while connected.
The pacer refilled the virtual playhead to a 600 ms reserve whenever it
dipped below it, so a ticker that ran while speech was still playing
spliced silence between speech chunks that arrived in time.

PAD_FLOOR_MS is now 0: silence is inserted only after the sent audio has
drained, and only enough to cover the actual deficit. Positive lead is
left alone.
Padding computed its chunk count once and then sent the whole batch, so
real audio or an end that arrived during an awaited padding send was
followed by stale silence. The lead is now rechecked before each chunk,
and padding stops as soon as the request closes.
…layback state

Preserve TEN session/turn metadata through the ordered audio sender so
late PCM or end events cannot close or restart a newer identified turn.
Keep request-end deduplication separate from turn retirement, and reject
old turn numbers per session without dropping earlier queued audio.

Wait for an interrupt send before admitting the next turn, and exclude
old padding completions from a new request's playhead accounting.

Add pure red/green regressions and native TEN lifecycle tests using the
production hooks and startup path with a recording session boundary.
Document identity requirements and the remaining unscoped-input limits.
…p retries

The input queue dropped its oldest frames past 10 s of PCM. A response
synthesized before the session came up lost its middle and was then
closed with a normal end, so the avatar played a shortened answer.

The queue no longer discards anything. Frames and ordered ends are kept
within 120 s of PCM, 16 MiB and 4096 items, the in-flight item included.
Admission beyond a limit cancels the buffered turn and reports a nonfatal
avatar error with vendor category InputQueueOverflow instead of playing
truncated speech; a failed turn can never receive a successful end.

Tests: a delayed-startup regression that keeps a 26 s response byte for
byte through 41 s of withheld readiness, atomic duration, byte and item
limits, in-flight budget, unknown and mixed metadata, and native runtime
cases for overflow reporting and stop.
Adds params.source_timeline_only (off in this commit). When set, the
Agora egress is asked to publish on the source audio timeline only, and
the extension refuses to start with an SDK that cannot request it or
cannot verify the server's acknowledgement. A server that does not
confirm the mode is a configuration error (-1012) with no retry.
Adds params.source_playback_profile: 0 keeps the earlier source-only
contract, 1 requests BOUNDED_BURST_V1 and requires source-only mode.
With a profile requested, the session must confirm both the
agora_source_timeline_only and agora_source_burst_v1 capabilities;
otherwise the session is closed, with its callbacks invalidated first,
and the start fails with a configuration error and no retry.
…fault

source_timeline_only now defaults to true and source_playback_profile to
1 when source-only is on (0 otherwise), so a default node negotiates the
bounded burst profile with the backend. The two keys are dropped from
property.json so the code defaults apply; explicit false/zero values are
still forwarded to SDKs that know the fields, for compatibility mode.
…then fails

The sender captures a frame's flush generation once, before the session
wait, and checks it on every retry: a flush that lands while the frame's
send is in flight retires it even when that send fails because the
session dropped. The existing flush test only covered a frame already
held for reconnect.

The new test parks a send, flushes, drops the session, lets the send
fail and connects a replacement session: the replacement receives
nothing from the cancelled turn, and the next turn's audio still goes
out on it.
…nd the gate

The input queue no longer evicts frames on enqueue, connected or not:
it preserves every frame and ordered end within 120 s of PCM, 16 MiB
and 4096 items, and admission beyond a limit cancels the turn with an
InputQueueOverflow error instead of dropping the oldest audio.

The new test parks the sender at the previous request's gate on a
connected session, queues 12 s of distinct 100 ms frames plus an end,
releases the gate and checks that every frame reaches the sink in
order, followed by the end. Under the old 10 s budget the same input
is refused at frame 101.
… a timed-out start

The SDK's start() waits for ServerConfirmSession with an unbounded
recv(). A socket that upgrades and answers pings but never confirms the
session held the connect loop forever: no retry, no idle timer.

The handshake, start() and the capability check that follows it, now
runs against START_TIMEOUT_S (20 s, through the injected sleep). On the
deadline the call is cancelled and a TimeoutError takes the normal
start-failure path: one 1001 report per outage and the fast schedule.
Cancelling start() skips the SDK's own cleanup of the half-open socket,
so every failed start now invalidates the session's callbacks and closes
it explicitly before the retry, as the capability check already did;
close() is idempotent for the other failures.

Test: a session whose start() never returns is cancelled at the
deadline, closed once, reported as non-fatal TimeoutError, and the next
attempt after the 1 s backoff connects.
…loses a request

The pacer's ticker closes a request on its own at the padding limit or
the stall backstop. Only the sender reported request state to the
session client, so after a request that ended without an end marker the
client kept _request_open set and the idle loop skipped its planned
reconnect indefinitely, letting egress leave the channel on inactivity.

Pacer takes an on_request_state callback and calls it with False
whenever end_request() closes a request, the ticker's closures
included; the extension wires it to SessionClient.note_request_state,
as it already does for the sender.

Test: the real sender, pacer and session client over a fake session.
500 ms of speech with no end marker is padded to the limit and closed
by the ticker, and the idle reconnect follows 10 s after the last send.
…t the viewer requirement

SDK 0.4.0 is the release whose Agora egress defaults to source-timeline-only
playback with the bounded burst profile, which the extension now also
defaults to. requirements.txt and pyproject.toml both pin
spatialreal>=0.4.0,<0.5; pyproject.toml still named the 0.2 line.

The README now states the viewer requirement (web-sdk 1.0.0-beta.7 or newer,
or beta.6 with agora.sourcePlaybackProfile set to bounded-burst-v1), how to
select compatibility mode, that the backend must confirm both capabilities
or the session fails with a configuration error, and the 20 s handshake
deadline.
@YuehengHan
YuehengHan force-pushed the feat/spatialreal-avatar branch from 2f6eeb6 to 391166d Compare November 10, 2026 00:39
@YuehengHan

Copy link
Copy Markdown
Author

The four findings against 2f6eeb6 are addressed on the updated branch (rebased onto current main). Two were already fixed by follow-up commits and now have the regression test described; two are fixed in new commits. In ten_agent_build:0.7.14, 227 tests pass (211 pure, 16 native runtime, none skipped); black and pylint (10.00/10) are clean.

1. Flush generation replaced across send retries. Already fixed by ee9439c; regression test added in cdf55fb. _send_frame() now reads the flush generation once, before the session wait, and checks it again after every _connected.wait(). A flush that lands while the frame's send is in flight therefore retires the frame even when that send fails because the session dropped; identified turns are also checked against the retired set. test_inflight_send_failed_after_a_flush_is_not_replayed parks a send, flushes, drops the session, lets the parked send fail and connects a replacement session: the replacement receives nothing from the cancelled turn, and the next turn's audio still goes out on it. Re-reading the generation inside the retry loop, as 2f6eeb6 did, makes this test fail.

2. 10-second eviction while connected at the playback gate. Already fixed by 825cfc3; regression test added in 93b59f6. The input queue no longer evicts on enqueue, connected or not. Frames and ordered end markers are kept within 120 s of PCM, 16 MiB and 4096 items, the in-flight item included. Input beyond a limit cancels the buffered turn and reports a non-fatal avatar error with vendor code InputQueueOverflow, instead of dropping the oldest audio and closing a shortened request normally. test_over_10s_queued_behind_an_active_gate_all_reach_the_sink parks the sender at the previous request's gate on a connected session, queues 12 s of distinct 100 ms frames plus an end, releases the gate, and asserts every frame reaches the sink in order with the end last. Under a 10 s budget the same input is refused at frame 101.

3. Unbounded application handshake. Fixed in 65332b2. The whole handshake, start() plus the capability check that follows it, now runs against START_TIMEOUT_S (20 s, measured with the client's injected sleep). At the deadline the call is cancelled and a TimeoutError follows the normal start-failure path: one 1001 report per outage, then the fast schedule. Because cancelling start() skips the SDK's own cleanup, every failed connect now invalidates the session's callbacks and closes it explicitly before the retry. close() is idempotent, so this is harmless for the other failure types. test_start_never_confirmed_times_out_closes_and_retries uses a session whose start() never returns. It asserts that the call is cancelled at the deadline, the session is closed once, a non-fatal TimeoutError is reported, and the next attempt after the 1 s backoff connects. Without the deadline, this test fails.

4. Ticker closures not reaching the idle timer. Fixed in e43519b. Pacer takes an on_request_state callback and calls it with False whenever end_request() closes a request, which includes the ticker's pad-max and stall closures. The extension wires it to SessionClient.note_request_state, as it already did for the sender. test_ticker_closed_request_lets_the_idle_reconnect_run runs the real sender, pacer and session client over a fake session. 500 ms of speech with no end marker is padded to the limit and closed by the ticker, and the planned idle reconnect follows 10 s after the last send. Without the callback, the client keeps waiting on an open request and the reconnect never happens.

@github-actions

Copy link
Copy Markdown
  1. [P2] Keep the padding ticker from overtaking an in-flight audio send — pacer.py:176

    The request is marked open before this await, but the real audio is not counted until it returns. If the WebSocket send yields under backpressure for a ticker interval, tick() sees the old playhead and sends silence even though the next speech chunk has already arrived. With a sufficiently delayed send, the ticker can even hit the padding limit and send the request end while that speech send is still in flight. This inserts gaps or splits/truncates a request on a slow connection. Coordinate real sends with padding/end decisions (while preserving immediate flush handling), and add a regression that holds a real send across ticker ticks and verifies that neither padding nor an end overtakes it.

…flight audio send

push_audio marks the request open before it awaits the sink, but counts the chunk only once
the send returns. A send that yields under backpressure for a tick left the ticker reading
the old playhead: it padded silence ahead of speech that had already arrived and, given
enough ticks, closed the request for pad max or stall while that speech was still in flight.

The pacer now counts real sends in flight. While one is pending, tick() neither pads, nor
counts toward pad max, nor closes for pad max or stall; a padding send that real audio
overtakes no longer closes the request after it. The next tick after the send completes
reads the updated playhead. flush() still acts at once, and a send that completes after a
flush, end or reset is not counted toward the request that boundary closed.
@YuehengHan

Copy link
Copy Markdown
Author

Fixed in 51050c4. The pacer now counts real audio sends in flight, and tick() is a no-op while one is pending: no silence, no contribution to PAD_MAX_MS, and no pad-max or stall closure until the send returns; a padding send that real audio overtakes no longer closes the request after it. The next tick reads the playhead with the real audio counted (or, for a refused opening send, with the request forgotten as before). flush() still interrupts immediately, and a send that completes after a flush, end or reset is not counted toward the request that boundary closed. Regressions in tests/test_pacer.py hold a real send across ticks with a manual clock: test_ticker_neither_pads_nor_ends_during_a_held_real_send (opening and mid-request chunk, 17 s of ticks), test_padding_resumes_from_the_playhead_after_a_held_send, test_flush_during_a_held_send_acts_at_once_and_stays_closed, test_refused_held_opening_send_is_forgotten_without_padding and test_pad_max_does_not_close_while_a_real_send_is_in_flight; all fail on 391166d and pass with the fix.

@github-actions

Copy link
Copy Markdown
  1. [P2] Retire a turn even when its first frame arrives after flush — sender.py:333

    If an interruption reaches the avatar before the old turn has delivered any PCM or end marker, none of these sets contains that turn. A late first frame from the interrupted TTS request that arrives before the successor is processed then passes the retired/latest checks and opens a new request after the interrupt, replaying cancelled speech. The existing unseen-turn test only exercises the inverse ordering, where the successor arrives first. Propagate the cancelled turn identity or another interruption boundary to the avatar so it can reject that late frame, and test flush followed by old-turn PCM before any successor PCM.

  2. [P2] Preserve disconnects that arrive during session startup — session_client.py:614

    The SDK starts its read task before start() returns. If the server closes immediately after confirming the session, its on_close or retryable on_error callback can run while _start_with_deadline() is still completing, before connected is set. This guard discards the event, after which _connect_once() marks the already-closed session connected and waits indefinitely for another callback; absent new audio, the avatar stays offline until the idle reconnect. A fatal callback in the same window can also be followed by _connect_once() setting connected after the client has stopped. Record startup-time callbacks and resolve them before publishing the connection, and add regressions for immediate close and fatal error during startup.

…g session startup

The SDK starts its read loop inside start(), so the server can close or
fail the session before _connect_once() publishes the connection. Those
callbacks were dropped (close, retryable error) or acted on while the
attempt was still in flight (fatal error), after which the attempt still
marked the session connected.

Callbacks of the attempt in progress are now recorded and resolved before
the connection is published: a close, transport_frames or retryable
error makes it a failed connect on the fast schedule, a fatal error stops
the client without ever reporting the session connected. Regressions
cover an immediate close, a retryable error and a fatal error during
startup.
…rame limit

A flush from main_python carries no turn identity, so an interrupted turn
that has not delivered any PCM yet cannot be told apart from its successor.
Document the bounded window and what would close it.
@YuehengHan

Copy link
Copy Markdown
Author

1. Interrupted turn whose first frame arrives after the flush — Confirmed, and it cannot be fixed correctly inside the extension with what reaches it today. The flush cmd from main_python carries no properties, pcm_frame carries only the request's {session_id, turn_id} metadata, and main_python sends the flush before it increments turn_id. So after a flush the avatar cannot tell the cancelled turn N (no PCM seen yet) from the successor of the last turn it did see (also N, e.g. an interruption during playback of N-1's reply); a rule based on turn order alone either replays N or mutes a legitimate reply. The window is bounded: it is the PCM the TTS emits between the avatar receiving the flush and the TTS handling its own tts_flush (after which ten_ai_base clears the request metadata), 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. This is documented as a known limit in the README (f629744). The complete fix is for main_python._interrupt() to put its current {session_id, turn_id} on the flush it sends to the avatar; the extension would then retire every turn id up to and including that one and keep today's behaviour when the property is absent. Happy to send that as a small follow-up PR if the main_python change is acceptable.

2. Disconnects during session startup — Fixed in 31b3087. While a connect attempt is in progress, on_close, transport_frames and on_error callbacks of that attempt are recorded instead of being dropped or acted on, and resolved after _start_with_deadline() returns and before the connection is published: a close, transport_frames or retryable error makes it a failed connect (session closed, callbacks invalidated, one 1001, fast retry), and a fatal error stops the client with one fatal report and without ever setting connected or calling on_connected. A fatal callback overrides an earlier retryable one in the same window; a 4010 server error that leaves the session running is still reported only. Regressions in tests/test_session_client.py: test_close_right_after_confirmation_is_a_failed_connect, test_retryable_error_right_after_confirmation_retries and test_fatal_error_during_startup_stops_without_connecting; all three fail on 51050c4 and pass with the fix.

@github-actions

Copy link
Copy Markdown
  1. [P2] Wait for ticker-driven end sends before opening another request — pacer.py:256-265

    The padding/stall ticker can run end_request() independently of the sender. It marks the request closed before awaiting the SDK end send, so a new frame can pass the playback gate (or a flush can waive it) and open the next request while that end is still in flight. In SpatialReal SDK 0.4.0, send_audio(end=True) retains _current_req_id until its awaited WebSocket send returns and then unconditionally clears it. Consequently the successor can be sent with the old request ID, or the delayed end can clear the successor ID and split subsequent chunks into another request. This can truncate or mix speech when an end send is delayed by backpressure. Coordinate ticker-initiated end completion with successor audio while preserving prompt interruption handling, and add a regression that holds the end send, starts successor audio, then releases the end and checks distinct, stable SDK request IDs.

@github-actions

Copy link
Copy Markdown
  1. [P2] Start the playhead when the opening send completes — pacer.py:204-208

    _first_send is recorded before the first await self._sink.send_audio(...). If that send is held by WebSocket backpressure, the virtual playhead advances while the server has not yet received the opening PCM. For example, a 200 ms opening chunk held for 4 seconds is treated as already drained when the send succeeds: the next tick can immediately send 3 seconds of silence and close the request, and an end followed by another request can bypass the playback gate and cut off the first chunk. The held-send regression currently asserts this negative lead but does not tick or open a successor after releasing it. Anchor the opening playhead to the successful send, and account for any later send that arrives after the existing playhead has drained; add a delayed-send regression that checks padding and successor gating after the send completes.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant