Repository navigation
fix(lemonade): wait for GAIA's restarted model server instead of failing the turn - #5264
Conversation
|
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:
Real-world evidenceThe CI evidence stage ran the real daemon on ubuntu-latest (no GPU). It staged a GAIA Lemonade process that is alive but never answers.
🔍 Technical details🟡 Docs overclaim: the startup path never waits (
🟢 Redundant second start inside the wait loop ( When no state file exists, Strengths
|
…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.
7976a87 to
83ecb93
Compare
|
Verdict: Approve with suggestions When GAIA's own model server briefly stops answering, a turn or One gap is worth closing before merge, or else documenting:
Real-world evidenceThe evidence stage ran the real daemon,
{"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 The bundle also noted that with 🔍 Technical details🟡 "Back" means the port is open, but "not answering" means health failed (
Suggested fix: make the loop's exit condition a short health probe (as 🟢 A failure that isn't about reachability (for example a malformed catalog) still goes through 🟢 The 60 s bound can be exceeded. The PR body already says so: a cold start inside a single Strengths
|
… 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]>
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
|
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 One thing to fix before merge:
Real-world evidenceThe evidence stage ran a real
🔍 Technical detailsIssues 🟡 Session-start wait is silent, and the doc says it isn't ( 🟢 Strengths
|
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.
…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]>
…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]>
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 remoteLEMONADE_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/ensurenow returns 503 withRetry-Afterfor "running but not answering" (EmbeddedLemonadeNotAnswering), andensure_lemonaderaisesLemonadeNotAnsweringErrorfor 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_lemonadepath every 2 s. Both_recover_stopped_gaia_lemonade(mid-turn, viamodel_load_listener(model, "reconnecting")) and/model(stdiostatusevent,phase: "reconnecting") use it.ensurecall can run past it, up to that call's 80 s timeout.tests/unit/test_lemonade*.pyon this machine fails the same ~135 tests on baremain. A live GAIA install's~/.gaia/lemonade/state.jsonleaks into them.Test plan
python -m pytest tests/unit/test_lemonade_restart_wait.py hub/agents/gaia/python/tests/test_stdio_lemonade_reconnect.pycovers the race, the 60 s bound, the user's and remote servers, the stale-port follow, and the 16-session stress testpython -m pytest tests/unit/test_lemonade_survives_idle_stop.py tests/unit/test_daemon_lemonade*.py hub/agents/gaia/python/tests/test_stdio.pypython util/lint.py --black --isort --flake8 --pylint --test-lanesgaia-tuisessions that each/modelto a cloud model, and check that none ends with "not reachable"