Skip to content

fix(tui): a turn waiting for the model is not reported as broken - #5319

Merged
kovtcharov-amd merged 7 commits into
amd:mainfrom
kovtcharov:claude/rel-tui-model-wait
Oct 19, 2026
Merged

kovtcharov-amd merged 7 commits into
amd:mainfrom
kovtcharov:claude/rel-tui-model-wait

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

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

  • go vet ./... clean; go test -p 1 ./internal/client/ ./internal/daemon/ ./internal/event/ ./internal/ui/chat/ ./internal/ui/preflight/ passes
  • 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)
  • TestAgentReadTimeoutMatchesThePythonTable: the Go fallback parser agrees with the same table (whitespace, +, underscores, inf, nan, hex rejected), capping only past Go's duration range
  • The stall check is tested for the exact time it re-arms with, including after a prompt closes
  • 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).
🔍 Technical details
  • /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 (fix(daemon): a queued model request waits instead of failing, and shows it is waiting #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; fix(daemon): never kill a live daemon because queued leases slowed its status #5327 makes that route async, a trivial conflict.

@github-actions github-actions Bot added the tui Go terminal UI (gaia-tui) label Oct 18, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

On a busy machine, a TUI turn waiting for the model will now show the daemon's reason for the wait instead of a bare header timeout. A queued follow-up that is still receiving updates is no longer called stalled. Both fixes are correct. The TUI's reading of the shared timeout setting matches the daemon's for every realistic value, and the new tests cover the race, the env setting, and the prompt-pending case.

Nothing blocks merge. One small hardening is suggested below: an absurdly large timeout value can wrap around and quietly shrink to the 300 s default.

Real-world evidence

N/A: there is no evidence bundle for this PR, and the change is a TUI timing fix with no CLI, REST, or Agent UI surface the evidence stage drives. The verdict rests on static review plus the package tests, which I re-ran on the PR head (go test -p 1 ./internal/client/ ./internal/ui/chat/, both ok). The real contended-model scenario was not exercised here.

🔍 Technical details

Issues

🟢 Huge GAIA_AGENT_TOOL_TIMEOUT silently wraps to the default (tui/internal/client/sse.go:55). time.Duration(secs*float64(time.Second)) overflows int64 above roughly 9.2e9 s. Go's out-of-range float→int conversion is implementation-defined (on amd64 it comes out negative), so max(...) returns 300 s. The relay meanwhile honours the large value. That is a quiet shortening, which the fail-loudly rule forbids, though no one will realistically set it. Clamping keeps it honest:

	d := time.Duration(math.Min(secs*float64(time.Second), float64(100*365*24*time.Hour)))
	return max(defaultReadTimeout, d+agentToolTimeoutGrace), nil

🟢 Parity note, no change needed. timeouts.py accepts nan (it returns 300 s) and surrounding whitespace, and Go rejects both. Go's handling is the stricter, louder one, so the TUI errors where the relay would quietly default. That's fine, but TestAgentReadTimeoutFollowsTheRelaySetting's claim that it "matches timeouts.py" holds only for well-formed input.

Strengths

  • Separating HeaderTimeout from the idle-read watchdog is the right fix. The relay's 502 now always arrives first, and TestRelayTimeoutReportReachesTheUserInsteadOfAHeaderTimeout reproduces the race deterministically with millisecond budgets.
  • A bad env value is held as configErr and returned from every Send, so the turn fails loudly with a remedy instead of falling back to a default.
  • The stall watchdog re-arms for exactly the remaining quiet time (queuedSendTimeout - quiet) and backs off while a prompt is pending, so it costs no timers or polling.

@kovtcharov

Copy link
Copy Markdown
Contributor Author

Live check passed: both fixes behave as described in the real TUI, and main shows the old behaviour side by side.

How it ran: the real TUI binary (one built from main, one from this branch merged with #5318) drove the installed-binary flagship over the daemon transport, with isolated HOME, GAIA_HOME, GAIA_DAEMON_HOME, GAIA_TUI_HOME and GAIA_MEMORY_DB. A fake daemon with its own instance.json played the relay, so nothing touched the shared daemon or Lemonade.

  • Header wait (the relay holds headers 310 s, then sends its own 502): this branch waited and showed the relay's reason at 310 s, the daemon relay refused the 'gaia' query (HTTP 502: sidecar for agent 'gaia' … did not answer (ReadTimeout: the model slot was still busy) … re-ensure it … and retry.). main cut in at about 300 s with net/http: timeout awaiting response headers.
  • Queued follow-up still sending updates (a status every 20 s for 200 s): no notice on this branch through the whole turn. main said at 3:00: the queued follow-up has been running for over 3m0s with no response … check gaia daemon status.
  • Queued follow-up truly silent for 190 s: this branch at 3:00: the queued follow-up has had no update for 3m0s. It is most likely waiting its turn for the model while another chat or app uses it. main kept the daemon wording.

Also pushed since the review: a huge GAIA_AGENT_TOOL_TIMEOUT now clamps to a century, like inf, instead of wrapping to 300 s.

🔍 Technical details
  • In the fake the follow-up queued because the peer reports contract 2.14, below mid-run follow-ups (2.15), the same path a released sidecar of that version takes.
  • The 310 s hold stands in for a sidecar that answers headers only after it gets the model slot. The real relay times out header waits at agent_read_timeout() (300 s default) and returns its 502. The TUI's header timeout is now that budget + 30 s, so the relay's reason arrives first.
  • Screenshots (SVG from the control API) were captured for each case on both builds.

kovtcharov added a commit to kovtcharov/gaia that referenced this pull request Oct 18, 2026
@github-actions github-actions Bot added tests Test changes daemon Daemon supervisor / sidecar control plane labels Oct 18, 2026
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Review follow-up: the TUI now waits on the budget the daemon reports, so a daemon at GAIA_AGENT_TOOL_TIMEOUT=600 no longer gets cut off at 330 s by a TUI whose shell doesn't set it.

  • /daemon/v1/status reports agent_read_timeout_s (or agent_read_timeout_error), and the TUI uses it; only a daemon that predates the field falls back to the shell, and that is logged. Live: daemon at 600 s, relay holding 400 s, TUI shell unset. This branch showed the relay's reason at 400 s; main cut in at 300 s.
  • The parser mirrors Python's float(); Go and Python both test against tests/fixtures/daemon/agent_read_timeout_cases.json, generated from timeouts.py (whitespace, nan, hex, underscores, overflow)
  • The notice uses fix(daemon): a queued model request waits instead of failing, and shows it is waiting #5328's phase: "model_queue" status when the agent sends one; without it, it keeps the gaia daemon status step instead of guessing
  • Answering a prompt restarts the quiet clock; the stall check is tested for the exact re-arm time
  • Nits: the comment at model.go:69; the relay-timeout test now holds for the daemon's advertised budget, the way the relay's httpx read timeout does

Two things this PR doesn't do:

  • It doesn't run the Python relay inside the Go tests. The shared table and the live run cover the cross-language contract.
  • Forwarding model_queue statuses from the sidecar to the TUI is the sidecar's change, not this PR's.

@kovtcharov

Copy link
Copy Markdown
Contributor Author

Second review round:

  • An unusable GAIA_AGENT_TOOL_TIMEOUT on the daemon now fails the turn naming the setting and gaia daemon restart, since the value lives in the daemon's environment.
  • Agreed: nothing sends phase: "model_queue" on a sidecar's stream yet (fix(daemon): a queued model request waits instead of failing, and shows it is waiting #5328 emits it on the Agent UI stream only). The description now says the TUI notice always takes the "no update… check gaia daemon status" form today; the queue form is ready for when the sidecar forwards these events.

kovtcharov added a commit to kovtcharov/gaia that referenced this pull request Oct 18, 2026
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.
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Third review round: agreed on all three points. I've removed the queue wording rather than patching it.

  • Nothing forwards model_queue to the TUI yet, and the description no longer claims it.
  • fix(daemon): a queued model request waits instead of failing, and shows it is waiting #5328's "granted" line uses the same phase, and queue updates come every ~2 s. So 180 s of silence after one can only mean the updates stopped, never "still waiting". The notice now always keeps the gaia daemon status step, and queue updates simply reset the quiet clock like any event.
  • The tests drive real events instead of backdating the last one. One checks that a queue update keeps a follow-up from being called stalled; another that silence after "Got the model…" gets the diagnostic notice.

@kovtcharov

Copy link
Copy Markdown
Contributor Author

Round-3 nit: the queuedStallNotice comment no longer claims queue updates reach the TUI. It now says none do yet, and that once a sidecar forwards them they will reset the quiet clock like any event.

On a shared machine a turn can wait minutes for the model slot. The TUI cut that wait short with a bare "timeout awaiting response headers", and a queued follow-up told the user to check `gaia daemon status` after 180 s even while it was still receiving updates.

- The relay waits the read budget for the sidecar to start answering, then reports why it did not. The TUI's header timeout is now that budget plus 30 s, separate from the idle-read timeout, so the relay's reason reaches the user.
- The read budget follows GAIA_AGENT_TOOL_TIMEOUT the way src/gaia/daemon/timeouts.py does, so the TUI and the relay give up together; an invalid value fails every send with the setting named.
- The queued follow-up notice fires only after 180 s with no event at all, waits while a prompt is open, and names the likely cause, a wait for the model, instead of the daemon.
… 300 s

A value past ~9e9 s overflowed the duration conversion and came out as the 300 s default, quietly shorter than what the relay honours. It now clamps to a century, the same as "inf".
… 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.
…daemon

The setting lives in the daemon's environment, so repeating the daemon's own "unset it" advice left out the step that makes the fix take effect: gaia daemon restart.
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 pushed a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
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.
@kovtcharov-amd
kovtcharov-amd force-pushed the claude/rel-tui-model-wait branch from f91cf39 to 5e305e5 Compare October 19, 2026 06:28
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 19, 2026
Merged via the queue into amd:main with commit 915d3a9 Oct 19, 2026
58 of 61 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claude/rel-tui-model-wait branch October 19, 2026 08:28
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
…ws it is waiting (amd#5328)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

daemon Daemon supervisor / sidecar control plane tests Test changes tui Go terminal UI (gaia-tui)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants