The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(remote-config): cold-process Nous boot, config-free auth import, lock-order regressions
Ben Barclay96c029315b10
diff --git a/tests/plugins/config_backends/stub_plane.py b/tests/plugins/config_backends/stub_plane.pyindex 3903b5432f7..02b4c7f5e6d 100644--- a/tests/plugins/config_backends/stub_plane.py+++ b/tests/plugins/config_backends/stub_plane.py@@ -25,6 +25,9 @@ from plugins.config_backends.remote.paths import decode, encodefrom plugins.config_backends.remote.values import secret_literal_pathTOKEN = "plane-token-1"+# Cloud mode: the agent sends its Nous Portal access token; the stub also serves the Portal's+# refresh route (``/api/oauth/token``), which hands out NOUS_TOKEN.+NOUS_TOKEN = "nous-access-token-1"CLIENT_ID = "agent-client"CLIENT_SECRET = "agent-secret"INSTANCE = "inst-0001"@@ -66,6 +69,7 @@ class StubPlane:self.fail_status: Optional[int] = None # every /self request returns thisself.requests: list[dict[str, Any]] = []self.token_requests = 0+ self.nous_refreshes = 0self.home: Optional[Path] = None # the test's HERMES_HOME, set by the fixtureself.lock = threading.Lock()self._server = ThreadingHTTPServer(("127.0.0.1", 0), self._handler())@@ -130,6 +134,12 @@ class StubPlane:return json.loads(self.rfile.read(n) or b"{}")def do_POST(self):+ if self.path == "/api/oauth/token":+ self.rfile.read(int(self.headers.get("Content-Length") or 0)) # a form body+ with plane.lock:+ plane.nous_refreshes += 1+ return self._send(200, {"access_token": NOUS_TOKEN, "refresh_token": "nous-refresh-2",+ "token_type": "Bearer", "expires_in": 3600})if self.path != "/token":return self._send(404, {"error": "not_found"})n = int(self.headers.get("Content-Length") or 0)@@ -154,7 +164,7 @@ class StubPlane:"if_none_match": self.headers.get("If-None-Match")})if plane.fail_status is not None:return self._send(plane.fail_status, {"error": "unavailable", "message": "stub outage"})- if self.headers.get("Authorization") != f"Bearer {TOKEN}":+ if self.headers.get("Authorization") not in (f"Bearer {TOKEN}", f"Bearer {NOUS_TOKEN}"):return self._send(401, {"error": "unauthorized", "message": "bad token"})if self.headers.get("X-Hermes-Instance-Id") != INSTANCE:return self._send(403, {"error": "config_agent_unknown", "message": "unknown instance"})diff --git a/tests/plugins/config_backends/test_remote_backend.py b/tests/plugins/config_backends/test_remote_backend.pyindex 8a7fd4927f8..b7067c6aa56 100644--- a/tests/plugins/config_backends/test_remote_backend.py+++ b/tests/plugins/config_backends/test_remote_backend.py@@ -1880,3 +1880,98 @@ def test_custom_endpoint_make_default_refuses_when_its_provider_entry_is_locked(id="new-probe", name="new-probe", base_url="https://new.example/v1", model="new-model", make_default=True))assert exc.value.status_code == 403, exc.valueassert plane.profile("default")["values"].get("model") in (None, {}), plane.profile("default")+++# --- re-entry ----------------------------------------------------------------------------++def _blocked_in_state(thread) -> bool:+ import sys+ frame = sys._current_frames().get(thread.ident)+ while frame is not None:+ if frame.f_code is backend_mod.RemoteBackend._state.__code__:+ return True+ frame = frame.f_back+ return False+++def test_same_thread_reentry_raises_while_other_threads_wait(plane, monkeypatch):+ """Code on a profile's boot path (its credential before the fetch, or anything during it) that+ reads that profile's config gets a loud ConfigBackendUnavailable at once instead of waiting on+ its own load forever; another thread still waits for the fetch in flight and shares it."""+ import threading+ import time++ from tests.waiting import wait_until++ backend = remote_pkg.get_remote_backend()+ home = plane.home+ real_token, real_request = backend_mod.client.plane_token, backend_mod.client.request+ errors: list = []+ other: dict = {}+ waiter = threading.Thread(target=lambda: other.setdefault("state", backend._state(home)), daemon=True)++ def reenter():+ started = time.monotonic()+ try:+ backend.version(home)+ except ConfigBackendUnavailable as exc:+ errors.append((str(exc), time.monotonic() - started))++ def token(h):+ if not errors:+ reenter() # before the fetch lock+ return real_token(h)++ def request(method, *args, **kwargs):+ if method == "GET" and len(errors) == 1:+ reenter() # under the fetch lock+ waiter.start()+ wait_until(lambda: _blocked_in_state(waiter), timeout=5, what="the other thread waits")+ return real_request(method, *args, **kwargs)++ monkeypatch.setattr(backend_mod.client, "plane_token", token)+ monkeypatch.setattr(backend_mod.client, "request", request)+ plane.upper = {"display": {"skin": "ares"}}+ assert backend.read_user_doc(home)["display"]["skin"] == "ares"+ assert len(errors) == 2 and all("re-entered" in msg and secs < 1.0 for msg, secs in errors)+ waiter.join(5)+ assert not waiter.is_alive() and other["state"] is backend._state(home)+ assert len(_gets(plane)) == 1 # the waiting thread used the fetch it waited for+ backend.version(home) # once loaded, the same thread reads normally+++def test_nothing_is_logged_under_a_backend_lock(plane, monkeypatch):+ """A log handler can read config, and a thread holding the handler's lock may be waiting for a+ backend lock: the boot retry warning and the write's inherited-key warning are both emitted+ with no fetch lock or profile state lock held."""+ import logging++ backend = remote_pkg.get_remote_backend()+ seen: list = []++ class Probe(logging.Handler):+ def emit(self, record):+ held = any(lk.locked() for lk in list(backend._fetch_locks.values()))+ held = held or any(st.lock._is_owned() for st in list(backend._states.values()))+ seen.append((record.getMessage(), held))++ real_request = backend_mod.client.request++ def first_get_fails(method, *args, **kwargs):+ resp = real_request(method, *args, **kwargs)+ plane.fail_status = None+ return resp++ monkeypatch.setattr(backend_mod.client, "request", first_get_fails)+ probe = Probe(level=logging.WARNING)+ backend_mod.logger.addHandler(probe)+ try:+ plane.upper = {"display": {"personality": "concise"}}+ plane.profile("default")["values"] = {"display": {"personality": "pirate"}}+ plane.fail_status = 503 # the first GET: a retryable outage, warned about before the retry+ write_config_key(plane.home / "config.yaml", "display.personality", None)+ finally:+ backend_mod.logger.removeHandler(probe)+ messages = [m for m, _ in seen]+ assert any("retrying" in m for m in messages) and any("still set by an upper level" in m for m in messages)+ assert [m for m, held in seen if held] == []diff --git a/tests/plugins/config_backends/test_remote_nous_cold_boot.py b/tests/plugins/config_backends/test_remote_nous_cold_boot.pynew file mode 100644index 00000000000..12d1cf8b5af--- /dev/null+++ b/tests/plugins/config_backends/test_remote_nous_cold_boot.py@@ -0,0 +1,182 @@+"""A Cloud agent's first remote config read, in a cold process, with the Nous credential.++In Cloud mode (no ``GATEWAY_RELAY_IDP_*``) the plane bearer is the Nous Portal access token from the+profile's ``auth.json``. Resolving it imports ``hermes_cli.auth`` inside the profile's first fetch;+that import discovers model providers, and provider discovery reads config (the gate on+pip-installed provider plugins). That read used to wait on the fetch's own lock forever, so a Cloud+agent never booted (stage2's ``refresh_dependencies`` hung). These tests run real imports in a+fresh interpreter, as the boot does; the in-process suites stub the credential and cannot see it.+"""+from __future__ import annotations++import json+import os+import subprocess+import sys+import time+from pathlib import Path++import pytest++from .stub_plane import INSTANCE, NOUS_TOKEN, StubPlane++REPO = Path(__file__).resolve().parents[3]+HARD_TIMEOUT_S = 60 # a healthy run takes about a second; the deadlock never ends++# What docker/stage2-hook.sh runs before the gateway starts: refresh_dependencies() first reads the+# plugin selection through pm.workspace (the read that hung), then the CLI reads a value.+STAGE2_SNIPPET = """+import json, os, sys+from pathlib import Path+from pm.recovery import refresh_dependencies # stage2-hook.sh's import+assert "hermes_cli.auth" not in sys.modules and "hermes_cli.config" not in sys.modules # cold+from pm.workspace import enabled_member_dirs+enabled_member_dirs() # refresh_dependencies -> venv_is_current -> expected_stamp reads this first+import providers+if os.environ.get("PROBE_PROVIDER"): # a $HERMES_HOME provider plugin loads once config is loaded+ assert providers.get_provider_profile("probe-provider") is not None+from hermes_cli.config import load_config+print("RESULT=" + json.dumps(load_config()["display"]["skin"]))+"""+++def _iso(offset_s: float) -> str:+ return time.strftime("%Y-%m-%dT%H:%M:%S+00:00", time.gmtime(time.time() + offset_s))+++def _auth_json(plane: StubPlane, *, expired: bool) -> dict:+ nous = {"access_token": "expired-token" if expired else NOUS_TOKEN, "refresh_token": "nous-refresh-1",+ "client_id": "hermes-cli-vps", "portal_base_url": plane.url,+ "expires_at": _iso(-3600 if expired else 3600)}+ return {"version": 1, "active_provider": "nous", "providers": {"nous": nous}}+++def _run(args, env):+ try:+ return subprocess.run(args, cwd=REPO, env=env, capture_output=True, text=True, timeout=HARD_TIMEOUT_S,+ stdin=subprocess.DEVNULL, check=False)+ except subprocess.TimeoutExpired as exc:+ pytest.fail(f"{args[1:]} did not finish in {HARD_TIMEOUT_S}s: the first remote read deadlocked.\n"+ f"{(exc.stderr or b'')[-3000:]!r}")+++def _value(proc) -> str:+ assert proc.returncode == 0, proc.stderr[-3000:]+ lines = [ln for ln in proc.stdout.splitlines() if ln.startswith("RESULT=")]+ assert lines, proc.stdout[-2000:] + proc.stderr[-2000:]+ return json.loads(lines[-1][len("RESULT="):])+++PROBE_INIT = (+ "from providers import register_provider\n"+ "from providers.base import ProviderProfile\n"+ "register_provider(ProviderProfile(name='probe-provider', base_url='https://probe.test/v1'))\n")+++def _install_probe_provider(home: Path, layout: str) -> None:+ """A $HERMES_HOME provider plugin: importing one reads ``plugins.isolation`` from config."""+ plugin = home / "plugins" / ("model-providers/probe" if layout == "model-providers" else "probe")+ plugin.mkdir(parents=True)+ (plugin / "plugin.yaml").write_text("name: probe\nkind: model-provider\nversion: 0.0.1\n")+ (plugin / "__init__.py").write_text(PROBE_INIT)++[email protected]("expired, layout", [(False, None), (True, None), (False, "model-providers"), (False, "flat")],+ ids=["valid-token", "token-refreshed-at-boot", "home-provider-plugin", "flat-provider-plugin"])+def test_cloud_agent_first_remote_read_completes_cold(tmp_path, expired, layout):+ home = tmp_path / "home"+ home.mkdir()+ if layout:+ _install_probe_provider(home, layout)+ with StubPlane() as plane:+ plane.upper = {"display": {"skin": "ares"}}+ (home / "auth.json").write_text(json.dumps(_auth_json(plane, expired=expired)))+ env = {k: v for k, v in os.environ.items() if k in {"PATH", "LANG", "TZ", "TMPDIR", "PYTHONHASHSEED"}}+ env.update(HOME=str(tmp_path), HERMES_HOME=str(home), PYTHONPATH=str(REPO), PYTHONDONTWRITEBYTECODE="1",+ HERMES_CONFIG_BACKEND="remote", HERMES_CONFIG_REMOTE_URL=plane.url,+ HERMES_CONFIG_INSTANCE_ID=INSTANCE, PROBE_PROVIDER="1" if layout else "")+ assert not any(k.startswith("GATEWAY_RELAY_IDP_") for k in env) # Cloud: the Nous credential++ assert _value(_run([sys.executable, "-c", STAGE2_SNIPPET], env)) == "ares"+ cli = _run([sys.executable, "-m", "hermes_cli.main", "config", "get", "display.skin"], env)+ assert cli.returncode == 0, cli.stderr[-3000:]+ assert cli.stdout.strip().splitlines()[-1] == "ares"++ gets = [r for r in plane.requests if r["method"] == "GET"]+ assert len(gets) >= 2 and {r["auth"] for r in gets} == {f"Bearer {NOUS_TOKEN}"}+ assert plane.nous_refreshes == (1 if expired else 0)+ assert not (home / "config.yaml").exists()+++AUTH_IMPORT_READS_NO_CONFIG = """+import sys+import hermes_cli.config_backend as cb+reads = []+def refuse(*a, **k):+ reads.append(1)+ raise cb.ConfigBackendUnavailable("this test's backend refuses every read")+cb._route = refuse # every config read, through any backend, now raises+import hermes_cli.auth+from hermes_cli.auth import resolve_nous_access_token+assert resolve_nous_access_token() == sys.argv[1]+assert reads == [], reads+print("RESULT=" + '"ok"')+"""+++def test_importing_auth_and_resolving_the_nous_token_read_no_config(tmp_path):+ """The Cloud credential path (import hermes_cli.auth, resolve the Nous token) must not need the+ config it is used to fetch: under a backend whose every read raises, both succeed cold."""+ home = tmp_path / "home"+ home.mkdir()+ _install_probe_provider(home, "model-providers") # a $HERMES_HOME provider plugin is not read either+ with StubPlane() as plane:+ (home / "auth.json").write_text(json.dumps(_auth_json(plane, expired=False)))+ env = {k: v for k, v in os.environ.items() if k in {"PATH", "LANG", "TZ", "TMPDIR", "PYTHONHASHSEED"}}+ env.update(HOME=str(tmp_path), HERMES_HOME=str(home), PYTHONPATH=str(REPO), PYTHONDONTWRITEBYTECODE="1")+ assert _value(_run([sys.executable, "-c", AUTH_IMPORT_READS_NO_CONFIG, NOUS_TOKEN], env)) == "ok"+++CONCURRENT_AUTH_IMPORT = """+import json, os, sys, threading+from pathlib import Path+from plugins.config_backends.remote import client+from plugins.config_backends.remote import get_remote_backend+home = Path(os.environ["HERMES_HOME"])+in_fetch, imported = threading.Event(), threading.Event()+real_request = client.request+waited = {}+def request(method, *args, **kwargs): # thread A, holding the profile's fetch lock+ in_fetch.set()+ waited["b_done"] = imported.wait(20)+ return real_request(method, *args, **kwargs)+client.request = request+def b():+ in_fetch.wait(20)+ import hermes_cli.auth # cold, while A holds the fetch lock+ imported.set()+tb = threading.Thread(target=b, daemon=True)+tb.start()+get_remote_backend().version(home) # thread A: the profile's first read+tb.join(20)+assert waited.get("b_done") and not tb.is_alive(), "the cold auth import waited for the fetch in flight"+from hermes_cli.config import load_config+print("RESULT=" + json.dumps(load_config()["display"]["skin"]))+"""+++def test_cold_auth_import_on_another_thread_never_waits_for_the_fetch(tmp_path):+ """Thread A holds a profile's fetch lock; thread B cold-imports hermes_cli.auth. The import+ must not read config (it would wait for A's fetch while A, resolving its own credential, can+ need the import lock B holds)."""+ from .stub_plane import remote_env++ home = tmp_path / "home"+ home.mkdir()+ with StubPlane() as plane:+ plane.upper = {"display": {"skin": "ares"}}+ env = {k: v for k, v in os.environ.items() if k in {"PATH", "LANG", "TZ", "TMPDIR", "PYTHONHASHSEED"}}+ env.update(remote_env(plane), HOME=str(tmp_path), HERMES_HOME=str(home), PYTHONPATH=str(REPO),+ PYTHONDONTWRITEBYTECODE="1")+ assert _value(_run([sys.executable, "-c", CONCURRENT_AUTH_IMPORT], env)) == "ares"+