Skip to content

test(unit): stop the unit suite from killing and replacing the real daemon - #4301

Merged
kovtcharov-amd merged 1 commit into
amd:mainfrom
kovtcharov:kalin/unit-daemon-isolation
Sep 25, 2026
Merged

kovtcharov-amd merged 1 commit into
amd:mainfrom
kovtcharov:kalin/unit-daemon-isolation

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

Running pytest tests/unit could kill a developer's running GAIA daemon and leave an orphaned test daemon registered in ~/.gaia/host in its place, which knocked any TUI session using the real daemon off discovery. The email wiring tests reached the real daemon client. The unit network guard made the live daemon fail its liveness probe, so the client treated it as hung, tree-killed it and spawned a new one. After this change, unit tests use a throwaway daemon home, and any test that tries to spawn a real daemon fails with a message saying which boundary to mock.

Test plan

  • pytest tests/unit -n 8: no new gaia.daemon process appears (ps aux | grep gaia.daemon), and ~/.gaia/host/instance.json and sidecars.json are unchanged
  • pytest tests/unit/test_email_sidecar_server_wiring.py tests/unit/test_unit_daemon_isolation.py passes
  • Removing the acquire_handle mock from the wiring tests makes them fail with "Unit test tried to spawn a real GAIA daemon"
🔍 Technical details
  • tests/unit/conftest.py: a session-scoped autouse fixture sets GAIA_DAEMON_HOME to a tmp dir (the only host-dir override gaia.daemon.paths honours). A per-test autouse fixture replaces gaia.daemon.client._spawn_and_wait, the one place python -m gaia.daemon is spawned. It raises, and it also fails the test at teardown, because the email router turns a spawn error into a 503 that the old != 404 assertion accepted.
  • test_email_sidecar_server_wiring.py now mocks daemon_client.acquire_handle and asserts == 503, which proves each route is mounted and reaches the daemon boundary.
  • Integration tests are unaffected: they spawn real daemons under their own GAIA_DAEMON_HOME.
  • The full unit run with this change: the 42 failures are all environmental (uninstall/profilespec/token-budget with GAIA_HOME set locally) and reproduce on unmodified main (43 there).

…aemon

Running `pytest tests/unit` could tree-kill the developer's live GAIA daemon
and leave an orphaned test daemon registered in ~/.gaia/host in its place.
The email wiring tests reached the real `start_or_attach()`; with the unit
network guard in place the real daemon failed its liveness probe, was treated
as hung and terminated, and a new `python -m gaia.daemon` was spawned.

- Point GAIA_DAEMON_HOME at a per-session tmp dir for all unit tests.
- Refuse `_spawn_and_wait` in unit tests and fail the test at teardown, so a
  caller that wraps the error (the email router returns 503) cannot hide it.
- Mock `acquire_handle` in the email wiring tests and assert the 503 the
  mocked daemon produces instead of "not 404".
@github-actions github-actions Bot added the tests Test changes label Sep 25, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve

This stops pytest tests/unit from tree-killing a developer's running GAIA daemon and leaving an orphaned test daemon registered in its place. It does it at the right place: unit tests now get a throwaway daemon home, and the single spot that launches a real daemon process is replaced with a guard that fails the test — and says which boundary to mock instead.

The part that makes this actually work rather than look like it works is the teardown check. The email route turns a daemon failure into a 503, so a raise alone would have been swallowed and the old not 404 assertion would have happily passed on a test that had just spawned a daemon. Recording the attempt and failing at teardown closes that hole, and the wiring tests got correspondingly stricter.

No blocking issues. Two small suggestions below, both optional.

Real-world evidence

N/A — tests-only change, no runtime surface. No evidence-bundle.md was produced by the evidence stage, which is correct for this diff.

I verified the change by reading the code rather than running it: pytest isn't installed in this review environment, so I could not execute the suite. What I did confirm from the source: the daemon is launched from exactly one place, the environment override the fixture uses is re-read on every call (so no import-time caching defeats it), and the error type the wiring test raises is the same class object the route handler catches — so the 503 it now asserts is genuinely produced by the route, not by chance. The PR's three test-plan boxes are still unchecked; worth ticking them before merge since they're the only proof the kill-and-replace is actually gone.

🔍 Technical details

Strengths

  • Correct chokepoint. client.py:130 is the only [sys.executable, "-m", "gaia.daemon"] spawn in src/ (grep confirms), and start_or_attach reaches it through a module-global reference at client.py:108 — so monkeypatch.setattr(client, "_spawn_and_wait", …) really does intercept every path. Using setattr with the default raising=True also means a rename of _spawn_and_wait breaks the whole unit suite loudly rather than silently disarming the guard.
  • The teardown backstop is the load-bearing bit. router.py:41-51 maps SidecarError → 503, so the RuntimeError alone would be swallowed. Recording into attempts and calling pytest.fail(..., pytrace=False) at teardown puts the failure where nothing can catch it (tests/unit/conftest.py:81-99).
  • The 503 assertion is real, not incidental. The test imports SidecarError from gaia.daemon.sidecars.errors, while router.py:34 imports it from gaia.ui.email_sidecar.errors — but that module is a pure re-export shim over the same class object, so except SidecarError catches it. All three probed routes take a bare Request (no Pydantic body model), so an empty {} body can't short-circuit to 422 before _get_proxy() runs. /calendar/events has only optional query params. The != 404 → == 503 tightening is sound.
  • Isolation matches the existing convention. GAIA_DAEMON_HOME is what tests/integration/test_daemon*.py already uses, and paths.host_dir() reads it on every call rather than caching at import. With the override pointed at a tmp dir, read_instance() returns None, so start_or_attach never reaches the terminate_instance branch at client.py:101-107 — the tree-kill is structurally unreachable, not just guarded. Under -n 8 each xdist worker gets its own tmp_path_factory base, so the homes stay distinct.
  • No unit test asserts the default ~/.gaia/host location, so nothing regresses from the session-wide override.

🟢 Minor: the guard check is indirect (tests/unit/test_unit_daemon_isolation.py:18)

client._spawn_and_wait.__module__ != client.__name__ infers "guarded" from a module-name string. It would also pass if the real implementation were legitimately relocated to another module and re-imported. Tagging the replacement makes the assertion say what it means. In tests/unit/conftest.py, add _refuse._gaia_unit_guard = True after the def _refuse block, then:

    assert getattr(client._spawn_and_wait, "_gaia_unit_guard", False)

