Skip to content

fix(daemon): a daemon for a scratch home exits once nothing has used it for two hours - #5359

Merged
kovtcharov-amd merged 4 commits into
amd:mainfrom
kovtcharov:kalin/daemon-idle-exit
Oct 19, 2026
Merged

kovtcharov-amd merged 4 commits into
amd:mainfrom
kovtcharov:kalin/daemon-idle-exit

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

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 ~/.gaia shuts 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 ~/.gaia daemon 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 --isort
  • Real daemon, scratch GAIA_HOME, GAIA_DAEMON_IDLE_EXIT_MINUTES=1, no client: logged "nothing has used it for 1 minutes" and exited 60 s after start
  • Same, with a registered app client: still running at 90 s. Once the client process ended, the daemon dropped it within 4 s and exited 60 s later
  • The ~/.gaia daemon never idles out: pinned by test_the_default_home_never_idles_out, and is_default_home by test_the_machine_home_is_the_default
🔍 Technical details
  • lifetime.exit_reason gains an idle reason that applies only when paths.host_dir() isn't ~/.gaia/host. LifetimeWatch takes idle and idle_limit.
  • The idle measure is lifetime.DaemonIdle. A held or queued ModelSlotBroker lease counts as use. The broker now reports last_activity_s_ago (stamped on grant, release and reclaim), so even leases shorter than the 5 s check restart the clock. Underneath it is LemonadeClients.snapshot()["idle_seconds"]: None while 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, 0 means off, and anything that isn't a non-negative integer raises DaemonStartError at startup.
  • Docs: the daemon section of docs/reference/cli.mdx.

@github-actions github-actions Bot added documentation Documentation changes tests Test changes daemon Daemon supervisor / sidecar control plane labels Oct 18, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

Daemons started for a scratch GAIA_HOME (evals, demos, test drives) now shut themselves down after two hours with no client, no busy sidecar and no pending scheduled job. The everyday ~/.gaia daemon is untouched. The logic is sound: the idle clock is the same one the Lemonade idle timeout already uses, a bad env value fails at startup instead of being guessed, and the CLI reference is updated. Nothing blocks the merge.

Two small things are worth a look:

  • If reading the scheduler database ever throws during the idle check, the whole lifetime watcher dies. That also turns off the existing "exit when the home folder is deleted" check, so the daemon could hang around again.
  • A scheduled job set far in the future keeps a scratch daemon alive until it fires. A restarted daemon fires past-due jobs anyway, so that guard may be stricter than it needs to be.

Real-world evidence

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

Issues

🟢 An exception from the idle probe kills the watch thread (src/gaia/daemon/lifetime.py:178)
self._idle() runs before exit_reason's home and instance checks and isn't guarded. Once idle passes the limit, _idle_seconds in server.py:364 calls clock.job_counts() on every tick (every 5 s), and that opens SQLite. One sqlite3.OperationalError (for example, locked past busy_timeout) ends _run through the thread excepthook. From then on the daemon also stops noticing a deleted home or instance.json, which is the #5294 behaviour. The scheduler clock's own loop already catches and logs its errors. One option is to do the cheap existence checks first, and to log the probe failure and keep watching:

            try:
                idle = self._idle() if self._idle is not None else None
            except Exception:
                logger.exception("daemon: idle check failed; will retry")
                idle = None
            reason = exit_reason(self._exit_with_pid, idle, self._idle_limit)

(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)
job_counts()["pending"] counts jobs whose fire time is days away. DaemonClock._run fires past-due jobs as soon as a fresh daemon starts, so a scratch daemon could exit and leave the job to the next start. Gating only on jobs due within the limit would keep the "no stragglers" goal. That's a design call, so I'm not posting a suggestion. Also, no executors are registered yet (_build_clock), so for now a "pending" job can only ever fail-mark.

🟢 The server-side composition is untested (src/gaia/daemon/server.py:358-364)
The tests cover exit_reason and LifetimeWatch well, but nothing covers _idle_seconds: a pending job holding the daemon past the limit, and not touching the DB while below it. It's a nested closure, so it would need lifting into a small helper to test. The author's real-daemon run covers the client path but not the pending-job path.

Strengths

  • It reuses LemonadeClients' existing idle clock instead of adding a second notion of "in use", and it only reads the scheduler DB near the limit.
  • GAIA_DAEMON_IDLE_EXIT_MINUTES follows fail-loudly: a malformed or negative value raises DaemonStartError with a fix, and 0 is an explicit opt-out.
  • is_default_home() compares resolved paths, so an explicit GAIA_HOME=~/.gaia is still treated as the machine daemon. A dedicated test pins that the default home never idles out.

kovtcharov and others added 4 commits October 18, 2026 23:07
…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.
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 19, 2026
Merged via the queue into amd:main with commit 0d77e3e Oct 19, 2026
80 of 81 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the kalin/daemon-idle-exit branch October 19, 2026 08:29
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
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
…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 documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants