Repository navigation
fix(daemon): a daemon for a scratch home exits once nothing has used it for two hours - #5359
Conversation
|
Verdict: Approve with suggestions Daemons started for a scratch Two small things are worth a look:
Real-world evidenceN/A: no evidence bundle was produced for this run. The verdict rests on static review plus the author's own real-daemon checks in the PR description (scratch home with a 1-minute limit exited at 60 s; with a registered client it stayed up and exited 60 s after the client ended). I couldn't run the unit tests on this runner because pytest isn't installed. 🔍 Technical detailsIssues 🟢 An exception from the idle probe kills the watch thread (src/gaia/daemon/lifetime.py:178) (This logs loudly rather than swallowing, and it only delays an idle exit. It never substitutes a different outcome.) 🟢 Any pending job pins the daemon, however far off (src/gaia/daemon/server.py:364) 🟢 The server-side composition is untested (src/gaia/daemon/server.py:358-364) Strengths
|
…it for two hours A daemon started for a temporary GAIA_HOME (an eval, a demo, a test drive) stayed up for good once its users were gone, as long as the folder still existed. A cleanup found such daemons running up to 43 hours old. Outside ~/.gaia, the daemon now shuts down gracefully after 120 minutes with no connected client, no busy sidecar and no pending scheduled job; the next GAIA command starts a fresh one. The daemon for ~/.gaia never idles out. GAIA_DAEMON_IDLE_EXIT_MINUTES changes the limit, 0 turns it off, and a bad value is a startup error.
… alive A process waiting on the daemon's model-slot broker holds no client lease, so an eval home's daemon could idle out under it. The idle measure moves into lifetime.DaemonIdle: a held or queued lease counts as use, and the idle clock restarts when the lease ends.
… leases count too The idle check sampled the broker every 5 s, so a burst of leases shorter than that, from a process with no registered client, was never seen. ModelSlotBroker now stamps the time a lease is granted, released or reclaimed and reports last_activity_s_ago in snapshot(); DaemonIdle takes the idle time from it directly.
If the idle probe threw (for example the scheduler database stayed locked), the lifetime watch thread died, so a daemon also stopped noticing that its home or instance.json was gone. The failure is now logged and retried. The default-home comparison now builds on default_gaia_home(), which the GAIA_HOME ratchet test requires.
7facefb to
4178cb4
Compare
Resolves conflicts with amd#5336, amd#5348 and amd#5359, and makes the additions this PR owes as the second to land: - _preflight_load keeps amd#5336's re-raise of InsufficientMemoryError and ModelInUseError, and adds `except LeaseWaitCancelled` ahead of its catch-all, so a stopped queued wait is not reported as a failed load. - The chat title's lease runs under lease_wait_limit(30), so a title gives up instead of holding a worker thread behind a long queue. - Background indexing keeps amd#5348's embedder wait callback inside detached_from_turn. - broker.py keeps both _renewed_at and amd#5359's _last_activity; a reclaim stamps _last_activity. Review follow-ups: an unreadable queue-stream line is a BrokerUnavailableError naming the daemon instead of a raw parse error, and a test pins the email translator's copy of _QUEUE_FIELDS to the core one.
…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]>
A GAIA daemon started for a temporary home (an eval, a demo, a test drive) kept running forever once its users were gone, as long as the folder still existed. A cleanup on one dev machine found 15 of them running at once, up to 43 hours old, along with the agent sidecars some still supervised. Now a daemon for any home other than
~/.gaiashuts itself down after two hours with no connected client, no busy sidecar, no model-slot lease held or queued, and no pending scheduled job, and the next GAIA command starts a fresh one. The everyday~/.gaiadaemon is unaffected.This completes #5294, which made a daemon exit when its home folder is deleted.
Test plan
pytest tests/unit/test_daemon_lifetime.py(45 passed) and every daemon and broker test (705 passed)python util/lint.py --black --isortGAIA_HOME,GAIA_DAEMON_IDLE_EXIT_MINUTES=1, no client: logged "nothing has used it for 1 minutes" and exited 60 s after start~/.gaiadaemon never idles out: pinned bytest_the_default_home_never_idles_out, andis_default_homebytest_the_machine_home_is_the_default🔍 Technical details
lifetime.exit_reasongains an idle reason that applies only whenpaths.host_dir()isn't~/.gaia/host.LifetimeWatchtakesidleandidle_limit.lifetime.DaemonIdle. A held or queuedModelSlotBrokerlease counts as use. The broker now reportslast_activity_s_ago(stamped on grant, release and reclaim), so even leases shorter than the 5 s check restart the clock. Underneath it isLemonadeClients.snapshot()["idle_seconds"]:Nonewhile any client lease is held, and reset by every sweep while a sidecar connection runs. Once that passes the limit,clock.job_counts()["pending"]is checked too, so the scheduler DB is read only near the limit.GAIA_DAEMON_IDLE_EXIT_MINUTES: unset means 120,0means off, and anything that isn't a non-negative integer raisesDaemonStartErrorat startup.docs/reference/cli.mdx.