(Asserting it raises directly isn't an option here — that would populate attempts and fail the test at teardown, which is presumably why __module__ was used.)

🟢 Minor: second assertion is true by construction (tests/unit/test_unit_daemon_isolation.py:18)

paths.instance_path().parent == paths.host_dir() holds for any value of host_dir() because instance_path() is defined as host_dir() / "instance.json". It can never fail while the isolation is broken, so it adds no coverage beyond the first assertion. Harmless as a structural guard against instance_path being moved out of the host dir — just don't read it as evidence that isolation is working.

Checked and clear

  • No other unit test patches or asserts on _spawn_and_wait; every existing daemon-touching unit test already mocks start_or_attach or sets its own GAIA_DAEMON_HOME (which function-scoped monkeypatch restores to the session value afterwards, not to the real one).
  • broker_client only calls attach(), never start_or_attach, so the root-level and MCP suites were never exposed to the kill-and-replace path — scoping the fixtures to tests/unit/ is sufficient, not a gap.
  • TestClient is used without a with block, so no lifespan startup runs and app creation never contacts the daemon.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 25, 2026
Merged via the queue into amd:main with commit 13b6147 Sep 25, 2026
27 checks passed
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 26, 2026
**Stacked on amd#4192. Land after amd#4301**, which stops unit tests from
spawning real daemons. With this PR a daemon starts GAIA's Lemonade
Server in the real `~/.gaia`, so a test-spawned one would start and stop
the developer's server. Until that merges, this diff includes its
commit; review only the last commit here.

After a reboot, GAIA's own Lemonade Server is stopped, and every entry
point said "Lemonade not running" until you re-ran `gaia init`. Now the
daemon starts it when the daemon comes up, and again whenever a GAIA
command finds it stopped. Agents, the TUI's first-launch check (`gaia
init --check`) and the Agent UI just work after a restart.

The daemon is careful about what it stops. `gaia daemon stop` stops the
server only if that daemon started it, so one started by `gaia init`, by
hand, or by another daemon (a second one used for testing, say) keeps
running. It never kills a server that is slow to answer (it may be
loading a large model) and never replaces one running a different
version: it reports both and points at `gaia init`. With
`LEMONADE_BASE_URL` set it leaves Lemonade alone, and it never installs
anything.

A daemon from before this change doesn't have the new endpoint. Instead
of a bare 404, clients get "restart it with `gaia daemon restart`" (host
API bumped to 1.2).

## Test plan
- [x] `pytest tests/unit/test_daemon_lemonade.py
tests/unit/test_daemon_clock_wiring.py tests/unit/test_init_command.py
tests/unit/test_daemon_agents_routes.py`; `go test ./internal/gaiainit/
./internal/daemon/`
- [x] With `GAIA_HOME`, `GAIA_DAEMON_HOME` and `GAIA_CONFIG_DIR` in a
scratch dir and the server stopped: `gaia init --check` has a new daemon
start it and prints READY (1.4 s); `gaia daemon stop` then stops it
- [x] Server started with `gaia lemonade embedded start`, then `gaia
daemon start` / `gaia daemon stop`: the server keeps running
- [x] Server stopped: `LemonadeManager.ensure_ready()` gets it started
through the daemon, loads Gemma and returns True
- [ ] Windows and Linux: reboot, then launch `gaia-tui` without running
`gaia init`; it should go straight to chat



<details>
<summary>Terminal output: the reboot case on Apple Silicon (GAIA set up,
no daemon or server running)</summary>

```
$ gaia daemon status
GAIA daemon: not running
$ gaia lemonade embedded status
Running:   no

$ time gaia init --check --profile minimal
READY: profile 'minimal' is already set up
(exit 0, 1 s)
$ gaia lemonade embedded status
Running:   yes on http://localhost:59768/api/v1 (pid 88967)

$ time gaia daemon stop
✅ GAIA daemon stopped (pid 88966)
(5 s)
$ gaia lemonade embedded status
Running:   no
```
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
Co-authored-by: Kalin Ovtcharov <[email protected]>
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 26, 2026
The Agent UI ignored `GAIA_HOME` and always saved Document Library
uploads and chat attachments under the real `~/.gaia`. So a run of the
document and file router tests left files in the developer's own GAIA
home, and those files could change the next run's results. Both folders
now live under `$GAIA_HOME` (default is still `~/.gaia`). The router
tests run under a fake home and fail if anything lands in
`<home>/.gaia`. A `GAIA_HOME` set to your home directory or one of its
parents is now rejected, because the server deletes files in
`<GAIA_HOME>/documents` as its own, and there that would be your real
Documents folder.

Merge amd#4343 first. It fixes three reindex tests in
`test_documents_router` that fail on `main` right now because they call
real RAG indexing without Lemonade. I checked this branch with amd#4343's
changes applied: both router files pass (89 passed, 1 skipped). This PR
edits different lines of that file, so the two won't conflict. It also
adds nothing to the unit conftest that amd#4301 changes.

## Test plan

- [x] `pytest tests/unit/chat/ui/test_gaia_home_storage.py`: fails on
`main` (4 failed, 2 errors), passes here (6 passed)
- [x] `pytest tests/unit/chat/ui tests/integration/test_files_router.py
tests/integration/test_documents_router.py`: 1127 passed. The only
failures are the 3 reindex tests that amd#4343 fixes
- [x] Same two router files with amd#4343's test changes applied: 89
passed, 1 skipped
- [x] Same run with `GAIA_HOME` unset and a fake `HOME`: default
`~/.gaia` layout unchanged
- [x] black, isort and pylint on the changed files (the one pylint
warning in `documents.py` is already on `main`)

Fixes amd#4347

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
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

tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants