The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(auth): `hermes auth reset` survives a live session's next pool flush
teknium1a564f777469a
diff --git a/agent/credential_pool.py b/agent/credential_pool.pyindex bff676c97f3..281be8e5fd9 100644--- a/agent/credential_pool.py+++ b/agent/credential_pool.py@@ -217,6 +217,9 @@ class PooledCredential:last_error_reason: Optional[str] = Nonelast_error_message: Optional[str] = Nonelast_error_reset_at: Optional[float] = None+ # Epoch of the last deliberate ``hermes auth reset`` of this entry. Sticky: a later exhaustion+ # stamps a newer ``last_status_at``, so "reset postdates status" stays decidable across processes.+ status_cleared_at: Optional[float] = Nonebase_url: Optional[str] = Noneexpires_at: Optional[str] = Noneexpires_at_ms: Optional[int] = None@@ -1727,14 +1730,32 @@ class CredentialPool(CredentialPoolAdminMixin, CredentialPoolModelCooldownMixin)for entry in pending:self._refresh_entry(entry, force=False)+ def _reset_cleared_after(self, entry: PooledCredential) -> Optional[float]:+ """Epoch of a ``hermes auth reset`` persisted by another process AFTER *entry*'s status, else None."""+ try:+ row = next((p for p in read_credential_pool(self.provider)+ if isinstance(p, dict) and p.get("id") == entry.id), None)+ cleared = _parse_absolute_timestamp((row or {}).get("status_cleared_at"))+ except Exception as exc:+ logger.debug("Pool entry %s: could not read reset marker: %s", entry.id, exc)+ return None+ return cleared if cleared and cleared > (entry.last_status_at or 0.0) else None+def _resync_stale_entry(self, entry: PooledCredential) -> PooledCredential:"""Re-read an exhausted/DEAD singleton-seeded entry from its token authority.The user may have re-authed (``hermes model`` / ``hermes auth``, theClaude Code CLI, another profile) leaving fresh tokens on disk while- the pool entry is frozen behind ``last_error_reset_at``.+ the pool entry is frozen behind ``last_error_reset_at``. A ``hermes auth+ reset`` run from another process while this pool is live is honoured the+ same way (#89415): the in-memory cooldown would otherwise outlive it."""- if entry.source != _RESYNC_SOURCE.get(self.provider) or entry.last_status not in {STATUS_EXHAUSTED, STATUS_DEAD}:+ if entry.last_status not in {STATUS_EXHAUSTED, STATUS_DEAD}:+ return entry+ cleared_at = self._reset_cleared_after(entry)+ if cleared_at is not None:+ return self._adopt(entry, persist=False, **_MARK_OK, status_cleared_at=cleared_at)+ if entry.source != _RESYNC_SOURCE.get(self.provider):return entryif self.provider == "anthropic":return self._sync_anthropic_entry_from_credentials_file(entry)diff --git a/agent/credential_pool_admin.py b/agent/credential_pool_admin.pyindex 441890a2958..515a2f09b90 100644--- a/agent/credential_pool_admin.py+++ b/agent/credential_pool_admin.py@@ -1,6 +1,7 @@"""Locked credential-pool administration and target resolution."""from __future__ import annotations+import timefrom dataclasses import replacefrom typing import Any, Optional, Tuple, TYPE_CHECKING@@ -11,7 +12,9 @@ if TYPE_CHECKING:def _cleared_status_copy(entry: PooledCredential) -> PooledCredential:from agent.credential_pool import _CLEAR_STATUS- return replace(entry, **_CLEAR_STATUS, model_cooldowns=None,+ # The reset marker lets a live pool in another process tell "reset after my cooldown" from+ # "never had a status" — both read as bare None on disk (#89415).+ return replace(entry, **_CLEAR_STATUS, model_cooldowns=None, status_cleared_at=time.time(),extra={k: v for k, v in entry.extra.items() if k != "failure_reason"})diff --git a/hermes_cli/auth.py b/hermes_cli/auth.pyindex 5b121a0f613..8cbe8576a16 100644--- a/hermes_cli/auth.py+++ b/hermes_cli/auth.py@@ -779,7 +779,7 @@ def read_credential_pool(provider_id: Optional[str] = None) -> Dict[str, Any]:_POOL_STATUS_FIELDS = ("last_status", "last_status_at", "last_error_code", "last_error_reason", "last_error_message",- "last_error_reset_at")+ "last_error_reset_at", "status_cleared_at")def _merge_disk_cooldown_state(@@ -789,7 +789,10 @@ def _merge_disk_cooldown_state(``write_credential_pool`` persists an in-memory snapshot that may predate another processmarking the same credential exhausted/dead; without this merge the later rewrite resurrects a- rate-limited key as healthy and both processes resume hammering it."""+ rate-limited key as healthy and both processes resume hammering it. The mirror image is a+ ``hermes auth reset`` that postdates the snapshot's cooldown (``status_cleared_at`` newer than+ its ``last_status_at``): the disk row wins there too, or a live session's next ordinary flush+ would write the reset cooldown straight back (#89415)."""if not isinstance(disk_entry, dict):return entrytry:@@ -802,7 +805,12 @@ def _merge_disk_cooldown_state(from agent.credential_pool_model_cooldowns import merge_model_cooldownsmerged_cooldowns = merge_model_cooldowns(disk_entry.get("model_cooldowns"), entry.get("model_cooldowns"))merged = {**entry, "model_cooldowns": merged_cooldowns} if merged_cooldowns else entry+ disk_status_fields = {f: disk_entry.get(f) for f in _POOL_STATUS_FIELDS}+ mem_ts = _parse_absolute_timestamp(entry.get("last_status_at")) or 0.0+ cleared_ts = _parse_absolute_timestamp(disk_entry.get("status_cleared_at")) or 0.0+ if entry.get("last_status") in (STATUS_DEAD, STATUS_EXHAUSTED) and cleared_ts > mem_ts:+ return {**merged, **disk_status_fields}disk_status = disk_entry.get("last_status")if disk_status not in (STATUS_DEAD, STATUS_EXHAUSTED):return merged@@ -813,14 +821,13 @@ def _merge_disk_cooldown_state(if mem_access and disk_access and mem_access != disk_access:return entrydisk_ts = _parse_absolute_timestamp(disk_entry.get("last_status_at")) or 0.0- mem_ts = _parse_absolute_timestamp(entry.get("last_status_at")) or 0.0if disk_ts <= mem_ts:return mergedif disk_status == STATUS_EXHAUSTED:until = _exhausted_until(PooledCredential.from_dict(provider_id, disk_entry))if until is None or until <= time.time():return merged- return {**merged, **{f: disk_entry.get(f) for f in _POOL_STATUS_FIELDS}}+ return {**merged, **disk_status_fields}except Exception: # pragma: no cover - best-effort mergereturn entrydiff --git a/tests/agent/test_credential_pool.py b/tests/agent/test_credential_pool.pyindex 4213bb611fc..faa3e4e36f5 100644--- a/tests/agent/test_credential_pool.py+++ b/tests/agent/test_credential_pool.py@@ -2209,3 +2209,52 @@ def test_a_persist_without_declared_intent_still_cannot_erase_a_cooldown(entry = _disk_entry(tmp_path)assert entry["last_status"] == "exhausted"assert entry["last_error_code"] == 402+++def test_live_pool_flush_does_not_resurrect_a_cooldown_reset_by_another_process(tmp_path, monkeypatch):+ """A running session's next ordinary flush must not undo ``hermes auth reset`` (#89415).++ The live pool still holds the entry as exhausted in memory; the CLI in another+ process clears it on disk. Before the fix the cleared disk row had no status,+ so the recency merge let the stale in-memory cooldown win and the reset was+ silently reverted by the next rotation / refresh / sibling 429. The reset's+ own ``status_cleared_at`` marker now outranks any older in-memory status, on+ the save side (disk stays clear) and on the read side (the live pool lifts+ its cooldown and serves the credential again).+ """+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))+ _exhausted_billing_store(tmp_path, age_seconds=5)++ from agent.credential_pool import load_pool++ live = load_pool("deepseek") # process A: session already running+ assert live.has_available() is False+ assert load_pool("deepseek").reset_statuses() == 1 # process B: `hermes auth reset deepseek`++ live._persist() # A's next ordinary flush+ assert _disk_entry(tmp_path)["last_status"] is None+ assert live.select() is not None # A honours the reset without a restart+ assert _disk_entry(tmp_path)["last_status"] != "exhausted"+++def test_an_exhaustion_newer_than_the_reset_still_binds(tmp_path, monkeypatch):+ """The reset marker is sticky, so it must only outrank OLDER statuses.++ Reset first, then a fresh 402 on the same entry: the new cooldown postdates+ the reset and has to survive both a flush and re-selection, or a single+ reset would make the credential immune to benching for the rest of the run.+ """+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))+ _exhausted_billing_store(tmp_path, age_seconds=5)++ from agent.credential_pool import load_pool++ assert load_pool("deepseek").reset_statuses() == 1+ live = load_pool("deepseek")+ assert live.select() is not None+ live.mark_exhausted_and_rotate(status_code=402, api_key_hint="sk-test",+ error_context={"message": "Insufficient Balance"})++ live._persist()+ assert _disk_entry(tmp_path)["last_status"] == "exhausted"+ assert live.select() is Nonediff --git a/website/docs/user-guide/features/credential-pools.md b/website/docs/user-guide/features/credential-pools.mdindex f8c4505cab8..d18ce29beaf 100644--- a/website/docs/user-guide/features/credential-pools.md+++ b/website/docs/user-guide/features/credential-pools.md@@ -125,7 +125,7 @@ Type [1/2]:| `hermes auth add <provider> --priority 0` | Add a credential and place it first in the `fill_first` order || `hermes auth priority <provider> <target> <n>` | Move a credential to priority `n` (0 = tried first); the rest are renumbered || `hermes auth remove <provider> <index>` | Remove credential by 1-based index |-| `hermes auth reset <provider>` | Clear all cooldowns/exhaustion status |+| `hermes auth reset <provider>` | Clear all cooldowns/exhaustion status (applies to running sessions too: a live gateway or chat picks the reset up on its next request instead of writing its stale cooldown back) || `hermes auth reset <provider> <target>` | Clear the cooldown on one credential by index, id, or label || `hermes auth refresh <provider> [target]` | Refresh one OAuth credential's tokens and return it to rotation (proves the grant is alive; the next request re-checks quota) |