Skip to content

fix(voice): tear down a partially started AgentSession - #8266

Open
BlueX888 wants to merge 8 commits into
livekit:mainfrom
BlueX888:fix/agent-session-failed-start-cleanup
Open

BlueX888 wants to merge 8 commits into
livekit:mainfrom
BlueX888:fix/agent-session-failed-start-cleanup

Conversation

@BlueX888

@BlueX888 BlueX888 commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Problem

AgentSession.start() can fail after it has already created resources, and aclose() then does nothing:

async with self._lock:
    if not self._started:
        return

_started is only set at the very end of start() (agent_session.py:1189), but before that the method starts the session span, creates room_io / session_host / RecorderIO, publishes the AgentActivity (setting agent._activity), and connects the realtime provider. Two failure windows are left uncleaned:

  1. After the activity is published, before _started — e.g. the realtime provider fails to connect, MCP toolset setup fails, or session_host.start() fails. aclose() returns at the guard; the realtime session stays open, no close event is emitted, room_io/session_host are never closed, and agent._activity stays set so reusing the agent raises cannot start agent: an activity is already running.
  2. Before the activity is published — e.g. room bring-up fails in RoomIO.start(). _activity is still None, so the same guard skips cleanup and room_io (plus its room listeners and the session span) leaks.

Observed on 049aea8 with a provider that fails to connect:

after start() failure: session._started=False, activity set, rt session created=1 closed=False
after aclose():        close events=[], rt session still open, agent._activity still set

Fix

Only treat a session as nothing-to-close when it has no activity and no session span:

if not self._started and self._activity is None and self._session_span is None:
    return
  • _session_span is created at the top of start() (before room io and the activity) and cleared in _aclose_locked's finally, so it is the sentinel that covers both failure windows.
  • A never-started session and a normally closed session both have _activity is None and _session_span is None, so they still no-op; a successful start() -> aclose() path is unchanged.
  • Teardown already tolerates a None activity: _teardown_activity skips the activity part, RoomIO.aclose closes whatever it registered, and close is emitted once.

Tests

Two regression tests in tests/test_agent_session.py:

  • test_failed_start_tears_down_partial_session — provider connect failure after the activity is published; asserts the close event, activity/realtime teardown, double aclose safety, and agent reuse in a fresh session.
  • test_failed_start_in_room_bring_up_is_still_closed — room on() raises before the activity exists; asserts close, _room_io is None, and the session span cleared.

Receipts on 049aea8: both tests fail at assert closes == [CloseReason.USER_INITIATED] (assert [] == [...]); the new pre-activity test also fails on the first commit alone. With the change: tests/test_agent_session.py 112 passed; 180 adjacent voice/realtime tests pass unchanged; ruff check and ruff format --check clean.

Note

Compose checks: auto-merges cleanly with #8147, #7956 and #7930; #7931 only conflicts in voice/agent.py (unrelated hunk) and #7940 only in this test file's import block — both trivial at rebase. Happy to rebase on request.

Update — partial-start detach

Addressing the review note that a failed start() can leave RoomIO's closed streams attached: RoomIO now records the session I/O it attaches and clears it on close (identity-checked, so caller-provided I/O is preserved), and RecorderIO restores the streams its wrappers replaced, which also covers record=True / server-side recording. Regression tests cover the same-session retry, caller-provided audio, and the recording path.

🤖 Generated with Claude Code

An unstarted SessionHost is now released too: aclose() unregisters the session and closes the event channel and transport even when start() never ran, with a retry test that asserts a fresh host is created.

BlueX888 and others added 2 commits October 30, 2026 00:30
AgentSession.start() publishes the AgentActivity (and sets agent._activity)
before the realtime provider connects. If bring-up then fails, _started is
still False, so aclose() returned early: the realtime session stayed open,
no close event was emitted, and the agent kept its activity. Retrying start()
with the same agent then raised "cannot start agent: an activity is already
running".

Skip close only when the session never started or was already closed: a
session that has an activity but no _started flag is a failed start and still
owns resources to release.

Add a regression test covering provider connect failure, the close event,
realtime session teardown, double aclose, and reusing the agent.

