Skip to content

fix(daemon): never stop GAIA's Lemonade while a process is using it - #5159

Merged
kovtcharov-amd merged 2 commits into
mainfrom
fix/daemon-never-stops-busy-lemonade
Oct 16, 2026
Merged

kovtcharov-amd merged 2 commits into
mainfrom
fix/daemon-never-stops-busy-lemonade

Conversation

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

GAIA's daemon stopped its own Lemonade Server in the middle of chat turns. Any process it did not know about, such as an Agent UI backend started under its own GAIA_HOME, lost its in-flight turns, local and cloud alike, to connection errors and 401s. Now every GAIA process that talks to the server holds a lease on it for as long as it runs, under any GAIA_HOME. The daemon also watches the server's own traffic: it never stops or unloads while a request is in flight, and any request restarts the idle clock. If the server is stopped anyway, the next request restarts it and goes through instead of failing the turn.

The idle timeout stays at 15 minutes. That balances giving GPU memory back to other apps against a 20–60 s cold model load the next time GAIA is used. It is still lemonade_idle_timeout_minutes, and 0 turns it off. Closing the last app still unloads, a truly idle server still stops, and a user's own Lemonade is never touched.

Test plan

  • pytest tests/unit/test_daemon_lemonade_clients.py tests/unit/test_daemon_lemonade.py tests/unit/test_daemon_lemonade_routes.py tests/unit/test_lemonade_client_hold.py tests/unit/test_lemonade_survives_idle_stop.py tests/unit/test_lemonade_follows_restart.py tests/unit/test_lemonade_embedded*.py tests/unit/test_gaia_lemonade_start_path.py tests/unit/test_users_lemonade_untouched.py passes on Windows. The new adversarial cases fail on main.
  • python util/lint.py --black --isort --flake8 --pylint --test-lanes
  • CI: Unit Tests (Linux, Windows), Code Quality, and tests/integration/test_lemonade_embedded_lifecycle.py against a real lemond.
  • On a machine with GAIA installed, start an Agent UI backend with GAIA_HOME set to a temp dir and LEMONADE_BASE_URL pointing at ~/.gaia's server. Set lemonade_idle_timeout_minutes 1, then chat for 5 minutes. ~/.gaia/gaia.log shows no "stopping embedded Lemonade" while it runs. Close it, wait 1 minute, and the server stops.
🔍 Technical details

Root cause: LemonadeClients._check_idle and the daemon's busy predicate counted only registered clients and sidecar connections. A process registered with the daemon of its own GAIA_HOME was invisible to the ~/.gaia daemon that owns the server, so that daemon stopped the server under it after 15 minutes.

Activity signal (Lemonade 2026.40+): /api/v1/health → all_models_loaded[].is_busy / is_streaming (true for the whole request, streams included), plus last_use, which moves at every request start and model load. last_use is a steady-clock value, not wall time, so the daemon only compares it with its own last reading. A recorded server that does not answer counts as busy.

Adversarial tests (each fails without the fix, except the guards noted):

  • A generation in progress with no client is never stopped. Neither is an unregistered process streaming turns, nor requests spaced just under the timeout.
  • A request or stream that lands while the stop or unload is being decided wins.
  • The last app closes while another process is mid-turn: no unload until the server has been quiet for 60 s.
  • A leased process quiet for 20 minutes is not stopped (guard). A hung process whose lease lapses lets the stop happen after the timeout. A sleeping machine lapses no lease.
  • Stopped under a request: the client restarts the server and answers. A restart by another process mid-request is followed, with no 401. A stream stopped before its first chunk starts over. One under way is not replayed (guard).
  • Another GAIA_HOME: the client leases from, and restarts through, the daemon that owns the server.
  • Two processes restarting at once start one server (guard).
  • Truly idle stops after the timeout, and a timeout of 0 never stops (guards).

The daemon stopped GAIA's Lemonade Server mid-turn whenever the process
using it had not registered: an Agent UI backend under its own GAIA_HOME
lost every in-flight chat, local or cloud, to connection errors and 401s.
Idle meant "no registered client", not "no one using the server".

Three layers now keep a server in use alive:

- Leases. Every LemonadeClient aimed at GAIA's server leases it for its
  process's life, renewed every 30 s, including a process under another
  GAIA_HOME whose LEMONADE_BASE_URL names the default home's server; it
  leases from that home's daemon too. A lease ends when its process exits
  or stops renewing for 2 minutes.
- Activity. The daemon also reads Lemonade's /health (is_busy and last_use,
  Lemonade 2026.40+): any request restarts the idle clock, nothing is
  unloaded or stopped while one is in flight, and the stop re-reads the
  server as its last step, so a request that lands mid-decision wins.
- Transparent restart. A client that finds the server stopped under a
  request has the daemon start it again and sends the request once more;
  a stream already under way is not replayed.

Not eval-gated: no prompt, tool, model or response-parsing change.
@github-actions github-actions Bot added documentation Documentation changes llm LLM backend changes tests Test changes performance Performance-critical changes daemon Daemon supervisor / sidecar control plane labels Oct 16, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

GAIA's daemon used to stop its own Lemonade Server in the middle of chat turns when the process using it was one the daemon didn't know about. This PR fixes that three ways. Every GAIA process now holds a renewable lease on the server. The daemon also reads the server's own traffic, so it never stops or unloads while a request is in flight. And a client that finds the server gone restarts it and retries once. The logic is careful: it re-checks right before acting, it doesn't treat a machine that slept as dead clients, and it never replays a stream that is already under way. The tests probe the race windows directly. I found no correctness blockers.

One thing to fix before or alongside merge:

  • The documented way to change the timeout doesn't work. Both edited docs tell users to run gaia config set lemonade_idle_timeout_minutes 30. The evidence run shows it fails with an unrelated message about API keys. The bug predates this PR, but this PR leans harder on that setting and repeats the command. Either let that key through the CLI guard, or stop documenting the command until it works.

Real-world evidence

The evidence stage ran the CLI and the daemon's HTTP API live on a Linux runner with no GPU. Lease register, renew, release, and the error codes all behave as designed. A lease taken under another GAIA_HOME lands on the daemon that owns the server:

--- owner daemon GET /daemon/v1/lemonade/clients -> 200
{
  "clients": [
    {"client_id": "HeBER3fkoLUqXKM1", "kind": "cli", "name": "xhome-evidence", "pids": [2939]}
  ],
  "idle_seconds": null,
  "seconds_since_request": 0.1457987800000069,
  "idle_timeout_error": null
}
--- after release_lemonade_hold(): clients=[]

The documented timeout command fails:

$ gaia config set lemonade_idle_timeout_minutes 30
❌ lemonade_idle_timeout_minutes is set by `gaia lemonade connect <url>`, which stores the key in the OS credential store.
exit=1

Two paths need a real server and are pending the strix-halo lane: the idle stop or unload against a real Lemonade, and restart-and-retry in the middle of a request. On those paths the verdict rests on static review and the unit tests. The PR's own manual test (chat for 5 minutes with a 1-minute timeout under a separate GAIA_HOME) is the right check for them.

🔍 Technical details

🟡 Important: the documented gaia config set lemonade_idle_timeout_minutes command is rejected (docs/guides/agent-ui.mdx:307, docs/reference/cli.mdx:3226)

src/gaia/cli.py:6422 sends every lemonade_* key to _set_lemonade_config. That function only handles lemonade_mode and lemonade_base_url, and its else branch raises the "set by gaia lemonade connect" error, which is only true for lemonade_api_key_stored. The guard came in with #5141, so this PR didn't cause it. But this PR makes the timeout central to its fix and repeats the command in two docs. The smallest fix is to narrow the guard:

if action == "set" and args.key in ("lemonade_mode", "lemonade_base_url", "lemonade_api_key_stored"):

lemonade_idle_timeout_minutes would then go through the normal cfg.set path. Add a CLI test for gaia config set lemonade_idle_timeout_minutes 30. If you'd rather keep this PR's scope tight, file an issue and hold the doc lines until it lands.

🟢 Nit: _register passes the earlier client id two different ways (src/gaia/llm/lemonade_service.py, _register)

The own-daemon branch uses *([previous] if previous else []), and the owner branch passes previous directly. register_lemonade_client already defaults client_id=None, so both branches can pass previous, or the two can be merged into one call with host_dir=host_dir:

client_id = daemon_client.register_lemonade_client(
    lease.kind, lease.pids, lease.name, previous, host_dir=host_dir
)

That only works if the tests that pin attach() with no arguments don't depend on the branch split. The same x(host_dir=h) if h else x() pattern appears in client.py and lemonade_client.py. It seems to exist so mocks see the old call shape. That's fine, but it's worth a sweep once the tests no longer need it.

Checked and fine

  • The daemon never leases from itself: lease_gaia_lemonade returns early when a supervisor is installed, and only daemon/server.py installs one.
  • A server that is unanswered but recorded counts as busy, so the daemon never idle-stops one that is still loading a large model.
  • still_wanted now runs after status(), under the start lock, and re-reads /health, which closes the window where a request arrives while the stop is being decided.
  • The retry only fires when _gaia_lemonade_gone() confirms the port, key, or socket is gone. Ordinary errors such as a timeout on a live server, a context overflow, or a 400 still raise and are not retried.
  • TUI app holds already renew every 30 s (tui/internal/lemonade/hold.go), so the new 120 s LEASE_TTL doesn't drop them.

Strengths

  • The adversarial tests are written as scenarios ("a generation in progress is never stopped", "a request that lands mid-decision wins") and cover the race windows, not just the happy path.
  • last_use is compared only with the previous reading, never with wall time, which matches what Lemonade actually guarantees.
  • Errors stay loud and actionable. For example, an owning daemon that isn't running reports which home owns the server and how to start its daemon.

The cross-home lease reads the default home's Lemonade state on purpose, so
it needs ~/.gaia even under GAIA_HOME. Resolve it in gaia.config, which the
GAIA_HOME ratchet exempts, rather than adding a hard-coded site.
@github-actions

Copy link
Copy Markdown
Contributor

Skill audit

Skill Verdict Claimed tier Cleared tiers Findings Rules
.claude/skills/gaia-testing ✅ ALLOW experimental experimental, community none —
hub/agents/gaia/npm ✅ ALLOW experimental experimental 2 high body.injection.credential_request, body.injection.persona_override

✅ All audited skills cleared the tier they claim.

Per-finding detail is withheld here on purpose. Read it in the Security > Code scanning tab, or download the skill-audit-reports artifact from this run. Offending source text is withheld from CI everywhere — reproduce it locally with gaia skill audit <dir> --show-snippets.

@kovtcharov-amd
kovtcharov-amd merged commit ddb4a35 into main Oct 16, 2026
75 of 76 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the fix/daemon-never-stops-busy-lemonade branch October 16, 2026 04:09
kovtcharov-amd added a commit that referenced this pull request Oct 16, 2026
…5166)

After GAIA's Lemonade Server stopped (the idle timeout, or any stop),
the next start went to the default port 13305: on one Strix Halo lab
host GAIA silently used another Lemonade already there, and on another
the daemon answered a bare "Internal Server Error". A stopped GAIA
server now always comes back through the daemon on its recorded port,
and a failed start says why. Two smaller bugs the same hardware CI
pinned are fixed too: `gaia config set lemonade_idle_timeout_minutes N`,
the command the docs give, is accepted and validated (0 = never) instead
of always rejected, and `gaia llm` shows the "Not enough free memory…
needs about X GB" refusal word for word and exits 1, rather than generic
restart advice and exit 0. Every `gaia llm` failure now exits non-zero
and prints its own error; the install/start advice appears only when
Lemonade really does not answer, so a stalled stream is no longer
reported as "not installed".

These are the three strict xfails in #5163's
`tests/hardware/test_linux_halo_user_issues.py`; the markers come off
there once this merges.

## Test plan
- [x] `pytest tests/unit/test_lemonade_restart_keeps_port.py
tests/unit/test_llm_memory_refusal.py tests/unit/test_cli_config.py
tests/unit/test_gaia_lemonade_start_path.py` plus the daemon/Lemonade
supervisor, service, embedded, choice and manager suites: 826 passed on
Windows. Every new test fails on `main` before this change.
- [x] Adversarial cases: an idle stop then a restart lands on GAIA's
port while another Lemonade answers on the default port, which receives
zero requests; a restart with nothing on the default port returns 200,
not 500; a transparent restart (#5159) follows to the recorded port;
GAIA's last port taken moves it and the client follows; the test fake
for the daemon's owner is now a subclass of the real one, so a removed
attribute fails the test as it fails the daemon.
- [x] `python util/lint.py --black --isort`
- [ ] Linux Strix Halo hardware job on #5163 passes with its three xfail
markers removed
kovtcharov-amd added a commit that referenced this pull request Oct 16, 2026
Against v0.25.0-rc16 the test app exited before registering on both Halo
hosts, failing EU-2 (app close frees memory) and EU-3 (relaunch keeps the
port) without testing either: #5159 replaced lemonade_service's single
held client id with a renewed lease holding one id per daemon. The app now
reads whichever the installed GAIA has.
kovtcharov-amd added a commit that referenced this pull request Oct 19, 2026
Against v0.25.0-rc16 the test app exited before registering on both Halo
hosts, failing EU-2 (app close frees memory) and EU-3 (relaunch keeps the
port) without testing either: #5159 replaced lemonade_service's single
held client id with a renewed lease holding one id per daemon. The app now
reads whichever the installed GAIA has.
kovtcharov-amd added a commit that referenced this pull request Oct 19, 2026
…ing the turn

A new session that switched models, or sent its first request, while GAIA's
own Lemonade Server was briefly not answering ended with "Lemonade Server is
not reachable", even though the daemon brought the server back seconds later.
It now shows "Reconnecting to the model server..." and waits up to 60 s for
the daemon's server, then carries on; if the server does not come back, it
fails with an error that says so and points at `gaia daemon status`.

- The daemon's /lemonade/ensure marks "running but not answering" with a
  503 + Retry-After, so a client can tell a transient state from a failed
  start. A failed start is still reported at once, never retried.
- LemonadeClient.wait_for_gaia_lemonade() does the bounded wait through the
  existing follow/ensure path; the mid-request recovery and the /model switch
  both use it. A user-run or remote Lemonade is never waited on.
- The "localhost:13305 has stopped" log came from a client built while no
  GAIA server was recorded (the daemon's provider-key route builds one per
  request), which holds the default port as a placeholder. It only asks the
  daemon's ensure, which never stops a running server, so it cannot violate
  #5159. The log now says no server was recorded instead.

Why the server on the new port stopped answering ~15 s after it was ready
is not identifiable from the code; the lemond and daemon logs from that run
are needed.

Closes #5261
kovtcharov-amd pushed a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
…mond

util/lemonade_restart_harness.py builds a throwaway GAIA home and user profile
with its own daemon and lemond, a local stub registered as the amd cloud
provider, and every fault on that server only: kills, hung starts, a server
that never returns, idle stops, the TUI's job object closing, the user's own
lemond and a remote URL. It refuses to kill any process outside its root.

Subcommands: repro (each scenario, also against another tree with --code),
stress (concurrent sessions under random crashes), tui (back-to-back real
gaia-tui sessions, --overlap for the incident's shape) and ui-lease (an Agent
UI backend under its own GAIA_HOME, amd#5159).

tests/integration/test_lemonade_restart_live.py runs the scenarios under
pytest and skips when no lemond can be had. It takes ~7 min and its job-object
case needs Windows, so it is allowlisted rather than in the Linux lane.
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
…ing the turn (amd#5264)

A new session that switched models, or sent its first request, while
GAIA's own model server was briefly down ended the turn with "Lemonade
Server is not reachable", even though the daemon had the server back
seconds later. Now the agent shows "Reconnecting to the model server…",
waits up to 60 seconds for the daemon's server, and carries on. If the
server doesn't come back, the turn fails with an error that says so and
points at `gaia daemon status`. A Lemonade you run yourself, or a remote
`LEMONADE_BASE_URL`, is never waited on.

We still don't know why the server on the new port stopped answering ~15
s after it was reported ready. The code doesn't show it, so the lemond
and daemon logs from an affected run are needed. The "localhost:13305
has stopped" line was a red herring. A client built while no GAIA server
was recorded holds the default port as a placeholder, and it can only
ask the daemon to *ensure* a server, which never stops a running one.
The amd#5159 rule holds.

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

- `/daemon/v1/lemonade/ensure` now returns 503 with `Retry-After` for
"running but not answering" (`EmbeddedLemonadeNotAnswering`), and
`ensure_lemonade` raises `LemonadeNotAnsweringError` for it. A failed
start is still a plain 503, reported at once and never retried. An older
daemon has no header, so a new client fails as it does today.
- `LemonadeClient.wait_for_gaia_lemonade()` polls the existing follow
and `_start_gaia_lemonade` path every 2 s. Both
`_recover_stopped_gaia_lemonade` (mid-turn, via
`model_load_listener(model, "reconnecting")`) and `/model` (stdio
`status` event, `phase: "reconnecting"`) use it.
- The 60 s bound is checked between daemon calls. A cold start already
under way inside one `ensure` call can run past it, up to that call's 80
s timeout.
- The issue's live 16-session TUI stress run was not done here. A
unit-level 16-session stress test stands in for it.
- Not part of this change: a run of `tests/unit/test_lemonade*.py` on
this machine fails the same ~135 tests on bare `main`. A live GAIA
install's `~/.gaia/lemonade/state.json` leaks into them.
</details>

## Test plan

- [ ] `python -m pytest tests/unit/test_lemonade_restart_wait.py
hub/agents/gaia/python/tests/test_stdio_lemonade_reconnect.py` covers
the race, the 60 s bound, the user's and remote servers, the stale-port
follow, and the 16-session stress test
- [ ] `python -m pytest tests/unit/test_lemonade_survives_idle_stop.py
tests/unit/test_daemon_lemonade*.py
hub/agents/gaia/python/tests/test_stdio.py`
- [ ] `python util/lint.py --black --isort --flake8 --pylint
--test-lanes`
- [ ] On Windows, run 16 back-to-back `gaia-tui` sessions that each
`/model` to a cloud model, and check that none ends with "not reachable"
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 llm LLM backend changes performance Performance-critical changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant