Skip to content

fix(lemonade): stop calling a busy shared server stalled, and retry a stolen port - #5314

Merged
kovtcharov-amd merged 10 commits into
amd:mainfrom
kovtcharov:fix/lemonade-busy-not-stalled
Oct 19, 2026
Merged

kovtcharov-amd merged 10 commits into
amd:mainfrom
kovtcharov:fix/lemonade-busy-not-stalled

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

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.

Captured output of that run
===== 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

Merging with #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.

🔍 Technical details
  • 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 fix(lemonade): wait for GAIA's restarted model server instead of failing the turn #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.

Test plan

  • 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")
  • 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
  • python util/lint.py --black --isort --flake8 --pylint --test-lanes: all pass
  • 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

… stolen port

A GAIA Lemonade swapping models looked dead to every other client, which
were told to stop it. Lemonade's /health waits on the router lock that an
eviction holds until the old model's in-flight request drains, so on a
shared machine it can miss a 3 s probe for minutes. A server that also
answers the lock-free /live is now reported running and busy: callers reuse
it and requests queue. Busy for longer than lemond's own request budget, it
counts as stalled again, so a wedged server still gets an actionable error.

The daemon's supervisor made the same mistake with a system install and
called a slow port a stranger after 20 s. It now attaches when the port
answers /live and lemond's /docs index.

Starting GAIA's server on a port it chose could fail when another program
bound that port first: lemond exits 1 when either loopback address is held.
GAIA now retries on a new port, logging each retry, at most three times
within the one start deadline. A port the caller named is never swapped.
@github-actions github-actions Bot added documentation Documentation changes llm LLM backend changes cli CLI changes tests Test changes performance Performance-critical changes labels Oct 18, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

Before this PR, GAIA called its own Lemonade dead while the server was swapping models, and gaia init restarted it. It also failed to start when another program took its chosen port first. Now a server that still answers Lemonade's lock-free liveness check counts as busy and gets reused, up to a time limit, and a port that was taken before Lemonade bound it gets retried on a new port, at most three times. I found nothing blocking. The checks are narrow where it matters: liveness alone never proves the server is GAIA's, and a port the user named is never swapped.

One gap is worth a follow-up. The time limit on "busy" only covers GAIA's own server. If a system install on the default port gets stuck while still answering liveness, GAIA now attaches to it with no limit. Before, it gave an immediate "port occupied" error.

Real-world evidence

N/A here: no evidence bundle was produced for this run. The PR description reports a manual run against a real isolated lemond (2026.40.0). On main it showed "not answering… run stop"; on this branch it showed running and busy. That report is a prose summary, not captured output, so this verdict rests on the code review plus the new socket-level tests for the gaia lemonade embedded status / gaia init surfaces.

🔍 Technical details

Issues

🟢 Supervisor's busy check has no time limit (src/gaia/llm/lemonade_supervisor.py, _busy_lemonade / _start_locked). On the embedded side, busy is capped by _busy_limit() and tracked in busy_since.json. The system-install path returns False ("already running") whenever /live plus the /api/v1/docs index answer, however long health has been stuck. Such a server can't be stopped by GAIA, so the old error at least told the user. Consider logging a warning (or raising _occupied_port_error) once the slow-health state outlasts request_budget_seconds(). A module-level timestamp would be enough; it doesn't need to persist.

🟢 CLI evidence is prose, not output. The status output gains a new busy loading or swapping a model line, but the PR body only describes it. Pasting the real gaia lemonade embedded status output from the isolated-lemond run would close this out.

🟢 status() now writes to disk (_busy_for creates busy_since.json). That's fine as written: only the first busy sighting writes, and _clear_state and a healthy probe both clear it. A line in the status() docstring saying a busy sighting is recorded would keep a future caller from treating it as read-only.

Checked, no issue

  • Port retry only triggers when GAIA chose the port, lemond has exited, and _port_free reports it held. _port_free already handles POSIX TIME_WAIT via SO_REUSEPORT, so a lemond that crashed after binding won't be misread as a stolen port.
  • _discard only clears state when the recorded pid is the failed process, so a racing start that took over is preserved. All attempts share one deadline.
  • Busy status keeps version from state, so the version-mismatch checks in daemon/lemonade.py and init_command.py still work. unresponsive_pid stays unset while busy, so gaia init no longer restarts a server that is mid-swap.
  • Docs (troubleshooting.mdx) cover both new messages.

Strengths

  • Tests use real loopback servers and real child processes rather than mocks. That's the right level for socket-race bugs. test_fake_lemond_matches_the_real_bind_rule also guards the fake against drifting from real lemond.
  • Identity stays tied to the pid/key gate (_identify == OWN) rather than to unauthenticated /live. test_liveness_alone_never_vouches_for_another_process pins this.
  • Pulling _spawn, _wait_healthy and _discard out of start() makes the retry loop easy to follow.

