Skip to content

fix(ui): don't evict a session's agent while a turn is running on it - #4277

Merged
kovtcharov-amd merged 8 commits into
amd:mainfrom
kovtcharov:claude/ui-session-mutation-during-run
Sep 26, 2026
Merged

kovtcharov-amd merged 8 commits into
amd:mainfrom
kovtcharov:claude/ui-session-mutation-during-run

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

Stacked on #4276 — merge that first (stack: #4274 → #4275 → #4276). Until then this diff also shows those commits; the change here is the top commit.

Deleting a session, switching its agent, device, or mail provider, or detaching a document mid-turn disconnected the running agent's MCP tools. The turn's final save then failed against the deleted session row, and the error was swallowed. Now a delete stops the running turn and waits for it to finish before removing anything. The other changes get a 409 while a turn is running.

  • Design choice: two answers, each following its endpoint's existing pattern.
    • DELETE already cancelled the run, so it keeps doing that and then waits on the session lock before deleting and evicting. Every turn and goal tick holds that lock for its whole run. The sidebar deletes optimistically, so the wait is invisible to the user. A 409 here would make a deleted session reappear on the next poll.
    • PUT (agent/device/mail provider) and document detach return 409, the same answer /api/chat/send gives for a busy session. Renames are still accepted, because auto-titling renames sessions mid-run.
  • Not in this PR: fix(ui): deleting a session mid-email-turn leaves the relay parked and the sidecar still generating #4140. The email-relay gap is still open. Until it lands, deleting mid-email-turn waits for the relay to return (worst case its 300 s read timeout) instead of racing it.
  • Docs. The endpoint docs in docs/sdk/sdks/agent-ui.mdx now describe the 409 and the wait.

Test plan

  • python -m pytest tests/unit/chat/ui/test_session_mutation_during_run.py -q: 7 failed before the fix (the rename test passed, as it should); all 8 pass after
  • python -m pytest tests/unit/chat/ui -q: 1041 passed
  • python -m pytest tests/unit/test_multi_device_wiring.py tests/unit/test_chat_inline_web_ssrf.py tests/unit/eval/test_scenario_agent_types.py tests/unit/eval/test_scenario_agent_provenance.py tests/integration/test_folder_indexing.py tests/integration/test_chat_ui_integration.py -q (plus the other session-endpoint neighbours): 330 passed, 2 skipped
  • python util/lint.py --black --isort + pylint (errors-only config) on changed files: clean
  • Manual: in gaia chat --ui, delete a session while a turn is streaming. It disappears and doesn't come back, and the server log has no "Chat streaming error"

Fixes #4199

Kalin Ovtcharov added 4 commits September 24, 2026 17:27
After one streaming turn, every later non-streaming turn and background goal tick on the same Agent UI session stopped at step 0 with "The request was stopped because it exceeded the allowed time", and tool confirmations were denied instantly.

The streaming cleanup fires the agent's cancel event and SSE console, and both stayed attached to the cached agent. Non-streaming cache hits now start with no cancel event and a fresh silent console; goal ticks clear the cancel event (they already install their own console).

Fixes amd#4196
Background goal ticks used a session's cached agent without the session lock or chat semaphore, and looked it up as a "chat" agent with the raw model id. On a gaia session that evicted the user's agent and disconnected its MCP tools; on a chat session the tick could run alongside the user's next turn on the same agent.

Ticks now take the session lock and chat semaphore, skip the session while it is busy (never queueing on the lock, so they can't stall the user's next message), and resolve agent type, model, and device the way the chat path does. A user-message followup waits up to 10 s for the turn that enqueued it to release the session, as docs/spec/autonomous-agent-mode.md section 17 describes.

Fixes amd#4197
When an Agent UI turn timed out, the session lock was released while the old worker thread was still running tools on the same cached agent, so the next turn could run concurrently with it.

Non-streaming turns and goal ticks now signal the agent's cancel event on timeout and wait for the worker thread before returning, so the session lock and chat semaphore stay held until it is gone. The streaming cleanup waits for the producer thread the same way (off the event loop, replacing a 5 s join that blocked it), so the run stays registered and the lock held until the producer exits.

Fixes amd#4198
Deleting a session, switching its agent, device, or mail provider, or detaching a document mid-turn disconnected the running agent's MCP tools, and the turn's final save then failed against the deleted session row with the error swallowed.

Delete now stops the running turn and waits for it to finish (on the session lock every turn and goal tick holds) before deleting the row and evicting the agent. Agent/device/mail-provider changes and document detach return 409 while a turn is running, the same answer /api/chat/send gives for a busy session; renames are still accepted.

Fixes amd#4199
@github-actions github-actions Bot added documentation Documentation changes tests Test changes labels Sep 25, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

Deleting a chat session, switching its agent, or detaching a document mid-turn used to pull the agent out from under the running turn and quietly lose its answer. This PR makes the delete wait for the turn and makes the other two return a "busy, try again" error, which is the right split — the sidebar already deletes optimistically, so the wait is invisible, and the frontend does surface the busy error to the user.

Two things to tighten before merge:

  • The docs promise more than the code does. The new endpoint docs say a running turn "is stopped" when you delete a session. That's only true for streaming turns — a non-streaming turn or a background goal tick gets no stop signal at all, so the delete simply waits for it to end (up to ten minutes in the worst case). Either soften the wording to "waits for the turn to finish" or actually signal those turns to stop.
  • A background goal tick can slip in right after the delete. If the agent's follow-up tick is waiting for the session at the moment the delete completes, it can start running on a session that no longer exists — rebuilding an agent for it and writing a message row to a deleted session. A quick re-check that the session still exists after the tick takes the session closes it.

Note this PR is stacked on #4274–#4276, so the diff shows those commits too; the review above is about the top commit.

Real-world evidence

No evidence bundle was produced for this run, and the PR description shows unit tests only — the manual "delete a session mid-stream in gaia chat --ui" item is still unchecked. This change alters HTTP API behaviour (two endpoints now return 409, DELETE now blocks), so the cheap missing artifact is a real request/response pair: a curl -X PUT /api/sessions/<id> returning 409 while a turn runs, and a DELETE issued mid-stream showing it returns once the turn ends with no "Chat streaming error" in the log. The verdict above therefore rests on static review plus the PR's unit tests for that surface.

🔍 Technical details

🟡 DELETE only stops streaming turns, but the docs claim it stops any turn (src/gaia/ui/routers/sessions.py:320-336, docs/sdk/sdks/agent-ui.mdx:15)

run_manager.cancel() is a no-op unless a run is registered, and only the streaming branch of /api/chat/send registers one (src/gaia/ui/routers/chat.py:171-217). For a non-streaming turn the delete just queues on the session lock until the turn ends or hits _CHAT_TIMEOUT_SECONDS (600 s); for a goal tick, until _TICK_TIMEOUT (300 s). Both are new blocking behaviour for an endpoint that previously returned immediately.

The stacked commits now attach agent._cancel_event to the cached agent on both the non-streaming and tick paths, so a real stop signal is available — setting that event alongside run_manager.cancel() would make the docstring true. Otherwise, adjust the wording in the docstring and agent-ui.mdx so it doesn't claim a stop that doesn't happen.

🟡 A user_message_followup tick can run on a just-deleted session (src/gaia/ui/agent_loop.py:311-337 × sessions.py:331-335)

The gate polls rather than queues, and the delete pops the lock from session_locks while still holding it. Sequence: a turn holds the lock → DELETE queues on it → a follow-up tick starts polling (10 s grace) → the turn releases → the DELETE (a real FIFO waiter) wins, deletes the row, pops the lock, evicts the agent, releases → the tick's next poll sees an unlocked lock and acquires the now-unregistered object. _execute_tick then builds a fresh agent for a deleted session, caches it, and add_messages an autonomous row against a session id with no row.

Cheapest fix is a liveness re-check after the tick takes the session:

        await session_lock.acquire()
        await chat_semaphore.acquire()
        try:
            if self._db.get_session(session_id) is None:
                return LoopDirective("idle", reason="session deleted")
            # Only a tick that reaches here spends hourly budget.
            self._calls_this_hour += 1
            return await self._execute_tick(session_id, session, goals)

Popping the lock while held also means a caller that setdefaults afterwards gets a different asyncio.Lock for the same session id — harmless today only because nothing should be starting a turn on a deleted session.

🟢 create=True on a patch target that exists (tests/unit/chat/ui/test_session_mutation_during_run.py:1018)

sessions.py now imports run_manager at module scope, so create=True only hides a future rename of the attribute.

        patch("gaia.ui.routers.sessions.run_manager", manager),

🟢 Second event loop used to prime a lock (tests/unit/chat/ui/test_session_mutation_during_run.py:1111-1124)

Acquiring an asyncio.Lock on a throwaway loop and handing it to TestClient's loop works because the check only reads locked(), but that's non-obvious — worth a one-line comment saying the lock is never awaited by the code under test.

Strengths

  • The two-answers design is the right call and is argued from existing behaviour: DELETE already cancelled the run, so it keeps that shape; PUT/detach return the same 409 /api/chat/send gives. Exempting renames because auto-titling renames mid-run is a detail that's easy to miss.
  • Tests assert the actual invariant (_mcp_manager.disconnect_all.assert_not_called() while the turn runs, called once after) rather than just status codes, and cover both busy signals — session lock held and a registered run.
  • The verified check-then-evict window in update_session is safe: _reject_if_turn_running and evict_session_agent are both synchronous with no await between them, so no turn can start in between.
  • attach_document doesn't evict, so leaving it unguarded is correct — all three eviction call sites are now covered.

Fixes a duplicate device= keyword argument the auto-merge produced:
this branch and main both added a device= line to ChatAgentConfig(...)
at slightly different positions, so git's 3-way merge kept both
instead of flagging a conflict -- a SyntaxError that broke collection
for every test importing gaia.ui.agent_loop. Also folds in main's
cancel-lock handling alongside this branch's own worker-exit fix.
Same duplicate device= keyword the sibling branch's merge produced
(this PR and amd#4276 both independently added a device= line to
ChatAgentConfig, at different diff positions, so git kept both
instead of flagging a conflict). Also combines this branch's
cancel_event assignment with main's result_holder capture.
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 26, 2026
Merged via the queue into amd:main with commit 71956ed Sep 26, 2026
32 of 35 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claude/ui-session-mutation-during-run branch September 26, 2026 05:00
kovtcharov-amd pushed a commit to kovtcharov/gaia that referenced this pull request Sep 26, 2026
… of the API (amd#4340)

## Summary

Following the Agent UI API docs to manage MCP servers got a client a
404: five documented `/api/mcp/*` endpoints
(register/enable/disable/delete a server, the catalog) moved to
`/api/connectors` when MCP-server lifecycle folded into the connectors
model, and the doc never caught up. About three-quarters of the real
backend was also simply undocumented — all of connectors, goals,
onboarding, schedules, and most of hub and memory — and the required
`X-Gaia-UI` CSRF header was never mentioned, so a doc-following client's
first mutating call got a silent 403.

Added a route-coverage test that builds the real FastAPI app and diffs
its route table against every documented endpoint in both directions, so
a route can't drift out of sync with the doc again the way this one did.

Overlaps with amd#4277 (also edits this file, in the Sessions accordion
group) in file only — rebased on latest `origin/main`, no shared lines.

## Test plan

- [x] `pytest tests/unit/chat/ui/test_route_doc_coverage.py -q` — 3
passed; confirmed it fails against the pre-fix doc (72 undocumented
routes, 4 fictional `/api/mcp/*` ones)
- [x] `pytest tests/unit/chat/ui/ -q` — 1038 passed, no regressions
- [x] `python util/check_doc_links.py --internal-only` — 1015 links
checked, 0 broken

Fixes amd#4255

Co-authored-by: Kalin Ovtcharov <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(ui): deleting or reconfiguring a session mid-run kills the running agent's tools

2 participants