Co-Authored-By: Claude Code <noreply@anthropic.com>
A start() that raises during room bring-up has already created the session
span and room io, but the activity is only published later. The previous
guard keyed only on the activity, so aclose() still returned early and left
the half-started RoomIO and session span behind.

Treat the session span as the marker of a start attempt: it is created at the
top of start() and cleared when the session closes. A session with no span,
no activity, and no _started flag never started or is already closed.

Add a regression test with a room whose on() raises: start() leaves _activity
None and _room_io set, and aclose() now emits the close event, clears room io
and the span, and stays safe when called twice.

Co-Authored-By: Claude Code <noreply@anthropic.com>
@BlueX888
BlueX888 requested a review from a team as a code owner October 29, 2026 17:06
devin-ai-integration[bot]

This comment was marked as resolved.

Resolved tests/test_agent_session.py imports: keep CloseReason/RoomOptions
(failed-start tests) together with main's AudioOutput/AudioOutputCapabilities
and FakeLLM.

Copy link
Copy Markdown
Member

Hi @BlueX888, thanks for the PR! Before we can merge, could you take a look at the critical issue Devin flagged here (if start() fails after RoomIO is up, aclose() may leave closed room streams attached on the session when no activity was created, so a retry won't get fresh room media)? Either a fix or a reply explaining why it's not an issue works. Once that's addressed we'd be happy to get this merged.

RoomIO attaches its inputs and outputs to the AgentSession at start(),
before AgentActivity is created, and RecorderIO then wraps the audio
streams. If activity bring-up fails there is no activity to detach them
in _teardown_activity, so a retry treats the closed streams as
caller-provided I/O and disables fresh room audio.

Release the I/O that RoomIO and RecorderIO attached on close,
identity-checked so caller-provided I/O is preserved, and restore what
the recorder wrapped.

Adds regression tests for the same-session retry, caller I/O, and the
recording path.
@BlueX888

Copy link
Copy Markdown
Contributor Author

Hi @davidzhao — fixed in f06733c. Devin's diagnosis was right, and I reproduced it: with room audio enabled and a realtime config AgentActivity rejects (server-side turn detection + allow_interruptions=False), RoomIO has already attached its streams but no activity is published, so _teardown_activity had nothing to detach. After aclose() the session kept the closed streams, and a retry then disabled its own room audio.

The teardown now releases exactly the I/O that start() installed:

  • RoomIO records the session streams it attaches and clears them in aclose(), identity-checked so caller-provided I/O is preserved.
  • RecorderIO restores what its wrappers replaced. This mattered too: with record=True (or server recording), the session holds the recorder wrappers rather than RoomIO's streams, so the same symptom occurred until the wrapper was unwrapped.

Regression tests cover the same-session retry with room audio (asserts fresh RoomIO input/output are attached after the retry), caller-provided audio preservation, and the recording path with a fake job context. The detach test fails on the previous head and passes with the change; the six related test modules (including test_recorder_io / test_recording) pass locally, ruff is clean, and CI will confirm on the new head.

Happy to adjust if you'd prefer the detach to live in AgentSession rather than in RoomIO/RecorderIO.

devin-ai-integration[bot]

This comment was marked as resolved.

When room audio output is disabled because the caller set its own output
(an avatar, for example), the transcription synchronizer still wraps that
output and RoomIO installs the wrapper. If activity bring-up fails before
anything detaches it, closing the partial session dropped the caller's
output, and a retry enabled the room track instead.

Remember the output the synchronizer replaced and restore it when the
wrapper is still attached, mirroring the recorder handling.
devin-ai-integration[bot]

This comment was marked as resolved.

A start() that fails between register_session() and SessionHost.start()
leaves the host subscribed to the session's events with the transport
and event channel built in __init__ still open. SessionHost.aclose()
returned early for a host whose start() never ran, so the callbacks
stayed attached and nothing released the transport or channel.

aclose() now unregisters the session and closes the event channel and
transport even when start() never ran, which is the only teardown for
that partial start.
@BlueX888

Copy link
Copy Markdown
Contributor Author

@davidzhao both Devin findings are now covered on the current head:

  • RoomIO/RecorderIO detach on a partial start (f06733c7, e571a074).
  • The unstarted SessionHost thread: aclose() now unregisters the session and releases the event channel and transport even when start() never ran (b084b5498), with a retry test that asserts a fresh host is attached.

The remaining avatar note is a plugin-owner contract: the core cannot observe whether a caller-owned sink still consumes after close. RoomIO restores only the exact object it replaced, so a sink that clears/replaces session.output.audio on close wins; Spatius currently leaves its closed queue mounted.

Tests: tests/test_agent_session.py + tests/test_session_host.py 174 passed; ruff check/format clean. CI is running on b084b5498.

@davidzhao davidzhao left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Upon further review, my concern is that widening the aclose() guard runs normal shutdown on a session that never finished starting. That has two concrete effects on retry: teardown can clear caller-provided audio, and a job-owned host can replay a stale session_closed event. The fixes for those effects are spreading across RoomIO, RecorderIO, and SessionHost.

Could we make start() roll back the failed attempt before re-raising the original error? A single private cleanup path under the session lock could cancel startup tasks and release the resources that attempt acquired, in reverse order. It should restore caller-owned I/O, close a session-owned host, and discard the failed attempt’s buffered events on a job-owned host. The resource classes can still provide the cleanup operations, with start() deciding when to call them.

@BlueX888

Copy link
Copy Markdown
Contributor Author

Implemented the rollback in bdbeca6.

start() now snapshots caller I/O and chat context, and on any failure — console/room bring-up, recorder setup, host attach, activity bring-up, or SessionHost.start() — runs one private _rollback_start() under the session lock before re-raising. It cancels the startup tasks (including activity._on_enter_task, so a slow on_enter cannot touch the retry), releases the activity/AMD/IVR, recorder, room I/O, and host that the attempt acquired, restores caller I/O and chat items, ends the session_start span, and cancels the capture_run state. No close event is emitted.

A session-owned host is closed; a job-owned host is only unregistered and its buffered events discarded, so the retry reuses it without replaying the failed attempt's events.

Tests: the failed-start cases now assert the resources are gone immediately after start() raises; added job-owned host reuse and slow-on_enter cancellation tests. 306 passed across test_agent_session, test_session_host, test_remote_session, test_room_io, and test_recorder_io; ruff clean. CI is running on bdbeca6.

devin-ai-integration[bot]

This comment was marked as resolved.

@BlueX888
BlueX888 force-pushed the fix/agent-session-failed-start-cleanup branch from bdbeca6 to 5c2d58d Compare November 28, 2026 06:28
@BlueX888

Copy link
Copy Markdown
Contributor Author

Addressed the three Devin findings in 5c2d58d:

  • Console retry: both AgentsConsole implementations now expose reattach_io(session). start() reattaches the existing console streams on a retry, and recreates the TCP SessionHost when one is missing, instead of leaving io_acquired set with no audio attached.
  • Stranded speech: rollback now awaits activity.interrupt(force=True) before activity.aclose(), so queued replies settle instead of waiting for authorization from a stopped scheduler.
  • Session toolsets: rollback leaves session-owned toolsets open for a retry but tracks _failed_start_toolsets; an explicit session.aclose() after the failed start still closes them, and a successful start clears the flag. Normal close keeps closing them exactly once.

New tests cover all three: test_failed_start_reattaches_console_io, test_failed_start_interrupts_the_activity, and test_failed_start_closes_session_toolsets_on_aclose. 354 passed across test_agent_session, test_session_host, test_remote_session, test_room_io, test_recorder_io, and test_cli; ruff clean. CI is running on 5c2d58d.

start() now releases the room I/O, recorder, host, and activity acquired by
the failed attempt before re-raising. Caller-provided I/O is restored, a
job-owned SessionHost stays open with its buffered events dropped, and no
close event is emitted for a session that never started, so the same
session can be retried.
@BlueX888
BlueX888 force-pushed the fix/agent-session-failed-start-cleanup branch from 5c2d58d to e29855a Compare November 28, 2026 06:36
The 9 test_room.py errors were setup timeouts (connection refused on :7880);
the other 7644 tests passed.

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.

2 participants