Repository navigation
fix(daemon): never kill a live daemon because queued leases slowed its status - #5327
Conversation
|
Verdict: Request changes (one small fix) This stops a What to fix before merge:
Real-world evidenceN/A: no evidence bundle was produced for this run. The verdict rests on static review and the PR's unit tests. The new 🔍 Technical details🟡 (Import All other 🟡 Real-world evidence for the CLI surface 🟢 Strengths
|
|
Addressed both points from the review.
Live run: the real daemon app ( main: status misses the probe, and the live daemon is reported stale. This branch, same load: This branch, a daemon that accepts connections and never answers. The process was still alive afterwards. I did not run |
|
🟡 The new 120-second "hung" timer can still kill a healthy daemon that is only busy. It counts from the first time any Fix: also record when each unanswered probe happened, and start a new spell when the last one is older than a short gap (say 2× the probe timeout). Add a test that writes an old marker and checks that a single slow probe raises a busy error, not a hung one. 🔍 Technical details
Sequence: run One way to fix it: store |
…s status Queued model-lease requests parked worker threads from the same pool the sync /daemon/v1/status route and its token check ran on. About 40 waiters filled it, status missed the client's 1.5 s probe, and the next gaia command took the silence for a hung daemon and tree-killed it along with every sidecar. - Status and the client-token check are async, so they never wait for that pool; the scheduler's job count runs on a small limiter of its own. - The probe now tells "busy" (connected, no answer yet) from "gone" (nothing listening, or not this daemon). A busy daemon gets a 10 s second probe and is then reported with DaemonBusyError; it is never killed. Only a live pid whose port is gone is still reclaimed. - attach() raises instead of returning None for a busy daemon, so a model load fails loudly as a broker error rather than running unbrokered against it. - gaia daemon status shows a busy daemon as running but not answering.
…tatus says it is waiting - _post_start turns DaemonBusyError into LemonadeStartError, the one error LemonadeManager.ensure_ready handles, so the user gets its message instead of a traceback. - gaia daemon status prints "slow to answer, waiting up to 10s…" before the longer second probe, so it does not look hung.
…n is bounded Second review round, each with a failing test: - The broker's credential check is async, so a holder's release no longer queues for the worker pool that lease waits fill. With 45 waiters it took 8-20 s before, and up to 300 s at defaults. - "Busy" is bounded. Status waits on nothing else, so a daemon that has not answered it for 120 s across probes is hung: start_or_attach replaces it, and other callers get DaemonHungError naming `gaia daemon restart`. - A registered pid now owned by another program reads as gone, not busy. - Registering and releasing a Lemonade client skip the 10 s patient re-probe, so an exiting app does not wait on a busy daemon.
It accepted any DaemonBusyError whose message mentioned "hung", and the busy
message does too ("treated as hung"). It now requires DaemonHungError.
… one hung A busy marker left from a spell that ended with no command checking in kept its old start time, so the daemon's next slow moment, even hours later, read as hours of silence and got it replaced with its sidecars. Each unanswered probe is now recorded, and one more than a minute after the last starts a new spell.
2066f1a to
0d6749c
Compare
|
Verdict: Approve with suggestions Before this PR, a busy daemon could get killed by mistake. When about 40 processes were queued for the model, its status check stopped answering, and the next Two small follow-ups, neither blocking:
Real-world evidenceNo evidence bundle was produced for this run. The PR links a live run instead: the real daemon app with one lease held and 45 queued, plus the real On main, the same load makes the live daemon read as dead: On this branch, under the same load: On this branch, with a daemon that accepts connections but never answers (the process was still alive afterwards): The author did not run a model load ( 🔍 Technical detailsIssues 🟢 Busy marker leaks between tests ( This also needs 🟢 The sidecar log lookup waits out a busy daemon ( 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>
# Conflicts: # src/gaia/daemon/client.py
…s the patient probe Each status-under-load test now gets its own daemon home, so a busy marker one test leaves can't read as two minutes of silence in another. The sidecar log lookup is best-effort, so it no longer waits out a busy daemon for 10 s.
…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]>
When other GAIA processes queued for the model, the next
gaiacommand 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).Independent review: a
code-revieweragent reviewed the diff. Its findings are fixed: the busy error is wrapped for model loads and for Lemonade auto-start,gaia daemon statushas 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 #5328. Both make the broker's credential check async with an identical hunk in
broker_routes.py, so they merge cleanly in either order. #5328 also moves lease waits off the shared pool entirely.Test plan
python -m pytest tests/unit/test_daemon_status_under_load.py tests/unit/test_lemonade_client_hold.py -qpython -m pytest tests/unit/ -k "daemon or broker or lemonade_service" -qpython util/lint.py --black --isort --flake8 --pylint --test-lanesPOST /host/v1/models/lease, queue about 40 more, then rungaia daemon status. It reports the daemon running and kills nothing.🔍 Technical details
/daemon/v1/statusand the sharedrequire_tokendependency areasyncnow. FastAPI runs a sync dependency on the same anyio pool, so the route alone was not enough. The scheduler'sjob_countsruns on its own 4-thread limiter.instance.probe_statereturnslive,busy(aReadTimeoutafter the connection was accepted) orgone.client._answersgivesbusya 10 s second probe, then raisesDaemonBusyError.attach()raises instead of returningNonefor a busy daemon.attach_broker_envturns that intoBrokerUnavailableError, so a model load fails as a broker error instead of running unbrokered against the daemon's sidecars.<host dir>/busy_since.jsonand cleared on the first answer.release_lemonade_clientandregister_lemonade_clientattach without the 10 s second probe.