Skip to content

fix(daemon): a queued model request waits instead of failing, and shows it is waiting - #5328

Merged
kovtcharov-amd merged 10 commits into
amd:mainfrom
kovtcharov:claude/broker-queue-semantics
Oct 19, 2026
Merged

kovtcharov-amd merged 10 commits into
amd:mainfrom
kovtcharov:claude/broker-queue-semantics

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

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 #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.

This PR's author does both if this lands second; #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 #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_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 #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_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.

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 -q
  • 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.
  • 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.
🔍 Technical details
  • 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; fix(tui): a turn waiting for the model is not reported as broken #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 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 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.

@github-actions github-actions Bot added documentation Documentation changes llm LLM backend changes tests Test changes performance Performance-critical changes daemon Daemon supervisor / sidecar control plane labels Oct 18, 2026
@github-actions

Copy link
Copy Markdown
Contributor

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.

  • Show it working on a real daemon before merge. This changes what Agent UI users see and adds two HTTP routes, but the PR has no captured run. The two manual test-plan items are the right ones: holding the slot with a raw lease while an Agent UI turn waits, and the GAIA_MODEL_LEASE_WAIT_S=5 failure. Paste their output (the queue route's response and the NDJSON lines), plus a screenshot of the waiting line if you can get one.
  • Two small hardening points are in the details below. Neither blocks.

Real-world evidence

N/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

  • No real-world evidence for the HTTP and Agent UI surfaces. The PR adds POST /host/v1/models/lease/{id}/renew and GET /host/v1/models/queue, changes POST …/lease to stream NDJSON, and adds the model_queue SSE status. The tests in tests/unit/test_daemon_broker_queue.py do run a real uvicorn daemon, which is strong. Under the rubric, though, the PR still needs the real request and response shown in the description or a linked comment. A screenshot of the UI line can wait for the strix-halo lane.

🟢 Minor

  • The heartbeat thread can die without the "lost the lease" log (src/gaia/daemon/broker_client.py, _Heartbeat._run). renew_lease() calls _credential(), which raises BrokerUnavailableError when the token file is missing or unreadable. That exception isn't caught, so the thread exits with a bare traceback. Sixty seconds later the lease is reclaimed under a holder that is still generating, and the clear "Another process may now load a model over this one's request" error never fires. Catch it next to the 4xx case:
        def _run(self, lease_id: str, model: Optional[str], interval: float) -> None:
            while not self._stop.wait(interval):
                try:
                    status = renew_lease(lease_id)
                except BrokerUnavailableError as e:
                    logger.error(
                        "broker client: cannot renew the model-slot lease for '%s' "
                        "(%s); it lapses after the broker's heartbeat TTL.",
                        model,
                        e,
                    )
                    return
    
    (Keep the existing if status is not None and 400 <= status < 500: block after it.)
  • Pressing Stop mid-wait is logged as an LLM error. When LeaseWaitCancelled is raised inside the agent's LLM call, it lands in the generic except Exception in agent.py (~line 9621). That logs "Unexpected error calling LLM" at error level and builds an error answer for a turn the user stopped on purpose. Consider re-raising it there, or treating it like the existing cancelled_by_console path, so stopped turns don't show up as LLM failures in logs or history.

Strengths

  • The abandon/grant race in broker_routes._Wait is handled carefully: _guard makes exactly one side release a late grant, and a streamed grant counts as delivered only after its send returns. The tests cover this, plus the client-side case where a cancel arrives with the grant.
  • Backward compatibility holds in both directions. A request without stream keeps the old 300 s JSON response and non-renewing 900 s TTL. A new client facing an old daemon checks the content-type, and starts no heartbeat when there is no renew_interval_s.
  • Each test reproduces a user-facing symptom on main (the 504 while the holder is alive, a dead waiter being granted the slot, a lease reclaimed mid-generation) rather than just exercising internals.

@kovtcharov

Copy link
Copy Markdown
Contributor Author

Addressed the review, and fixed the red Linux unit check.

  • The Linux unit failure: a race in the test, not in the product. The holder helper recorded its release time after leaving model_lease, so a fast grant could read it before it was written (KeyError: 'at'). The helper now records it before the release. I ran the file three times with no failures.
  • The heartbeat thread dying silently: fixed. When it can't read its credential, it now logs that the lease will lapse after the heartbeat TTL, then stops. A new test pins it.
  • Stop logged as an LLM error: fixed. The agent loop treats LeaseWaitCancelled as a cancelled turn on both the streaming and non-streaming paths, so there is no "Unexpected error calling LLM" and no error answer in the history. A new test covers both paths.

Live run: the real daemon app on :18302 under a throwaway GAIA_HOME, driven with curl and model_lease.

Queue stream, queue route, a requester that leaves, and the wait cap (output)
== 1. hold the slot with a raw lease
{"lease_id":"<redacted>","model":"holder-model","priority":"background","holder":"host","waited":false,"renewable":false}

== 2. a streaming request queues behind it; the slot is released after ~5 s
{"event": "queued", "position": 1, "queue_length": 1, "model": "waiter-model", "waited_s": 0.0, "holder": "host", "holder_model": "holder-model", "held_for_s": 0.69, ...}
{"event": "queued", "position": 1, "queue_length": 1, "model": "waiter-model", "waited_s": 2.02, ...}
{"event": "queued", "position": 1, "queue_length": 1, "model": "waiter-model", "waited_s": 4.02, ...}
{"event": "granted", "lease_id": "<redacted>", "model": "waiter-model", "waited": true, "switching": true, "renewable": true, "heartbeat_ttl_s": 60.0, "renew_interval_s": 15.0}

== 3. the queue route while it is held (lease ids stripped)
{"active":{"model":"waiter-model","holder":"host","priority":"background","held_for_s":0.36,"renewable":true,"expires_in_s":59.64},"loaded_model":"waiter-model","waiting":[]}

== 4. a requester that leaves (curl gives up after 3 s) drops out of the queue
-- while it waits:
{"active":{...},"waiting":[{"model":"leaver","holder":"host","priority":"background","waited_s":1.08}]}
-- after it left:
{"active":{...},"waiting":[]}

== 5. GAIA_MODEL_LEASE_WAIT_S=5 through model_lease, the API every caller uses
on_wait: Waiting for the model — 'host' is using it for 'waiter-model'
after 5.0s: no model-slot lease for 'turn-model': model-slot lease for 'turn-model' (holder 'host', priority background) was not granted within its 5s wait limit. The slot is held by 'host' running 'waiter-model' (for 14s); this request was #1 of 1 waiting. The model is busy, not broken: wait longer, or retry when that request ends. To wait longer, raise GAIA_MODEL_LEASE_WAIT_S, or unset it to wait for as long as the model is in use.

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 tests/unit/chat/ui/test_model_queue_status.py.

kovtcharov added a commit to kovtcharov/gaia that referenced this pull request Oct 18, 2026
… 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.
kovtcharov added a commit to kovtcharov/gaia that referenced this pull request Oct 18, 2026
…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.
@github-actions github-actions Bot added the agent::email Email agent changes label Oct 18, 2026
kovtcharov added a commit to kovtcharov/gaia that referenced this pull request Oct 18, 2026
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.
@kovtcharov-amd
kovtcharov-amd force-pushed the claude/broker-queue-semantics branch from 3000efc to 1cfe64f Compare October 19, 2026 06:23
kovtcharov-amd pushed a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
…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.
kovtcharov-amd pushed a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
… 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.
kovtcharov-amd pushed a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
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.
@kovtcharov-amd kovtcharov-amd added the ready_for_ci Run CI workflows on draft PR without requesting review label Oct 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

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 /query streams show where it stands in line. Stop, cancel and disconnect take it out of the queue, and a lease the holder keeps renewing is no longer taken back partway through a generation. I found no blocking issues: the cancel-versus-grant races, the holder-only renew and release, and the fallback for older daemons all look right. There is one small robustness gap: a corrupt line on the queue stream surfaces as a raw parse error rather than the usual "check the daemon" message.

Real-world evidence

N/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 details

Issues found

🟢 A malformed NDJSON line skips the error contract (src/gaia/daemon/broker_client.py, json.loads(raw) inside acquire_lease's stream loop). The docstring promises BrokerUnavailableError on any transport failure, but a garbled line raises json.JSONDecodeError. That escapes _acquire_with_reattach and reaches the agent loop's generic except Exception as "Unexpected error during streaming", with no mention of the daemon.

                try:
                    event = json.loads(raw)
                except ValueError as e:
                    raise BrokerUnavailableError(
                        f"the model-slot broker at {url} sent an unreadable queue "
                        f"update for '{model}': {raw[:200]!r}. Check `gaia daemon logs`."
                    ) from e

🟢 Every lease request starts its own thread, with no cap (broker_routes._Wait). Taking waits off the shared worker pool is right, but every queued request now holds a daemon thread for as long as it waits, and nothing limits how many. The callers are authenticated, so this is not a security issue. Still, one buggy sidecar that retries in a loop could pile up hundreds of threads. A small cap per caller (rejected with 429) or a log line when waiting threads pass N would make that visible.

🟢 _QUEUE_FIELDS is copied into the email translator (gaia_agent_email/sse_translation.py). It already imports from gaia.daemon.broker_client, so the tuple could live there once, next to queue_status_event, which builds the shape. Then the two translators can't drift when a field is added.

Verified while reviewing

  • In the agent loop, except LeaseWaitCancelled comes after the connection-error handler and before the catch-all, on both the streaming and non-streaming paths. It sets cancelled_by_console, which the loop already handles.
  • DEFAULT_RETRY_DEADLINE (120 s) and the 15 s / 60 s renew numbers in cli.mdx match the code.
  • Docs agree with each other: the SSE contract §4.4, the gaia npm SKILL.md, the email npm SPEC.md and both CHANGELOGs describe the same queue shape.
  • _TurnIdleClock.progressed takes a max, so the queue_seen value of 0.0 before the first update can't move the idle clock backwards.

Strengths

  • Cancel-versus-grant is handled carefully on both sides. _Wait._guard makes exactly one path release a lease granted just as the requester left, and the client releases a granted line that arrives after its own cancel.
  • The client detects a dead daemon by setting a timeout on the socket for the response body only, so a slow old daemon still gets its full 300 s before sending headers.
  • Turn scope travels in context vars, and detached_from_turn covers background indexing. Work a turn starts in the background doesn't inherit the turn's priority or its Stop, and its waits don't appear on the turn's stream.

kovtcharov-amd pushed a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
…#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>
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
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]>
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
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.
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
…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]>
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
…#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]>
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 19, 2026
Merged via the queue into amd:main with commit f004bae Oct 19, 2026
120 of 123 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claude/broker-queue-semantics branch October 19, 2026 17:01
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 21, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent::email Email agent changes agents daemon Daemon supervisor / sidecar control plane documentation Documentation changes llm LLM backend changes performance Performance-critical changes ready_for_ci Run CI workflows on draft PR without requesting review tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants