Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(subscription): poll with the refreshed credentials-file OAuth token (#3916)

yi1112dc9fc22f09e
diff --git a/headroom/subscription/tracker.py b/headroom/subscription/tracker.py
index 818ae6880..14bdf5b26 100644
--- a/headroom/subscription/tracker.py
+++ b/headroom/subscription/tracker.py
@@ -399,16 +399,31 @@ class SubscriptionTracker(QuotaTracker):
is_active = self._state.is_active(active_window_s=self._active_window_s)
token = self._current_token
- if not is_active:
- # Try background poll using credentials file token
- from headroom.subscription.client import read_cached_oauth_token
+ # Always consult the credentials file: it is the source Claude Code
+ # refreshes in place, so it holds the *current* token. `self._current_token`
+ # is a snapshot of the last proxied Authorization header and goes stale
+ # as soon as Claude Code rotates its OAuth token — it is only replaced
+ # when a request flows through the proxy, which an idle client never
+ # does. Preferring it (`token or bg_token`) therefore pinned polling to
+ # an expired token and surfaced as permanent `poll_errors` /
+ # "fetch returned None" with a stale `polled_at` (issue #3913).
+ from headroom.subscription.client import read_cached_oauth_token
+
+ bg_token = read_cached_oauth_token()
+ if not is_active and not bg_token:
+ return
- bg_token = read_cached_oauth_token()
- if not bg_token:
- return
- token = token or bg_token
+ snapshot = None
+ # Fresh credentials-file token first, so a normal poll costs one request.
+ if bg_token:
+ snapshot = await self._client.fetch(bg_token)
+ # Only spend a second request on the remembered header token when it is
+ # a *different* token that could still be the live one (no credentials
+ # file, e.g. CLAUDE_CODE_OAUTH_TOKEN absent and polling off a proxied
+ # header).
+ if snapshot is None and token and token != bg_token:
+ snapshot = await self._client.fetch(token)
- snapshot = await self._client.fetch(token)
if snapshot is None:
with self._lock:
self._state.mark_error("fetch returned None")
diff --git a/tests/test_subscription_poll_credential_policy.py b/tests/test_subscription_poll_credential_policy.py
index 790245754..9ed1826d5 100644
--- a/tests/test_subscription_poll_credential_policy.py
+++ b/tests/test_subscription_poll_credential_policy.py
@@ -103,9 +103,11 @@ def test_foreign_bearer_never_reaches_the_usage_poll(tmp_path, monkeypatch) -> N
tracker._client.fetch = fetch # type: ignore[method-assign]
asyncio.run(tracker._maybe_poll())
- # The poll ran (the caller marked activity) but with no adopted token, so
- # the client falls back to the operator's own credential.
- assert polled == [None]
+ # Activity was marked, but with no adopted local-operator token and no
+ # operator-configured credential there is nothing to poll — and specifically
+ # the foreign bearer must never be spent. Skip the unnecessary fetch(None).
+ assert polled == []
+ assert "tenant-b-oauth-token" not in {t for t in polled if t}
# ---------------------------------------------------------------------------
diff --git a/tests/test_subscription_tracker.py b/tests/test_subscription_tracker.py
index 1ae4267f9..e95834a19 100644
--- a/tests/test_subscription_tracker.py
+++ b/tests/test_subscription_tracker.py
@@ -174,6 +174,106 @@ async def test_maybe_poll_handles_inactive_and_none_snapshot(
assert tracker._state.poll_errors == 1
+async def test_maybe_poll_prefers_refreshed_credentials_token_over_stale_header(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Regression (#3913): the credentials file is where Claude Code writes the
+ *refreshed* OAuth token. Polling the remembered Authorization-header token
+ first pinned every poll to an expired credential, so `/stats` reported
+ permanent `poll_errors` and a `polled_at` that never advanced."""
+ monkeypatch.setattr(SubscriptionTracker, "_load_persisted_state", lambda self: None)
+ tracker = SubscriptionTracker()
+ # Token captured from a proxied local-operator request, before Claude Code rotated it.
+ tracker.notify_active("Bearer stale-header-token", from_local_operator=True)
+
+ monkeypatch.setattr(
+ "headroom.subscription.client.read_cached_oauth_token", lambda: "refreshed-file-token"
+ )
+
+ snapshot = _make_snapshot()
+ attempted: list[str | None] = []
+
+ async def fetch_snapshot(token: str | None):
+ attempted.append(token)
+ # The stale header token is what Anthropic rejects with 401 -> None.
+ if token == "stale-header-token":
+ return None
+ return snapshot
+
+ tracker._client = SimpleNamespace(fetch=fetch_snapshot)
+ monkeypatch.setattr(tracker, "_persist_state", lambda: None)
+
+ await tracker._maybe_poll()
+
+ assert attempted == ["refreshed-file-token"]
+ assert tracker.latest_snapshot is snapshot
+ assert tracker._state.poll_errors == 0
+ assert tracker._state.last_error is None
+
+
+async def test_maybe_poll_falls_back_to_header_token_when_file_token_rejected(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The remembered header token is still the only credential when no
+ credentials file exists, so a rejection of the file token must fall back to
+ it rather than mark the tracker errored."""
+ monkeypatch.setattr(SubscriptionTracker, "_load_persisted_state", lambda self: None)
+ tracker = SubscriptionTracker()
+ tracker.notify_active("Bearer header-only-token", from_local_operator=True)
+
+ monkeypatch.setattr(
+ "headroom.subscription.client.read_cached_oauth_token", lambda: "revoked-file-token"
+ )
+
+ snapshot = _make_snapshot()
+ attempted: list[str | None] = []
+
+ async def fetch_snapshot(token: str | None):
+ attempted.append(token)
+ if token == "revoked-file-token":
+ return None
+ return snapshot
+
+ tracker._client = SimpleNamespace(fetch=fetch_snapshot)
+ monkeypatch.setattr(tracker, "_persist_state", lambda: None)
+
+ await tracker._maybe_poll()
+
+ assert attempted == ["revoked-file-token", "header-only-token"]
+ assert tracker.latest_snapshot is snapshot
+ assert tracker._state.poll_errors == 0
+
+
+async def test_maybe_poll_single_request_when_file_token_matches_header(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Identical tokens must not be spent twice — the common case for a proxy
+ session whose credentials file holds the same token as the header."""
+ monkeypatch.setattr(SubscriptionTracker, "_load_persisted_state", lambda self: None)
+ tracker = SubscriptionTracker()
+ tracker.notify_active("Bearer shared-token", from_local_operator=True)
+
+ monkeypatch.setattr(
+ "headroom.subscription.client.read_cached_oauth_token", lambda: "shared-token"
+ )
+
+ attempted: list[str | None] = []
+
+ async def fetch_snapshot(token: str | None):
+ attempted.append(token)
+ return _make_snapshot()
+
+ tracker._client = SimpleNamespace(fetch=fetch_snapshot)
+ monkeypatch.setattr(tracker, "_persist_state", lambda: None)
+
+ await tracker._maybe_poll()
+
+ assert attempted == ["shared-token"]
+
+
@pytest.mark.asyncio
async def test_maybe_poll_success_updates_state_and_metrics(
monkeypatch: pytest.MonkeyPatch,
@@ -181,6 +281,9 @@ async def test_maybe_poll_success_updates_state_and_metrics(
monkeypatch.setattr(SubscriptionTracker, "_load_persisted_state", lambda self: None)
tracker = SubscriptionTracker()
tracker.notify_active("Bearer live-oauth-token", from_local_operator=True)
+ # Pin the credentials-file/env source so this exercises the adopted
+ # local-operator header path, not whatever token the host happens to hold.
+ monkeypatch.setattr("headroom.subscription.client.read_cached_oauth_token", lambda: None)
snapshot = _make_snapshot()
discrepancies = [WindowDiscrepancy(kind="cache_miss", description="miss", severity="warning")]
@@ -227,6 +330,7 @@ async def test_maybe_poll_runs_transcript_scan_off_event_loop(
monkeypatch.setattr(SubscriptionTracker, "_load_persisted_state", lambda self: None)
tracker = SubscriptionTracker()
tracker.notify_active("Bearer live-oauth-token", from_local_operator=True)
+ monkeypatch.setattr("headroom.subscription.client.read_cached_oauth_token", lambda: None)
snapshot = _make_snapshot()