…monade-lifecycle-a3c88f

# Conflicts:
#	src/gaia/llm/lemonade_embedded.py
A system Lemonade stuck with its router lock held still answers /live, so
the supervisor would attach to it forever. Past lemond's request budget it
now raises an error naming how to restart it, the same bound GAIA's own
server already had.

The port-retry test's fake lemond also stopped answering on macOS CI: its
HTTPServer did a reverse DNS lookup on bind, and the test probe read the
system proxy. Both fakes now bind without the lookup, and the probe goes
direct.
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Addressed all three suggestions, and fixed the red macOS check.

  • Supervisor busy had no time limit: fixed. A system server busy for longer than any request may run now gets an error with the restart command, the same bound GAIA's own server has.
  • CLI evidence was prose: the PR body now has the captured output of the real isolated-lemond run.
  • status() writes to disk: its docstring now says so.
🔍 Technical details
  • Supervisor: _attach_if_busy records the first busy sighting per (host, port) and raises LemonadeStartError past busy_limit() (request_budget_seconds() + 60). Covered by test_busy_longer_than_any_request_is_an_error.
  • macOS failure (test_a_lost_port_is_retried_on_a_new_one): the retry itself worked (port 49550 → 49553), but the test's fake lemond never answered within 30 s. Both fakes now skip HTTPServer's reverse DNS lookup on bind, and the test's probe uses a proxy-free opener. The exact macOS cause isn't confirmed locally, since there's no Mac here; the next CI run will tell.

@github-actions

Copy link
Copy Markdown
Contributor

🟡 The new "stuck server" timer never resets once the server recovers, so a later, ordinary model swap gets reported as a wedged server.

The daemon keeps one supervisor for its whole life. The first time a system Lemonade is busy, its start time is recorded. That record is only cleared if the supervisor later sees the port open, not busy, and not healthy. When the server simply recovers and answers health, the record stays. Hours later the next model swap makes it busy again. The supervisor then measures from the first busy moment, decides the server has been busy for hours, and fails the request with "restart it". Clear the record whenever health answers, and add a test for busy → healthy → busy again.

🔍 Technical details
  • src/gaia/llm/lemonade_supervisor.py:419-424: _attach_if_busy pops _busy_since[key] only when _busy_lemonade(client) is false. That branch runs only from _start_locked, which runs only after _probe failed.
  • ensure_running returns early when _probe(client) succeeds (both the fast path and the re-probe under the lock), and _wait_for_health succeeding returns False the same way. None of these clear the entry.
  • LemonadeSupervisor is built once in src/gaia/daemon/server.py:347, so a stale entry lives until the daemon restarts.

Simplest fix: in ensure_running, after a successful _probe, call self._busy_since.pop((client.host, client.port), None). Do the same after _wait_for_health returns true. The dict is touched outside self._lock on the fast path, but a single pop is atomic under the GIL.

…orking

The busy limit from the previous commit counted time between sightings, so
a swap seen hours after an earlier one read as hours busy and `gaia init`
restarted a working server, while a truly wedged one was never caught
because nothing polls status() often enough. Each sighting now records the
cumulative CPU and disk counters of lemond's backend processes; the server
counts as stuck only when a later sighting finds exactly the same backends
with exactly the same counters more than five minutes on. Any work, or a
backend starting or exiting, restarts the record, and no evidence never
yields a verdict.

On a real lemond 2026.40.0 holding its router lock for an eviction, the
llama-server's counters rose ~10 s per second and /api/v1/docs answered in
0.02 s; the supervisor's fingerprint test now serves that recorded body.
The supervisor also drops its record whenever health answers, so a server
that recovered starts fresh at its next swap.
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Fixed. The supervisor now drops its record whenever health answers, on both probes and after the grace wait, so a server that recovered starts fresh at its next swap. test_a_recovered_server_starts_fresh_at_its_next_swap covers busy → healthy → busy.

That record also no longer measures time. It now holds the backends' CPU and disk counters, and a server counts as stuck only when they haven't moved at all for five minutes. So even a record that outlived a recovery can't flag a server that did any work since.

…isteners

An unreadable backend process was dropped from the activity snapshot, so a
working server whose backend GAIA could not read looked idle and was called
stuck after five minutes. It now counts as no evidence, which never yields a
verdict. On macOS the supervisor could never find a system server's pid,
because the machine-wide socket table needs root; it now walks the user's
own processes when that table is refused.

Tests now fail without each fix they cover: the record reset on a healthy
probe and on clear, the supervisor attaching before the stranger grace, and
the /docs format check, against a stranger that answers /live and /docs.
The troubleshooting page and docstrings quote the current messages.
A loading server now reads as running and busy, so one the daemon reports
as not answering is stuck: "wait and retry" no longer helps, `gaia init`
does. The troubleshooting page gains an entry for the "stuck rather than
loading a model" error the supervisor links to.

Two more tests now fail without the code they cover: a server that turns
busy during the stranger grace window, and a replaced backend that lands on
the old one's exact counter.
@github-actions github-actions Bot added the daemon Daemon supervisor / sidecar control plane label Oct 18, 2026
… can't

A machine suspended past the quiet window froze the backends' counters while
the clock ran, so the first check after waking found identical counters more
than five minutes apart and called a working server stuck; `gaia init` then
restarted it. Both GAIA's own server and the supervisor now sample again a
few seconds later before that verdict, and any movement, or a sample that
can't be read, counts as busy.

The troubleshooting entry now quotes GAIA's own messages ("running but
stuck", "running but not answering") with the same remedy start() gives, and
an unrelated accordion icon changed by an earlier edit is restored.
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 19, 2026
Merged via the queue into amd:main with commit ade5bab Oct 19, 2026
69 of 70 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the fix/lemonade-busy-not-stalled branch October 19, 2026 08:28
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
…d#5352)

When GAIA's own Lemonade server crashed or was killed by itself, its
model servers kept running. Each one holds gigabytes of memory, and the
next start loaded the same models again beside them, doubling GPU and
RAM use. On one machine a Gemma and an embedding server ran for about 30
hours after their server died. Now GAIA stops them when it starts its
server, and when it finds the old one gone. It stops a process only when
it runs from GAIA's own install and the process that started it has
exited. Another Lemonade's processes, a live server's, and a tool such
as `llama-bench` that you run from a terminal are never touched.

Reproduced by `tests/unit/test_lemonade_orphaned_backends.py`: on main,
two of its real-process tests fail with the symptom ("the dead lemond's
llama-server is still running"), and the others fail because the reaper
doesn't exist yet. All pass here. Each runs a real process tree on
Windows: a copy of the interpreter stands in for `llama-server.exe`
under the install's `cache/bin`, and the test kills its stand-in lemond
without the tree.

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

- `EmbeddedLemonade._reap_orphaned_backends()` runs from `_start_locked`
before spawning, and from `status()` only when the recorded lemond is
gone. A healthy `status()` never scans, and a test pins that.
- A process qualifies only when its executable resolves under
`<GAIA_HOME>/lemonade/cache/bin` and its anchor is gone, or its pid now
names a younger process. The anchor is the parent on Windows, which
never reparents. On POSIX it is the session leader: lemond starts its
own session, and an orphan reparented to init or a subreaper stays in
it. An anchor the OS hides counts as alive.
- The scan filters on the file names in `cache/bin` before reading any
process's path or parent, which takes ~0.1 s instead of ~5–8 s on a
machine with ~400 processes. It then waits up to 5 s for the killed
servers to exit, so the next model load sees their memory free.
- Each stop is logged with its pid. If GAIA may not stop one, the
warning names the pid and how to end it by hand.
- A read-only dry run on the reporting machine kept the live lemond's
four backends and singled out the two orphans of the dead one (a
`whisper-server` and a `koko`). They were left running for the user to
decide.
- Reviewed independently twice. The first review found a 5 s scan,
leaking tests, a timing sleep, a leftover fake pid, a missing wait for
exit, and uncovered branches. The second found that a user's terminal
tool from `cache/bin` was killed. That one is fixed by the anchor rule
above, with a real-process test, plus POSIX reparenting and pid-reuse
cases. A gone server's record is now cleared only if no new start
recorded itself meanwhile, and a start scans once. Removing each of
those guards fails its test. The real-process tests are Windows-only;
Linux and macOS run the portable `TestOrphanedBackends` cases.
- Independent of amd#5314. Both add methods after `status()`, so they
conflict on text: keep both.
</details>

## Test plan

- [x] `python -m pytest tests/unit/test_lemonade_orphaned_backends.py
tests/unit/test_lemonade_embedded.py`: 91 passed, no stray processes
left (Windows)
- [x] The real-process tests on `origin/main`: the status and start
cases fail with the symptom
- [x] Related suites (`test_lemonade_embedded*`,
`test_daemon_lemonade*`, `test_init_command`,
`test_cli_lemonade_embedded`, uninstall, restart and child-env tests):
660 passed, isolated `GAIA_HOME`
- [x] `python util/lint.py --black --isort --flake8 --pylint
--test-lanes`: all pass
- [ ] CI: Unit Tests (Linux, Windows, macOS), 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

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

2 participants