Skip to content

fix(ui): never take a model from under another chat or app - #5336

Merged
kovtcharov-amd merged 9 commits into
amd:mainfrom
kovtcharov:claude/rel-ui-model-slot
Oct 19, 2026
Merged

kovtcharov-amd merged 9 commits into
amd:mainfrom
kovtcharov:claude/rel-ui-model-slot

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Before: two Agent UI chats on different models swapped models on every turn, and starting a turn unloaded models that other apps sharing Lemonade were answering with. When GAIA couldn't get the model (lease timeout, not enough memory, server not answering), it showed a warning and answered anyway, so Lemonade loaded the model itself and skipped the free-memory check. Settings → Load and the auto-title went straight to Lemonade with no lease or lock, so either could evict a model mid-answer, and a title could load a second model. After: GAIA only ever unloads models it loaded itself, and only to make room. A turn that can't get its model fails and says why. Titles run on the side slot and never load anything. Load asks before interrupting a chat that's answering.

  • Shared server, shared rules. Settings → Load, the post-download auto-load and titles take the same lease and lock a chat turn does, in the same order.
  • Stop is honoured before a load. A turn stopped while waiting for the model slot or another chat's load ends there: no load, no query. The wait for another chat's load is shown.
  • A restart still knows GAIA's own models. Chat models already on GAIA's own Lemonade at startup count as its own, so they can be unloaded to make room; on a server you run, nothing is.

Reproduced by tests/unit/chat/ui/test_model_slot_discipline.py; each case fails on main and passes here, including a whole turn stopped during the pre-flight.

Overlaps #5241 and #5275 (both edit _chat_helpers.py; different functions). Builds on the #4772 discussion without fixing #4772 itself: the title still uses the model it's given, but it can no longer load it.

Merging with #5328: whichever of the two lands second also carries, as agreed with that PR's author:

  • except LeaseWaitCancelled (quiet) in _preflight_load, ahead of its catch-all;
  • the chat title's wait for the model wrapped in lease_wait_limit(30), with the 504 logged at info and the title skipped that turn, plus a test that it gives up.
  • keep this PR's own raises of InsufficientMemoryError and ModelInUseError ahead of that clause.

Merging with #5337: the two PRs conflict in one hunk of _chat_helpers.py next to model_load_lock. Both sides only add code there, so keep both. I ran a trial merge of the two locally: the UI suite and #5337's non-streamed timeout test passed 8 times out of 8. That test was racy with #5336's stop check, and #5337 now fixes it.

Test plan

  • pytest tests/unit/chat/ui tests/unit/test_chat_preflight.py tests/unit/test_model_server_info.py tests/unit/test_users_lemonade_untouched.py tests/unit/test_ui_warmup.py tests/unit/test_broker_wiring.py: all pass
  • npx vitest run in src/gaia/apps/webui: all pass, new api.loadModel.test.ts
  • python util/lint.py --black --isort --pylint --flake8
  • Live: two chats on two models that both fit, and confirm neither is unloaded between turns
🔍 Technical details
  • _maybe_load_expected_model no longer unloads other resident chat models. On InsufficientMemoryError it unloads only models in _models_loaded_here (pre-flight and Settings loads record there, with names normalized), says so in a status event, and loads once more. Otherwise it raises.
  • Exceptions now raised instead of a warning status: BrokerUnavailableError (with the model and what to check), InsufficientMemoryError (unchanged text), and RuntimeError for anything else, including a non-200 /health. The streaming and non-streamed paths both show the reason. The non-streamed path used to substitute "make sure Lemonade is running" for every unclassified error.
  • _maybe_load_expected_model wraps _preflight_load: any exception raised while the turn's Stop flag or its own cancel event is set is read as the Stop. That covers turns that pass those in, which the streamed turn does. A non-streamed turn's Stop reaches the wait only through fix(daemon): a queued model request waits instead of failing, and shows it is waiting #5328's interactive_turn(cancel=...), so there only the except LeaseWaitCancelled clause above keeps it quiet. fix(daemon): a queued model request waits instead of failing, and shows it is waiting #5328's test_stop_during_a_queued_preflight_stays_quiet_on_the_non_streaming_path guards that.
  • A failed Settings or post-download load shows in /api/system/status probe_warnings until a load succeeds.
  • model_load_lock is taken with _take_model_load_lock (polls, shows status, returns on Stop) after the lease. _load_through_the_slot in routers/system.py uses the same lease-then-lock order.
  • Title: LemonadeClient.chat_completions under one background-priority model_lease spanning the residency check and the call; id_slot=SIDE_SLOT when the model has two slots; auto_download=False.
  • Ownership: the UI keeps a record of the models it loaded (<GAIA home>/ui/loaded_models.json, written whole under a lock): pre-flight and Settings loads, and any load its own agents make (a LemonadeClient load listener). Models Lemonade no longer has loaded drop out of it. A same-name copy at too small a window is reloaded only if the UI loaded it or it is an auto-load (Lemonade's 4096 default or the supervisor's profile window); otherwise ModelInUseError says another app has it.
  • /api/system/load-model gains force. Without it the endpoint returns 409 while any run is active. loadModelAskingFirst turns that into a confirm() in Settings. The API schema and types are regenerated.
  • Updated tests that pinned the old behaviour: unload-before-load ([Bug]: Custom Agent not working #1382's double-load case is now covered by the free-memory check), swallowed pre-flight failures, and raw-HTTP titles.
  • Not changed here: the retry-on-error path that re-runs the whole query is fix(ui): never re-run a failed chat turn behind the user's back #5338.
  • LLM-affecting? Error surfacing only; prompts and tools are unchanged. Categories to watch on the next RC: rag_quality, gaia_core.

@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

This PR makes the Agent UI share Lemonade properly. A chat turn no longer unloads models that other chats or apps are using. Settings → Load, the load after a download, and auto-titles now wait their turn for the model the same way a chat does. A turn that can't get its model now fails with the reason instead of answering anyway. The lock ordering, Stop handling and title changes all check out against the broker's one-lease-at-a-time rule.

Two things to fix before merge:

  • A broken ~/.gaia/config.json now makes Settings → Load fail silently. Before, the load returned an error right away. Now it returns "loading", the error escapes the background task, and nothing appears in the status panel. Catch that error alongside the others.
  • No live evidence yet. This changes behaviour users can see: a new confirm dialog in Settings, and new error messages when a turn can't load its model. The PR has no request/response or screenshot, and its one live test-plan item is unchecked.

Real-world evidence

N/A: no evidence bundle was produced for this run. The verdict rests on static review and the PR's unit/vitest results. The two-chat live check and the Settings confirm dialog have not been exercised on a real Lemonade.

🔍 Technical details

🟡 Important

🟡 GaiaConfigError escapes _load_through_the_slot (src/gaia/ui/routers/system.py:771)
LemonadeClient.load_model → chosen_backend_for → preferred_llamacpp_backend() → GaiaConfig.load(), which can raise GaiaConfigError (a plain Exception subclass). The removed _with_chosen_backend path caught it and returned 502. Now it is raised inside asyncio.to_thread in a fire-and-forget task. The endpoint has already returned 202, _last_load_failure is never set, and the only trace is asyncio's "Task exception was never retrieved". The post-download auto-load has the same gap.

    except (LemonadeClientError, BrokerUnavailableError, GaiaConfigError, OSError) as exc:

(plus from gaia.config import GaiaConfigError in the function's imports). Worth a test that sets a bad config and asserts probe_warnings shows it.

🟡 Real-world evidence missing for user-visible surfaces
Changed: the /api/system/load-model 409/force contract, the Settings confirm() flow, and the turn-ending pre-flight errors in the chat stream. The CI lane could produce the route evidence: a 409 while a run is active, then a 202 with force: true. The screenshot of the confirm dialog and the error status can wait for the strix-halo lane. The "two chats, two models, no swap" item is the core claim and is still unchecked.

🟢 Minor

🟢 "Idle" isn't enforced (src/gaia/ui/_chat_helpers.py:241)
_load_making_room unloads every model this process loaded, not just idle ones. A model can be unloaded while another chat's turn is between LLM calls (for example, during a tool call), and that turn then reloads it on its next step. This is much better than before, and the broker lease does protect each in-flight request. The test name ..._unloads_its_own_idle_models and the test-module docstring do promise idleness, though. Either skip models whose session has an active run, or drop "idle" from the wording.

🟢 Stop swallows any pre-flight error (src/gaia/ui/_chat_helpers.py:630)
Treating any exception as a Stop once cancelled is set is the right call for #5328's LeaseWaitCancelled. Consider logging exc at info level so a real failure that races a Stop still leaves a trace.

Strengths

  • Lease-then-lock ordering is applied the same way in the pre-flight, Settings load, and auto-load. The nested lease always targets the same model, so the broker's different-model guard can't trip. unload_model takes no lease, so unloading inside _load_making_room is safe.
  • Replacing warning statuses with raised, actionable errors follows the fail-loudly rule. The non-streamed path no longer guesses "make sure Lemonade is running" for every failure.
  • test_model_slot_discipline.py reproduces each scenario through the real _stream_chat_impl, including a Stop that arrives mid-lease both as a return and as a raise.

kovtcharov added a commit to kovtcharov/gaia that referenced this pull request Oct 18, 2026
… cover retries

Third review round, each with a failing test:

- The email sidecar's /query runs as the user's turn, like the gaia agent's:
  model_queue status on its stream (its translator now keeps phase and queue
  on those events only), interactive priority, and /cancel ends the wait.
- lease_wait_limit(seconds) caps a model-slot wait for side work that must not
  hold a worker thread behind a long queue (chat titles under amd#5336). It caps
  the daemon queue and this process's model lock alike.
- A lease's declared hold is the call's own timeout when one is passed, plus
  the retry deadline after which no new attempt starts, plus a model load.
- The lease route refuses a NaN or infinite timeout or max_hold_s; NaN
  compared false with everything and turned the cap off.
- A test pins that Stop during a queued pre-flight load stays quiet, which
  guards the except order when this merges with amd#5336.
- The aging test fails instead of hanging when aging regresses.
@github-actions

Copy link
Copy Markdown
Contributor

🟡 The Agent UI's record of models it loaded never forgets a model that someone else unloaded. That brings back the problem this push meant to fix. The record now lives on disk, and the Agent UI only removes a model from it when the UI unloads that model itself. Suppose Lemonade evicts the model, or the user or another app unloads it. Later the email agent or gaia chat loads the same model, which is often the case because agents share the default model on purpose. The Agent UI still lists that model as its own, so its next "make room" step can unload it out from under the other app. Before this push the record lasted only for one run of the process. Now it survives restarts, so after one Agent UI turn the default model can count as the UI's from then on.

Suggested fix: whenever the pre-flight reads what is loaded, drop every recorded model that isn't loaded anymore. Whoever loads it next is its owner.

🔍 Technical details
  • src/gaia/ui/_chat_helpers.py: _forget_model is only called from _load_making_room after the UI's own unload_model. Nothing removes a stale key when the model is gone from resident / all_models_loaded.
  • _load_making_room already has resident. Before building ours, prune it:
    live = {_model_key(m["model_name"]) for m in resident if m.get("model_name")}
    stale = _owned_models() - live
    if stale:
        _owned_models().difference_update(stale)
        _save_owned_models()
    This only helps if resident reflects the server at the moment of the call, so it may be better to do the pruning in the pre-flight where /health is read. Add a test: the model is recorded, then it is missing from resident, then another app's copy shows up in resident. Assert that the copy is not unloaded.
  • Minor: _save_owned_models uses a plain write_text with no lock. Settings load, auto-load and the pre-flight can all call it from different threads. Consider a temp-file write followed by os.replace.

kovtcharov added a commit to kovtcharov/gaia that referenced this pull request Oct 18, 2026
…ds refused

Fourth review round, each with a failing test:

- A lease failure re-discovers the daemon only when the daemon could not be
  reached, or answered 401/403. Before, any failure without an HTTP status
  re-queued once: a daemon that went silent mid-queue sent the request to the
  back of the line, and a bad GAIA_MODEL_LEASE_WAIT_S was retried pointlessly.
- The in-process broker refuses a NaN, infinite or non-positive max_hold_s,
  which would have turned the hold cap off.
- A second merge-guard test covers the non-streaming turn: no handler, and
  the Stop reaches the queued pre-flight only through the turn scope. Only the
  LeaseWaitCancelled branch keeps that quiet once merged with amd#5336.
@github-actions github-actions Bot added llm LLM backend changes performance Performance-critical changes labels Oct 18, 2026
kovtcharov added a commit to kovtcharov/gaia that referenced this pull request Oct 18, 2026
… starts

Its 0.1 s no-progress limit could fire before the worker reached the
agent; with the pre-flight's stop check (amd#5336) the turn then ended early
and the test waited on an agent that never started, about 1 run in 4.
The limit now drops to 0.1 s only once the agent is running.
Two chats on different models swapped models on every turn, and a chat
turn unloaded models other apps on the same Lemonade were answering with.
A lease timeout, a refused load or an unreachable server only showed a
warning and the turn went on, so Lemonade auto-loaded the model itself,
past the free-memory check. Settings -> Load and the auto-title posted
straight to Lemonade, with no lease or load lock, so either could evict a
model mid-answer, and a title could load a different model.

- The pre-flight never unloads a model this process did not load. When a
  load won't fit, it unloads only this process's own other models, says
  so, and loads once more; otherwise the turn fails with the reason.
- A lease timeout, a memory refusal or any other pre-flight failure ends
  the turn with an actionable error instead of answering anyway.
- A Stop seen after the lease or load-lock wait loads nothing, and the
  load-lock wait is shown and ends on Stop.
- The auto-title goes through the model client (lease at background
  priority, per-model lock), on the side slot when there is one, and never
  loads a model: an unloaded model titles from the first question.
- Settings -> Load and the post-download auto-load go through the model
  client under the load lock; while a chat is answering, Load returns 409
  and the UI asks before loading anyway.
Review follow-ups on the model-slot change:

- Settings -> Load took the load lock before the broker lease, the reverse
  of a chat turn, so the two could deadlock. It now takes the lease first.
- The boot preload and Settings loads now count as this process's own
  models, and names match the way Lemonade reports them, so a session that
  switches to a model that won't fit unloads GAIA's old one instead of
  failing.
- The title's residency check and its request share one background lease,
  so the model can't be swapped out between them.
- A non-streamed turn shows the real reason a pre-flight failed, and a
  non-200 /health ends the turn instead of answering blind.
…its models

Review follow-ups on the model-slot change:

- A Stop while the pre-flight waited for the model slot or another load
  returned quietly, and the turn then sent its query anyway, so Lemonade
  loaded the model itself past the free-memory check. The turn now ends
  as stopped. Any error a wait raises after the Stop (such as the broker's
  cancelled wait from amd#5328) is read as the Stop, not as 'check that
  Lemonade is running'.
- After an Agent UI restart, models the previous run loaded counted as
  another app's and could never be unloaded to make room. Chat models
  already on GAIA's own Lemonade at startup now count as its own; a
  server the user runs adopts nothing.
- A failed Settings or post-download load now shows in the status's probe
  warnings until a load succeeds, instead of only in the log.
- The pre-flight no longer shows 'another app is using it' after the
  wait is already over; the broker reports waits.
…counts

Second-round review follow-ups on the model-slot change:

- Startup claimed every chat model on GAIA's Lemonade as the Agent UI's,
  including ones the email agent or gaia chat loaded, so the pre-flight
  could unload them. The Agent UI now keeps its own record of the models
  it loaded (<GAIA home>/ui/loaded_models.json), read on first use, so a
  restart remembers exactly those and nothing else.
- The pre-flight also stops on the turn's own cancel event, which
  teardown and the idle stop set, not only on the Stop flag; an error a
  stopped wait raises is not logged as a load failure.
- A stop during the retry's model reload no longer shows 'retrying' and
  re-runs the query.
- tests/conftest.py keeps that record in a tmp file for every test.
…window alone

Third-round review follow-ups on the model-slot change:

- The record of the Agent UI's models never forgot a model Lemonade
  evicted, so a copy another app loaded later counted as the UI's and
  could be unloaded. Each pre-flight now drops recorded models that are no
  longer loaded.
- The same model loaded at too small a window was unloaded and reloaded
  whoever loaded it, cutting another app's request off. It is reloaded
  only if the UI loaded it or Lemonade auto-loaded it at its default
  window (the amd#1030 case); otherwise the turn says another app has it.
- A config error in Settings -> Load escaped the background task; it now
  shows in the status like any other load failure.
- The load-lock wait also stops on the turn's own cancel; the record is
  written whole and under a lock; Settings records its load under the
  load lock. Tests cover the retry path's Stop.
…ks like

Fourth-round review follow-ups on the model-slot change:

- An auto-loaded model was recognised only at Lemonade's 4096 default, but
  GAIA's supervisor starts Lemonade with the profile window, so a request-
  triggered load comes up at 64K (or 32K on NPU). A copy at that window now
  counts as an auto-load too, not as another app's choice.
- A model the UI's own agent reloaded mid-turn (LemonadeClient's
  _ensure_model_loaded) was never recorded, so it later counted as another
  app's. LemonadeClient now calls registered load listeners after every
  load, and the Agent UI records through one.
- The non-streamed turn passes its cancel event to the pre-flight, so its
  idle stop ends a wait for the model instead of failing it.
- The stop-aware load lock, the whole-file record write and the record
  lock each have a test that fails with the fix reverted.
A copy of the chat's model that Lemonade reports with no ctx_size read as
window 0, which matched neither auto-load window, so the turn said another
app had it instead of reloading: the very state amd#1030 needs a reload for.
No reported window now counts as nobody's choice.
…ssage

A window of 0 now counts as an auto-load and never reaches this error, so
the window is always known there.
kovtcharov-amd pushed a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
… cover retries

Third review round, each with a failing test:

- The email sidecar's /query runs as the user's turn, like the gaia agent's:
  model_queue status on its stream (its translator now keeps phase and queue
  on those events only), interactive priority, and /cancel ends the wait.
- lease_wait_limit(seconds) caps a model-slot wait for side work that must not
  hold a worker thread behind a long queue (chat titles under amd#5336). It caps
  the daemon queue and this process's model lock alike.
- A lease's declared hold is the call's own timeout when one is passed, plus
  the retry deadline after which no new attempt starts, plus a model load.
- The lease route refuses a NaN or infinite timeout or max_hold_s; NaN
  compared false with everything and turned the cap off.
- A test pins that Stop during a queued pre-flight load stays quiet, which
  guards the except order when this merges with amd#5336.
- The aging test fails instead of hanging when aging regresses.
kovtcharov-amd pushed a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
…ds refused

Fourth review round, each with a failing test:

- A lease failure re-discovers the daemon only when the daemon could not be
  reached, or answered 401/403. Before, any failure without an HTTP status
  re-queued once: a daemon that went silent mid-queue sent the request to the
  back of the line, and a bad GAIA_MODEL_LEASE_WAIT_S was retried pointlessly.
- The in-process broker refuses a NaN, infinite or non-positive max_hold_s,
  which would have turned the hold cap off.
- A second merge-guard test covers the non-streaming turn: no handler, and
  the Stop reaches the queued pre-flight only through the turn scope. Only the
  LeaseWaitCancelled branch keeps that quiet once merged with amd#5336.
A real failure that races a Stop now leaves a trace in the log instead of
disappearing behind the Stop.
@kovtcharov-amd
kovtcharov-amd force-pushed the claude/rel-ui-model-slot branch from c7b53aa to 11f45e9 Compare October 19, 2026 06:26
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 19, 2026
Merged via the queue into amd:main with commit 75fd6ea Oct 19, 2026
58 of 60 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claude/rel-ui-model-slot branch October 19, 2026 08:28
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
Resolves conflicts with amd#5336, amd#5348 and amd#5359, and makes the additions
this PR owes as the second to land:

- _preflight_load keeps amd#5336's re-raise of InsufficientMemoryError and
  ModelInUseError, and adds `except LeaseWaitCancelled` ahead of its
  catch-all, so a stopped queued wait is not reported as a failed load.
- The chat title's lease runs under lease_wait_limit(30), so a title gives
  up instead of holding a worker thread behind a long queue.
- Background indexing keeps amd#5348's embedder wait callback inside
  detached_from_turn.
- broker.py keeps both _renewed_at and amd#5359's _last_activity; a reclaim
  stamps _last_activity.

Review follow-ups: an unreadable queue-stream line is a
BrokerUnavailableError naming the daemon instead of a raw parse error, and
a test pins the email translator's copy of _QUEUE_FIELDS to the core one.
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
…5338)

Before: when an Agent UI turn hit a retryable model error (the model got
evicted, a network blip), GAIA reloaded the model and ran the whole
query again. Every tool the turn had already run (a file write, a shell
command, a sent email) ran a second time, and all the user saw was
"Model reloaded — retrying...". After: the turn ends with the error,
which says whether sending it again can help, and the user decides. The
next turn's pre-flight reloads an evicted model.

Reproduced by `tests/unit/chat/ui/test_no_hidden_retry.py`: on main the
tool runs twice, here once. Covers both the streamed and the
non-streamed paths.

Overlaps amd#5241 and amd#5275 (they also edit `_chat_helpers.py`, in
different functions) and amd#5336 (its pre-flight docstring touches the
same note; whichever lands second keeps one sentence).

## Test plan
- [x] `pytest tests/unit/chat/ui tests/unit/test_chat_preflight.py
tests/unit/test_ctx_overflow_device_profile_2884.py
tests/unit/test_lemonade_error_classification.py`: all pass
- [x] `python util/lint.py --black --isort --pylint --flake8
--test-lanes`

<details>
<summary>🔍 Technical details</summary>

- Removed the `except → _maybe_load_expected_model → process_query`
replay in `_run_agent` (streamed) and `_query` (non-streamed). Errors
still go through `_classify_chat_exception`, so the user sees the
classified `user_message`.
- Resuming from the failed model call would need the agent loop to
checkpoint mid-turn (`agents/base`), which is outside the UI backend.
Failing visibly is the safe half; resuming can follow there.
- `LemonadeModelNotLoadedError.user_message` now says the model was
unloaded and to send the message again, since nothing reloads it
mid-turn any more.
- LLM-affecting (error path): watch `gaia_core` and `rag_quality` on the
next RC. A turn that used to recover silently from an eviction now fails
once.
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
…long" (amd#5322)

**Stacked on amd#5321**, which is merged in. Review only the commits that
aren't in amd#5321.

**Depends on amd#5336 for the complete fix.** The Agent UI auto-title still
posts outside the model lease on main, so it can still collide with a
turn. amd#5336 moves titles onto the side slot under the lease. Until amd#5336
lands, this PR retries such a collision and stops misreporting it, but
the auto-title can still cause one.

Users were told "This conversation got too long… Start a fresh task"
when their conversation wasn't long at all. With `--kv-unified`, two
requests on one model share a single KV pool. If they outgrow it
together, llama.cpp fails both with "Context size has been exceeded."
GAIA treated that as an overflow: it didn't retry, the agent trimmed
history, and the user saw the fresh-task advice. Now that error is
recognised as a collision. The client retries it under its normal
bounded policy, and if it still fails, the user is told the likely cause
and to send the message again. A real overflow ("the request exceeds the
available context size") is unchanged. Text completions, which RAG uses,
now take the same per-model lease as chat, so they no longer run
alongside a turn.

Reproduced by `tests/unit/test_lemonade_kv_cache_shared.py`; fails on
main, passes here. On main, 11 of its 12 tests fail on behaviour (the
12th checks that a real overflow is still an overflow). On main the
collision classifies as `LemonadeContextOverflowError` with "Start a
fresh task", and a chat that hits it fails after one request. Here it
succeeds on the second request.

## Test plan
- [x] `pytest tests/unit/test_lemonade_kv_cache_shared.py
tests/unit/test_lemonade_chat_slots.py`
- [x] Classification, retry, chat-helper and agent-retry suites: 619
pass.
- [x] `python util/lint.py --black --isort --flake8 --pylint` is clean.

<details>
<summary>🔍 Technical details</summary>

- `KV_CACHE_SHARED_PHRASES` are moved out of `CONTEXT_OVERFLOW_PHRASES`.
`is_kv_cache_shared_error()` is new, and `classify_http_failure` returns
`"KV cache shared with another request"` for these errors.
- `LemonadeKVCacheSharedError` (retryable) is checked before the
overflow branch in both `_classify_lemonade_response` and
`classify_lemonade_exception`.
- `test_an_exhausted_kv_pool_is_a_context_overflow` encoded the old
misdiagnosis. It is inverted here.
- llama.cpp emits this text only when a decode can't find a free KV
cell, and it sends it to every active slot. A single request that fills
its own slot stops with `finish_reason=length`, and one that doesn't fit
at all gets "exceeds the available context size".
- The Agent UI auto-title, which posted outside the lease, moves onto
the side slot under the lease in amd#5336.
- A collision after output has started is surfaced rather than replayed,
and is still marked transient
(`test_a_collision_after_output_is_not_replayed`).
- Categories to watch: `error_recovery`, `context_retention`, `memory`,
`rag_quality`.
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
amd#5337)

Builds on amd#5242's turn queue (now merged); the diff is this change
alone.

Before: one chat could hold the model away from every other chat. A
permission prompt left unanswered in a background tab blocked all chats
for up to 10 minutes; Stop couldn't end a turn whose agent thread was
stuck in a tool or MCP call; a non-streamed message waited 60 s, got a
429 and was never saved; scheduled runs skipped the line, and a
timed-out one (or autonomous tick) kept running and piling up. After: a
turn waiting on you steps out of line and comes back at the front once
answered, Stop ends the turn and frees the model within 5 s, a busy
model queues a message instead of dropping it, and scheduled runs and
ticks wait their turn and stop when they time out.

- **Back from a prompt, the model is checked again.** Another chat may
have changed the loaded model while you were deciding; if it can't be
loaded, the turn ends with the reason before the approved tool runs.

- **Waiting on you doesn't hold the GPU.** Other chats run while a
prompt or question is open; the answered turn goes ahead of chats that
arrived meanwhile.
- **Stop really stops.** If the agent thread can't see the Stop, the
turn still ends and the model is freed; only that chat stays busy, with
a 409 that says it's still stopping, until the thread exits.
- **Nothing silent.** A turn waiting on the start-up warm-up says what
it's waiting on, and Stop ends the wait. Agent setup that waits on
another chat's setup says so, frees the model meanwhile, and fails with
a reason after 2 minutes.

Reproduced by `tests/unit/chat/ui/test_turn_slot_reliability.py`,
`test_scheduled_run_slot.py` and
`test_agent_loop_session_lock.py::test_timed_out_tick_frees_the_model_while_its_thread_winds_down`;
they fail on amd#5242's branch and pass here.

Overlaps amd#5242 (builds on it), amd#5241, amd#5239 and amd#5246 (all edit
`_chat_helpers.py` / `routers/chat.py`; no shared hunks with this change
when I checked).

**Merging with amd#5336:** the two PRs conflict in one hunk of
`_chat_helpers.py` next to `model_load_lock`. Both sides only add code
there, so keep both.
`test_non_streaming_timeout_holds_session_until_worker_exits` used to
race amd#5336's pre-flight stop check (about 1 run in 4). It now lowers the
no-progress limit only once the agent is running, and passed 8 of 8 in a
local trial merge.

## Test plan
- [x] `pytest tests/unit/chat/ui tests/unit/test_ui_warmup.py
tests/unit/test_chat_preflight.py tests/unit/test_relay_*.py`: all pass
- [x] `python util/lint.py --black --isort --pylint --flake8
--test-lanes`
- [x] Stuck-thread, open-tab Stop, question and permission waits,
front-of-line resume: each a failing test first
- [x] Live: two chats against the Agent UI server on this branch
(Gemma-4-E4B on Lemonade, GPU), one left on a permission prompt while
the other answers. `/api/chat/active` at each step:
1. A on its prompt:
`{"session_ids":["A"],"queued":[],"awaiting_user":{"A":"permission"}}`
2. B sent while A waits, B answers `51` without queuing:
`{"session_ids":["A","B"],"queued":[],"awaiting_user":{"A":"permission"}}`
3. A answered while B streams a long reply; A goes back in line and
stops showing "needs you":
`{"session_ids":["A","B"],"queued":["A"],"awaiting_user":{}}`, and A's
stream shows `Waiting for the GPU — 1st in line`
  4. Both finish: `{"session_ids":[],"queued":[],"awaiting_user":{}}`

<details>
<summary>🔍 Technical details</summary>

- `TurnSlot` (turn_queue.py) is a turn's handle on the queue.
`SSEOutputHandler._away_from_model` calls `step_away()` around the
confirm/question waits and `come_back()` to re-enter with `front=True`.
A Stop while waiting there withdraws it, and the handler marks the turn
cancelled so it never calls the model unheld.
- `_stream_chat_impl` breaks its event loop 5 s after Stop when the
producer is still alive. `_cleanup_stream` closes the slot (a late
`come_back` can't retake it) and records the thread in
`_stopping_sessions`. `routers/chat.py` releases the session lock only
when that thread exits, by polling, not `to_thread(join)`, so it doesn't
pin a shared-executor worker.
- `tool_registry_lock` (`writing_tool_registry`) now guards every agent
build and `_register_tools()` call: UI turns, agent loop, scheduled runs
and warm-up. These write the process-global `_TOOL_REGISTRY` and then
snapshot it, so before this lock, a stopped turn's lingering thread
could interleave with the next turn's build.
- A timed-out scheduled run stops its agent (a streaming reply included,
via its console's `cancelled`) and keeps its turn-queue slot until its
thread has stopped, so it never shares the GPU with the next turn;
waiting chats see their place in line.
- A turn waiting in line sends `: keepalive` every 5 s.
- `wait_for_warm_up` no longer sends the turn anyway after 300 s; it
raises with the reason.
- Ticks and scheduled runs run on their own daemon threads
(`agent_threads.run_in_own_thread`), not the default executor that the
SSE loop polls with.
- Removed: the non-streamed 429. Its test now lives in the new file as
"saved, then waits in line".
- Known gap: a lingering autonomous tick shows the generic "already in
progress" 409 rather than "still stopping". The chat is still protected;
only the wording differs.
- LLM-affecting? No prompt, tool, or classification changes; no eval
categories needed.
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
…ws it is waiting (amd#5328)

When several GAIA processes shared the model, a turn queued behind
another failed after 300 s with "Check `gaia daemon logs`", even though
the request ahead was legitimately running (local calls may take up to
an hour). Leases were reclaimed mid-generation after 900 s. A request
whose client had gone (Ctrl+C, Stop, app closed) still got the slot
later and held it for nobody. The user saw nothing while waiting. Now a
queued request waits for as long as the request ahead is alive. The
Agent UI shows "Waiting for the model — `<who>` is using it" with its
place in line and seconds waited. Stop or disconnect takes it out of the
queue, and the holder keeps its lease while it renews.

Independent review: a `code-reviewer` agent reviewed the diff. Its
findings are fixed: Stop now cancels a queued wait, a grant that races a
cancel is released on both sides, a stop during the pre-flight load
stays quiet, only the holder can renew or release, and error messages
don't leak lease ids. A bot review's follow-ups are fixed too: a Stop
while queued is a cancelled turn, not an LLM error, and the heartbeat
logs when it loses its credential.

Reproduced by `tests/unit/test_daemon_broker_queue.py`. All of its 13
original tests fail on main and pass here. The two that show the
user-facing symptoms with main's own API are
`test_model_lease_waits_out_a_busy_holder_instead_of_failing` (504 on
main) and `test_a_waiter_that_disconnects_is_never_granted_the_slot`
(the dead waiter stays queued on main).

Builds alongside amd#5327, which stops a busy daemon being killed. They
share one identical hunk (the async credential check in
`broker_routes.py`), so either can land first. amd#5287 replaces the
per-model lock this PR makes reportable; whichever lands second keeps
the wait reporting and cancel on the slot gate. Its shared-lease TTL
margin can go once leases renew.

Merge order with amd#5336: whichever lands second makes two additions.
- `except LeaseWaitCancelled` in amd#5336's `_preflight_load`, ahead of its
catch-all.
- `lease_wait_limit(30)` around `_generate_session_title._ask`'s lease,
so a title gives up rather than holding a default-pool thread behind a
long queue.

This PR's author does both if this lands second; amd#5336's does if that
does.

For the `except` clause, the guard is
`test_stop_during_a_queued_preflight_stays_quiet_on_the_non_streaming_path`.
It covers the turn that passes no handler and no cancel event, where
only that clause keeps a stopped wait from being reported as a failed
load. The handler-based variant passes either way, because amd#5336's
wrapper already ignores errors once Stop is set.

Merge order with amd#5339 (Agent UI indexing), same rule: whichever lands
second wraps `rag.index_document(...)` in `_index_document._do_index`
with `lease_wait_listener(lambda _event: _step())`. Queue updates then
count as indexing progress, so an upload waiting for the embedder behind
a long chat isn't stopped at amd#5339's 600 s no-progress limit. A test
covers an index that waits on a lease longer than that limit.

Merge order with amd#5359 (idle exit for non-default daemons), same rule.
It stamps `_last_activity` in `ModelSlotBroker`, which conflicts with
this PR in `broker.py` in two places, each resolved by keeping both
sides. In `_grant_locked`, keep `_renewed_at` and `_last_activity`. In
`_reclaim_if_stale_locked`, take this PR's version and add
`self._last_activity = self._now()` before `notify_all()`.

Eval categories to watch at the next RC. No prompt or tool surface
changed. The agent-loop catchall gained one case: a Stop while queued
for the model is a cancelled turn. Turn timing under a busy model also
changed. Watch `rag_quality` and the `gaia_*` turn timings.

Live run against the real daemon app (queue stream, queue route, a
requester leaving, the wait cap):
[output](amd#5328 (comment)).

## Test plan
- [x] `python -m pytest tests/unit/test_daemon_broker_queue.py
tests/unit/test_daemon_broker.py tests/unit/test_daemon_broker_routes.py
tests/unit/test_broker_wiring.py
tests/unit/chat/ui/test_model_queue_status.py -q`
- [x] `python util/lint.py --black --isort --flake8 --pylint
--test-lanes`
- [ ] With a daemon running, hold the slot with a raw `POST
/host/v1/models/lease`, then send an Agent UI turn. It shows the waiting
line and updates it every 2 s. Press Stop, and `GET
/host/v1/models/queue` shows nothing waiting.
- [x] With `GAIA_MODEL_LEASE_WAIT_S=5`, the same turn fails after 5 s
with where it stood in line and who held the model.

<details>
<summary>🔍 Technical details</summary>

- **Protocol.** `POST /host/v1/models/lease` with `"stream": true`
returns NDJSON: `queued` lines, then one `granted` or `error` line.
Without `stream`, it is the old single JSON response with the old 300 s
default, so older clients are unchanged. A new client talking to an
older daemon reads its JSON reply, and never starts a heartbeat because
there is no `renew_interval_s`.
- **Renewal.** `"renewable": true` leases are kept by `POST
…/lease/{id}/renew` every `heartbeat_ttl/4`. They are reclaimed after 60
s without a renewal, with a 4 h cap. Non-renewing leases keep the 900 s
TTL.
- **Cancellation.** Each wait runs on its own daemon thread
(`broker_routes._Wait`), never the shared anyio pool. A disconnect or
abandon sets the broker's `cancel` and calls `wake()`. A grant that
races the abandon is released exactly once, under `_Wait._guard`. A
streamed grant counts as delivered only after its send returns.
- **Silence detection.** The client sets a 30 s socket timeout on the
body only, so older daemons can still take 300 s to send headers. On the
client, a cancel that arrives with the grant line releases that lease.
- **Turn scope.** `broker_client.interactive_turn` sets context vars for
priority, the wait listener and cancel. Plain threads (memory
extraction) start without them and stay background. Threads that copy
the context (tool runners, the stream watchdog) stay part of the turn.
The UI cancel checks both `TurnCancel` and the SSE handler's Stop flag.
- **Ownership.** Renew and release check the caller is the lease's
holder. `LeaseNotHeldError` no longer echoes the active lease id. `GET
/host/v1/models/queue` strips it too.
- **Surfaces.** The queued state goes out as a `status` event with
`phase: "model_queue"` and a `queue` object (`event` queued/granted,
position, holder, seconds waited). It goes on the Agent UI's SSE stream
and on the `/query` streams of the gaia agent (which the TUI reads;
amd#5319 renders it) and the email agent. Both canonical translators keep
`queue`, and the contract is in `agent-ui-query-sse-contract.md` §4.4.
Stop in the Agent UI and `/query/{run_id}/cancel` on either sidecar end
the wait. The stdio transport still only logs it. A non-streaming Agent
UI turn has no stream to show it on, so queue updates only keep its idle
stop from firing.
- **Bounds.** A renewing lease is held at most its holder's declared
hold. LemonadeClient declares the call's own timeout (the request budget
when none is passed), plus the retry deadline after which no new attempt
starts, plus 15 min for a load. Undeclared leases keep main's 900 s, and
the ceiling is 2 h. Background waits have no ceiling, but they age:
after 10 min queued they rank as interactive. Side work that must not
tie up a worker thread wraps itself in `lease_wait_limit(seconds)`; the
chat title gets it from whichever of this and amd#5336 lands second
(above). Background work a turn starts (indexing) runs outside the
turn's scope. The lease route refuses NaN or infinite `timeout` and
`max_hold_s`.
- **Not in this PR.** Cross-home arbitration (eval homes sharing one
Lemonade through separate brokers) is designed and staged for a
follow-up.
</details>

---------

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 llm LLM backend changes performance Performance-critical changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants