Repository navigation
fix(daemon): a queued model request waits instead of failing, and shows it is waiting - #5328
Conversation
|
Verdict: Request changes (only for the missing live evidence; the code itself looks correct) A request queued behind another now waits as long as the request ahead is alive. It no longer fails at 300 s. Long generations keep their slot by renewing it, a caller that leaves drops out of the queue, and the Agent UI shows a live "Waiting for the model" line. The design holds up: the race where a grant lands just as its requester leaves is handled exactly once on both sides, older clients and daemons keep their old behaviour, and lease ids no longer leak in error messages or the new queue route.
Real-world evidenceN/A: no evidence bundle was produced for this run, and this runner couldn't run the PR's tests either (pytest isn't installed). For the daemon routes and the Agent UI status line, this verdict rests on reading the code alone. 🔍 Technical details🟡 Important
🟢 Minor
Strengths
|
|
Addressed the review, and fixed the red Linux unit check.
Live run: the real daemon app on :18302 under a throwaway Queue stream, queue route, a requester that leaves, and the wait cap (output)I don't have an Agent UI screenshot. A live UI turn would load a model on the shared Lemonade, which I won't touch from this machine. The waiting line, its consolidation into one status row, and Stop ending the wait are covered end to end through the real streaming chat route by |
… when the agent reports one The TUI computed the relay's idle budget from its own shell, but the relay uses the daemon's environment. With the daemon at GAIA_AGENT_TOOL_TIMEOUT=600 and the TUI's shell unset, the TUI still cut in at 330 s. Its parser also disagreed with timeouts.py on whitespace, nan and hex. The queued-follow-up notice guessed "most likely waiting for the model" with nothing to go on, and fired seconds after the user answered a prompt. - The daemon reports its relay budget on /daemon/v1/status (agent_read_timeout_s, null for no limit, or agent_read_timeout_error), and the TUI waits on that. A daemon too old to report it falls back to this shell's setting, logged. - The fallback parser mirrors Python's float(). Both sides are checked against one table, tests/fixtures/daemon/agent_read_timeout_cases.json, generated from timeouts.py. - A status with phase "model_queue" (amd#5328) makes the notice name the queue; without one, the notice keeps the gaia daemon status step and guesses nothing. - Answering a prompt restarts the quiet clock, and the stall check is a pure function tested for the time it re-arms with.
…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.
The second review showed the queue form of the stall notice was wrong both ways. amd#5328 sends its "granted" line under the same model_queue phase, so a hang after the grant read "still waiting for the model: Got the model after waiting 12s". And queue updates come every couple of seconds, so three minutes of silence after one means the updates stopped, not that the turn is still queued. Nothing sends these events to the TUI yet either. The notice now always keeps the gaia daemon status step. Queue updates, like any event, reset the quiet clock, so a turn that really is queued is never called stalled. The notice text is a pure helper; the tests drive real events instead of backdating the last one.
…ws it is waiting A request queued behind another for the model slot failed after 300 s with "Check gaia daemon logs", though a local call may run for an hour; a lease was reclaimed mid-generation after 900 s; a waiter whose client had gone still got the slot and held it for nobody; and the user saw nothing while queued. - Lease requests stream the queue: a "queued" line with place in line, holder and seconds waited, every 2 s, then the grant. No fixed ceiling: a wait lasts while the holder is alive. GAIA_MODEL_LEASE_WAIT_S is the explicit cap. A daemon silent for 30 s is reported as down. - Waits run on threads of their own, leave the queue when the requester disconnects or its turn stops, and a grant that never reached it is released. - Granted leases are renewed every 15 s; one not renewed for 60 s is reclaimed (4 h cap). Clients that do not renew keep the 900 s TTL. - An Agent UI turn leases at interactive priority, its waits appear on its stream as a live status line, and Stop ends them. Waits on this process's own per-model lock are reported and cancellable the same way. - Renew and release work only for the lease's holder, and errors never name another caller's lease id.
…t says so - The agent loop treats LeaseWaitCancelled as a cancelled turn on both the streaming and non-streaming paths, instead of logging "Unexpected error calling LLM" and writing an error answer into the history. - The lease heartbeat logs that the lease will lapse when it cannot read its credential, instead of dying with a bare traceback. - The holder test helper records its release time before releasing, so a fast grant can no longer read it before it is written (CI flake on Linux).
…es the slot Second review round on the queued-lease change, each with a failing test: - Background indexing a turn starts runs outside the turn's scope. It copied the turn's context, so the turn's normal end cancelled its later model leases (LeaseWaitCancelled on an idle slot) and its waits jumped the queue. - A renewal that lands after the lease is released is ignored instead of logging a false "lost the model-slot lease" error on every clean exit. - A lease carries its holder's call budget. LemonadeClient declares its request budget plus 15 minutes for a load. A renewing holder still holding it past that is wedged and loses the slot. Undeclared leases keep the old 900 s cap. - Background requests queued for 10 minutes rank as interactive, so a stream of turns cannot starve them. - A non-streaming Agent UI turn counts queue updates as progress, so a long wait for the model is not stopped as idle. - GAIA_MODEL_LEASE_WAIT_S also caps a wait on this process's own model lock. - Docs say which surfaces show the wait (Agent UI and CLI; not yet the TUI or sidecars).
The model_queue status reached only the Agent UI's stream. The gaia agent's /query routes, which the TUI reads, ran the turn outside any turn scope: its lease was background priority, /cancel did not end a wait for the model, and the stream went silent for the whole wait, so the TUI could not tell queued from broken (amd#5319). - The /query run thread runs as an interactive turn: wait events go out on the run's stream and /query/{run_id}/cancel ends the wait. - One event builder (broker_client.queue_status_event) for both streams. - The canonical translator keeps the `queue` object on a model_queue status. - Contract spec §4.4, the agent's SKILL.md and CHANGELOG describe the phase.
… 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 read timeout before the response headers means the daemon accepted the request, so it no longer counts as a stale address worth re-attaching to, which would re-queue the request at the back of the line.
3000efc to
1cfe64f
Compare
…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.
… when the agent reports one The TUI computed the relay's idle budget from its own shell, but the relay uses the daemon's environment. With the daemon at GAIA_AGENT_TOOL_TIMEOUT=600 and the TUI's shell unset, the TUI still cut in at 330 s. Its parser also disagreed with timeouts.py on whitespace, nan and hex. The queued-follow-up notice guessed "most likely waiting for the model" with nothing to go on, and fired seconds after the user answered a prompt. - The daemon reports its relay budget on /daemon/v1/status (agent_read_timeout_s, null for no limit, or agent_read_timeout_error), and the TUI waits on that. A daemon too old to report it falls back to this shell's setting, logged. - The fallback parser mirrors Python's float(). Both sides are checked against one table, tests/fixtures/daemon/agent_read_timeout_cases.json, generated from timeouts.py. - A status with phase "model_queue" (amd#5328) makes the notice name the queue; without one, the notice keeps the gaia daemon status step and guesses nothing. - Answering a prompt restarts the quiet clock, and the stall check is a pure function tested for the time it re-arms with.
The second review showed the queue form of the stall notice was wrong both ways. amd#5328 sends its "granted" line under the same model_queue phase, so a hang after the grant read "still waiting for the model: Got the model after waiting 12s". And queue updates come every couple of seconds, so three minutes of silence after one means the updates stopped, not that the turn is still queued. Nothing sends these events to the TUI yet either. The notice now always keeps the gaia daemon status step. Queue updates, like any event, reset the quiet clock, so a turn that really is queued is never called stalled. The notice text is a pure helper; the tests drive real events instead of backdating the last one.
|
Verdict: Approve with suggestions A chat turn queued behind another GAIA process now waits instead of failing after 5 minutes. While it waits, the Agent UI and the gaia and email Real-world evidenceN/A here: no evidence bundle was produced for this run. The PR description links a live run against a real daemon (queue stream, queue route, a requester leaving, the wait cap), but I have not checked that output myself. The Agent UI waiting line still has no screenshot, and the PR's own test plan leaves that item unchecked. Get one from the strix-halo lane or a manual run before release. This runner had no Python environment, so I could not run the tests either. This verdict rests on reading the code. 🔍 Technical detailsIssues found 🟢 A malformed NDJSON line skips the error contract ( 🟢 Every lease request starts its own thread, with no cap ( 🟢 Verified while reviewing
Strengths
|
…#5319) Before: on a shared machine, a TUI turn waiting for the model slot could fail with a bare "timeout awaiting response headers" before the daemon's relay sent its own explanation. The TUI used its own shell's timeout, not the daemon's, so raising `GAIA_AGENT_TOOL_TIMEOUT` on the daemon didn't help. A queued follow-up also told the user to "check `gaia daemon status`" after 180 s, even while it was still receiving updates or had just had a prompt answered. After: the TUI waits on the budget the daemon actually uses, so the relay's reason always reaches the user. The queued-follow-up notice appears only after 180 s of real silence and keeps the diagnostic step without guessing at a cause. Lands after v0.25.0. Reproduced by `TestRelayTimeoutReportReachesTheUserInsteadOfAHeaderTimeout`, `TestTheTUIUsesTheBudgetTheDaemonReports`, `TestQueuedSendStalledMsgIsQuietWhileTheTurnKeepsUpdating` and `TestAnsweringAPromptRestartsTheQuietClock`; all fail on main and pass here. ## Test plan - [x] `go vet ./...` clean; `go test -p 1 ./internal/client/ ./internal/daemon/ ./internal/event/ ./internal/ui/chat/ ./internal/ui/preflight/` passes - [x] `pytest tests/unit/test_agent_read_timeout_table.py`: `timeouts.py` matches the shared table, and `/daemon/v1/status` reports the budget (a number, `null` for no limit, or `agent_read_timeout_error`, without breaking status) - [x] `TestAgentReadTimeoutMatchesThePythonTable`: the Go fallback parser agrees with the same table (whitespace, `+`, underscores, `inf`, `nan`, hex rejected), capping only past Go's duration range - [x] The stall check is tested for the exact time it re-arms with, including after a prompt closes - [x] Live, real TUI against a fake daemon reporting a 600 s budget, with the TUI's shell unset, the relay holding 400 s and then sending its 502: this branch showed the relay's reason at 400 s; main cut in at 300 s with "timeout awaiting response headers". Earlier live runs: a queued follow-up still sending updates got no notice (main: "no response… check gaia daemon status" at 3:00). <details> <summary>🔍 Technical details</summary> - `/daemon/v1/status` gains `agent_read_timeout_s` (`null` = no limit) or `agent_read_timeout_error`; an unusable value fails the turn naming the setting and `gaia daemon restart`, since it lives in the daemon's environment. The TUI reads them in its status probe (`Instance.RelayBudget`). An explicit `SSEOptions.ReadTimeout` wins; a daemon that predates the field falls back to this shell's setting, and the fallback is logged. - `HeaderTimeout` defaults to the turn's read budget + 30 s, since the relay's httpx read timeout also covers waiting for the sidecar's headers. - `tests/fixtures/daemon/agent_read_timeout_cases.json` is generated from `timeouts.py`; Python and Go both test against it. - The notice never reads silence as a queue wait: queue updates (amd#5328's `model_queue` statuses, once a sidecar forwards them) come every few seconds and, like any event, reset the quiet clock. So the notice always keeps the `gaia daemon status` step. - The daemon change is one additive field in `app.py`; amd#5327 makes that route async, a trivial conflict. </details>
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 amd#5241 and amd#5275 (both edit `_chat_helpers.py`; different functions). Builds on the amd#4772 discussion without fixing amd#4772 itself: the title still uses the model it's given, but it can no longer load it. **Merging with amd#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 amd#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 amd#5337's non-streamed timeout test passed 8 times out of 8. That test was racy with amd#5336's stop check, and amd#5337 now fixes it. ## Test plan - [x] `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 - [x] `npx vitest run` in `src/gaia/apps/webui`: all pass, new `api.loadModel.test.ts` - [x] `python util/lint.py --black --isort --pylint --flake8` - [ ] Live: two chats on two models that both fit, and confirm neither is unloaded between turns <details> <summary>🔍 Technical details</summary> - `_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 amd#5328's `interactive_turn(cancel=...)`, so there only the `except LeaseWaitCancelled` clause above keeps it quiet. amd#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 (amd#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 amd#5338. - LLM-affecting? Error surfacing only; prompts and tools are unchanged. Categories to watch on the next RC: `rag_quality`, `gaia_core`. </details> --------- Co-authored-by: Kalin Ovtcharov <[email protected]>
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. <details> <summary>🔍 Technical details</summary> - `_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. - amd#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. amd#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. </details> ## 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. --------- Co-authored-by: Kalin Ovtcharov <[email protected]>
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.
…s status (amd#5327) When other GAIA processes queued for the model, the next `gaia` command could kill the daemon and every sidecar agent. Queued lease requests used the same worker pool as the daemon's status check. About 40 of them filled it, status missed the client's 1.5 s probe, and the client read that as a hung daemon and tree-killed it. Now status never waits on that pool. A daemon that answers slowly is re-probed and then reported busy, and is never killed for it. Reproduced by `tests/unit/test_daemon_status_under_load.py::test_status_answers_while_lease_waiters_fill_the_thread_pool`. It fails on main (status misses the probe with 40+ queued leases, and the holder's release waits for the pool) and passes here. The hung, reused-pid and exit-delay cases each have a test that failed before its fix. A live run against the real daemon app shows the same: main reports the daemon stale, and this branch reports it running ([output](amd#5327 (comment))). Independent review: a `code-reviewer` agent reviewed the diff. Its findings are fixed: the busy error is wrapped for model loads and for Lemonade auto-start, `gaia daemon status` has its own busy state and says when it is waiting, and the test waits for a full worker pool. A slow daemon is reported busy, not killed, and "busy" is bounded. Status waits on nothing else, so a daemon that has not answered it for 120 s across probes is hung. The next start replaces it, and other commands get an error naming `gaia daemon restart`. A daemon whose port refuses connections, answers as something else, or whose pid now belongs to another program is still replaced at once. The slot holder can also release under load: with 45 queued leases, a release took 8–20 s on main and is now immediate. Lands on its own, before or after amd#5328. Both make the broker's credential check async with an identical hunk in `broker_routes.py`, so they merge cleanly in either order. amd#5328 also moves lease waits off the shared pool entirely. ## Test plan - [x] `python -m pytest tests/unit/test_daemon_status_under_load.py tests/unit/test_lemonade_client_hold.py -q` - [x] `python -m pytest tests/unit/ -k "daemon or broker or lemonade_service" -q` - [x] `python util/lint.py --black --isort --flake8 --pylint --test-lanes` - [x] With a daemon running, hold the slot with a raw `POST /host/v1/models/lease`, queue about 40 more, then run `gaia daemon status`. It reports the daemon running and kills nothing. <details> <summary>🔍 Technical details</summary> - `/daemon/v1/status` and the shared `require_token` dependency are `async` now. FastAPI runs a sync dependency on the same anyio pool, so the route alone was not enough. The scheduler's `job_counts` runs on its own 4-thread limiter. - `instance.probe_state` returns `live`, `busy` (a `ReadTimeout` after the connection was accepted) or `gone`. `client._answers` gives `busy` a 10 s second probe, then raises `DaemonBusyError`. - `attach()` raises instead of returning `None` for a busy daemon. `attach_broker_env` turns that into `BrokerUnavailableError`, so a model load fails as a broker error instead of running unbrokered against the daemon's sidecars. - The busy spell is recorded per pid in `<host dir>/busy_since.json` and cleared on the first answer. `release_lemonade_client` and `register_lemonade_client` attach without the 10 s second probe. - The broker's own queue semantics (no fixed 300 s ceiling, waits that can be cancelled, lease renewal, waits on their own threads) are amd#5328. </details> --------- Co-authored-by: Kalin Ovtcharov <[email protected]>
…#5339) Before: uploading a few large documents indexed them all at once on the event loop's shared thread pool, the same pool the chat stream loop polls with, so open chats stalled while documents embedded. Cancel marked a document cancelled while its indexing ran on, and a stuck index had no limit. After: indexing has its own pools, two large documents at a time, and small files get two slots of their own so they never wait behind big PDFs. Cancel stops the work at the next page or embedding batch. A document that keeps making progress indexes to the end; one that makes no progress for 10 minutes stops with an error. Reproduced by `tests/unit/chat/ui/test_indexing_bounds.py` and `tests/unit/rag/test_indexing_stopped.py`. On main, six uploads index at once on the shared pool, Cancel leaves the work running, and nothing stops a stalled index. All pass here, including the review's cases: a long but moving PDF finishes, a stalled one stops between pages, a small file finishes while big ones hold the large pool, and a cancelled cached document keeps its cache. Related to amd#4744 (the agent's `index_document` tool timing out on big PDFs). This doesn't change that tool. It bounds the Agent UI's upload indexing, and adds the page heartbeat and stop that the tool could use too. **Merging with amd#5328:** whichever of the two lands second wraps `rag.index_document(...)` in `_index_document._do_index` with `lease_wait_listener(lambda _e: _step())`. That makes lease-queue updates (embedder and VLM waits) count as progress, so an upload waiting behind a long chat isn't stopped as "no progress". Add a test that a long lease queue with updates doesn't trip the limit. Agreed with amd#5328's author. ## Test plan - [x] `pytest tests/unit/chat/ui tests/unit/rag tests/unit/agents/tools tests/integration/test_files_router.py`: all pass - [x] `python util/lint.py --black --isort --pylint --flake8 --test-lanes` <details> <summary>🔍 Technical details</summary> - `_index_document` runs on `_INDEX_EXECUTOR` (2 workers), or `_INDEX_SMALL_EXECUTOR` (2) for files under 20 MB, never the default executor. - `RAGSDK.index_document(..., heartbeat=)` runs the callback once per PDF page through a thread-local. Raising `IndexingStopped` from it or from `progress_callback` leaves `index_document` as raised: no partial index, cache kept. The body moved to `_index_document`, and one source-inspection test follows it. - The no-progress clock starts when a worker picks the document up, so queued uploads wait without timing out. A job that stops making progress is failed after the limit, and its worker is freed at the job's next page or batch. - `GAIA_INDEX_TIMEOUT` is read at import, so a bad value stops start-up, the same as `GAIA_STREAM_TIMEOUT`. Documented in the Agent UI guide. - Known gaps: - A single page's VLM call has no stop point inside it; it's bounded by its own HTTP timeout. - After a cancel on Windows, the upload's temp file may stay in the temp dir until its worker lets go. - No separate "queued" document state: queued uploads show as indexing. - Not LLM-affecting. </details> --------- Co-authored-by: Kalin Ovtcharov <[email protected]>
…ancel reaches it (amd#5448) Before: an Agent UI upload waiting in line for the model slot (the embedder load, or a vision model call) got no page or batch done, so after `GAIA_INDEX_TIMEOUT` (10 min) it was stopped as "no progress", even though it was only queued behind a long chat. Cancel didn't reach it either: it waited for the slot, loaded the model, embedded a batch, and only then stopped. After: queue updates from the broker count as progress, and Cancel or the no-progress stop end the wait at once. A cancelled wait on a cached document keeps its cache. This is the amd#5339 × amd#5328 merge item, "whichever lands second wires `lease_wait_listener`". It didn't land with either PR. Reproduced by `tests/unit/chat/ui/test_indexing_bounds.py::test_waiting_in_line_for_the_embedder_counts_as_progress`, `::test_cancel_reaches_an_index_waiting_in_line_for_the_model` and `tests/unit/rag/test_indexing_stopped.py::test_a_cancelled_wait_for_the_model_keeps_the_cache_too`; all three fail on main and pass here. ## Test plan - [x] `pytest tests/unit/chat/ui tests/unit/rag tests/unit/agents/tools tests/unit/test_broker_wiring.py`: 2655 passed - [x] `python util/lint.py --black --isort --pylint --flake8 --imports --test-lanes` <details> <summary>🔍 Technical details</summary> - `_index_document._do_index` runs `rag.index_document` inside `lease_wait_listener(_queue_update)` and `lease_cancel_scope(stop)`. Both are contextvars set on the indexing thread, which is where the embedder's `load_model` and the VLM calls take their leases. The listener only notes the time, since it runs on the waiting thread and must not block or raise. - `LeaseWaitCancelled` from that scope becomes `IndexingStopped`. In `rag/sdk.py`, both of `index_document`'s broad handlers re-raise it, as they do `IndexingStopped`. Without that, the cache-hit path took it for a corrupt cache. - Not LLM-affecting. </details> --------- Co-authored-by: Kalin Ovtcharov <[email protected]>
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-revieweragent 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 aretest_model_lease_waits_out_a_busy_holder_instead_of_failing(504 on main) andtest_a_waiter_that_disconnects_is_never_granted_the_slot(the dead waiter stays queued on main).Builds alongside #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. #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 #5336: whichever lands second makes two additions.
except LeaseWaitCancelledin fix(ui): never take a model from under another chat or app #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; #5336's does if that does.
For the
exceptclause, the guard istest_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 #5336's wrapper already ignores errors once Stop is set.Merge order with #5339 (Agent UI indexing), same rule: whichever lands second wraps
rag.index_document(...)in_index_document._do_indexwithlease_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 #5339's 600 s no-progress limit. A test covers an index that waits on a lease longer than that limit.Merge order with #5359 (idle exit for non-default daemons), same rule. It stamps
_last_activityinModelSlotBroker, which conflicts with this PR inbroker.pyin two places, each resolved by keeping both sides. In_grant_locked, keep_renewed_atand_last_activity. In_reclaim_if_stale_locked, take this PR's version and addself._last_activity = self._now()beforenotify_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_qualityand thegaia_*turn timings.Live run against the real daemon app (queue stream, queue route, a requester leaving, the wait cap): output.
Test plan
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 -qpython util/lint.py --black --isort --flake8 --pylint --test-lanesPOST /host/v1/models/lease, then send an Agent UI turn. It shows the waiting line and updates it every 2 s. Press Stop, andGET /host/v1/models/queueshows nothing waiting.GAIA_MODEL_LEASE_WAIT_S=5, the same turn fails after 5 s with where it stood in line and who held the model.🔍 Technical details
POST /host/v1/models/leasewith"stream": truereturns NDJSON:queuedlines, then onegrantedorerrorline. Withoutstream, 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 norenew_interval_s."renewable": trueleases are kept byPOST …/lease/{id}/reneweveryheartbeat_ttl/4. They are reclaimed after 60 s without a renewal, with a 4 h cap. Non-renewing leases keep the 900 s TTL.broker_routes._Wait), never the shared anyio pool. A disconnect or abandon sets the broker'scanceland callswake(). A grant that races the abandon is released exactly once, under_Wait._guard. A streamed grant counts as delivered only after its send returns.broker_client.interactive_turnsets 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 bothTurnCanceland the SSE handler's Stop flag.LeaseNotHeldErrorno longer echoes the active lease id.GET /host/v1/models/queuestrips it too.statusevent withphase: "model_queue"and aqueueobject (eventqueued/granted, position, holder, seconds waited). It goes on the Agent UI's SSE stream and on the/querystreams of the gaia agent (which the TUI reads; fix(tui): a turn waiting for the model is not reported as broken #5319 renders it) and the email agent. Both canonical translators keepqueue, and the contract is inagent-ui-query-sse-contract.md§4.4. Stop in the Agent UI and/query/{run_id}/cancelon 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.lease_wait_limit(seconds); the chat title gets it from whichever of this and fix(ui): never take a model from under another chat or app #5336 lands second (above). Background work a turn starts (indexing) runs outside the turn's scope. The lease route refuses NaN or infinitetimeoutandmax_hold_s.