Skip to content

fix(lemonade): wait for GAIA's restarted model server instead of failing the turn - #5264

Merged
kovtcharov-amd merged 4 commits into
mainfrom
fix/lemonade-restart-wait
Oct 19, 2026
Merged

kovtcharov-amd merged 4 commits into
mainfrom
fix/lemonade-restart-wait

Conversation

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

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 #5159 rule holds.

🔍 Technical details
  • /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.

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"

@github-actions github-actions Bot added documentation Documentation changes llm LLM backend changes tests Test changes performance Performance-critical changes agents daemon Daemon supervisor / sidecar control plane labels Oct 17, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Request changes (one small fix: narrow the docs claim, or extend the wait to startup)

When GAIA's own model server goes quiet for a few seconds, an agent that is already running now waits for the daemon to bring it back, and shows "Reconnecting to the model server…", instead of failing the turn. A model switch or an in-flight request gets the same treatment. The design is sound: only GAIA's own server is ever waited on, a server that fails to start is still reported at once, an older daemon behaves as before, and the tests reach the real HTTP boundary. The evidence run confirms all of that.

Blocking issue:

  • Startup still fails at once, but the docs say it waits. The new CLI reference text says any request that finds GAIA's server unreachable waits up to 60 seconds. The evidence shows gaia llm "hello" against a silent server failing in 1 second. Building a new agent session takes the same startup path, so a session that opens during the gap fails immediately; the wait only covers sessions already running. The PR description's "or sent its first request" overstates it in the same way. Either narrow the doc sentence to running sessions and /model, or apply the same bounded wait to the startup check.

Real-world evidence

The CI evidence stage ran the real daemon on ubuntu-latest (no GPU). It staged a GAIA Lemonade process that is alive but never answers.

  • Daemon route, server silent: returns 503 with a retry hint and leaves the process running:
    HTTP/1.1 503 Service Unavailable
    retry-after: 2
    {"detail":"GAIA's Lemonade Server (pid 2713) is running but not answering; it may still be loading a model. Wait and retry, or run `gaia init` to restart it. ..."}
    
    It returned 200 once a healthy server replaced it. Not installed gave 409 with no retry header, and a missing token gave 401.
  • /model switch through the real stdio agent: emits the reconnecting status, then a clear error once 60 s pass:
    {"type": "status", "status": "working", "message": "Reconnecting to the model server…", "phase": "reconnecting"}
    {"type": "error", "detail": "GAIA's Lemonade Server at http://localhost:18555/api/v1 stopped answering and was not back within 60s. ... Run `gaia daemon status`, and read the daemon log at /tmp/gh-evidence/host/daemon.log for why it stopped."}
    
  • Recovery: the server came back about 5 s into the wait, and the client returned True after 6.0s. A user-set LEMONADE_BASE_URL was never waited on (wait returned False in 0.00s).
  • The gap behind the blocking issue:
    $ gaia llm "hello"
    ❌ Could not start GAIA's Lemonade Server: GAIA's Lemonade Server (pid 2713) is running but not answering; ...
    exit=1 elapsed=1s
    
  • Spot regression: daemon status, the Lemonade target route, and gaia daemon start/status/stop all still work.
  • Pending strix-halo lane: the rendered "Reconnecting…" line in the TUI and Agent UI, and a real mid-turn replay against a server that drops mid-request. The verdict rests on static review for those two.
🔍 Technical details

🟡 Docs overclaim: the startup path never waits (docs/reference/cli.mdx:3232)

Agent.__init__ calls LemonadeManager.ensure_ready (src/gaia/agents/base/agent.py:2367). That goes through start_embedded_if_stopped, which catches DaemonError and returns False (src/gaia/llm/lemonade_manager.py:907-915). LemonadeNotAnsweringError subclasses DaemonError, so that path still fails on the first 503, exactly as the evidence shows. Two ways to fix it:

  1. Narrow the doc:
- **A server that is briefly not answering is waited for.** A running session's
  request or `/model` switch that finds GAIA's server unreachable shows
  "Reconnecting to the model server…" and waits up to 60 seconds while the
  daemon brings it back, then carries on. If it is not back by then, the
  request fails with an error that says so and points at `gaia daemon status`.
  Starting a new session or `gaia llm` while the server is not answering still
  fails at once. A Lemonade you run yourself, or one `LEMONADE_BASE_URL` names,
  is never waited on.
  1. Or catch LemonadeNotAnsweringError in ensure_ready and route it through LemonadeClient.wait_for_gaia_lemonade. That closes the gap for new sessions too, and matches the PR body's "first request" claim.

