|
| 1 | +"""A daemon left running OLD code after an `ultan` tool update must be detected |
| 2 | +and restarted — a long-running process keeps the code it loaded at spawn, so |
| 3 | +`uv tool install` swapping the venv underneath it doesn't take effect until the |
| 4 | +process is replaced. The version-aware restart lives in the session-start path |
| 5 | +(NOT the per-turn hot path) and the mismatch is surfaced by `ultan doctor`. |
| 6 | +""" |
| 7 | + |
| 8 | +import json |
| 9 | +import os |
| 10 | +from pathlib import Path |
| 11 | +from typing import Any |
| 12 | + |
| 13 | +import pytest |
| 14 | + |
| 15 | +from ultan import _daemon, _doctor, _hooks |
| 16 | + |
| 17 | + |
| 18 | +@pytest.fixture() |
| 19 | +def home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: |
| 20 | + h = tmp_path / "agent-mem" |
| 21 | + h.mkdir() |
| 22 | + monkeypatch.setenv("AGENT_MEM_HOME", str(h)) |
| 23 | + return h |
| 24 | + |
| 25 | + |
| 26 | +def _write_state(home: Path, *, pid: int, version: Any) -> None: |
| 27 | + state: dict[str, Any] = {"phase": "ready", "pid": pid, "since": "x"} |
| 28 | + if version is not None: |
| 29 | + state["version"] = version |
| 30 | + (home / "daemon.state").write_text(json.dumps(state), encoding="utf-8") |
| 31 | + |
| 32 | + |
| 33 | +# ── restart_if_stale: only restarts on a genuine version mismatch ────── |
| 34 | + |
| 35 | + |
| 36 | +def test_no_restart_when_no_state(home: Path, monkeypatch: pytest.MonkeyPatch) -> None: |
| 37 | + monkeypatch.setattr(_daemon, "_installed_daemon_version", lambda: "0.3.0") |
| 38 | + assert _daemon.restart_if_stale() is False |
| 39 | + |
| 40 | + |
| 41 | +def test_no_restart_when_pid_dead(home: Path, monkeypatch: pytest.MonkeyPatch) -> None: |
| 42 | + _write_state(home, pid=99999999, version="0.2.0") |
| 43 | + monkeypatch.setattr(_daemon, "_installed_daemon_version", lambda: "0.3.0") |
| 44 | + assert _daemon.restart_if_stale() is False |
| 45 | + |
| 46 | + |
| 47 | +def test_no_restart_when_versions_match(home: Path, monkeypatch: pytest.MonkeyPatch) -> None: |
| 48 | + _write_state(home, pid=os.getpid(), version="0.3.0") |
| 49 | + monkeypatch.setattr(_daemon, "_installed_daemon_version", lambda: "0.3.0") |
| 50 | + stopped: list[int] = [] |
| 51 | + monkeypatch.setattr(_daemon, "_stop_daemon", lambda pid, **k: stopped.append(pid)) |
| 52 | + assert _daemon.restart_if_stale() is False |
| 53 | + assert stopped == [] |
| 54 | + |
| 55 | + |
| 56 | +def test_no_restart_when_installed_version_unknown( |
| 57 | + home: Path, monkeypatch: pytest.MonkeyPatch |
| 58 | +) -> None: |
| 59 | + _write_state(home, pid=os.getpid(), version="0.2.0") |
| 60 | + monkeypatch.setattr(_daemon, "_installed_daemon_version", lambda: None) |
| 61 | + stopped: list[int] = [] |
| 62 | + monkeypatch.setattr(_daemon, "_stop_daemon", lambda pid, **k: stopped.append(pid)) |
| 63 | + assert _daemon.restart_if_stale() is False |
| 64 | + assert stopped == [] |
| 65 | + |
| 66 | + |
| 67 | +def test_restart_legacy_daemon_with_no_version_stamp( |
| 68 | + home: Path, monkeypatch: pytest.MonkeyPatch |
| 69 | +) -> None: |
| 70 | + # A legacy daemon (pre-this-feature) wrote no version. Anchored on a KNOWN |
| 71 | + # installed version, that's unambiguously old code → restart. This is the |
| 72 | + # migration case: the daemon a user already has running when they first adopt |
| 73 | + # the feature has no stamp, and must still be replaced. |
| 74 | + _write_state(home, pid=os.getpid(), version=None) |
| 75 | + monkeypatch.setattr(_daemon, "_installed_daemon_version", lambda: "0.3.0") |
| 76 | + stopped: list[int] = [] |
| 77 | + monkeypatch.setattr(_daemon, "_stop_daemon", lambda pid, **k: stopped.append(pid)) |
| 78 | + assert _daemon.restart_if_stale() is True |
| 79 | + assert stopped == [os.getpid()] |
| 80 | + |
| 81 | + |
| 82 | +def test_restart_when_stale_stops_and_clears_backoff( |
| 83 | + home: Path, monkeypatch: pytest.MonkeyPatch |
| 84 | +) -> None: |
| 85 | + _write_state(home, pid=os.getpid(), version="0.2.0") |
| 86 | + (home / ".daemon-spawn-attempt").write_text("x", encoding="utf-8") |
| 87 | + monkeypatch.setattr(_daemon, "_installed_daemon_version", lambda: "0.3.0") |
| 88 | + stopped: list[int] = [] |
| 89 | + monkeypatch.setattr(_daemon, "_stop_daemon", lambda pid, **k: stopped.append(pid)) |
| 90 | + |
| 91 | + assert _daemon.restart_if_stale() is True |
| 92 | + assert stopped == [os.getpid()] # stopped the stale daemon |
| 93 | + # backoff stamp cleared so ensure_running() respawns immediately, not throttled |
| 94 | + assert not (home / ".daemon-spawn-attempt").exists() |
| 95 | + |
| 96 | + |
| 97 | +# ── _installed_daemon_version ───────────────────────────────────────── |
| 98 | + |
| 99 | + |
| 100 | +def test_installed_version_matches_metadata_or_none() -> None: |
| 101 | + import importlib.metadata as md |
| 102 | + |
| 103 | + # Env-agnostic: in a full `ultan[retrieval]` install the daemon dist resolves; |
| 104 | + # in the thin root/CI venv (no extras) it doesn't and the helper returns None. |
| 105 | + # Either way it must agree with importlib.metadata — never invent a version. |
| 106 | + try: |
| 107 | + expected: str | None = md.version("agent-mem-daemon") |
| 108 | + except md.PackageNotFoundError: |
| 109 | + expected = None |
| 110 | + assert _daemon._installed_daemon_version() == expected |
| 111 | + |
| 112 | + |
| 113 | +def test_installed_version_none_when_dist_absent(monkeypatch: pytest.MonkeyPatch) -> None: |
| 114 | + import importlib.metadata as md |
| 115 | + |
| 116 | + def _raise(_name: str) -> str: |
| 117 | + raise md.PackageNotFoundError |
| 118 | + |
| 119 | + monkeypatch.setattr(md, "version", _raise) |
| 120 | + assert _daemon._installed_daemon_version() is None |
| 121 | + |
| 122 | + |
| 123 | +# ── session-start wires the restart in (before warming) ─────────────── |
| 124 | + |
| 125 | + |
| 126 | +def test_session_start_calls_restart_if_stale(monkeypatch: pytest.MonkeyPatch) -> None: |
| 127 | + order: list[str] = [] |
| 128 | + monkeypatch.setattr( |
| 129 | + _hooks._daemon, "restart_if_stale", lambda: order.append("restart") or False |
| 130 | + ) |
| 131 | + monkeypatch.setattr(_hooks._daemon, "ensure_running", lambda: order.append("ensure") or True) |
| 132 | + monkeypatch.setattr(_hooks._events, "append_event", lambda *a, **k: None) |
| 133 | + |
| 134 | + rc = _hooks.dispatch("session-start", {"session_id": "s", "source": "startup"}) |
| 135 | + |
| 136 | + assert rc == 0 |
| 137 | + assert order == ["restart", "ensure"] # stale-check BEFORE warming |
| 138 | + |
| 139 | + |
| 140 | +# ── doctor surfaces the mismatch even before the restart lands ───────── |
| 141 | + |
| 142 | + |
| 143 | +def test_doctor_flags_stale_daemon( |
| 144 | + home: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] |
| 145 | +) -> None: |
| 146 | + monkeypatch.setattr(_doctor, "_report_runtime", lambda home: False) |
| 147 | + (home / "daemon.pid").write_text(f"{os.getpid()}\n", encoding="utf-8") |
| 148 | + _write_state(home, pid=os.getpid(), version="0.2.0") |
| 149 | + monkeypatch.setattr(_daemon, "_installed_daemon_version", lambda: "0.3.0") |
| 150 | + |
| 151 | + _doctor.run() |
| 152 | + out = capsys.readouterr().out |
| 153 | + |
| 154 | + assert "daemon code: 0.2.0 — STALE (installed 0.3.0)" in out |
| 155 | + |
| 156 | + |
| 157 | +def test_doctor_no_stale_line_when_versions_match( |
| 158 | + home: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] |
| 159 | +) -> None: |
| 160 | + monkeypatch.setattr(_doctor, "_report_runtime", lambda home: False) |
| 161 | + (home / "daemon.pid").write_text(f"{os.getpid()}\n", encoding="utf-8") |
| 162 | + _write_state(home, pid=os.getpid(), version="0.3.0") |
| 163 | + monkeypatch.setattr(_daemon, "_installed_daemon_version", lambda: "0.3.0") |
| 164 | + |
| 165 | + _doctor.run() |
| 166 | + out = capsys.readouterr().out |
| 167 | + |
| 168 | + assert "daemon code: 0.3.0" in out |
| 169 | + assert "STALE" not in out |
0 commit comments