Skip to content

fix(gaia-agent): set up a /query turn off the event loop - #5349

Merged
kovtcharov-amd merged 5 commits into
amd:mainfrom
kovtcharov:kalin/sidecar-setup-off-loop
Oct 19, 2026
Merged

kovtcharov-amd merged 5 commits into
amd:mainfrom
kovtcharov:kalin/sidecar-setup-off-loop

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

When one session started, or switched model with /model, every other session on the same sidecar froze. No tokens or heartbeats arrived for as long as the agent build or client switch took, so the TUI and the daemon relay saw an idle connection. Session setup now runs on a worker thread, so other sessions keep streaming. A busy or failed session still returns the same 409, 503 or 500 as before.

Reproduced by hub/agents/gaia/python/tests/test_server_event_loop.py, which runs a real uvicorn sidecar and measures the heartbeat gap on one stream while another session builds, switches, or runs a one-shot. It fails on main with a 1.5 s gap and passes here. test_another_session_cannot_evict_this_one_mid_setup reproduces the spurious "already running a turn" 409 that a worker thread would otherwise open.

🔍 Technical details
  • _off_loop() runs the blocking setup on a worker thread: the session checkout, session.switch_model, and the one-shot build_query_agent.
  • The new _SessionRegistry.checkout() takes the session's run lock under the same lock eviction holds. Another request therefore can't evict the session between finding it and taking its turn. That window appeared once setup awaited a worker.
  • If the request is cancelled mid-setup, the abandoned call still releases what it took (the run lock, or the agent it built). That cleanup runs on its own thread, since closing an agent blocks. Route-level tests cover a cancelled /model switch, a cancelled one-shot build, and a cancelled wait for a stopped turn. These paths can't be cancelled on main at all, since setup there is synchronous.
  • Not done here: sending response headers before setup and streaming a "waiting" status. That would turn today's 409 and 503 into in-stream errors, a contract change for the TUI and relay.
  • fix(daemon): a queued model request waits instead of failing, and shows it is waiting #5328 also edits this file and conflicts where _acquire_turn used to be. This PR replaces that function with _checkout_turn; keep this version when resolving, and keep both CHANGELOG entries. perf(llm): side work runs beside the conversation instead of queueing behind it #5287 touches other hunks.
  • test_full_tool_bundles and test_manifest_tools_count_matches_real_registry also fail on main on this dev box, where the optional browser tools aren't installed.
  • The real two-session check below hasn't run yet: another session's eval was using the shared Lemonade.

Test plan

  • python -m pytest hub/agents/gaia/python/tests/test_server_event_loop.py hub/agents/gaia/python/tests/test_server_query.py hub/agents/gaia/python/tests/test_session_registry.py -q
  • With two TUI sessions on one sidecar, stream a long answer in one and run /model <other> in the other. The first keeps streaming.

@kovtcharov
kovtcharov marked this pull request as ready for review October 18, 2026 18:23
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve

Starting a session or switching its model no longer freezes the other sessions on the same sidecar. The slow setup now runs on a worker thread. The PR also closes the race that moving it off the loop would have opened: another session can no longer evict this one between finding it and taking its turn. A request cancelled mid-setup still releases the session lock, or closes the agent it built. I found no blocking issues.

Real-world evidence

N/A. No evidence bundle was produced for this run. This is a change to the sidecar's internal /query setup, and no CLI output, response shape or UI changes. Its proof is the new real-uvicorn heartbeat-gap test. That test couldn't run on this review runner (pytest isn't installed here), so this verdict rests on static review alone. The PR's manual check with two TUI sessions on one sidecar is still unchecked, so please run it before merge.

🔍 Technical details

Issues found

No 🔴 or 🟡 issues. Things I checked that hold up:

  • Cancellation is cleaned up exactly once. CancelledError is a BaseException, so none of the route's except arms (HTTPException, Exception, …) run _unwind_setup on a cancel. Only on_abandon runs it, so nothing is released twice. In the switch path, on_abandon ignores its argument and always unwinds, so a switch that fails after its request was cancelled still releases run_lock.
  • Cancel arriving just as the work finishes. shield plus add_done_callback on an already-done task still schedules the cleanup, so there's no leak if the cancel lands right as the worker returns. In _cleanup, the done.cancelled() check runs before done.exception(), so it never calls exception() on a cancelled future.
  • Taking the turn is atomic. _get_or_create tries run_lock inside with self._lock on both the existing-session path and the new-session path (including the lost-the-race branch). _claim_lru_locked, reap and delete all claim run_lock under that same lock, so the "holding it means still registered" comment in _checkout_turn is true.

🟢 Long waits on a stopped turn now share the general thread pool (server.py:933). A stopped turn is still waited out for up to 240 s, now inside the same worker-pool task as the agent build. Before, it ran in its own to_thread call. A pile-up of stopped-turn waits could queue other sessions' builds behind the default executor's worker limit. This is worth knowing about, not changing here.

Strengths

  • Adding checkout() to the registry fixes the eviction window at its source. Wrapping the route in more locking would have been the weaker fix.
  • The tests target the real symptom. They measure the heartbeat gap on a live uvicorn stream, which TestClient can't do. They also drive cancellation through the actual route coroutine for all three setup paths.
  • The CHANGELOG entry describes the user-visible before and after, not the implementation.

@kovtcharov
kovtcharov marked this pull request as draft October 18, 2026 19:02
@kovtcharov
kovtcharov marked this pull request as ready for review October 18, 2026 19:02
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

Before this change, one session starting up or switching models on the gaia agent sidecar froze every other session's stream, heartbeats included. Now that setup runs on a worker thread. I found no correctness problems. The cancellation and eviction cases are handled carefully, and each one has a test.

  • The PR's own test plan still has the real two-session check unticked: stream in one TUI session while running /model in another. Please run it and tick it before merging. The new tests use a real uvicorn server, but they never touch the TUI or the daemon relay, and that is where users saw the freeze.

Real-world evidence

N/A: there is no evidence bundle for this PR. The change is limited to the sidecar's /query setup path. The new test file starts a real HTTP server and measures heartbeat gaps, but I couldn't run it here because pytest isn't installed on this runner. This verdict rests on static review. The real two-session check through the TUI is still pending, as the author notes.

🔍 Technical details

Issues found

🟡 Live two-session evidence is still outstanding (PR test plan, item 2). The rubric expects real-surface proof for a user-visible change. test_server_event_loop.py does drive a real uvicorn sidecar over HTTP, which is good route-level evidence. The symptom users hit, though, was idle timeouts in the TUI and the relay. Paste the heartbeat or stream behaviour from the manual run into the PR before merge. This doesn't block on code grounds.

🟢 on_abandon failures are only reported through threading.excepthook (server.py, _off_loop._cleanup). If close_agent or run_lock.release() raises in the cleanup thread, the default hook prints it to stderr and the sidecar logger never sees it. Wrap the call and send failures to logger.exception, so a leaked lock or agent leaves a trace in the sidecar logs.

What I checked and found correct

  • No double release on cancel. CancelledError is a BaseException, so the route's except Exception → _unwind_setup() never fires on cancellation. Only on_abandon releases the lock.
  • The stopped-turn wait can't land on a closed agent. _claim_lru_locked, reap and delete all claim run_lock and never release it. Getting the lock after the blocking wait therefore means the session is still registered, as the new comment in _checkout_turn says.
  • Abandoning a failed setup leaks nothing. _cleanup checks done.cancelled() before calling done.exception(), so a failed checkout or build passes None to the cleanup and releases nothing it didn't take.
  • checkout() closes the find-then-lock window. It tries the lock under the registry lock on both the existing-session and the newly-created path, and test_checkout_takes_the_turn_atomically_with_eviction pins this.

Strengths

  • The regression test measures the actual symptom: the heartbeat gap on a live SSE stream during another session's slow setup. It fails on main.
  • Every cancellation path you added (switch, one-shot build, stopped-turn wait) has a route-level test proving the lock or agent is released.
  • You chose not to send headers early or stream a "waiting" status, which keeps the existing 409/503/500 contract. That was the right call, and the PR explains why.

kovtcharov and others added 5 commits October 18, 2026 23:10
Starting a new session, or a /model switch that waits for a model to
load, ran on the sidecar's event loop. Every other session's SSE stream
stopped for that long, heartbeats included, so the TUI and the daemon
relay saw an idle connection and their idle timers kept counting.

Building the session's agent, building a one-shot agent and switching the
model now run on worker threads; the HTTP status codes for a busy or
failed session are unchanged. If the request goes away mid-setup, the
abandoned call still releases what it took: the session's run lock, or
the agent it built.
Review follow-ups. With setup on a worker thread, another request's
get_or_create could evict a session between this request finding it and
taking its run lock, and the turn then got a spurious 409 "already running
a turn". The registry's new checkout() tries the lock under the same lock
eviction holds, so a found session can no longer be evicted before its turn
starts.

Cleanup for an abandoned setup call now runs on its own thread, since
closing an agent blocks. Route-level tests cover a cancelled /model switch,
a cancelled one-shot build, a cancelled wait for a stopped turn, and one-shot
heartbeats. Comments and the changelog no longer claim a switch loads a
model.
If releasing a cancelled request's lock or agent raised on its cleanup
thread, the error went only to stderr and a leaked lock left no trace in
the sidecar log. It is now logged.
@kovtcharov-amd
kovtcharov-amd force-pushed the kalin/sidecar-setup-off-loop branch from bc6ed19 to 3c85686 Compare October 19, 2026 06:13
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 19, 2026
Merged via the queue into amd:main with commit 5d45d70 Oct 19, 2026
24 of 25 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the kalin/sidecar-setup-off-loop branch October 19, 2026 08:29
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