Repository navigation
fix(lemonade): ignore a dead embedded server's leftover state file - #4284
github-actions[bot] wants to merge 2 commits into
Conversation
A killed or crashed `gaia lemonade embedded` cannot clear ~/.gaia/lemonade/state.json, and every client read that file ahead of the default — so `gaia llm`, the Agent SDK and the API server all dialled the port it once held and reported Lemonade as down while a healthy server answered on 13305. The only cure was deleting a file users have never heard of; on the persistent Windows runner it failed the Agent SDK lane on three unrelated branches. The state file is now honoured only while the pid it records is still a live lemond. Gating inside the reader covers the credential path too, so a dead instance stops donating its API key as well as its port, and the fallback warns once naming the file instead of failing silently. Liveness is checked with psutil rather than reusing EmbeddedLemonade._daemon_alive: this sits on the base-URL resolution path that every client construction and UI health poll crosses, where ps and tasklist would mean a subprocess per request. It keeps the same image-name rule, so a recycled pid never passes, and fails closed. Closes #4281
kovtcharov-amd
left a comment
There was a problem hiding this comment.
The fix is correct — I verified it end-to-end against real processes, not mocks. But the regression tests don't actually catch the bug: I reintroduced #4281 in one line and the whole suite stayed green.
The four tests that prove "a stale file no longer hijacks the endpoint" all replace the liveness check with a lambda, so they only prove the resolver calls something. The two tests that run the real check feed it type-garbage and this test process's own pid. Nothing anywhere feeds it a pid that is genuinely gone — which is the one condition #4281 is about. Revert the fix and the tests go red, but only because the mocked symbol disappears; ship a fix that gets dead pids wrong and they stay green.
One unmocked test closes it — code below, it costs about a second and needs no fixture changes.
🔍 Technical details
The mutation. With this one change to _embedded_lemonade_alive — the exact #4281 behaviour, a dead daemon's state file honoured:
try:
return "lemond" in psutil.Process(pid).name().lower()
except psutil.NoSuchProcess:
return True # <- bug reintroduced
except (psutil.Error, OSError, ValueError):
return Falsepytest tests/unit/test_lemonade_client_api_key.py tests/unit/test_base_agent_lemonade_api_key.py tests/unit/test_lemonade_asr.py → 157 passed (the single failure is TestRealServer::test_real_transcription_round_trip, a pre-existing 401 on my box against a running Lemonade — unrelated).
Reverting lemonade_client.py to base instead gives 16 failures / 54 errors, but every one is AttributeError: module 'gaia.llm.lemonade_client' has no attribute '_embedded_lemonade_alive' from the monkeypatch.setattr in the fixtures — a missing-symbol error, not a behavioural failure.
The missing test. Spawns a process, waits for it, and uses the pid it just vacated, so the real psutil path runs against a pid that is genuinely gone:
def reaped_pid() -> int:
"""A pid that really is gone: spawned, waited on, and exited.
Beats a made-up number — the liveness check runs for real against it, so
the dead-state path is exercised end to end rather than mocked past.
"""
process = subprocess.Popen(
[sys.executable, "-c", "pass"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
process.wait(timeout=60)
return process.pid
def closed_port() -> int:
"""A port nothing is listening on — the stale file's recorded port."""
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
return sock.getsockname()[1]
def test_a_dead_daemon_does_not_hijack_the_endpoint(self, tmp_path, monkeypatch, caplog):
"""Regression: a stale file made a healthy server on 13305 invisible.
No stub on the liveness check — a fix that gets real dead pids wrong
has to fail here.
"""
monkeypatch.delenv("GAIA_HOME", raising=False)
monkeypatch.delenv("LEMONADE_BASE_URL", raising=False)
monkeypatch.delenv("LEMONADE_API_KEY", raising=False)
monkeypatch.setattr(lc, "_WARNED_STALE_EMBEDDED_STATE", set())
dead, port = reaped_pid(), closed_port()
path = tmp_path / "state.json"
path.write_text(
json.dumps({"pid": dead, "port": port, "api_key": "stale-key"}),
encoding="utf-8",
)
monkeypatch.setattr(lc, "EMBEDDED_LEMONADE_STATE", path)
caplog.set_level(logging.WARNING, logger="gaia.llm.lemonade_client")
assert lc.resolve_lemonade_base_url() == lc.DEFAULT_LEMONADE_URL
assert lc._get_lemonade_config()[1] == lc.DEFAULT_PORT
assert lc.resolve_lemonade_api_key() is None
warning = "\n".join(
r.getMessage() for r in caplog.records if r.levelno >= logging.WARNING
)
assert str(path) in warning and str(port) in warning and str(dead) in warningFails on the mutated build above; passes on this branch. It also subsumes test_dead_pid_does_not_change_the_base_url, test_dead_pid_does_not_hand_out_its_key and test_the_fallback_names_the_leftover_file — those three could keep their stubs or go, either way.
What I checked and found fine, running against this branch with real processes rather than stubs:
| behaviour | result |
|---|---|
| real reaped pid + closed port | falls back to DEFAULT_LEMONADE_URL, key None |
| pid reuse — recorded pid now an unrelated live process | falls back (image-name match, not mere existence) |
state file with no pid key at all |
falls back, warns with pid None — fail-closed, and deliberate |
LEMONADE_BASE_URL set alongside a stale file |
env still wins unconditionally |
| warning | names path, port and pid, once per (path, pid) |
psutil over importing EmbeddedLemonade._daemon_alive is the right call on the resolution path, and the docstring already says why — no import cycle either way, since lemonade_embedded only pulls gaia.logger and gaia.version.
Scope. The three existing test files and the ai-providers.mdx paragraph all had to move: the test files write state fixtures that would now read as stale, and the doc states the credential-resolution order this changes. Not scope creep.
One inverse failure mode, not a blocker. The client now decides liveness by pid alone, whereas EmbeddedLemonade.status() health-probes first and treats the process check as a second opinion. If psutil.Process(pid).name() ever raises AccessDenied — a lemond started elevated or under another user while the client is not — a live embedded server fails closed and every request silently moves to 13305. psutil's Windows name() has a snapshot fallback that usually avoids this, so it may never fire in practice; the warning at least names the file when it does.
|
Follow-up to my review above, with two things about CI. The Windows job that reproduces this bug has never run on this PR. It skips drafts, so the only checks here are CodeQL and friends — a fix for a CI failure whose own CI never exercised it. Worth fixing before merge. A manual run of that job on this branch did prove the fix, though — and more convincingly than a plain green tick would. The runner still had the poisoned state file on it, and the log shows the new warning firing against it: port 59939, the exact port from the #4281 report. The tests then ran on 13305 and passed. So this is not "no stale file happened to exist that day" — the stale path was genuinely taken and the fix stepped over it. That warning line is what makes the run readable; without it a pass would have been ambiguous. One caveat on getting the job to run here: the 🔍 Technical detailsThe gate — if: github.event_name != 'pull_request' || github.event.pull_request.draft == false || contains(github.event.pull_request.labels.*.name, 'ready_for_ci')and its triggers on line 23: types: [opened, synchronize, reopened, ready_for_review]
The dispatched run — Every endpoint in the log is The runner is persistent, so Still the gap from my earlier review: this run proves the shipped implementation behaves, not that the tests would catch it breaking. Reintroducing #4281 as a one-line change to |
|
Verdict: Approve A leftover state file from a dead embedded Lemonade no longer redirects every client to a port nothing is listening on — the file is only trusted while the process it names is still a live Two things I looked at specifically and found sound: the state file has recorded a pid since the embedded server shipped, so there's no older-install shape that now gets ignored; and the recorded pid really is the daemon binary, not a wrapper, so matching on the image name holds. The one behaviour worth knowing: any pid the check can't positively identify counts as gone, so an unverifiable file loses to the default port rather than hijacking traffic — the right default here, and the reason the fix is safe to ship. Nothing blocking. The manual boxes in the test plan (a real Real-world evidence
Stale file (dead pid recorded) — the recorded port saw zero requests, and the warning names the file: Same file naming a live The HTTP API showed the same split on Deferred: the rendered Agent UI screenshot — pending strix-halo lane (no real inference on this runner). I could not run pytest in this environment (not installed), so the new unit tests rest on CI; the CLI and API behaviour above is observed, not inferred. 🔍 Technical detailsStrengths
🟢 Minor
|
The existing regression tests replaced `_embedded_lemonade_alive` with a lambda, so they pinned the wiring but not the check itself. Reintroducing #4281 as a one-line change — `except psutil.NoSuchProcess: return True` — left the whole suite green, which means a fix that got dead pids wrong would have shipped unnoticed. This test spawns a process, waits for it, and writes the pid it just vacated into the state file, so the real psutil check runs against a pid that is genuinely gone. Against the mutated build it is the only failure; the other thirteen still pass.
Verdict: ApproveA killed or crashed embedded Lemonade used to leave behind a file that quietly redirected every GAIA client to a port with nothing on it — so Nothing blocking. Two small things worth a look: the "is this really the Lemonade daemon?" rule now exists in three places in the tree and will drift unless one of them becomes the owner, and the new warning also fires for people who deliberately point GAIA at a different server, where its advice ("start the embedded server") doesn't fit what they're doing. One caveat the author already flagged and I agree with: this lane can't run a real Real-world evidence
$ GAIA_HOME=/tmp/ev/home PYTHONPATH=/tmp/ev/base/src python -c "..." # BEFORE
base_url : http://localhost:58125/api/v1 ← dead port
api_key : stale-key ← credential for a port with nothing on it
$ GAIA_HOME=/tmp/ev/home PYTHONPATH=/home/runner/work/gaia/gaia/src python -c "..." # AFTER
WARNING | ... | Ignoring /tmp/ev/home/lemonade/state.json: ... port 58125 under pid 10863 ...
base_url : http://localhost:13305/api/v1
api_key : NoneThe real I also ran the affected suites locally: The bundle's own observation — that the warning fires even when 🔍 Technical detailsIssues🟢 The "is this pid our daemon?" rule now lives in three places (
🟢 The warning also fires for users who aren't using the embedded server ( With Strengths
|
…md#4186) The website, the Agent UI, and the terminal each carried their own palette, so GAIA's copper appeared as three near-but-unequal golds and the same assistant looked like three products. All three now implement one set of colour roles from one set of literals, and each surface has a test that fails when a component writes a hex inline instead of asking for a role. `docs/spec/gaia-design-language.mdx` is the source of truth for what the roles are, what contrast each owes the reader, and why the light copper is not a darkening of the dark one. Implements milestone 0 of the redesign plan in amd#3803, plus the theming half of milestone 5. The shell simplification (milestone 2) stacks on top of this in a follow-up. ## What it looks like The welcome headline used to keep a cursor blinking at a sentence nothing was writing to — the first thing every new user saw. The chat transcript had the same defect. Both now go quiet the moment the text stops. | Before | After | | --- | --- | |  |  | |  |  | Dark mode on the same palette — copper is the only accent; green and amber appear solely as status, never decoration:   The agent-picker grid under the headline is the surface milestone 2 removes — the shell is being rebuilt around the flagship agent, not a hub of them. ## The other threads - **The website now offers both downloads.** It advertised the desktop app only, so the terminal build — which ships six platform targets to the desktop's three — was invisible to anyone who did not already know it existed. Both are presented side by side, and asymmetric platform coverage raises an actionable error instead of rendering an empty card. - **Three controls had no visible keyboard focus at all**, light-theme status badges read below 4.5:1, and picking an agent then clicking a welcome chip quietly opened a session on a different one. All three shipped green because the guards meant to catch them each matched exactly one spelling of the mistake. ## Two design calls worth a second opinion Both change what users see, so please push back if you disagree rather than let them ride in: - **Tools in the activity list no longer have their own colours.** Green, amber, red, and blue carry status meaning, so they are not available for decoration — keeping the per-tool table meant a green tool badge sitting directly beside a red failure icon in the same row. Tools are now told apart by their icon. - **The animated starfield and constellation backgrounds on the website are gone.** The design language rules out decorative motion; nothing else referenced them. - **Inline code keeps the accent in the terminal renderer.** A code span is a different kind of token rather than a louder one, and the accent is what makes it findable — but a paragraph with six `` `flags` `` in it does speckle, so it is worth a second read. ## What catches the next regression Guards, each written because a real defect got past the previous one: token contrast per surface in both themes, no colour literal outside the token file, and call-site pairing — the fg/bg pair a component actually ships is measured, not just the pairing the tokens intended. That last one matters most: token-level assertions rated a hover state fine that shipped at 4.15:1. **Two of these guards were green while broken**, and neither was found by reading them. A focus-ring regex backtracked to zero width, so `outline: none` counted as "paints an outline"; an Electron assertion matched a type annotation instead of the default it was pinning. Every guard here is now mutation-proven — the mistake it exists to reject is re-injected and observed to fail it. That is the argument for the mutation step, not a footnote to it. ## Known non-conformance `--accent` on `--bg-active` reads 4.15:1 against a 4.5 floor, and is excluded deliberately. The copper is pinned across all three surfaces, and lightening the active surface enough to clear the floor pushes it past `--bg-hover`, inverting the depth ramp. It needs a cross-surface accent decision, which is larger than this PR. ## Test plan - [x] `cd src/gaia/apps/webui && npx vitest run` — 637 pass, 59 files - [x] `cd src/gaia/apps/webui && npx tsc --noEmit` — clean - [x] `cd src/gaia/apps/webui && npm run build` — clean - [x] `cd tests/electron && npx jest test_electron_chat_app.js` — 196 pass - [x] `cd website && npx vitest run` — 213 pass - [x] `cd website && npx astro check` — 0 errors, 0 warnings - [x] `cd website && HUB_CATALOG_URL=https://hub.amd-gaia.ai npm run build` — completes (needs network; the build has no fixture fallback by design. Behind a TLS-inspecting proxy add `NODE_OPTIONS=--use-system-ca`.) - [x] `cd tui && go vet ./... && go test -count=1 ./internal/ui/...` — clean, all packages pass - [x] `python util/check_doc_links.py` — 2496 links, 0 broken - [x] Toggle light/dark in the Agent UI and on the website; confirm code panels stay dark in both and the `>` prompt, focus ring, and primary button are the only coloured things on screen - [x] Tab through the file browser, activity filters, and update chip in both themes; every control shows a ring `Test Agent SDK on Windows (Lemonade Integration)` is red here for amd#4281, a self-hosted-runner bug unrelated to this PR — a leftover state file points the tests at a dead port. It fails the same way on unrelated branches and is fixed by amd#4284. --------- Co-authored-by: f <f@f>
|
Closing as superseded — |
A
gaia lemonade embeddedserver that was killed, crashed, or lost to a reboot leftbehind a state file naming the port it once held — and every GAIA client read that file
ahead of the default. From then on
gaia llm, the Agent SDK, and the API server alldialled a port with nothing on it and reported Lemonade as down, while a perfectly
healthy server answered on 13305. The only cure was knowing to delete a file most users
have never heard of. Now that file is only honoured while the process it records is
actually alive; otherwise GAIA falls back to the normal endpoint and says so in a
warning that names the leftover file. This also unsticks the Windows Agent SDK CI lane,
which has been failing on three unrelated branches because a stale embedded port on the
persistent runner outvoted the server the setup step had just readied.
Closes #4281
Test plan
python -m pytest tests/unit/ -xpassespython util/lint.py --allpasses~/.gaia/lemonade/state.jsoncontaining{"pid": 999999, "port": 59939, "api_key": "x"}, then rungaia llm "hello"—it must reach the real server (13305 /
LEMONADE_BASE_URL), not 59939, and log awarning naming the file.
gaia lemonade embedded start) and confirmgaia llm "hello"still reaches its chosen port with its own API key — the gatemust not cost a genuinely running instance.
actions-runner-01, re-runTest Agent SDK on Windows (Lemonade Integration)without deleting
C:\Users\Administrator\.gaia\lemonade\state.jsonand confirmthe tests now dial the port the setup step readied.
🔍 Technical details
Root cause.
_read_embedded_lemonade_state()(src/gaia/llm/lemonade_client.py)validated only that
portwas an int in1..65535— no pid check, no health probe, notimestamp — and
_get_lemonade_config()preferred its result overDEFAULT_LEMONADE_URLwheneverLEMONADE_BASE_URLwas unset. The asymmetry was thebug:
state.jsonalready records apid, andEmbeddedLemonade.status()does the fulljob (health probe →
_daemon_alive(pid)→_clear_state()), but the client-side readerbypassed all of it. The manager cannot fix this from its own side — a
SIGKILLor areboot gives it no chance to clear the file — so the reader-side check is the one that
closes the hole.
The fix.
_read_embedded_lemonade_state()now requires_embedded_lemonade_alive(state["pid"])before returning the state. That single gatecovers both consumers —
_embedded_lemonade_url()and_embedded_lemonade_api_key()—so a dead instance stops donating its port and stops donating its credential
(credentials naming a dead port are worse than none: the next process to grab that port
inherits the trust). The reader does not delete the file;
status()still owns clearing.Why a second liveness implementation.
_embedded_lemonade_alive()repeatsEmbeddedLemonade._daemon_alive's rule — match the image name, not mere existence, so arecycled pid is never mistaken for the daemon — but on
psutil(already a module-levelimport here) rather than
ps/tasklist. This runs on the base-URL resolution path,which every client construction and UI health poll crosses; a subprocess spawn per
request would be a real cost, on Windows especially. It fails closed: an unidentifiable
pid counts as gone, so an unverifiable state file loses to the documented default. The
docstring records the intentional divergence.
Verified that the recorded pid really is a
lemondimage and not a wrapper —start()Popensself.daemon_path(dist/<version>/lemond[.exe]) directly and storesprocess.pid, sopsutil.Process(pid).name()islemond/lemond.exe.status()onlyconsults
_daemon_aliveafter a health probe, so it would have masked a wrong imagename; this path would not, which is why it was checked explicitly.
Verification. Both directions were exercised against real processes, not mocks: a
reaped pid and a live non-
lemondpid (a recycled-pid stand-in) both fall back tohttp://localhost:13305/api/v1with no key; a real process whose image name islemondis still honoured on its own port with its own key.
tests/unit/test_lemonade_client_api_key.pygains
TestStaleEmbeddedStatefor the gate itself, the warn-once behaviour, and thefail-closed pid validation. Three existing tests wrote state files with no pid (or a
placeholder
pid: 1) and asserted the embedded endpoint wins; they now record a pid andstub liveness, since no test can produce a real
lemond.Scope note. The issue also suggested a workflow-level assertion or exporting
LEMONADE_BASE_URLin CI. Both were interim unblocks for the stale file; with the readerfixed, the runner no longer needs hand-cleaning, so the workflows are left alone.
docs/guides/ai-providers.mdxis updated too: its credential-resolution paragraphpromised the state file applied to "the matching local HTTP server and port" with no
liveness caveat, which this change narrows.