Skip to content

fix(daemon): never kill a live daemon because queued leases slowed its status - #5327

Merged
kovtcharov-amd merged 8 commits into
amd:mainfrom
kovtcharov:claude/daemon-busy-not-dead
Oct 19, 2026
Merged

kovtcharov-amd merged 8 commits into
amd:mainfrom
kovtcharov:claude/daemon-busy-not-dead

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

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

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 #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 -q
  • python -m pytest tests/unit/ -k "daemon or broker or lemonade_service" -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, queue about 40 more, then run gaia daemon status. It reports the daemon running and kills nothing.
🔍 Technical details
  • /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 fix(daemon): a queued model request waits instead of failing, and shows it is waiting #5328.

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

Copy link
Copy Markdown
Contributor

Verdict: Request changes (one small fix)

This stops a gaia command from killing a healthy daemon and all its sidecars just because queued model requests slowed its status reply. The fix is sound: the status route no longer competes with lease waits for worker threads, and a slow-but-connected daemon is re-probed and then reported as busy instead of killed. There's a good repro test that fails on main.

What to fix before merge:

  • The busy error skips the Lemonade auto-start path's error handling. When GAIA tries to auto-start the model server while the daemon is busy, it now raises a new daemon error the caller doesn't catch. That caller only handles "couldn't start Lemonade" errors, so the user gets a traceback instead of the clean ❌ message. Converting the error to the type that path already handles fixes it.
  • No real output is shown for the new gaia daemon status "busy" state. The manual test-plan item is unchecked. Pasting the real output from the 40-queued-lease repro would show the CLI change works.

Real-world evidence

N/A: no evidence bundle was produced for this run. The verdict rests on static review and the PR's unit tests. The new gaia daemon status "running, but not answering" output wasn't exercised here.

🔍 Technical details

🟡 DaemonBusyError escapes LemonadeManager.ensure_ready (src/gaia/llm/lemonade_service.py:499)
_post_start calls daemon_client.attach(), which can now raise DaemonBusyError. The only caller up the chain, lemonade_manager.py:1237, catches LemonadeStartError alone. On a busy daemon the exception therefore propagates out of ensure_ready as an uncaught traceback instead of hitting the print-and-return False path. Before this PR, attach() returned None, so the user got a (misleading) "daemon not running" LemonadeStartError. Translate it at the boundary, the same way broker_client.attach_broker_env does:

    try:
        inst = daemon_client.attach()
    except DaemonBusyError as e:
        raise LemonadeStartError(
            f"Could not ask the GAIA background service to start the local model server: {e}"
        ) from e

(Import DaemonBusyError from gaia.daemon.errors next to the other deferred imports. A unit test like test_a_busy_daemon_fails_a_model_load_as_a_broker_error that targets ensure_lemonade_running would pin it.)

All other attach() callers I checked already catch DaemonError: the CLI agents/stop-agent handlers, _resolve_sidecar_log (via except Exception), the email sidecar's stop_sidecar, and the lease-renew loop. gaia daemon stop/restart use read_instance() plus request_shutdown, so the remedy in the error message still works on a busy daemon.

🟡 Real-world evidence for the CLI surface
_handle_daemon_status gains a new busy branch (src/gaia/cli.py:8587). The PR's last test-plan item describes the right repro (hold the slot, queue about 40 leases, run gaia daemon status), but no output is shown. Please paste the real terminal output, plus a gaia llm run during the same load to show the broker-error path.

🟢 gaia daemon status can now take about 11.5 s on a busy daemon
status_report uses _patient_probe(inst, 1.5), so the worst case is 1.5 s plus 10 s. That fits the "never kill" goal. Consider printing a "waiting for the daemon to answer…" line once the first probe times out, so the command doesn't look hung.

Strengths

  • The fix targets the root cause, not the symptom. Making both status and the shared require_token dependency async is the subtle part: a sync dependency alone would have kept status on the anyio pool. Running job_counts on its own limiter keeps it off that pool too.
  • probe_state splits ReadTimeout (connected, slow) from everything else, so a daemon that refuses connections or answers as a foreign server is still reclaimed automatically. Tests pin both branches.
  • attach() raising instead of returning None closes a real hole: a busy daemon would otherwise read as absent and let model loads run unbrokered against its sidecars.

@github-actions github-actions Bot added llm LLM backend changes performance Performance-critical changes labels Oct 18, 2026
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Addressed both points from the review.

  • The busy error escaping the Lemonade auto-start path: fixed. _post_start now raises LemonadeStartError, the error ensure_ready handles, so the user gets the clean ❌ message. A new test pins it.
  • Real output for the busy state: captured below.
  • The nit about status looking hung: also done. gaia daemon status now prints slow to answer, waiting up to 10s… before the longer second probe.

Live run: the real daemon app (create_app plus broker) on :18300 under a throwaway GAIA_HOME, with the real gaia daemon status CLI. One lease is held and 45 more are queued.

main: status misses the probe, and the live daemon is reported stale. start_or_attach reclaims (kills) a daemon in exactly that state.

GAIA daemon: stale (process is alive but not answering the client API)
  Registry: …\host\instance.json (pid 30576, port 18300)
  Reclaim it with `gaia daemon restart`.

This branch, same load:

GAIA daemon: running
  pid:        9168
  port:       18300
  uptime:     11s
  api:        v1.5

This branch, a daemon that accepts connections and never answers. The process was still alive afterwards.

GAIA daemon: slow to answer, waiting up to 10s…
GAIA daemon: running, but not answering (busy or stuck)
  Registry: …\host\instance.json (pid 30800, port 18301)
  It was left running. Retry in a moment; if it stays like this,
  `gaia daemon restart` restarts it and its sidecar agents.
  Where to look: `gaia daemon logs`.

I did not run gaia llm against the busy daemon, because it would need a model on the shared Lemonade. That path, where a busy daemon becomes a broker error, is covered by test_a_busy_daemon_fails_a_model_load_as_a_broker_error.

@github-actions

Copy link
Copy Markdown
Contributor

🟡 The new 120-second "hung" timer can still kill a healthy daemon that is only busy. It counts from the first time any gaia command saw the daemon slow, and only resets when a later command gets an answer. If one busy spell ends with no command checking in, the old start time stays on disk. The next time that daemon is busy, even hours later, it looks like it has been silent for hours. gaia daemon start (and anything that auto-starts the daemon) then replaces it and its sidecars, which is the failure this PR set out to fix.

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

src/gaia/daemon/client.py:172 _busy_since returns data["since"] whenever data["pid"] == inst.pid, with no check on how old it is. _clear_busy runs only on a non-busy probe in _answers (line 227) or after a reclaim (line 306). The daemon itself never clears it.

Sequence: run gaia daemon status while leases are queued, so the marker is written at T0. The load drains and no client probes. At T0 + 1h the load returns and start_or_attach() runs. The first probe times out, silent_for is about 3600 s, which is at least HUNG_AFTER_S, so DaemonHungError is raised and terminate_instance runs.

One way to fix it: store {"pid", "since", "last"}. If now - last > 2 * BUSY_PROBE_TIMEOUT_S, reset since = now. Rewrite last on every busy probe.

kovtcharov and others added 6 commits October 18, 2026 23:22
…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.
@kovtcharov-amd
kovtcharov-amd force-pushed the claude/daemon-busy-not-dead branch from 2066f1a to 0d6749c Compare October 19, 2026 06:23
@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

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 gaia command treated it as hung and killed it along with every sidecar agent. Now the status check never queues behind that work. A slow daemon is checked again and reported as busy rather than killed. It is replaced only after two minutes of silence, or when its port is plainly dead or a different program has taken over its pid. I found no blocking issues. Every existing caller of the attach path already handles the new "busy" error, and the failures in the model-load and Lemonade-start paths come out as their existing clean errors.

Two small follow-ups, neither blocking:

  • A possible flaky test. The new tests leave a "busy since" marker in a daemon-home folder that the whole test session shares. Under a slow or parallel run, a later test could read an old marker as two minutes of silence and fail. Giving each test its own folder fixes it.
  • gaia agent logs can stall. When the daemon is busy, the log lookup now waits about 10 extra seconds before it falls back to the newest file on disk. A quick check is enough there.

Real-world evidence

No 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 gaia daemon status command. This review relays that comment and did not re-run it.

On main, the same load makes the live daemon read as dead:

GAIA daemon: stale (process is alive but not answering the client API)
  Registry: …\host\instance.json (pid 30576, port 18300)
  Reclaim it with `gaia daemon restart`.

On this branch, under the same load:

GAIA daemon: running
  pid:        9168
  port:       18300
  uptime:     11s
  api:        v1.5

On this branch, with a daemon that accepts connections but never answers (the process was still alive afterwards):

GAIA daemon: slow to answer, waiting up to 10s…
GAIA daemon: running, but not answering (busy or stuck)
  Registry: …\host\instance.json (pid 30800, port 18301)
  It was left running. Retry in a moment; if it stays like this,
  `gaia daemon restart` restarts it and its sidecar agents.
  Where to look: `gaia daemon logs`.

The author did not run a model load (gaia llm) against a busy daemon. That path is covered only by a unit test, so the verdict on it rests on static review.

🔍 Technical details

Issues

🟢 Busy marker leaks between tests (tests/unit/test_daemon_status_under_load.py:670). _answers writes busy_since.json under paths.host_dir(). The root conftest.py points GAIA_DAEMON_HOME at one tmp dir for the whole session, so every test that raises DaemonBusyError leaves a pid-4242 marker with last=now. _busy_since keeps the earliest since as long as consecutive probes are under 60 s apart. If this file's tests are spread over more than 120 s (xdist interleaving, a slow runner), test_start_or_attach_never_kills_a_daemon_that_stays_busy gets DaemonHungError, kills the instance, and fails. Isolate it in _stale_registry:

    """A registered daemon whose pid is alive; *outcomes* script its probes."""
    monkeypatch.setenv("GAIA_DAEMON_HOME", str(tmp_path))

This also needs tmp_path threaded through as a parameter. _busy_for already resolves paths.host_dir() at call time, so it follows the change.

🟢 The sidecar log lookup waits out a busy daemon (src/gaia/cli.py:8902). _resolve_sidecar_log is best-effort and falls back to the disk, but it calls client.attach() with the default patient=True, which adds a 10 s probe. client.attach(patient=False) keeps it quick; the DaemonBusyError it raises is already caught by the except Exception below.

Strengths

  • The three-state probe_state (live/busy/gone) cleanly separates "accepted but slow" (ReadTimeout) from "dead", while probe() keeps its old contract for existing callers.
  • Making the require_token/require_caller dependencies async is the subtle part: a sync dependency would have kept status on the anyio pool even with an async route. The load test reproduces the original starvation against a real uvicorn server, and also pins how long the holder takes to release.
  • The busy limit is bounded and keyed by pid, with the gap rule so a busy spell that ended unobserved doesn't count toward "hung". The exit paths (register/release_lemonade_client) skip the long probe, and a reused pid is detected through its cmdline.

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>
# 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.
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 19, 2026
Merged via the queue into amd:main with commit b8c2264 Oct 19, 2026
66 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claude/daemon-busy-not-dead branch October 19, 2026 12:54
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

cli CLI changes 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