Repository navigation
feat(llm): OHE-3276 refresh API key and retry once on a 401 - #5218
Conversation
REST API breakage checks (OpenAPI) — ✅ PASSEDResult: ✅ PASSED |
Coverage Report •
|
||||||||||||||||||||
aivong-openhands
left a comment
There was a problem hiding this comment.
Code Review — feat(llm): refresh API key and retry once on a 401
Taste rating: Good — focused, opt-in, well-tested, and consistent with an existing retry pattern in the same file.
What the change does
Adds an opt-in LLM.set_api_key_refresh_hook(...) primitive. When a completion/responses call fails with an authentication error and a hook is registered, the LLM re-resolves the API key once and retries the call a single time. It covers all four paths (completion, acompletion, responses, aresponses), with the async paths resolving the key off the event loop via run_in_executor.
Verification performed
- Pattern consistency — Mirrors the pre-existing
is_prompt_cache_too_smallretry (catch outside the retry decorator, thenmodel_copy(update=...), then recursive re-call). Same idiom, low surprise. - Bounded retry / no loop —
_auth_refreshed_llmsets_auth_refresh_attempted=Trueon the copy;_resolve_refreshed_api_keyreturnsNonewhen that guard is set, so a still-bad key surfaces the original error. Verified bytest_completion_refresh_retries_only_once(hook called once, 2 transport calls). - Correct trigger conditions — Refresh fires only when the error passes
looks_like_auth_error, a hook is set,auth_type == "api_key", and the hook yields a non-empty key that differs from the current one.AuthenticationErroris not inLLM_RETRY_EXCEPTIONS, so the retry decorator does not retry it first (confirmed: no-hook 401 givescall_count == 1). - Secrets handling — No new secret field; the refreshed key rides the existing
api_key: SecretStrfield. The hook is aPrivateAttr, never serialized — asserted bytest_refresh_hook_not_serialized. Warning logs contain no key material. Satisfies the repo's "Secrets and authentication" checkpoint. - Tests — 8 targeted tests drive the real 401 path (sync + async), including no-hook,
Nonekey, identical key, non-auth error, and serialization. They assert observable behavior (retry count, that the retried call uses the fresh key), not just mock wiring. - CI — All checks green on the current head (
15b7c30).
Non-blocking observations (not findings)
- The async retry calls (
acompletion/aresponses) omitcall_context, while the synccompletionrefresh path forwards it. This matches the pre-existing asyncis_prompt_cache_too_smallretry, which also omits it —call_contextonly feeds telemetry context, so this is consistent with established behavior. - Scope is intentionally the SDK primitive; the server-side hook registration that would actually resolve #5189's Hosted Cloud symptom is a stated follow-up. The issue's acceptance criteria are therefore not fully closed by this PR alone, but that is a documented, reasonable decomposition rather than a defect.
Process gate
The PR is currently a draft, and the HUMAN: section of the description still contains the unfilled template placeholder. The Validate PR description check is SKIPPED for that reason. It is not ready to be marked for review/merge until a human author fills that section — a process gate, not a code defect.
Material findings
None. No correctness, compatibility, lifecycle, or security defect was proven on the current head.
[RISK ASSESSMENT] 🟡 MEDIUM — The change is opt-in and a no-op unless a hook is registered, which strongly bounds blast radius. However, it touches credential handling and all four core LLM call paths (a security-sensitive, widely-used surface). The secret path was traced and is clean (existing SecretStr field, PrivateAttr hook, no log leakage), and the retry is capped at one refresh + one retry with a same-key guard. A human maintainer should sanity-check the intended server-side hook contract (thread-safety/latency of the injected callback, since the async paths resolve it in a worker thread) before the end-to-end wiring lands, and the draft/HUMAN-section gate must be resolved before this is marked ready.
Verdict: No material findings — approvable on code grounds per the repo review guide, but deferring approval because the PR is a draft with an incomplete required description. Recommend not auto-merging; finish the HUMAN section, mark ready, and get a maintainer eye on the auth surface.
Key architectural insight: The design keeps the SDK ignorant of how keys are resolved (a pluggable hook held as non-serialized private state) while owning the when/how-often policy (auth-only, one refresh, one retry, same-key short-circuit). This cleanly separates the transient mitigation from the durable reference-only-credential fix (#4288) without changing any existing caller's behavior.
Improve this review? If feedback seems incorrect or irrelevant, update the repository's
.agents/skills/custom-codereview-guide.md(with the/codereviewtrigger), then re-request review. The reviewer reads the guide from the PR head.Resolve with AI? Install the iterate skill and run
/iterate.Was this review helpful? React with 👍 or 👎.
This review was generated by an AI agent (OpenHands) on behalf of the user.
Mutation review of the refresh-on-401 testsI mutation-tested the tests this PR adds ( Controls — the fix is asserted (all died ✅)
What makes these land is that the happy-path tests assert Survivors — gaps (all ✅ passed with the behaviour broken)
M6 / M7 — the Responses API paths are entirely unassertedThe PR adds the same refresh-then-retry block to all four call paths, but the tests only drive Kill (mirrors the existing sync/async completion tests; two 401s prove exactly one refreshed retry then stop): @patch("openhands.sdk.llm.llm.litellm_responses")
def test_responses_refreshes_and_retries_once(mock_litellm_responses):
mock_litellm_responses.side_effect = [_auth_error(), _auth_error()]
calls = {"count": 0}
def refresh() -> str:
calls["count"] += 1
return f"fresh_{calls['count']}"
llm = _make_llm()
llm.set_api_key_refresh_hook(refresh)
with pytest.raises(LLMAuthenticationError):
llm.responses(messages=_message())
assert mock_litellm_responses.call_count == 2 # initial + one refreshed retry
assert calls["count"] == 1
@pytest.mark.asyncio
@patch("openhands.sdk.llm.llm.litellm_aresponses")
async def test_aresponses_refreshes_and_retries_once(mock_litellm_aresponses):
mock_litellm_aresponses.side_effect = [_auth_error(), _auth_error()]
calls = {"count": 0}
def refresh() -> str:
calls["count"] += 1
return f"fresh_{calls['count']}"
llm = _make_llm()
llm.set_api_key_refresh_hook(refresh)
with pytest.raises(LLMAuthenticationError):
await llm.aresponses(messages=_message())
assert mock_litellm_aresponses.call_count == 2
assert calls["count"] == 1Verified: both pass on the branch as-is and fail when the retry block is removed from the respective path. (A stronger version would also assert the retried call used M2 — the
|
|
Thanks for the thorough mutation review — all four survivors are now killed in 7bdd4be.
I re-ran your mutants locally to confirm the kills: neutralizing the refresh-retry block in This comment was created by an AI agent (OpenHands) on behalf of the user. |
Wire the SDK's opt-in API-key refresh hook (set_api_key_refresh_hook, added in #5218) at LocalConversation build time so a managed proxy key rotated/healed after the conversation snapshot recovers in place instead of failing the first call with 401 token_not_found_in_db (#5189). The hook is a non-serializable Python callable, so it must be registered in the process where the LLM runs (the sandbox agent-server), not where the app-server builds and serializes the LLM. - managed_llm_key.register_managed_llm_key_refresh(agent): iterates agent.get_all_llms() and registers a hook on in-scope managed LLMs. - Re-resolves the current key via LookupSecret (fresh per call, strips whitespace, never raises -> returns None so the original 401 surfaces). - Opt-in and inert by default: no-op unless the control plane sets OH_LLM_API_KEY_REFRESH_URL. Optional OH_LLM_API_KEY_REFRESH_HEADERS and OH_LLM_API_KEY_REFRESH_BASE_URLS (scope to the managed proxy; keep BYOK LLMs untouched). Subscription auth is skipped. - event_service wires one register call after LocalConversation build. - Tests cover: off=no-op, feeds SDK resolution, base-url scoping, skips subscription, empty/failed refresh -> no retry, bad headers ignored. Co-authored-by: openhands <openhands@all-hands.dev>
7bdd4be to
51bb808
Compare
juanmichelini
left a comment
There was a problem hiding this comment.
Overall looks good! only comment _resolve_refreshed_api_key (~L1065) calls the hook with no try/except so a flaky server-side hook would mask the original 401 with the hook's own exception.
|
Thanks @juanmichelini — good catch. Fixed in 92d26e1: This comment was created by an AI agent (OpenHands) on behalf of the user. |
Wire the SDK's opt-in API-key refresh hook (set_api_key_refresh_hook, added in #5218) at LocalConversation build time so a managed proxy key rotated/healed after the conversation snapshot recovers in place instead of failing the first call with 401 token_not_found_in_db (#5189). The hook is a non-serializable Python callable, so it must be registered in the process where the LLM runs (the sandbox agent-server), not where the app-server builds and serializes the LLM. - managed_llm_key.register_managed_llm_key_refresh(agent): iterates agent.get_all_llms() and registers a hook on in-scope managed LLMs. - Re-resolves the current key via LookupSecret (fresh per call, strips whitespace, never raises -> returns None so the original 401 surfaces). - Opt-in and inert by default: no-op unless the control plane sets OH_LLM_API_KEY_REFRESH_URL. Optional OH_LLM_API_KEY_REFRESH_HEADERS and OH_LLM_API_KEY_REFRESH_BASE_URLS (scope to the managed proxy; keep BYOK LLMs untouched). Subscription auth is skipped. - event_service wires one register call after LocalConversation build. - Tests cover: off=no-op, feeds SDK resolution, base-url scoping, skips subscription, empty/failed refresh -> no retry, bad headers ignored. Co-authored-by: openhands <openhands@all-hands.dev>
92d26e1 to
915fc3d
Compare
all-hands-bot
left a comment
There was a problem hiding this comment.
This review was posted by an AI agent (OpenHands).
Summary
This PR adds an opt-in LLM.set_api_key_refresh_hook() and a refresh-then-retry-once path on a 401 across completion/acompletion/responses/aresponses. The design is sound: the hook is a PrivateAttr so it is not serialized, refresh is gated on looks_like_auth_error, auth_type == "api_key", a non-empty and different key, a raising hook is caught, and the _auth_refresh_attempted guard caps it at one retry. I ran the new tests (tests/sdk/llm/test_auth_refresh_retry.py: 15 passed on the current head) and the current-head CI is green.
I found one material correctness inconsistency between the sync and async retry paths.
Finding: async refresh retry drops the threaded call_context
The completion and responses retry blocks forward call_context=call_context to the refreshed call, but the new acompletion and aresponses blocks omit it. Because apply_call_context() prefers the explicitly threaded context and only falls back to the LLM's _call_context PrivateAttr, the async retry silently switches to the bound fallback context while the initial attempt used the threaded one.
I reproduced this on the current head: with the bound context and the threaded context differing, the sync retry sends the threaded prompt_cache_key, whereas the async retry sends the bound one:
SYNC retry pck: threaded-pck
ASYNC attempt0 pck: threaded-pck
ASYNC retry pck: bound-pck
Why it matters: the retry re-issues the same logical LLM call, so it should carry the same per-conversation prompt_cache_key and x-litellm-session-id as the attempt it replaces. Dropping the threaded context reintroduces exactly the shared-mutable-state hazard that threading call_context was introduced to avoid (#3443): any LLM instance whose bound _call_context differs from the threaded context (e.g. a sub-agent/conversation whose cache-shard override is supplied at construction) will issue its authentication retry under a different cache shard/session identity than the initial call, fragmenting prompt-cache reuse and per-session routing/telemetry on the managed proxy. It also makes the four duplicated blocks non-equivalent.
The fix is to pass call_context=call_context in both async branches, matching the sync branches.
Verdict
The refresh mechanism itself is correct and safe; the async paths just need to thread the same call_context the sync paths already do.
🔄 CHANGES REQUESTED
|
Addressed the review finding in Fix: both async refresh-on-401 retry branches now forward
Regression tests ( Verified they are real regressions: with the source fix reverted, both fail with This comment was posted by an AI agent (OpenHands) on behalf of the user. |
Wire the SDK's opt-in API-key refresh hook (set_api_key_refresh_hook, added in #5218) at LocalConversation build time so a managed proxy key rotated/healed after the conversation snapshot recovers in place instead of failing the first call with 401 token_not_found_in_db (#5189). The hook is a non-serializable Python callable, so it must be registered in the process where the LLM runs (the sandbox agent-server), not where the app-server builds and serializes the LLM. - managed_llm_key.register_managed_llm_key_refresh(agent): iterates agent.get_all_llms() and registers a hook on in-scope managed LLMs. - Re-resolves the current key via LookupSecret (fresh per call, strips whitespace, never raises -> returns None so the original 401 surfaces). - Opt-in and inert by default: no-op unless the control plane sets OH_LLM_API_KEY_REFRESH_URL. Optional OH_LLM_API_KEY_REFRESH_HEADERS and OH_LLM_API_KEY_REFRESH_BASE_URLS (scope to the managed proxy; keep BYOK LLMs untouched). Subscription auth is skipped. - event_service wires one register call after LocalConversation build. - Tests cover: off=no-op, feeds SDK resolution, base-url scoping, skips subscription, empty/failed refresh -> no retry, bad headers ignored. Co-authored-by: openhands <openhands@all-hands.dev>
779bb40 to
e27cfb4
Compare
Wire the SDK's opt-in API-key refresh hook (set_api_key_refresh_hook, added in #5218) at LocalConversation build time so a managed proxy key rotated/healed after the conversation snapshot recovers in place instead of failing the first call with 401 token_not_found_in_db (#5189). The hook is a non-serializable Python callable, so it must be registered in the process where the LLM runs (the sandbox agent-server), not where the app-server builds and serializes the LLM. - managed_llm_key.register_managed_llm_key_refresh(agent): iterates agent.get_all_llms() and registers a hook on in-scope managed LLMs. - Re-resolves the current key via LookupSecret (fresh per call, strips whitespace, never raises -> returns None so the original 401 surfaces). - Opt-in and inert by default: no-op unless the control plane sets OH_LLM_API_KEY_REFRESH_URL. Optional OH_LLM_API_KEY_REFRESH_HEADERS and OH_LLM_API_KEY_REFRESH_BASE_URLS (scope to the managed proxy; keep BYOK LLMs untouched). Subscription auth is skipped. - event_service wires one register call after LocalConversation build. - Tests cover: off=no-op, feeds SDK resolution, base-url scoping, skips subscription, empty/failed refresh -> no retry, bad headers ignored. Co-authored-by: openhands <openhands@all-hands.dev>
e27cfb4 to
0b98760
Compare
|
@juanmichelini can you assist with the merge? |
Add an optional API-key refresh hook to LLM. When a completion/responses call fails with an authentication error (HTTP 401, e.g. a rotated or healed managed proxy key that LiteLLM reports as token_not_found_in_db) and a hook is registered, the LLM re-resolves the key once and retries the call a single time before surfacing the error. This is a near-term mitigation for stale credentials reaching a sandbox runtime agent, where the first conversation after a server-side managed-key rotation/heal currently 401s once and only self-heals on the next conversation. The durable fix remains reference-only credential delivery (#4288). - Hook stored as a PrivateAttr (never serialized into conversation state) - Recursion guarded: one refresh + one retry per call chain - Skips refresh for non-auth errors, subscription auth, no-op/same keys - Async paths resolve the key off the event loop - Wired into completion/acompletion/responses/aresponses Co-authored-by: openhands <openhands@all-hands.dev>
Close mutation-testing gaps flagged in review: - Add responses()/aresponses() refresh-and-retry tests (M6/M7): both the success path (asserts the retry used the fresh key) and the repeat-401 loop guard (exactly one refreshed retry). - Add a resolver test that subscription (non-api-key) auth skips refresh (M2). - Add a test that an empty-string refreshed key does not drive a credential-less retry (M3). Co-authored-by: openhands <openhands@all-hands.dev>
Wrap the API key refresh hook invocation in try/except in _resolve_refreshed_api_key. A flaky server-side hook that raises would otherwise mask the original authentication error; now we log a warning and skip the refresh so the caller sees the real 401. Addresses PR review feedback. Co-authored-by: openhands <openhands@all-hands.dev>
The acompletion/aresponses refresh-then-retry blocks omitted call_context, so the retried call fell back to the LLM's bound _call_context PrivateAttr instead of the threaded per-conversation context used by the initial attempt (and by the sync completion/ responses retries). That dropped prompt_cache_key / x-litellm-session-id on the retry, reintroducing the shared-context divergence #3443 removed. Pass call_context=call_context in both async retry branches for parity with the sync paths, and add regression tests asserting the async retry carries the same threaded prompt_cache_key / session id as attempt 0. Co-authored-by: openhands <openhands@all-hands.dev>
Wire the SDK's opt-in API-key refresh hook (set_api_key_refresh_hook, added in #5218) at LocalConversation build time so a managed proxy key rotated/healed after the conversation snapshot recovers in place instead of failing the first call with 401 token_not_found_in_db (#5189). The hook is a non-serializable Python callable, so it must be registered in the process where the LLM runs (the sandbox agent-server), not where the app-server builds and serializes the LLM. - managed_llm_key.register_managed_llm_key_refresh(agent): iterates agent.get_all_llms() and registers a hook on in-scope managed LLMs. - Re-resolves the current key via LookupSecret (fresh per call, strips whitespace, never raises -> returns None so the original 401 surfaces). - Opt-in and inert by default: no-op unless the control plane sets OH_LLM_API_KEY_REFRESH_URL. Optional OH_LLM_API_KEY_REFRESH_HEADERS and OH_LLM_API_KEY_REFRESH_BASE_URLS (scope to the managed proxy; keep BYOK LLMs untouched). Subscription auth is skipped. - event_service wires one register call after LocalConversation build. - Tests cover: off=no-op, feeds SDK resolution, base-url scoping, skips subscription, empty/failed refresh -> no retry, bad headers ignored. Co-authored-by: openhands <openhands@all-hands.dev>
0b98760 to
7013f7c
Compare
Wire the SDK's opt-in API-key refresh hook (set_api_key_refresh_hook, added in #5218) at LocalConversation build time so a managed proxy key rotated/healed after the conversation snapshot recovers in place instead of failing the first call with 401 token_not_found_in_db (#5189). The hook is a non-serializable Python callable, so it must be registered in the process where the LLM runs (the sandbox agent-server), not where the app-server builds and serializes the LLM. - managed_llm_key.register_managed_llm_key_refresh(agent): iterates agent.get_all_llms() and registers a hook on in-scope managed LLMs. - Re-resolves the current key via LookupSecret (fresh per call, strips whitespace, never raises -> returns None so the original 401 surfaces). - Opt-in and inert by default: no-op unless the control plane sets OH_LLM_API_KEY_REFRESH_URL. Optional OH_LLM_API_KEY_REFRESH_HEADERS and OH_LLM_API_KEY_REFRESH_BASE_URLS (scope to the managed proxy; keep BYOK LLMs untouched). Subscription auth is skipped. - event_service wires one register call after LocalConversation build. - Tests cover: off=no-op, feeds SDK resolution, base-url scoping, skips subscription, empty/failed refresh -> no retry, bad headers ignored. Co-authored-by: openhands <openhands@all-hands.dev>
Wire the SDK's opt-in API-key refresh hook (set_api_key_refresh_hook, added in #5218) at LocalConversation build time so a managed proxy key rotated/healed after the conversation snapshot recovers in place instead of failing the first call with 401 token_not_found_in_db (#5189). The hook is a non-serializable Python callable, so it must be registered in the process where the LLM runs (the sandbox agent-server), not where the app-server builds and serializes the LLM. - managed_llm_key.register_managed_llm_key_refresh(agent): iterates agent.get_all_llms() and registers a hook on in-scope managed LLMs. - Re-resolves the current key via LookupSecret (fresh per call, strips whitespace, never raises -> returns None so the original 401 surfaces). - Opt-in and inert by default: no-op unless the control plane sets OH_LLM_API_KEY_REFRESH_URL. Optional OH_LLM_API_KEY_REFRESH_HEADERS and OH_LLM_API_KEY_REFRESH_BASE_URLS (scope to the managed proxy; keep BYOK LLMs untouched). Subscription auth is skipped. - event_service wires one register call after LocalConversation build. - Tests cover: off=no-op, feeds SDK resolution, base-url scoping, skips subscription, empty/failed refresh -> no retry, bad headers ignored. Co-authored-by: openhands <openhands@all-hands.dev>
HUMAN:
add an opt in refresh and retry hook on 401s so that the first conversation can recover
AGENT:
Why
A sandbox runtime agent receives its LLM credential snapshotted at conversation launch. When the managed proxy key is rotated or healed on the server after that snapshot is taken, the in-flight conversation keeps sending the old value, so its first LLM call fails with a 401 (
token_not_found_in_db) and only the next conversation picks up the fresh key — the "first conversation fails once, then self-heals" behaviour in #5189.This adds an opt-in refresh path so the failing conversation can recover in place:
LLM.set_api_key_refresh_hook(...)registers a callback that returns a freshly-resolved key, and on an authentication error the LLM re-resolves the key once and retries the call a single time. It is safe because it changes nothing unless a hook is registered, it is capped at one refresh and one retry per call chain (no loop on a still-bad key), it ignores non-auth errors, subscription auth, and empty/identical keys, and the hook is a private attribute that never serializes into conversation state.This is the SDK primitive only; the agent-server/enterprise side supplies the hook that knows how to re-resolve a managed key, and the durable fix remains reference-only credential delivery (#4288), which this bridges until it lands.
Summary
LLM.set_api_key_refresh_hook()and refresh-then-retry-once handling incompletion,acompletion,responses, andaresponses(async paths resolve the key off the event loop).auth_type == "api_key", and the hook returns a new non-empty key; a recursion guard limits it to one retry.PrivateAttr, so it is never written to serialized state.Issue Number
Fixes #5189. Related: #4533 (sibling launch-path bug), #4288 (durable fix).
How to Test
A full managed-key-rotation reproduction needs the server-side wiring that registers the hook, which is intentionally not part of this PR, so the behaviour here is exercised by unit tests that drive the exact 401 path:
The new tests assert that a 401 with a hook triggers exactly one re-resolve + retry and that the retry uses the new key; that a repeated 401, a
None/empty key, an identical key, a non-auth error, and subscription auth each skip the refresh; and that the hook does not appear inmodel_dump(). Sync and async paths are both covered.Video/Screenshots
Not applicable — SDK-internal control-flow change with no user-facing surface.
Type
Notes
Follow-up to make this effective end to end: register a hook where the agent-server builds the conversation's LLM so it re-resolves the managed key on a 401. No behaviour changes for any caller that does not set a hook.
This PR was drafted by an AI agent on behalf of the user.
🐳 Agent Server images for this PR — GHCR package, pull/run commands, and all pushed tags (click to expand)
• GHCR package: https://github.com/OpenHands/agent-sdk/pkgs/container/agent-server
Variants & Base Images
eclipse-temurin:17-jdkpython-node-runtimepython-node-runtimepython-node-runtimegolang:1.21-bookwormPull (multi-arch manifest)
# Each variant is a multi-arch manifest supporting both amd64 and arm64 docker pull ghcr.io/openhands/agent-server:7013f7c-pythonRun
All tags pushed for this build
About Multi-Architecture Support
7013f7c-python) is a multi-arch manifest supporting both amd64 and arm647013f7c-python-amd64) are also available if needed