🟢 Redundant second start inside the wait loop (src/gaia/llm/lemonade_client.py, wait_for_gaia_lemonade)

When no state file exists, _follow_gaia_lemonade already calls _start_gaia_lemonade and _replay_cloud_key. If the probe right after that still reports the server gone, the loop calls both again in the same pass. It is harmless, since the daemon never starts a second server, but it doubles the ensure calls and key replays on that path. Optional.

Strengths

  • A transient "not answering" is cleanly separated from a hard start failure (a 503 with Retry-After vs a plain 503). An older daemon sends no header, so a new client falls back to today's behaviour with nothing to negotiate.
  • The wait is bounded, and its timeout error names the daemon's own reason and the log path. That follows the fail-loudly rule rather than retrying forever.
  • TestTheRegression drives a real LemonadeClient and the real daemon client, mocking only at HTTP, the socket and the clock. It asserts the outgoing auth headers and the replayed cloud key, which proves the calls are valid and not just made.

…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
Opening a session or running `gaia llm` while GAIA's own model server was
running but not answering still failed at once, so only sessions already
running got the 60-second wait. Startup now takes the same bounded wait,
shows "Reconnecting to the model server…", and fails with the same
actionable error if the server is not back. A failed start is still
reported at once.
@kovtcharov-amd
kovtcharov-amd force-pushed the fix/lemonade-restart-wait branch from 7976a87 to 83ecb93 Compare October 19, 2026 06:37
@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

When GAIA's own model server briefly stops answering, a turn or /model switch now shows "Reconnecting to the model server…" and waits up to 60 s for the daemon to bring it back, instead of failing with "not reachable". A server the user runs, or a remote one, is never waited on. The design is sound: the daemon only marks the transient "up but not answering" case as retryable, so a real start failure still fails at once, and the evidence shows that working.

One gap is worth closing before merge, or else documenting:

  • The wait can be skipped in the exact state it targets. The daemon calls a server "not answering" when its health check fails. The client counts the server as "back" as soon as its port accepts a connection. A server that has its port open but is still loading a backend therefore ends the wait at once, and the request fails the old way. Only the closed-port case was exercised. Either make the client's "back" check ask the server's health endpoint, or add a test that pins the open-port case.

Real-world evidence

The evidence stage ran the real daemon, gaia llm, and the stdio agent against a staged Lemonade whose process was alive but had nothing listening on its port. Every surface behaved as described:

Surface Result
POST /daemon/v1/lemonade/ensure, server not answering ✅ 503 with Retry-After: 2
Same route, version mismatch (not transient) ✅ 503 with no Retry-After; client raises plain DaemonError
gaia llm, server never returns ✅ "Reconnecting…", gives up at 60 s with an actionable error
gaia llm, server returns 10 s into the wait ✅ continues after ~11 s and goes on to model load
gaia llm with LEMONADE_BASE_URL set ✅ no wait, fails in 2 s
stdio /model <id> ✅ one reconnecting status event, then exactly one error
Agent UI / TUI rendering pending strix-halo lane
$ gaia llm "hello"          # server never comes back
WARN  wait_for_gaia_lemonade | GAIA's Lemonade Server at http://localhost:18999/api/v1 is not answering; waiting up to 60s for the GAIA daemon to bring it back.
Reconnecting to the model server…
❌ GAIA's Lemonade Server at http://localhost:18999/api/v1 stopped answering and was not back within 60s. The daemon reports: GAIA's Lemonade Server (pid 2710) is running but not answering; ... Run `gaia daemon status`, and read the daemon log at /tmp/ev/gh/host/daemon.log for why it stopped.
{"type": "status", "status": "working", "message": "Reconnecting to the model server…", "phase": "reconnecting"}
{"type": "error", "detail": "GAIA's Lemonade Server at http://localhost:18999/api/v1 stopped answering and was not back within 60s. ..."}

Spot checks of gaia daemon status, /daemon/v1/status, /lemonade/target and /lemonade/status all passed. The daemon never killed the stuck process.

The bundle also noted that with LEMONADE_BASE_URL set, the error still talks about "GAIA's own" server. That message comes from code this PR doesn't touch, so it's a follow-up, not a blocker. The stub server listened on no port at all, so the evidence doesn't cover the open-port case above. The new tests could not run on this review runner (pytest isn't installed), so I'm relying on CI for them.

🔍 Technical details

🟡 "Back" means the port is open, but "not answering" means health failed (src/gaia/llm/lemonade_client.py, wait_for_gaia_lemonade)

_gaia_lemonade_gone() returns False as soon as socket.create_connection succeeds. The daemon's EmbeddedLemonadeNotAnswering comes from EmbeddedLemonade.status(), which sets unresponsive_pid when _health() fails. Per lemonade_embedded.py:1088, that includes "loading a multi-gigabyte backend". In that state:

  • wait_for_gaia_lemonade hits if not self._gaia_lemonade_gone(): return (self.base_url, self.api_key) != was before the loop and returns False without waiting.
  • stdio _reachable_lemonade_models then re-raises the original "not reachable".
  • LemonadeManager._wait_for_gaia_lemonade returns True at once, and ensure_ready falls through to get_status() / _autostart against a server that still doesn't answer.

Suggested fix: make the loop's exit condition a short health probe (as EmbeddedLemonade._health does), or keep looping while _start_gaia_lemonade still raises GaiaLemonadeNotAnsweringError. Add a World case where listening contains the port but the daemon keeps answering not_answering.

🟢 _reachable_lemonade_models waits on any RuntimeError (hub/agents/gaia/python/gaia_agent/stdio.py)

A failure that isn't about reachability (for example a malformed catalog) still goes through _wait_for_gaia_lemonade. This is harmless today, because the wait returns False when the port answers and the original error is re-raised. A narrower trigger would make the intent clearer.

🟢 The 60 s bound can be exceeded. The PR body already says so: a cold start inside a single ensure call can run to its 80 s read timeout. A one-line note in the wait_for_gaia_lemonade docstring would keep a future reader from relying on 60 s as a hard limit.

Strengths

  • Only the transient case is retryable: the daemon sets Retry-After on it, and the client checks for that header. An older daemon that doesn't send it degrades to today's behaviour, and a real start failure is never retried, which fits the fail-loudly rule.
  • The tests mock only real boundaries: HTTP to Lemonade and the daemon, the port probe, and the clock. They also assert the shape of the /lemonade/ensure request, as CLAUDE.md asks.
  • docs/reference/cli.mdx is updated in the same change.

kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
… stolen port (amd#5314)

On a shared machine, GAIA called its own Lemonade dead whenever the
server was swapping models, and told the user to stop it. Lemonade's
health check waits on the lock that model eviction holds until the old
model's request finishes, so it can miss GAIA's 3-second probe for
minutes. `gaia init` restarted such a server, and the daemon's
supervisor gave a "stranger on the port" error for a slow system
install. Now a server that still answers Lemonade's lock-free liveness
check reads as running and busy, so requests wait for it. One whose
model backends then do no work at all for five minutes is still flagged,
with the restart command; any work, or a backend starting or exiting,
resets that. Separately, starting GAIA's server failed outright when
another program took the chosen port before Lemonade could bind it. GAIA
now picks a new port, logs the retry, and stops after three tries.

Reproduced by `tests/unit/test_lemonade_shared_lifecycle.py`: 5 tests
fail on main, all pass here. On a real, isolated lemond (2026.40.0, CPU
backend, port 18326), an `/unload` waiting on a running generation kept
`/health` past 10 s for ~85 s while `/live` answered in 0.00 s. Main
reported "not answering… Run `gaia lemonade embedded stop`". This branch
reported running and busy, and reused the server.

<details>
<summary>Captured output of that run</summary>

```
===== MAIN
loaded Qwen3-VL-4B-Instruct-GGUF on cpu in 12.9s
probe 0: /health FAILED after 10.01s (TimeoutError) | /live 0.00s
   status(): running=False busy=n/a unresponsive_pid=64180
   start(): raised: Embedded Lemonade (pid 64180) is running but not answering on port 18326. Starting another would leave two servers behind. Run `gaia lemonade embedded stop`, ...
...(same for probes 1-3)
unload returned after 85.14s
===== BRANCH
loaded Qwen3-VL-4B-Instruct-GGUF on cpu in 6.6s
probe 0: /health FAILED after 10.02s (TimeoutError) | /live 0.00s
   status(): running=True busy=True unresponsive_pid=None
   start(): returned the running server
unload returned after 21.25s
probe 1: /health 3.25s | /live 0.02s
   status(): running=True busy=False unresponsive_pid=None
```
</details>

**Merging with amd#5282:** both change the `Popen` that launches lemond.
Here that call moved into `_spawn`, so whichever lands second swaps
`subprocess.Popen(` for `popen_outliving_job(` there.

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

- `EmbeddedStatus.busy`: the pid must pass `_identify == OWN` and
`/live` must return `{"status":"ok"}`. `/live` carries no key, so on its
own it proves nothing about identity.
- Busy versus stuck comes from evidence, not a clock. Each sighting
records the cumulative CPU plus disk counters of lemond's backend
processes in `busy_since.json`. The server counts as stuck only when a
later sighting finds the same backends with identical counters more than
300 s on, so the verdict holds however rarely `status()` is called. No
evidence (processes not inspectable) never gives a verdict. Before a
stuck verdict it samples again 3 s later, because a machine that slept
past the window has frozen counters that move again on waking.
- On a real lemond 2026.40.0 holding its router lock, the llama-server's
counters rose ~10 s per second and stayed flat once idle. `/api/v1/docs`
answered in 0.02 s while `/health` timed out at 10 s. That recorded body
is the fixture the supervisor test serves.
- In Lemonade's source, backend downloads and installs run inside
`load()` after the router lock is released, so they never read as busy.
- Supervisor: a slow port is attached to only when `/live` and the
`/api/v1/docs` index (`"format": "text/markdown"`, also lock-free) both
answer. Anything else still gets the occupied-port error.
- Port retry: only when GAIA chose the port, lemond has exited, and
`_port_free` says the port is held. All attempts share one deadline, and
a retry needs at least 5 s left.
- `daemon/lemonade.py`: its "not answering" error now says the server is
stuck and names `gaia init`, instead of "may still be loading, wait and
retry". `init_command.py` changes only through `status()`. If amd#5264
lands first, its retryable `EmbeddedLemonadeNotAnswering` for this case
now waits on a stuck server; that wait is bounded, so it's harmless, but
it is worth a look when merging.
- **Accepted trade-off: there is no absolute ceiling on busy.** A server
counts as stuck only when its backends do no work at all for 5 minutes.
A backend that spins its CPU, such as a GPU driver busy-waiting on a
hang, counts as working, so GAIA keeps waiting on it. Requests still
fail at their own timeouts. The alternative, a wall-clock limit, either
restarted working servers or never fired, because nothing polls
`status()`.
- A system server gets the same verdict in memory, cleared whenever
health answers. The listener is found from the machine-wide socket
table, or, where that needs root (macOS), by walking the user's own
processes. A server run by another user stays hidden, and is attached to
rather than flagged: no evidence, no verdict. The same holds for any
backend process GAIA cannot read.
- Reviewed independently by a `code-reviewer` agent before the PR
opened, and by the PR bot afterwards. Fixed from those reviews: a wedged
server answering `/live` read as healthy forever; a time-based limit
that either restarted a working server or never caught a wedge (replaced
by the counter evidence above); the `/docs` fingerprint; the retry
deadline; the supervisor keeping a stale record; a macOS-only test hang
in the fake lemond. A second review of the final design found nothing
blocking. A third round's items are fixed too: unreadable backends
counted as idle, the macOS listener lookup, and four tests that passed
without the fix they cover (each was checked by removing that fix). Not
changed: the C1 tests keep lemond's real 3 s probe (~6 s each) so they
fail on `main` for the real reason; shrinking the timeout would make
them pass on `main`.
</details>

## Test plan

- [x] `python -m pytest tests/unit/test_lemonade_shared_lifecycle.py`:
31 passed (Windows). Removing each fix in turn (the record reset on
health and on clear, the early attach, the busy check after the grace
window, the pid comparison, the `/docs` format check, and the daemon's
stuck-not-loading remedy, and the wake-from-sleep re-sample on both
paths) fails its test On `origin/main`, 5 fail with the real symptoms
("busy server reported as not running", the occupied-port error, "exited
immediately")
- [x] Related suites (`test_lemonade_embedded*`,
`test_lemonade_supervisor`, `test_daemon_lemonade*`,
`test_init_command`, `test_cli_lemonade_embedded`,
launcher/choice/restart tests, and 15 more files): 709 passed after
merging main, isolated `GAIA_HOME`, Windows
- [x] `python util/lint.py --black --isort --flake8 --pylint
--test-lanes`: all pass
- [x] Real isolated lemond, same scenario on main and on this branch
(above), plus the `/docs` and backend-counter checks
- [ ] CI: Unit Tests (Linux, Windows, macOS), Code Quality

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
kovtcharov-amd pushed a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
Before: after the daemon restarted on a new port, Cancel, Respond,
Confirm and the full-access toggle in the TUI failed with "connection
refused", which says nothing about what happened. After: the TUI finds
the restarted daemon and says plainly that the restart ended the agent
session and nothing was sent; the next message starts a fresh session
there. A run cannot be carried over, because the daemon stops its
sidecars on shutdown and the next one starts fresh. Lands after v0.25.0.

Sending a new message already re-read `instance.json` (through
`EnsureAgent`) before this change. What was broken was every call made
against the session the TUI already held.

Reproduced by `TestCancelAfterADaemonRestartSaysTheRunEnded` and
`TestDoDoesNotCarryARunScopedCallToARestartedDaemon`: on main the first
fails with "connection refused", and the second can't compile because
main has no way to tell run-scoped calls apart. Both pass here.

## Test plan
- [x] `go vet ./...` clean; `go test -p 1 ./internal/daemon/
./internal/client/ ./internal/ui/preflight/` passes
- [x] Run-scoped calls (cancel, answer, confirmation, follow-up,
permission decision, full access) are never sent to a restarted daemon;
the client still learns the new instance
- [x] Other relayed calls ensure the agent on the restarted daemon, then
replay
(`TestDoEnsuresTheAgentBeforeReplayingARelayCallToARestartedDaemon`)
- [x] A call whose connection drops after a daemon received it is never
replayed (`TestDoNeverReplaysARequestThatReachedTheDaemon`)
- [x] A replacement that fails its checks keeps its typed
`VersionError`/`StaleError` in the chain, plus the original failure
- [x] Live, real TUI against a fake daemon that, like the real one, has
no sidecar after a restart (isolated homes): `/full-access confirm`
after the restart said "GAIA's daemon restarted, which ended the agent
session this belonged to. Nothing was sent", and the restarted daemon
received no `/bypass`. The next message ensured the agent and was
answered. Main says "actively refused it".

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

- `Client.Do` re-reads `instance.json` only on a dial failure
(`*net.OpError` with `Op == "dial"`, reachable through the new
`RequestError.Unwrap`). The new instance goes through the same `verify`
and `CheckVersion` as attach.
- `Request.RunScoped` marks calls about state in a running sidecar. They
return `DaemonRestartedError` together with the new instance. Other
`/v1/<agent>/…` calls run `ensureOn` (split out of `EnsureAgent`, with
its agents-floor check) on the new daemon first.
- A restart on the same port shows up as a rotated token (401) rather
than a refused connection; that path takes the same step, so it is
covered too (`TestDoDoesNotCarryARunScopedCallAcrossASamePortRestart`).
- `SSEClient.do` keeps whichever instance answered, so the six calls
that used to drop it also follow a plain token rotation.
- The client test fake answers 503 "no running sidecar" after a restart
until the agent is ensured, the way the real daemon does.
- The log names the dial's own failure (refused, timed out,
unreachable).
- No overlap with amd#5264/amd#5282 (daemon close) or amd#5237 (sessions).
</details>
# Conflicts:
#	src/gaia/llm/lemonade_embedded.py
@kovtcharov-amd kovtcharov-amd added ready_for_ci Run CI workflows on draft PR without requesting review and removed ready_for_ci Run CI workflows on draft PR without requesting review labels Oct 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

Before this change, a session that met GAIA's own model server in the middle of a restart failed at once with "not reachable", even though the daemon had the server back seconds later. Now it waits up to 60 s, says it is reconnecting, carries on when the server returns, and fails with an error that names a next step. The real-daemon evidence shows all three outcomes. A server the user runs themselves, or one named by LEMONADE_BASE_URL, is still never waited on.

One thing to fix before merge:

  • A new agent session waits 60 s with no message, but the docs say it shows one. When a stdio/TUI session starts while the server is stuck, "Reconnecting…" only goes to the log, so the user sees a minute of nothing. If they then run /model, that waits another 60 s, about two minutes in total. Either emit the reconnecting status during startup too, or make the CLI doc say only requests and /model show it.

Real-world evidence

The evidence stage ran a real gaia daemon on ubuntu-latest (no GPU). To get a server that runs but doesn't answer, it used a placeholder lemond process. None of GAIA's code was stubbed. Excerpts:

$ curl -i -X POST http://127.0.0.1:38161/daemon/v1/lemonade/ensure -H "Authorization: Bearer <redacted>"
HTTP/1.1 503 Service Unavailable
retry-after: 2
{"detail":"GAIA's Lemonade Server (pid 2781) is running but stuck: ... Run `gaia init` to restart it. ..."}
$ gaia llm "Hello"          # server never comes back
Reconnecting to the model server…
❌ GAIA's Lemonade Server at http://localhost:47999/api/v1 stopped answering and was not back within 60s. ... Run `gaia daemon status`, and read the daemon log at ...
exit=1  elapsed=61s
$ gaia llm "Hello"          # server comes back at +8s
Reconnecting to the model server…
[08:47:40] INFO | ... Preloading 'Gemma-4-E4B-it-GGUF' ...   (wait ended; later preload error expected — stub serves no model)
elapsed=9s
# stdio /model, server returns 6 s into the switch's wait
+ 60.9s {"type": "status", "status": "working", "message": "Reconnecting to the model server…", "phase": "reconnecting"}
+ 66.9s [driver] server on :47999 is answering again
+ 68.9s {"type": "error", "detail": "Unknown Lemonade model 'Qwen3-0.6B-GGUF'. ..."}   (expected: stub lists no models)
  • LEMONADE_BASE_URL pointing at a dead server: no wait (0 "Reconnecting" lines, 1 s).
  • Spot checks all came back as expected: the 409 when nothing is installed, the 401 without a token, gaia lemonade embedded status, and gaia daemon status.
  • Not exercised here: the rendered TUI and Agent UI "Reconnecting" phase is pending the strix-halo lane, and so is a real lemond restarted mid-turn (the retry-once path inside a request). The verdict on those rests on static review.
🔍 Technical details

Issues

🟡 Session-start wait is silent, and the doc says it isn't (docs/reference/cli.mdx:3232, src/gaia/llm/lemonade_manager.py _wait_for_gaia_lemonade)
At agent startup ensure_ready runs with quiet=True, so on_status is None and stdio emits nothing for up to 60 s. The evidence log shows the first stdio event at +60.9 s. A following /model then calls wait_for_gaia_lemonade again for another 60 s. There are two options. One is to thread a status callback into the startup wait so stdio can write a phase: "reconnecting" status event, which would also make the doc true. The other is to narrow the doc:

- **A server that is briefly not answering is waited for.** A request or a
  `/model` switch that finds GAIA's server unreachable shows
  "Reconnecting to the model server…" and waits up to 60 seconds while the daemon brings it
  back, then carries on; a new session waits the same way while it starts. If it is not back by then, the request fails with an
  error that says so and points at `gaia daemon status`. A Lemonade you run
  yourself, or one `LEMONADE_BASE_URL` names, is never waited on.

🟢 LemonadeManager._wait_for_gaia_lemonade ignores the bool result (src/gaia/llm/lemonade_manager.py)
wait_for_gaia_lemonade returns False both for "not GAIA's server" and for "answered where it already pointed", and the helper treats both as success. That holds today because the gaia_runs_lemonade(...) guard comes first. A one-line comment saying so would stop a later caller from depending on it in the wrong context.

Strengths

  • Makes "not answering" its own error type, all the way through: EmbeddedLemonadeNotAnswering, then a 503 with Retry-After, then LemonadeNotAnsweringError, then GaiaLemonadeNotAnsweringError. A failed start stays an immediate 503, and an older daemon (no header) fails as before. This is fail-loudly done right.
  • The 60 s wait is a bounded, explicit poll with an injectable clock and sleep, and its final error carries the daemon's own reason and the log path.
  • Strong tests. The end-to-end TestTheRegression mocks only at the HTTP, daemon and socket boundaries and asserts the outgoing request's shape (URL, bearer headers). Other tests cover the 16-session stress case, the user's and remote servers never being waited on, and a stale default port never restarting a server another session leases.

The CLI reference said every new session shows "Reconnecting to the model
server…" while it waits, but an agent session starts quietly, so the
message only reaches the log. The doc now says so, and the manager notes
why it can ignore the wait's False result.
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 19, 2026
Merged via the queue into main with commit 1851259 Oct 19, 2026
106 of 109 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the fix/lemonade-restart-wait branch October 19, 2026 10:17
@kovtcharov-amd
kovtcharov-amd restored the fix/lemonade-restart-wait branch October 19, 2026 10:21
@kovtcharov-amd
kovtcharov-amd deleted the fix/lemonade-restart-wait branch October 19, 2026 10:21
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
…erver (amd#5282)

Stacked on amd#5264. Closing one TUI session on Windows killed GAIA's
daemon and model server for every other session, and that is the "server
stopped answering ~15 s after it was ready" behind amd#5261. The TUI runs
each session's agent in a kill-on-close job, so a daemon started by that
agent joined the job and died with it. Now the daemon and its server
leave the job when they start. Live tests against a real, restarting
server also found four gaps in amd#5264's wait, fixed here. `/model` during
a restart still said "not reachable". A server that never came back took
~105 s to fail, not ~60. Embeddings were never waited for, and a cloud
key replay after a restart crashed the turn.

**Measured on an isolated GAIA home with a real lemond, `main` vs this
branch:**

| Run | `main` | this branch |
|---|---|---|
| Closing the session that started the daemon | daemon + server killed |
both keep running |
| 16 back-to-back TUI sessions, each `/model` to a cloud model | 16/16
ok; **every close killed the daemon**; median switch 16.6 s | 16/16 ok;
daemon never killed; median 5.5 s |
| 16 overlapping TUI sessions (the incident's shape) | 16/16 ok; 5
closes killed the daemon | 16/16 ok; none |
| `/model` while the server restarts | **"Lemonade Server is not
reachable"** | switches |
| Server never returns | fails at 50 s, without pointing at the daemon |
fails at ~83 s naming `gaia daemon status` (60 s wait + Windows
refused-connect time) |
| 16 concurrent sessions, 480 mixed local/cloud/embedding turns, 3
server crashes | 6 failed (embeddings) | 0 failed; 15 turns rode a
restart (median 23 s, max 27 s) |
| Agent UI under its own `GAIA_HOME`, 1-min idle timeout | — | leased;
kept 150 s past the timeout; a restart was followed across homes;
stopped 66 s after the UI closed |

A user's own lemond, killed mid-session, and an unreachable remote
`LEMONADE_BASE_URL` were never waited on or restarted, and the daemon
was never asked (live and mocked).

## How to reproduce

```
python util/lemonade_restart_harness.py repro                       # every scenario, this checkout
python util/lemonade_restart_harness.py --code <export of main> repro model_switch_during_restart
python util/lemonade_restart_harness.py tui --tui-exe <gaia-tui.exe> --sessions 16 --overlap
python util/lemonade_restart_harness.py stress --sessions 16 --turns 30 --min-gap 40 --max-gap 80
python util/lemonade_restart_harness.py ui-lease
```

Everything runs under a temp `GAIA_HOME` and user profile with its own
daemon and port. lemond is copied from `~/.gaia/lemonade` (or
downloaded), cloud turns go to a local stub registered as the `amd`
provider, and no other Lemonade is touched.

## Test plan

- [x] `python -m pytest tests/unit/test_lemonade_restart_wait.py
hub/agents/gaia/python/tests/test_stdio_lemonade_reconnect.py`: 254
passed (Windows, isolated `GAIA_HOME`)
- [x] `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`: 219 passed
- [x] `python -m pytest tests/unit/test_background_spawn_leaves_job.py
tests/unit/test_windows_hidden_console.py tests/unit/test_gateway.py
tests/unit/test_llm_retry*.py`: 275 passed
- [x] `go test ./internal/client` (tui): ok.
`TestAgentJobKeepsOnlyABreakawayChild` fails without the `BREAKAWAY_OK`
flag.
- [x] `python util/lint.py --black --isort --flake8 --pylint
--test-lanes`: all pass
- [x] `python -m pytest tests/integration/test_lemonade_restart_live.py`
on Windows with a real lemond: 9 passed (6 min 48 s)
- [x] On Windows, 16 back-to-back `gaia-tui` sessions that each `/model`
to a cloud model: none ends "not reachable" (also 16 overlapping)
- [ ] CI: Unit Tests (Linux, Windows), Code Quality

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

**Root cause.** `tui/internal/client/procgroup_windows.go` puts the
agent in a `KILL_ON_JOB_CLOSE` job. `start_or_attach` spawns the daemon
from the agent with no breakaway, so the daemon (and the lemond it
spawns) join that job. Unix was never affected: `start_new_session`
escapes the TUI's process-group kill.
- The TUI job now sets `JOB_OBJECT_LIMIT_BREAKAWAY_OK`.
- `popen_outliving_job` (`gaia.utils.terminal`) adds
`CREATE_BREAKAWAY_FROM_JOB` for the daemon and embedded-lemond spawns.
On `ERROR_ACCESS_DENIED` it starts in the job and warns.
- Measured: breakaway leaves only the immediate job, and only if it
allows it. `QueryInformationJobObject(NULL)` reports the outermost job,
so nothing queries it. With the flag where breakaway isn't allowed,
Python's `Popen` silently stays in the job and Go's `exec` is refused.
Both outcomes behave as before.

**Wait fixes.**
- stdio checks `follows_gaia_lemonade` (new passthrough on
`LemonadeProvider`) instead of reading `wait_for_gaia_lemonade() is
False` as "not GAIA's server".
- `ModelCallRetrier` gains `hand_off`, consulted only before output. For
the two `chat_completions` sites, a connection failure that
`_gaia_lemonade_gone()` confirms skips the backoff. A per-thread flag
makes `_recover_stopped_gaia_lemonade` resend even if the server is back
by its own probe.
- `embeddings` goes through `_survive_gaia_lemonade_stop`.
- `GatewayManager._http_error` accepts `{"error": "<text>"}`.

**Unit tier added:** 200 randomized-gap seeds asserting the whole turn,
retry backoff included, stays within bound + one poll. Also 20 seeds of
16 overlapping `ensure()` calls that never start twice or stop, an older
daemon without `Retry-After`, a stream cut after output keeping its
retry state, and embeddings during a restart. Without the bound fix, 87
of them fail.

**Run against which code.** The TUI and the first chaos runs used this
branch before the embeddings, gateway and hand-off refinements. The
480-turn chaos run, the Agent UI run and the 9 live tests used the final
commit.

**Not fixed here.**
- Under a crash every 8–25 s with 16 clients, turns still fail. Each
resend after a successful reconnect is hit by the next crash, and the
policy is one resend.
- The live test is allowlisted, not in a lane: ~7 min, and its job case
needs Windows. Wiring it into a Windows lane is a follow-up.
- `~/.gaia/gaia.log` ignores `GAIA_HOME`, so tests under temp homes
write into the real log.
- The harness's hung restart is for single clients only. Under many, a
suspended-at-birth lemond can fail the daemon's identity check, and the
daemon starts a second one on the same port.
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 21, 2026
…server (amd#5444)

While GAIA waits for its own model server to come back, each 2-second
poll asked the daemon to start the server twice when no server was
recorded. That doubled the daemon calls and cloud-key replays for up to
60 seconds. Now each poll asks once. This was the remaining open note
from the amd#5264 review; the rest landed in amd#5282.

## Test plan

- [x] `python -m pytest tests/unit/test_lemonade_restart_wait.py
tests/unit/test_lemonade_follows_restart.py
tests/unit/test_lemonade_survives_idle_stop.py
tests/unit/test_daemon_lemonade.py
hub/agents/gaia/python/tests/test_stdio_lemonade_reconnect.py`: 336
passed (Windows). The new
`test_with_nothing_recorded_each_poll_asks_the_daemon_once` fails on
`main`.
- [x] `python util/lint.py --black --isort --flake8 --pylint
--test-lanes`: all pass
- [ ] CI: Unit Tests (Linux, Windows), Code Quality

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

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

1 participant