Skip to content

fix(ui): keep a session busy until its timed-out worker thread exits - #4276

Merged
kovtcharov-amd merged 5 commits into
amd:mainfrom
kovtcharov:claude/ui-hold-lock-until-worker-exits
Sep 26, 2026
Merged

kovtcharov-amd merged 5 commits into
amd:mainfrom
kovtcharov:claude/ui-hold-lock-until-worker-exits

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

Stacked on #4275 — merge that first (it is itself stacked on #4274). Until then this diff also shows those commits; the change here is the top commit.

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. Now a timed-out non-streaming turn signals the agent to stop and waits for its thread before it returns. The streaming cleanup also waits for the producer thread, so the session lock, chat semaphore, and run registration stay held until the worker is actually gone.

  • Goal ticks too. fix(ui): goal ticks take the session lock and look up the right agent #4275 gave ticks the session lock, so a timed-out tick now also stops its agent and waits for the worker before releasing it.
  • No more event-loop stall. The streaming cleanup used to block the event loop for up to 5 s in producer.join. The wait now runs off the loop.
  • Trade-off. A turn that ignores its cancel signal now keeps its session busy until the worker exits, not just until the 600 s timeout. The agent checks for cancel at every step boundary, and per-tool timeouts bound each step.

Test plan

  • python -m pytest tests/unit/chat/ui/test_run_outlives_timeout.py -q: all 3 fail before the fix, all pass after
  • python -m pytest tests/unit/chat/ui -q: 1033 passed
  • python -m pytest tests/unit/agents/test_console_tool_confirmation.py tests/integration/test_chat_ui_integration.py tests/integration/eval/test_behavior_e2e.py -q: 155 passed, 1 skipped
  • python util/lint.py --black --isort + pylint (errors-only config) on changed files: clean

Fixes #4198

Kalin Ovtcharov added 3 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
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Request changes — one fixable hole in the very invariant this PR establishes, plus a trade-off the stack introduces that needs a maintainer's call.

The change is right in shape: a timed-out chat turn now tells its agent to stop and keeps the session reserved until the worker thread is actually gone, so the next turn can't run concurrently on the same cached agent. The streaming path also stops blocking the event loop while it waits.

What needs fixing

  • The stream cleanup can still let go of the session early. Cleanup marks itself "done" before it starts waiting for the worker thread. If the turn is torn down while that wait is in progress, the second cleanup pass sees the "done" mark and returns immediately — the session is freed with the worker still running tools, which is the exact race this PR is closing. Nothing in the server tears a run down that way today, so it's latent rather than live, but it's the same teardown path one of the new tests drives, and it's a small fix: do the signalling once, but always wait for the worker.

  • A background goal tick now blocks every user's chat, and Stop can't reach it. Chat is serialized server-wide with a single permit, and the stacked commit makes a tick take it. While a tick runs — up to 5 minutes, and after this PR potentially longer if its agent ignores the stop signal — a message in that session is rejected as "already in progress" and messages in other sessions fail after a 60-second wait. The tick isn't registered as a run, so the Stop button has nothing to cancel. Reserving the session is the correct fix for the corruption bug; the missing half is a way for an arriving user message to preempt the tick. This one belongs to the stacked commit, not the top one — but it should be settled before the stack lands.

  • The timeout no longer bounds the reply. If an agent never reaches a stop checkpoint, the request now waits indefinitely instead of returning the "took too long" message, and nothing is logged while it waits. The trade-off is deliberate and stated, but it should at least be visible in the logs so an operator can tell a stuck turn from a slow one.

Real-world evidence

N/A — no evidence bundle was produced for this run, so the verdict rests on static review plus the author's reported test results. This is an Agent-UI-backed change: the listed unit and integration runs gate the concurrency logic, not the surface, and no Agent UI screenshot or HTTP-route capture is attached. Worth adding the /api/chat/send request/response for a timed-out turn (or the eventual strix-halo screenshot) so the user-visible half is shown rather than inferred. I could not re-run anything here — this checkout has no pytest available.

🔍 Technical details

Note: the PR is stacked (top commit 039cfce6; 62bc7dca = #4275, 81123d18 = #4196 also appear in the diff). Findings are attributed below.

Issues

🟡 cleanup_done is set before the joins, so an interrupted cleanup skips the producer wait (src/gaia/ui/_chat_helpers.py:1880-1900)

_cleanup_stream sets cleanup_done = True at the top, then awaits asyncio.to_thread(producer.join, ...). If the lifecycle task is cancelled while suspended in that to_thread, CancelledError propagates out of the call at line 2698, and the generator's finally (line 2929) re-enters _cleanup_stream, hits the guard, and returns without waiting. _run_chat_lifecycle's task then completes, run.task's done callback fires _release_stream_locks (routers/chat.py:133-148), and the session lock + chat_semaphore are released with the producer thread still executing tools on the cached agent — the race #4198 exists to close.

No production caller cancels run.task today (run_manager.cancel only sets handler.cancelled), so this is latent — but test_torn_down_stream_holds_session_until_producer_exits drives exactly this teardown, just with the cancel landing before cleanup starts rather than during the ≥5 s join window. Signalling is what must be once-only; join is idempotent, so it can move outside the guard:

    async def _cleanup_stream():
        nonlocal cleanup_done
        if not cleanup_done:
            cleanup_done = True
            cancel_event.set()
            if sse_handler is not None:
                sse_handler.cancelled.set()
                # #2109: force a blocked email-relay socket read to error out —
                # the orphan-cleanup mirror of the explicit /api/chat/cancel path.
                sse_handler.close_active_relay_response()
            _active_sse_handlers.pop(session_id, None)
        # Always re-waited: an interrupted join must not leave the producer
        # alive after the run (and so the session lock) is released.
        if producer is not None:
            await asyncio.to_thread(producer.join, 5.0)
            if producer.is_alive():
                logger.warning(
                    "Producer thread still running after stream ended; "
                    "holding the session until it exits"
                )
                # The run (and so the session lock) must outlive the producer.
                await asyncio.to_thread(producer.join)

🟡 A goal tick holds Semaphore(1) + the session lock for the whole tick, and isn't cancellable (src/gaia/ui/agent_loop.py:307-334 — from 62bc7dca/#4275)

app.state.chat_semaphore is asyncio.Semaphore(1) (server.py:600, "serialize: _TOOL_REGISTRY is global"). Once _run_step acquires it, POST /api/chat/send for the same session gets 409 (routers/chat.py:96) and any other session gets 429 after wait_for(..., timeout=60.0) (chat.py:109). The hold lasts up to _TICK_TIMEOUT (300 s default) and, with this PR, longer if the agent misses its cancel checkpoints. The tick never calls run_manager.start, so run_manager.is_running(sid) is False and /api/chat/cancel can't reach it — the UI Stop button is inert against a tick that is blocking the user.

Taking the lock is the right fix for the shared-agent corruption; what's missing is preemption. Two options worth a maintainer's call: register the tick as a Run (Stop then works, and the sidebar shows the session busy), and/or have notify_user_message set the tick's cancel_event so an arriving user turn wins.

🟡 The extended wait after a timeout is unbounded and unlogged (src/gaia/ui/_chat_helpers.py:1812-1822)

The streaming path logs before it waits without a bound; the non-streaming path doesn't. A turn stuck past the timeout now produces a request that never returns, with no log line distinguishing it from a slow one. The trade-off is deliberate, but make it observable:

        try:
            done, _ = await asyncio.wait({worker}, timeout=_CHAT_TIMEOUT_SECONDS)
        finally:
            if not worker.done():
                cancel_event.set()
                logger.warning(
                    "Chat worker exceeded %ss; holding the session until it "
                    "reaches its next step boundary",
                    _CHAT_TIMEOUT_SECONDS,
                )
                # The caller's session lock must outlive the worker thread.
                await asyncio.wait({worker})

Nits

🟢 The unbounded join occupies a thread from the same pool as chat workers (_chat_helpers.py:1900). asyncio.to_thread and run_in_executor(None, ...) share the loop's default executor, so a producer that never exits pins a pool thread indefinitely. Bounded in practice by Semaphore(1), but a dedicated single-thread executor for reaping would remove the coupling.

🟢 The tick's cache-miss path still builds a ChatAgent for any session type (agent_loop.py:444-468). 62bc7dca correctly makes the lookup type-aware, so a gaia session now hits its own agent — but on a miss (first tick after a restart) the tick constructs a ChatAgent regardless of agent_type, and never _store_agents it, so it rebuilds every 60 s. Pre-existing and strictly less frequent after this change; worth a follow-up so hit and miss agree on which agent a tick drives.

Strengths

  • Extracting _CHAT_TIMEOUT_SECONDS is what makes the timeout path testable at all — test_run_outlives_timeout.py patches it to 0.1 s and asserts the real invariants (lock held, semaphore held, _cancel_event set, run still registered) rather than asserting a mock was called.
  • Moving producer.join off the event loop fixes a genuine 5-second stall that had nothing to do with the bug being fixed, and the diff keeps the two concerns separate.
  • 81123d18's console/cancel-event reset is the right diagnosis: a cached agent carrying a fired cancel event and a dead SSE console would bail at step 0 with a timeout message, and the new test pins both halves.
  • Making the tick's model/agent-type resolution mirror the chat path stops ticks from evicting and disconnect_all-ing a live session's agent (_get_cached_agent → _disconnect_cached_agent).

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.
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 25, 2026
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.
@github-actions

Copy link
Copy Markdown
Contributor

🟡 The cleanup_done race the previous review flagged is still present — the join is still inside the once-only guard, so a task cancelled during the 5-second join will let the producer thread outlive the session lock.

The new push correctly makes _cleanup_stream async and adds the unbounded fallback join, but the structure is unchanged: cleanup_done = True is set on line 1889, then both joins happen inside the same block. If asyncio.to_thread(producer.join, 5.0) is interrupted by a CancelledError, the finally at line 2911 re-enters _cleanup_stream, hits if cleanup_done: return on line 1887, and exits — the producer thread is still alive but the session lock is about to be released.

The previous review's suggested fix was to move the joins outside the guard so re-entry always waits. That change wasn't made.

The new test (test_torn_down_stream_holds_session_until_producer_exits) only covers the cancel landing before cleanup starts, not during the join window, so the gap isn't caught.

🔍 Technical details

_chat_helpers.py:1885-1905 — the one-time block ends at line 1905, but both joins are inside it. Restructure so signalling is once-only but joining is always:

async def _cleanup_stream():
    nonlocal cleanup_done
    if not cleanup_done:
        cleanup_done = True
        cancel_event.set()
        if sse_handler is not None:
            sse_handler.cancelled.set()
            sse_handler.close_active_relay_response()
        _active_sse_handlers.pop(session_id, None)
    # Always re-waited: an interrupted join must not leave the producer
    # alive after the run (and so the session lock) is released.
    if producer is not None:
        await asyncio.to_thread(producer.join, 5.0)
        if producer.is_alive():
            logger.warning(
                "Producer thread still running after stream ended; "
                "holding the session until it exits"
            )
            await asyncio.to_thread(producer.join)

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 26, 2026
Merged via the queue into amd:main with commit b879400 Sep 26, 2026
28 of 31 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claude/ui-hold-lock-until-worker-exits branch September 26, 2026 05:00
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 26, 2026
…md#4277)

Stacked on amd#4276 — merge that first (stack: amd#4274 → amd#4275 → amd#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: amd#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
- [x] `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
- [x] `python -m pytest tests/unit/chat/ui -q`: 1041 passed
- [x] `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
- [x] `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 amd#4199

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
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

tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(ui): session lock released on timeout while the worker thread still uses the agent

2 participants