Skip to content

fix(daemon): closing a TUI session no longer kills the shared model server - #5282

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

kovtcharov-amd merged 13 commits into
amd:mainfrom
kovtcharov:fix/lemonade-restart-wait-proven

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

Stacked on #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 #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 #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

  • 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)
  • 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
  • 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
  • go test ./internal/client (tui): ok. TestAgentJobKeepsOnlyABreakawayChild fails without the BREAKAWAY_OK flag.
  • python util/lint.py --black --isort --flake8 --pylint --test-lanes: all pass
  • python -m pytest tests/integration/test_lemonade_restart_live.py on Windows with a real lemond: 9 passed (6 min 48 s)
  • 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
🔍 Technical details

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.

@github-actions github-actions Bot added documentation Documentation changes llm LLM backend changes tests Test changes performance Performance-critical changes tui Go terminal UI (gaia-tui) daemon Daemon supervisor / sidecar control plane labels Oct 17, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

On Windows, closing one TUI session killed the daemon and the model server that every other session was using. This PR fixes that by having the daemon and GAIA's server leave the session's process group when they start. It also fixes four gaps in the reconnect wait from #5264: /model during a restart, the overall time bound, embeddings, and the cloud-key replay. The root cause is well argued and the fix is small: one job flag in the TUI and one spawn helper in Python. The retry hand-off is the subtle part, and its unit tests cover it, including randomized timing seeds. Nothing blocks merge.

One small thing to look at: when Windows won't let the server leave the group, the server falls back to starting inside it, as before, and only logs a warning to the log file. A TUI user never sees that warning, and the old bug comes back without a sign. Consider a visible signal, or at least name the cause in gaia daemon status.

Real-world evidence

N/A here. No evidence bundle was produced for this run, so this verdict rests on static review of the diff. The PR description has the author's own Windows runs against a real, isolated lemond, comparing main with this branch:

  • Closing the session that started the daemon left the daemon and server running.
  • 16 back-to-back and 16 overlapping gaia-tui sessions finished with no daemon kills.
  • /model worked while the server was restarting.
  • A 480-turn chaos run with 3 server crashes had 0 failures.
  • The 9 live integration tests passed.

That covers the TUI/daemon surface this change touches. CI hasn't run the new live test, which is allowlisted rather than placed in a lane, so the Windows job-object behaviour is proven only by the author's runs and the Windows-only Go test.

🔍 Technical details

Issues

🟢 Breakaway refusal falls back with only a log warning (src/gaia/utils/terminal.py:52-82): on ERROR_ACCESS_DENIED, the spawn retries inside the job and calls log.warning. That keeps the old behaviour, which is reasonable, but the warning only lands in gaia.log. An older gaia-tui without BREAKAWAY_OK, or any host job that forbids breakaway, brings back #5261 with nothing the user can see. Consider surfacing it in gaia daemon status or the daemon's startup line. This is not blocking: it is logged, not swallowed.

🟢 Lazy per-instance thread-local (src/gaia/llm/lemonade_client.py:2813): self.__dict__.setdefault("_gone_handoff_state", threading.local()) builds a throwaway threading.local() on every call and hides the attribute from __init__. If this is for test doubles built with __new__, a one-line comment saying so would help. Otherwise, initialise it in __init__.

🟢 Stale pending after a failed streaming resend (lemonade_client.py:2940-2958): the resend in _stream_surviving_gaia_lemonade_stop calls start() directly, not through _survive_gaia_lemonade_stop. A hand-off on that second stream therefore leaves pending=True until the next _survive_* call resets it. No current path reads it in between, so this is harmless today, but it is an invariant worth one comment or a reset in _recover_stopped_gaia_lemonade's caller.

🟢 Allowlist runtime disagrees with the PR (util/test_lane_allowlist.yml:40): the entry says "~8 min", but the PR and test plan say 6 min 48 s / ~7 min. Trivial.

Strengths

  • follows_gaia_lemonade now decides whether to wait, instead of reading wait() is False as "not GAIA's server". That removes the misread behind the /model "not reachable" failure. The new "back" test case and the stricter "never waited on" assertion cover both sides.
  • hand_off in ModelCallRetrier is a narrow hook: consulted only before output, only for connect failures, only on GAIA's own server, and only after a probe confirms it is gone. Backoff can no longer stack on top of the 60 s wait. The randomized-gap seeds test that bound directly.
  • The Go test (TestAgentJobKeepsOnlyABreakawayChild) shows tool children are still reaped while the breakaway child survives, and the author confirmed it fails without the flag. The gateway _http_error change also fixes a latent AttributeError on Lemonade's string-shaped 401 body.

…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
  amd#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 amd#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 and others added 4 commits October 19, 2026 00:33
…essions use

On Windows the TUI runs each session's agent in a kill-on-close job object,
and a process started from inside a job joins it. So when a session's agent
was the first GAIA process to need the daemon, the daemon and its Lemonade
Server joined that session's job, and closing the session killed both under
every other session. That is the "server stopped answering ~15 s after it was
reported ready" in amd#5261.

- The TUI's job now allows breakaway (JOB_OBJECT_LIMIT_BREAKAWAY_OK). Tool
  children don't ask to leave, so cancelling a turn still reaps them.
- The daemon and embedded lemond spawns go through popen_outliving_job, which
  asks to leave the job. Where Windows refuses, the server starts in the job
  as before and a warning says why it will stop with its parent.

Measured on an isolated home with a real lemond: closing the session that
started the daemon left it and lemond running only with both halves changed;
over 16 back-to-back TUI sessions, main lost the daemon on all 16 closes and
this change on none.
…hole turn

Live runs against a real, restarting lemond found four gaps in the wait.

- /model during a restart still ended "Lemonade Server is not reachable": the
  server came back while the failed listing was still retrying, and the switch
  read "nothing to wait for" as "not GAIA's server". It now asks whether the
  client follows GAIA's server, and lists again once it answers.
- A server that never came back failed the turn after ~105 s, not ~60: the
  request first backed off 5 times against the dead port. A connection failure
  to GAIA's own gone server, before any output, now goes straight to the
  bounded wait. A stream already under way keeps its retry state, and a request
  handed off this way is resent even if the server is back by the second look.
- Embeddings had no restart guard, so memory and RAG, a session's first
  requests, failed on a restart. They now ride it like a chat turn.
- After a restart, replaying the cloud key read Lemonade's 401 body
  ({"error": "<text>"}) as an object and crashed the turn with AttributeError.
…mond

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

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

tests/integration/test_lemonade_restart_live.py runs the scenarios under
pytest and skips when no lemond can be had. It takes ~7 min and its job-object
case needs Windows, so it is allowlisted rather than in the Linux lane.
A streaming resend that handed its failure to the reconnect wait left that
flag set on the thread until the next call reset it. It is now cleared when
the resend ends, with a test that fails without the reset.

Also stops building a throwaway thread-local on every hand-off lookup, and
corrects the live test's runtime in the lane allowlist to ~7 min.
@kovtcharov-amd
kovtcharov-amd force-pushed the fix/lemonade-restart-wait-proven branch from c6742bb to 617e370 Compare October 19, 2026 07:35
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
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 deleted the branch amd:fix/lemonade-restart-wait October 19, 2026 10:17
@kovtcharov-amd
kovtcharov-amd changed the base branch from fix/lemonade-restart-wait to main October 19, 2026 10:21
…wait-proven

# Conflicts:
#	docs/reference/cli.mdx
#	hub/agents/gaia/python/gaia_agent/stdio.py
#	hub/agents/gaia/python/tests/test_stdio_lemonade_reconnect.py
#	src/gaia/llm/lemonade_client.py
#	src/gaia/llm/providers/lemonade.py
#	tests/unit/test_lemonade_restart_wait.py
The full-queue drop test stopped the running extraction and then queued the
next turn. On a slow Windows runner the turn's two SQLite writes outlasted the
extraction's cancel poll, so the stop landed on an empty queue, the job was
requeued and rerun, and the test saw three prompts instead of two. Queueing the
turn first makes the queue full when the stop lands, which is the case the
test is about.
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 19, 2026
Merged via the queue into amd:main with commit 04698b6 Oct 19, 2026
70 of 71 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the fix/lemonade-restart-wait-proven branch October 19, 2026 12:47
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
…ng (amd#5321)

When another app was loading a model on the shared Lemonade, GAIA froze
or failed. A server that accepted connections but stayed silent mid-load
blocked every agent construction in the process for up to 15 minutes,
because status checks used the 900 s generation timeout under a
class-wide lock. Every chat call also re-read `/health` and `/models`
with that timeout while holding the model lease. And a request that
failed after waiting out someone else's 30B cold load got no retry at
all, because the time it spent queued had already used up the 120 s
retry budget.

Now a busy server reads as **busy**, not down:
- Agent construction comes back within seconds, and GAIA never starts or
takes over a busy server.
- A request waits for a busy server and says so through the retry
notice. It honours Stop within half a second and gives up after
`GAIA_LLM_LOAD_WAIT` (600 s) with an error that names that setting.
- Time spent behind another app's LLM load no longer counts against the
retry budget. Attempts still do: `GAIA_LLM_RETRY_ATTEMPTS=1` still means
no retries.

Reproduced by `tests/unit/test_lemonade_shared_server.py` and
`tests/unit/test_retry_load_wait.py`; they fail on main and pass here.
On main:
- Two agents built against a stalled server are both still blocked after
30 s.
- `get_status()` hangs past 90 s.
- A request queued 150 s behind a load fails after one attempt.
- `test_retry_load_wait.py`: all 23 fail.

## Test plan
- [x] `pytest tests/unit/test_lemonade_shared_server.py
tests/unit/test_retry_load_wait.py` passes, using loopback fakes only.
- [x] The 165 unit files that touch the LLM client, retry or manager,
run with amd#5322 on top: 5,094 pass. The 17 failures are the 16 that fail
on clean main plus `test_verification_scope`, a flake listed in amd#5325.
- [x] `python util/lint.py --black --isort --flake8 --pylint` is clean.
- [ ] Live check on hardware: load a large model from one session and
send a chat from another.

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

- Probe timeouts are `PROBE_TIMEOUT` (3.05, 5), `SYSTEM_INFO_TIMEOUT`
(3.05, 15) and `CATALOG_TIMEOUT` (3.05, 30).
- A status GET that times out raises `LemonadeUnresponsiveError`, which
keeps the `Request failed:` prefix existing callers match on.
`LemonadeStatus.busy` carries the same state. A POST that times out
stays a plain `LemonadeClientError`.
- `ensure_ready`, `initialize()`,
`create_lemonade_client(auto_start=True)` and `launch_server` all treat
busy as "up". Before this, a failed probe could reach `_stop_listeners`
and kill a server in the middle of another app's load.
- Every request makes one `get_status(include_catalog=False)` probe.
There is no residency cache: another app can evict the model, and
Lemonade can reload it at its 32K default, inside any trust window
(amd#1030).
- `ModelCallRetrier` takes a `server_loading` probe. Only `type ==
"llm"` entries with status `loading`, `evicting`, `pending` or `queued`
count as a load; downloads don't. The probe is attached only for local
models, it is not consulted once attempts run out, the wait is measured
on the wall clock, and Stop is checked every 0.5 s.
- `_model_retrier` and `_call_with_retry` take a `model` argument. amd#5282
edits the same signatures, so a mechanical merge conflict is expected.
- Error classification is LLM-affecting, so watch `error_recovery`,
`context_retention`, `rag_quality` and `memory` on the next RC. No eval
was run here: one was already running on the shared machine.
- The `/health` status names come from the Lemonade 2026.40 binary; they
weren't observed during a live load.
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
grtninja pushed a commit to grtninja/gaia that referenced this pull request Oct 20, 2026
…ming them (amd#5409)

Two unit tests failed whenever a CI runner was busy, so unrelated PRs
went red (the envelope test on amd#5282 and amd#5337; the ping test timed out
on loaded machines). Before: the envelope "not quadratic" test raced a 5
s wall clock, and the ping test needed a ping to land in a 0.5 s window
that the stub's own start-up ate into. After: both assert what they
claim directly, so they pass or fail the same way on any machine. Under
a 40-process CPU burn they went from 16/16 and 10/16 failing to 0 of
120. The third test from the report,
`test_turn_waiting_on_the_user_lets_other_chats_run`, was already fixed
on main by amd#5396. Both of its CI failures predate that fix, and it
passed 325/325 under the same burn.

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

- **Envelope test:** the test now counts the characters
`_json_object_end` examines. A 400,089-char envelope scans exactly
400,089 characters. A per-token rescan scans ~2e10 and fails the `≤
2×len` bound; I checked this on a 20 KB envelope, where a rescan was
2,500× over.
- **Ping test:** the stub is now warmed with a first request so its boot
time sits outside the deadline window. The test spies `_write` and
asserts the ping reply gets the same deadline as the request. If the
product gives the ping reply a fresh `self.timeout`, the test fails
deterministically.
- **Not a product race:** the remaining superlinear cost in the envelope
path is `self._stream_buffer += chunk` copying the held buffer per
token. That is microseconds per token at real generation rates.
- **Follow-ups:** other tests in `test_stdio_hung_server.py` also fail
under heavy load. `test_redaction_stays_fast_on_dense_escapes` and
`..._linear_on_long_non_ascii_secrets` use a `< 0.25 s` wall-clock
assert. `test_a_server_that_misses_the_connect_deadline_is_stopped` and
`test_a_timed_out_request_is_cancelled_on_the_server` read marker files
before the stub writes them.
</details>

## Test plan
- [x] `pytest -p no:randomly --count 60 -n 8` on both fixed tests:
120/120 idle, 120/120 under a 40-process CPU burn (before: 16/16 and
10/16 failing under the same burn)
- [x] Adversarial: dropping the scanner's resume or giving the ping
reply a fresh timeout makes the respective test fail
- [x] `test_sse_handler.py`, `test_stdio_hung_server.py`,
`test_turn_slot_reliability.py` in full: 521 passed
- [x] `python util/lint.py --black --isort`
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]>
kovtcharov pushed a commit to kovtcharov/gaia that referenced this pull request Oct 30, 2026
…er (amd#5404)

The proactive Claude reviews were failing about half the time, and each
failure was lost. The code and security audits failed 5 of the last 10
nights, and the doc walkthrough failed 4 of its last 5 runs. Running
three audits every night used up both Claude accounts' weekly limit by
mid-week, so most of those runs stopped before reviewing anything and
blamed a missing file. The next run never went back for the missed work.
Now one audit runs each night between 2 and 4am Pacific, so each audit
runs every third night. Each run checks Claude is available before
starting, and says plainly when it isn't. It picks up everything since
its last successful run, starts from what merged since then, and checks
against the bug types past audits missed. The dedup pass no longer
re-files duplicates that were already closed: 34 of them were closed
alongside this change.

## Test plan

- [ ] `python -m pytest tests/unit/test_audit_synthesis_prep.py
tests/unit/test_audit_history.py tests/unit/test_audit_rotation.py
tests/unit/test_require_claude.py tests/unit/test_recent_changes.py
tests/unit/test_miss_analysis.py
tests/unit/test_claude_audit_workflow_contract.py
tests/unit/test_closed_duplicates.py -q` passes (277 tests)
- [ ] After merge: `gh workflow run claude-audit-rotation.yml -R
amd/gaia -f dry_run=true`. The summary names tonight's audit and the
next five nights, and nothing is dispatched.
- [ ] After merge: `gh workflow run claude-nightly-audit.yml -R amd/gaia
-f dry_run=true`. Check the preflight summary: the mode, a window
reading "since this audit's last successful run", the Claude probe
passing, and "Recent changes read first". At the end, "Dry run
confirmed: no issue created".
- [ ] After merge: `gh workflow run claude-weekly-doc-walkthrough.yml -R
amd/gaia -f doc_filter=docs/quickstart.mdx -f dry_run=true`. The guide
is walked, "Using bash.exe from …" appears, and the dry-run watermark
step passes (it crashed before this change).
- [ ] After merge: `gh workflow run claude-security-audit.yml -R
amd/gaia`. Semgrep scans `tui`, `installer` and `.github/workflows`, and
the SARIF uploads.
- [ ] First scheduled night (10:13 UTC): the dispatched run is titled "…
rotation night N", files at most what's new, and an issue it files
carries `audit-cluster` / `audit-key` markers.

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

**Root causes (last ~2 weeks)**
- Code and security audits, Oct 7/10/12/13/14/17: every lens returned
`is_error` in under a second with "You've hit your weekly limit". The
primary account ran out on Oct 10, the secondary on Oct 12–14, both on
Oct 17. The account switch fired correctly; both accounts were spent.
- Walkthrough Oct 12: same weekly limit on every guide, queued over 57
hours on the Strix Point pool. Oct 5 and Oct 19: the `xsj-aimlab-stxp`
images have no Git for Windows (only WSL's `bash.exe`). Also on Oct 5,
the executor step's `GITHUB_OUTPUT` got UTF-16 appended by
`start-lemonade.ps1` under PowerShell 5.1 `>>`. Sep 21–28: Application
Control blocked `LemonadeServer.exe` and the job landed on Strix Halo
machines; both were fixed by the move to the `xsj-dispatch` pool on Oct
1.
- The walkthrough's two dry-run steps had a literal `\n` mid-command, so
`dry_run=true` always failed.

**Schedule.** One cron, `13 10 * * *` = 03:13 PDT / 02:13 PST. Only
10:00–11:00 UTC is inside 2–4am Pacific in both seasons. Slot = days
since epoch mod 3 → code audit, security audit, doc walkthrough. The
audits lost their own crons; `workflow_dispatch` still runs any of them
on demand. Deep code sweep: whenever the last successful one is over 8
days old (every third turn, retried on the next turn if it fails).

**Dedup bug.** The 2026-09-07 burst (78 issues) predates the dedup pass:
the run checked out main 7 hours before amd#3310 merged. Three duplicate
pairs still got through after amd#3310 (amd#3832/amd#3471, amd#3825/amd#3414,
amd#5199/amd#4875). Backlog matching compared findings against issue titles
only, so a same-section duplicate worded differently scored 0.05–0.15,
below the 0.18 threshold. Now matching includes each audit issue's own
markers (all 13 known pairs rank 1st–2nd). Closed duplicates hand their
keys to the open canonical, so consolidating into amd#1077/amd#4331 does not
trigger re-filing. Both syntheses share the `claude-audit-issue-filing`
concurrency group. The security audit files to private code scanning,
not issues, so it cannot duplicate the other two.

**Closed as duplicates (34):** into amd#4331: amd#3204 amd#3413 amd#3422 amd#3439 amd#3466
amd#3476. Into amd#1077: amd#3173 amd#3412 amd#3418 amd#3426 amd#3429 amd#3430 amd#3433 amd#3437 amd#3442
amd#3449 amd#3454 amd#3455 amd#3464 amd#3468 amd#3475 amd#3477 amd#3482. Into amd#3198: amd#3436
amd#3462. Others: amd#3425→amd#3169, amd#3457→amd#3195, amd#3440→amd#3180, amd#3486→amd#3064,
amd#3471→amd#3832, amd#3414→amd#3825, amd#3434 amd#3485→amd#3219, amd#5199→amd#4875.

**Miss-analysis (merged `fix` PRs, Jun 21–Oct 19).** 29 of 1005 (3%)
closed an issue an audit filed first. Missed, by title: no deadline 90
(amd#5346 amd#5384 amd#5380), release/CI ordering 71 (amd#5127 amd#5147), Windows
behaviour 38 (amd#5018 amd#5377), dishonest status 36 (amd#5112 amd#5317), shared
state across processes 34 (amd#5337 amd#5282 amd#5378), model output handling 27
(amd#4973 amd#5103), doc drift 27, cold start / non-default setup 26 (amd#4951
amd#5130). About 380 more were Agent UI/TUI or agent-behaviour fixes, which
a static read rarely catches. Noise: of the audit issues closed as
duplicate or not planned, 31 were duplicates of amd#1077, 12 of the
test-coverage umbrella amd#2988, and 6 each of amd#4331, amd#3149, amd#3308 and
amd#2922. What changed: `scripts/audit/missed_bug_classes.md` has a
checklist per class and a "Don't report" list, and all three prompts
read it at run time. The code audit gets a deterministic list of calls
with no deadline. The security audit's semgrep run and worklist now
cover TypeScript, Go, the installer and the workflows.
`scripts/audit/miss_analysis.py` refreshes the evidence monthly.

**Recent changes.** Each audit's first job writes `recent-changes.md`:
first-parent commits since the commit its last successful run checked
out, read from the run history, with PR title, a short body excerpt and
the paths each touched, capped at 30 KB. If that commit is unknown it
covers 3 days and says so.
</details>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

daemon Daemon supervisor / sidecar control plane documentation Documentation changes llm LLM backend changes performance Performance-critical changes tests Test changes tui Go terminal UI (gaia-tui)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants