The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
perf(auth): persist the forked-OAuth clean mark so a fresh process skips the heal's locks
John Paul Soliva57e03e2be66c
diff --git a/hermes_cli/auth_oauth_grants.py b/hermes_cli/auth_oauth_grants.pyindex 71932322cdc..6e1ee26f7cf 100644--- a/hermes_cli/auth_oauth_grants.py+++ b/hermes_cli/auth_oauth_grants.py@@ -131,9 +131,94 @@ _OAUTH_TOKEN_FIELDS = (_oauth_heal_notices: List[str] = []-# provider -> (profile auth.json path, auth.json mtime_ns, singleton mtime_ns) of the last store+# provider -> fingerprint (see ``_heal_forked_single_use_oauth_grants``) of the last store# verified fork-free; lets load_pool() skip the locked scan.-_oauth_heal_clean_marks: Dict[str, Tuple[str, Optional[int], Optional[int]]] = {}+_oauth_heal_clean_marks: Dict[str, Tuple[Any, ...]] = {}++# Filename for the ON-DISK twin of ``_oauth_heal_clean_marks``. The in-memory mark only silences+# the heal for the life of ONE process, so every fresh `hermes` invocation and every new worker+# re-pays the heal's two nested EXCLUSIVE auth-store locks just to discover there is nothing to+# consolidate. Behind a sibling holding those locks that costs a full AUTH_LOCK_TIMEOUT_SECONDS+# per provider (measured: 30s for two providers on an otherwise-idle machine) before the process+# can do anything at all.+_OAUTH_HEAL_CLEAN_MARK_FILENAME = "oauth_heal_clean.json"+++def _size(p: Optional[Path]) -> Optional[int]:+ try:+ return p.stat().st_size if p is not None else None+ except OSError:+ return None+++def _oauth_heal_clean_mark_path() -> Optional[Path]:+ """Where the persisted clean marks live, or None when unavailable."""+ try:+ from hermes_cli.auth import _auth_file_path++ return _auth_file_path().parent / "cache" / _OAUTH_HEAL_CLEAN_MARK_FILENAME+ except Exception:+ return None+++def _persisted_oauth_heal_fingerprint(provider_id: str) -> Optional[list]:+ """The stored clean-mark fingerprint for ``provider_id``, or None.++ Pure cache read: any problem at all (absent, unreadable, corrupt, wrong shape) means "no+ mark", which falls through to the locked heal — the pre-existing behaviour. It must never+ raise into a credential path.+ """+ path = _oauth_heal_clean_mark_path()+ if path is None:+ return None+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ except Exception:+ return None+ if not isinstance(data, dict):+ return None+ stored = data.get(provider_id)+ return stored if isinstance(stored, list) else None+++def _persist_oauth_heal_clean_mark(provider_id: str, fingerprint: tuple) -> None:+ """Record ``provider_id`` as clean for this exact fingerprint.++ Best-effort by design: a failed write only means the next process re-runs the heal, which is+ what it did before this cache existed.+ """+ path = _oauth_heal_clean_mark_path()+ if path is None:+ return+ try:+ from utils import atomic_json_write++ try:+ existing = json.loads(path.read_text(encoding="utf-8"))+ except Exception:+ existing = {}+ if not isinstance(existing, dict):+ existing = {}+ marks = {+ key: value for key, value in existing.items()+ if isinstance(key, str) and isinstance(value, list)+ }+ new_mark = list(fingerprint)+ if marks.get(provider_id) == new_mark:+ return # already recorded; skip the rewrite+ marks[provider_id] = new_mark+ path.parent.mkdir(parents=True, exist_ok=True)+ # 0o600 like the MCP schema cache: this names credential-store paths.+ atomic_json_write(path, marks, mode=0o600)+ except Exception:+ logger.debug(+ "%s: could not persist the forked-OAuth clean mark", provider_id, exc_info=True)+++def _mark_oauth_heal_clean(provider_id: str, fingerprint: tuple) -> None:+ """Stamp the clean mark both in memory and on disk."""+ _oauth_heal_clean_marks[provider_id] = fingerprint+ _persist_oauth_heal_clean_mark(provider_id, fingerprint)def consume_oauth_heal_notices() -> List[str]:@@ -479,20 +564,45 @@ def _heal_forked_single_use_oauth_grants(provider_id: str) -> Optional[Dict[str,root_singleton = root_path.parent / ".anthropic_oauth.json" if is_anthropic else None# Hot-path short-circuit: load_pool() runs per model call. Once this profile's store was- # verified clean for *provider_id*, skip the locked read-modify-write until the profile's own- # files change (mtime key).- fingerprint = (str(profile_path), _mtime_ns(profile_path), _mtime_ns(profile_singleton))+ # verified clean for *provider_id*, skip the locked read-modify-write until one of the files+ # it reads changes.+ #+ # The ROOT store is part of the fingerprint even though only the profile side is read above:+ # this heal consolidates root -> profile, so a new forked grant appearing in ROOT must+ # invalidate the mark. The in-memory mark omitted it and got away with it because it died+ # with the process; a persisted mark would otherwise keep skipping a heal that has become+ # necessary. Sizes ride along with the mtimes for the same reason: a metadata-preserving+ # rewrite (``rsync -t``, ``tar -p``, a restore) would otherwise leave a stale mark looking+ # current indefinitely rather than for one process.+ fingerprint = (+ str(profile_path),+ _mtime_ns(profile_path),+ _mtime_ns(profile_singleton),+ str(root_path),+ _mtime_ns(root_path),+ _mtime_ns(root_singleton),+ _size(profile_path),+ _size(profile_singleton),+ _size(root_path),+ _size(root_singleton),+ )if _oauth_heal_clean_marks.get(provider_id) == fingerprint:return None- if fingerprint[1] is None and fingerprint[2] is None:+ # Same check against the on-disk mark, BEFORE taking any lock: a fresh process would+ # otherwise pay two nested exclusive auth-store locks — a full AUTH_LOCK_TIMEOUT_SECONDS+ # each behind a sibling holding them — only to find nothing to consolidate.+ if _persisted_oauth_heal_fingerprint(provider_id) == list(fingerprint):_oauth_heal_clean_marks[provider_id] = fingerprintreturn None+ if fingerprint[1] is None and fingerprint[2] is None:+ _mark_oauth_heal_clean(provider_id, fingerprint)+ return Noneif _is_same_auth_store(profile_path, root_path):# The profile's auth.json IS the root store (symlink/hardlink alias — a deliberate way to# share one grant). Both "sides" would read the same file, every OAuth row would match# itself, and the strip would write through the alias and delete the shared credential.# Nothing to consolidate; the mtime mark keeps this off the per-call hot path.- _oauth_heal_clean_marks[provider_id] = fingerprint+ _mark_oauth_heal_clean(provider_id, fingerprint)# See #101356.logger.debug("%s: forked-OAuth heal skipped, %s is the root store", provider_id, profile_path)return None@@ -509,7 +619,7 @@ def _heal_forked_single_use_oauth_grants(provider_id: str) -> Optional[Dict[str,run.heal_provider_block()run.heal_profile_singleton(profile_singleton)if not run.dirty:- _oauth_heal_clean_marks[provider_id] = fingerprint+ _mark_oauth_heal_clean(provider_id, fingerprint)return Nonerun.sync_root_singleton_with_pkce_row()summary = run.summarydiff --git a/tests/agent/test_credential_pool_profile_oauth_fork.py b/tests/agent/test_credential_pool_profile_oauth_fork.pyindex 0c96c4431e4..b16e8993d7f 100644--- a/tests/agent/test_credential_pool_profile_oauth_fork.py+++ b/tests/agent/test_credential_pool_profile_oauth_fork.py@@ -694,3 +694,173 @@ def test_heal_same_store_skip_is_memoized_off_the_hot_path(fleet, monkeypatch):monkeypatch.setattr(auth_mod, "_is_same_auth_store", lambda *a: calls.append(a) or True)assert auth_mod.heal_forked_single_use_oauth_grants("openai-codex") is Noneassert calls == [], "same-store check ran again despite the clean mark"+++# ── E. the clean mark outlives the process ──────────────────────────────+#+# The in-memory mark only silences the heal for one process, so every fresh+# `hermes` invocation re-paid its two nested EXCLUSIVE auth-store locks to+# rediscover a store it had already cleared. Persisting the mark removes that,+# but a mark that outlives the process must also invalidate on anything the+# heal reads -- including the ROOT store, which the in-memory fingerprint+# could safely ignore precisely because it died with the process.++def _new_process(auth_mod):+ """Simulate a fresh `hermes` invocation: in-memory state gone, disk kept."""+ auth_mod._oauth_heal_clean_marks.clear()+ auth_mod._global_auth_store_cache = None+++def _count_locks(monkeypatch):+ """Count _auth_store_lock acquisitions, still really taking them.++ The heal imports the lock from ``hermes_cli.auth`` inside the function, so+ patching it on that module is what the call site actually resolves.+ """+ import contextlib++ import hermes_cli.auth as auth_mod++ taken = []+ real = auth_mod._auth_store_lock++ @contextlib.contextmanager+ def counting(*a, **k):+ taken.append(k.get("target_path"))+ with real(*a, **k):+ yield++ monkeypatch.setattr(auth_mod, "_auth_store_lock", counting)+ return taken+++def _kid_with_api_key_only(fleet, name="kid"):+ """Profile whose store exists and is genuinely fork-free, so the heal has+ to run its locked body to find that out (not the no-files fast path)."""+ pdir = _profile(fleet, name)+ pdir.mkdir(parents=True, exist_ok=True)+ (pdir / "auth.json").write_text(json.dumps({+ "version": 1, "providers": {},+ "credential_pool": {"openai": [{+ "id": "k1", "label": "static", "auth_type": "api_key",+ "priority": 0, "source": "manual", "access_token": "sk-local",+ }]},+ }))+ return pdir+++def test_clean_mark_persists_so_a_fresh_process_takes_no_auth_lock(fleet, monkeypatch):+ import hermes_cli.auth as auth_mod+ from hermes_cli import auth_oauth_grants as grants++ kid = _kid_with_api_key_only(fleet)+ fleet["use"](kid)+ first = _count_locks(monkeypatch)+ assert auth_mod.heal_forked_single_use_oauth_grants("anthropic") is None+ assert len(first) == 2, "cold heal should take the profile and root locks"+ assert grants._oauth_heal_clean_mark_path().exists(), "clean mark not written"++ _new_process(auth_mod)+ second = _count_locks(monkeypatch)+ assert auth_mod.heal_forked_single_use_oauth_grants("anthropic") is None+ assert second == [], "a fresh process re-locked the auth store to redo a clean heal"+++def test_persisted_mark_still_re_heals_when_the_root_store_gains_a_grant(fleet):+ """The mark may not outlive the facts. Root acquiring a counterpart turns+ a row the heal deliberately KEPT into a fork it must strip -- with the+ profile's own files untouched, so only root's stamp can catch it."""+ import hermes_cli.auth as auth_mod+ from hermes_cli import auth_oauth_grants as grants++ root = fleet["root"]+ store = json.loads((root / "auth.json").read_text())+ store["credential_pool"].pop("anthropic")+ (root / "auth.json").write_text(json.dumps(store))++ kid = _kid_with_api_key_only(fleet, "kid2")+ fork = {+ "id": "abc123", "label": "team-grant", "auth_type": "oauth",+ "priority": 0, "source": "manual:hermes_pkce",+ "access_token": "sk-ant-oat01-AT0", "refresh_token": "sk-ant-ort-RT0",+ "expires_at_ms": int((time.time() + 3600) * 1000),+ "base_url": "https://api.anthropic.com",+ }+ kid_store = json.loads((kid / "auth.json").read_text())+ kid_store["credential_pool"]["anthropic"] = [dict(fork)]+ (kid / "auth.json").write_text(json.dumps(kid_store))++ fleet["use"](kid)+ assert auth_mod.heal_forked_single_use_oauth_grants("anthropic") is None+ assert fleet["rows"](kid), "the only surviving copy must not be stripped"+ marked = grants._oauth_heal_clean_mark_path().read_text()++ store["credential_pool"]["anthropic"] = [dict(fork)]+ (root / "auth.json").write_text(json.dumps(store))+ _new_process(auth_mod)+ assert auth_mod.heal_forked_single_use_oauth_grants("anthropic") is not None, (+ "the persisted mark skipped a heal that had become necessary")+ assert not fleet["rows"](kid), "the fork survived in the profile store"++ # A heal that actually did work writes no mark, so the one on disk is now+ # stale -- it describes the pre-heal files and can no longer match. The+ # next process re-checks, finds the store clean, and re-stamps.+ _new_process(auth_mod)+ assert auth_mod.heal_forked_single_use_oauth_grants("anthropic") is None+ assert grants._oauth_heal_clean_mark_path().read_text() != marked+++def test_unreadable_clean_mark_falls_back_to_healing(fleet, monkeypatch):+ """The mark is a cache: corrupt, truncated or wrong-shaped content must+ mean 'unknown' and re-run the heal, never raise into a credential path."""+ import hermes_cli.auth as auth_mod+ from hermes_cli import auth_oauth_grants as grants++ kid = _kid_with_api_key_only(fleet, "kid3")+ fleet["use"](kid)+ assert auth_mod.heal_forked_single_use_oauth_grants("anthropic") is None+ mark = grants._oauth_heal_clean_mark_path()++ taken = _count_locks(monkeypatch)+ for junk in ("{not json", "[]", '{"anthropic": "clean"}', ""):+ mark.write_text(junk)+ _new_process(auth_mod)+ taken.clear()+ assert auth_mod.heal_forked_single_use_oauth_grants("anthropic") is None+ assert len(taken) == 2, f"{junk!r} did not fall back to the locked heal"+++def test_persisted_mark_invalidates_on_a_size_change_that_keeps_the_mtime(fleet, monkeypatch):+ """An mtime-only key is fine for a mark that dies with the process; one+ that outlives it must also survive `rsync -t` / `tar -p` / a restore,+ which put a file's timestamp back after rewriting its contents."""+ import hermes_cli.auth as auth_mod++ kid = _kid_with_api_key_only(fleet, "kid4")+ fleet["use"](kid)+ assert auth_mod.heal_forked_single_use_oauth_grants("anthropic") is None++ target = kid / "auth.json"+ before = target.stat()+ target.write_text(target.read_text() + " " * 32)+ os.utime(target, ns=(before.st_atime_ns, before.st_mtime_ns))+ assert target.stat().st_mtime_ns == before.st_mtime_ns, "mtime was not restored"++ _new_process(auth_mod)+ taken = _count_locks(monkeypatch)+ assert auth_mod.heal_forked_single_use_oauth_grants("anthropic") is None+ assert len(taken) == 2, "a same-mtime rewrite kept the stale clean mark alive"+++def test_clean_mark_records_no_credential_material(fleet):+ """It lands next to the store it describes; it must stay a stat cache."""+ import hermes_cli.auth as auth_mod+ from hermes_cli import auth_oauth_grants as grants++ kid = _kid_with_api_key_only(fleet, "kid5")+ fleet["use"](kid)+ assert auth_mod.heal_forked_single_use_oauth_grants("anthropic") is None+ body = grants._oauth_heal_clean_mark_path().read_text()+ for secret in ("sk-ant-oat01", "sk-ant-ort", "sk-static-key", "sk-local",+ "access_token", "refresh_token"):+ assert secret not in body, f"clean mark leaked {secret}"