Repository navigation
fix(ui): never take a model from under another chat or app - #5336
Conversation
|
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:
Real-world evidenceN/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 🟡 (plus 🟡 Real-world evidence missing for user-visible surfaces 🟢 Minor 🟢 "Idle" isn't enforced (src/gaia/ui/_chat_helpers.py:241) 🟢 Stop swallows any pre-flight error (src/gaia/ui/_chat_helpers.py:630) Strengths
|
… 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.
|
🟡 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 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
|
…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.
… 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.
… 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.
…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.
c7b53aa to
11f45e9
Compare
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.
…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]>
…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]>
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]>
…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]>
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.
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;lease_wait_limit(30), with the 504 logged at info and the title skipped that turn, plus a test that it gives up.InsufficientMemoryErrorandModelInUseErrorahead of that clause.Merging with #5337: the two PRs conflict in one hunk of
_chat_helpers.pynext tomodel_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 passnpx vitest runinsrc/gaia/apps/webui: all pass, newapi.loadModel.test.tspython util/lint.py --black --isort --pylint --flake8🔍 Technical details
_maybe_load_expected_modelno longer unloads other resident chat models. OnInsufficientMemoryErrorit 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.BrokerUnavailableError(with the model and what to check),InsufficientMemoryError(unchanged text), andRuntimeErrorfor 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_modelwraps_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'sinteractive_turn(cancel=...), so there only theexcept LeaseWaitCancelledclause above keeps it quiet. fix(daemon): a queued model request waits instead of failing, and shows it is waiting #5328'stest_stop_during_a_queued_preflight_stays_quiet_on_the_non_streaming_pathguards that./api/system/statusprobe_warningsuntil a load succeeds.model_load_lockis taken with_take_model_load_lock(polls, shows status, returns on Stop) after the lease._load_through_the_slotinrouters/system.pyuses the same lease-then-lock order.LemonadeClient.chat_completionsunder one background-prioritymodel_leasespanning the residency check and the call;id_slot=SIDE_SLOTwhen the model has two slots;auto_download=False.<GAIA home>/ui/loaded_models.json, written whole under a lock): pre-flight and Settings loads, and any load its own agents make (aLemonadeClientload 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); otherwiseModelInUseErrorsays another app has it./api/system/load-modelgainsforce. Without it the endpoint returns 409 while any run is active.loadModelAskingFirstturns that into aconfirm()in Settings. The API schema and types are regenerated.rag_quality,gaia_core.