Skip to content

feat(llm): OHE-3276 refresh API key and retry once on a 401 - #5218

Merged
ak684 merged 4 commits into
mainfrom
fix/llm-refresh-on-401-5189
Sep 25, 2026
Merged

ak684 merged 4 commits into
mainfrom
fix/llm-refresh-on-401-5189

Conversation

@aivong-openhands

@aivong-openhands aivong-openhands commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

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

  • Add LLM.set_api_key_refresh_hook() and refresh-then-retry-once handling in completion, acompletion, responses, and aresponses (async paths resolve the key off the event loop).
  • Refresh fires only for genuine auth errors when a hook is set, auth_type == "api_key", and the hook returns a new non-empty key; a recursion guard limits it to one retry.
  • Hook held as a 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:

uv run pytest tests/sdk/llm/test_auth_refresh_retry.py   # 8 passed
uv run pytest tests/sdk/llm/                              # 1019 passed
uv run ruff check openhands-sdk/openhands/sdk/llm/llm.py tests/sdk/llm/test_auth_refresh_retry.py
uv run pyright openhands-sdk/openhands/sdk/llm/llm.py tests/sdk/llm/test_auth_refresh_retry.py

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 in model_dump(). Sync and async paths are both covered.

Video/Screenshots

Not applicable — SDK-internal control-flow change with no user-facing surface.

Type

  • Bug fix
  • Feature
  • Refactor
  • Breaking change
  • Docs / chore

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

Variant Architectures Base Image Docs / Tags
java amd64, arm64 eclipse-temurin:17-jdk Link
python-slim amd64, arm64 python-node-runtime Link
python-minimal amd64, arm64 python-node-runtime Link
python amd64, arm64 python-node-runtime Link
golang amd64, arm64 golang:1.21-bookworm Link

Pull (multi-arch manifest)

# Each variant is a multi-arch manifest supporting both amd64 and arm64
docker pull ghcr.io/openhands/agent-server:7013f7c-python

Run

docker run -it --rm \
  -p 8000:8000 \
  --name agent-server-7013f7c-python \
  ghcr.io/openhands/agent-server:7013f7c-python

All tags pushed for this build

ghcr.io/openhands/agent-server:7013f7c-golang-amd64
ghcr.io/openhands/agent-server:7013f7c711260b481b4829509addcc5e6fc29917-golang-amd64
ghcr.io/openhands/agent-server:fix-llm-refresh-on-401-5189-golang-amd64
ghcr.io/openhands/agent-server:7013f7c-golang_tag_1.21-bookworm-amd64
ghcr.io/openhands/agent-server:7013f7c-golang-arm64
ghcr.io/openhands/agent-server:7013f7c711260b481b4829509addcc5e6fc29917-golang-arm64
ghcr.io/openhands/agent-server:fix-llm-refresh-on-401-5189-golang-arm64
ghcr.io/openhands/agent-server:7013f7c-golang_tag_1.21-bookworm-arm64
ghcr.io/openhands/agent-server:7013f7c-java-amd64
ghcr.io/openhands/agent-server:7013f7c711260b481b4829509addcc5e6fc29917-java-amd64
ghcr.io/openhands/agent-server:fix-llm-refresh-on-401-5189-java-amd64
ghcr.io/openhands/agent-server:7013f7c-eclipse-temurin_tag_17-jdk-amd64
ghcr.io/openhands/agent-server:7013f7c-java-arm64
ghcr.io/openhands/agent-server:7013f7c711260b481b4829509addcc5e6fc29917-java-arm64
ghcr.io/openhands/agent-server:fix-llm-refresh-on-401-5189-java-arm64
ghcr.io/openhands/agent-server:7013f7c-eclipse-temurin_tag_17-jdk-arm64
ghcr.io/openhands/agent-server:7013f7c-python-amd64
ghcr.io/openhands/agent-server:7013f7c711260b481b4829509addcc5e6fc29917-python-amd64
ghcr.io/openhands/agent-server:fix-llm-refresh-on-401-5189-python-amd64
ghcr.io/openhands/agent-server:7013f7c-python-node-runtime-amd64
ghcr.io/openhands/agent-server:7013f7c-python-arm64
ghcr.io/openhands/agent-server:7013f7c711260b481b4829509addcc5e6fc29917-python-arm64
ghcr.io/openhands/agent-server:fix-llm-refresh-on-401-5189-python-arm64
ghcr.io/openhands/agent-server:7013f7c-python-node-runtime-arm64
ghcr.io/openhands/agent-server:7013f7c-python-minimal-amd64
ghcr.io/openhands/agent-server:7013f7c711260b481b4829509addcc5e6fc29917-python-minimal-amd64
ghcr.io/openhands/agent-server:fix-llm-refresh-on-401-5189-python-minimal-amd64
ghcr.io/openhands/agent-server:7013f7c-python-node-runtime-minimal-amd64
ghcr.io/openhands/agent-server:7013f7c-python-minimal-arm64
ghcr.io/openhands/agent-server:7013f7c711260b481b4829509addcc5e6fc29917-python-minimal-arm64
ghcr.io/openhands/agent-server:fix-llm-refresh-on-401-5189-python-minimal-arm64
ghcr.io/openhands/agent-server:7013f7c-python-node-runtime-minimal-arm64
ghcr.io/openhands/agent-server:7013f7c-python-slim-amd64
ghcr.io/openhands/agent-server:7013f7c711260b481b4829509addcc5e6fc29917-python-slim-amd64
ghcr.io/openhands/agent-server:fix-llm-refresh-on-401-5189-python-slim-amd64
ghcr.io/openhands/agent-server:7013f7c-python-node-runtime-slim-amd64
ghcr.io/openhands/agent-server:7013f7c-python-slim-arm64
ghcr.io/openhands/agent-server:7013f7c711260b481b4829509addcc5e6fc29917-python-slim-arm64
ghcr.io/openhands/agent-server:fix-llm-refresh-on-401-5189-python-slim-arm64
ghcr.io/openhands/agent-server:7013f7c-python-node-runtime-slim-arm64
ghcr.io/openhands/agent-server:7013f7c-golang
ghcr.io/openhands/agent-server:7013f7c711260b481b4829509addcc5e6fc29917-golang
ghcr.io/openhands/agent-server:fix-llm-refresh-on-401-5189-golang
ghcr.io/openhands/agent-server:7013f7c-golang_tag_1.21-bookworm
ghcr.io/openhands/agent-server:7013f7c-java
ghcr.io/openhands/agent-server:7013f7c711260b481b4829509addcc5e6fc29917-java
ghcr.io/openhands/agent-server:fix-llm-refresh-on-401-5189-java
ghcr.io/openhands/agent-server:7013f7c-eclipse-temurin_tag_17-jdk
ghcr.io/openhands/agent-server:7013f7c-python-minimal
ghcr.io/openhands/agent-server:7013f7c711260b481b4829509addcc5e6fc29917-python-minimal
ghcr.io/openhands/agent-server:fix-llm-refresh-on-401-5189-python-minimal
ghcr.io/openhands/agent-server:7013f7c-python-node-runtime-minimal
ghcr.io/openhands/agent-server:7013f7c-python-slim
ghcr.io/openhands/agent-server:7013f7c711260b481b4829509addcc5e6fc29917-python-slim
ghcr.io/openhands/agent-server:fix-llm-refresh-on-401-5189-python-slim
ghcr.io/openhands/agent-server:7013f7c-python-node-runtime-slim
ghcr.io/openhands/agent-server:7013f7c-python
ghcr.io/openhands/agent-server:7013f7c711260b481b4829509addcc5e6fc29917-python
ghcr.io/openhands/agent-server:fix-llm-refresh-on-401-5189-python
ghcr.io/openhands/agent-server:7013f7c-python-node-runtime

About Multi-Architecture Support

  • Each variant tag (e.g., 7013f7c-python) is a multi-arch manifest supporting both amd64 and arm64
  • Docker automatically pulls the correct architecture for your platform
  • Individual architecture tags (e.g., 7013f7c-python-amd64) are also available if needed

@github-actions

github-actions Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

REST API breakage checks (OpenAPI) — ✅ PASSED

Result: ✅ PASSED

Action log

@github-actions

github-actions Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Coverage

Coverage Report •
FileStmtsMissCoverMissing
openhands-sdk/openhands/sdk/llm
   llm.py11228992%719, 758–759, 764, 874, 890, 1158, 1198–1200, 1237, 1244, 1394, 1522, 1808, 1812–1813, 2013, 2020, 2031, 2116, 2120–2121, 2190, 2197, 2207, 2214, 2225, 2293, 2306, 2324, 2338, 2340, 2342, 2367, 2369, 2378–2379, 2403, 2548, 2704–2705, 2818, 3131–3132, 3141, 3159, 3186–3187, 3189, 3191, 3193, 3201, 3204, 3206, 3208, 3219–3220, 3228, 3231, 3234–3235, 3246–3248, 3252, 3256–3257, 3262, 3272, 3277, 3341, 3343, 3345–3348, 3350–3353, 3358–3361, 3376, 3387, 3447, 3449
TOTAL436881209672% 

@aivong-openhands aivong-openhands changed the title feat(llm): refresh API key and retry once on 401 (#5189) feat(llm): refresh API key and retry once on a 401 Sep 22, 2026

@aivong-openhands aivong-openhands left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_small retry (catch outside the retry decorator, then model_copy(update=...), then recursive re-call). Same idiom, low surprise.
  • Bounded retry / no loop — _auth_refreshed_llm sets _auth_refresh_attempted=True on the copy; _resolve_refreshed_api_key returns None when that guard is set, so a still-bad key surfaces the original error. Verified by test_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. AuthenticationError is not in LLM_RETRY_EXCEPTIONS, so the retry decorator does not retry it first (confirmed: no-hook 401 gives call_count == 1).
  • Secrets handling — No new secret field; the refreshed key rides the existing api_key: SecretStr field. The hook is a PrivateAttr, never serialized — asserted by test_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, None key, 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) omit call_context, while the sync completion refresh path forwards it. This matches the pre-existing async is_prompt_cache_too_small retry, which also omits it — call_context only 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 /codereview trigger), 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.

@aivong-openhands

Copy link
Copy Markdown
Contributor Author

Mutation review of the refresh-on-401 tests

I mutation-tested the tests this PR adds (tests/sdk/llm/test_auth_refresh_retry.py) — hand-written mutants applied to a pristine worktree, each run against a green baseline of 8 passed. Scope is test strength only, not correctness. The good news first: the central claim is well pinned; the gaps are in the edges around it.

Controls — the fix is asserted (all died ✅)

Mutant Result
Disable the refresh-retry in completion() (revert the fix) ❌ caught
Disable the refresh-retry in acompletion() (revert the fix) ❌ caught
Recursion guard: mark the refreshed copy _auth_refresh_attempted = False ❌ caught
Drop the same-key guard (retry with the already-rejected key) ❌ caught
Drop the auth-error guard (refresh on any error, not just 401s) ❌ caught

What makes these land is that the happy-path tests assert call_args_list[1].kwargs["api_key"] == "fresh_key" — they check the retry actually used the new key, not merely that a second call happened — and the loop/non-auth tests pin exact call_count and hook-invocation counts. That is the difference between "a retry occurred" and "the retry did the right thing."

Survivors — gaps (all ✅ passed with the behaviour broken)

Mutant Result
M6: disable refresh-retry in responses() ✅ survived
M7: disable refresh-retry in aresponses() ✅ survived
M2: drop the auth_type != "api_key" guard ✅ survived
M3: drop the empty-key guard ✅ survived

M6 / M7 — the Responses API paths are entirely unasserted

The PR adds the same refresh-then-retry block to all four call paths, but the tests only drive completion() and acompletion(). I deleted the retry in responses() and aresponses() and the suite stayed green. These are the paths GPT-5 / reasoning-effort models take, so a future edit that breaks refresh there would ship silently while the chat-completions tests stay green. This is the highest-consequence gap: two of the four surfaces the PR ships have no coverage at all.

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"] == 1

Verified: 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 api_key == "fresh_...", matching the completion tests — worth adding a parseable success response so the whole path is exercised, not just the error edge.)

M2 — the auth_type != "api_key" guard is unasserted

_resolve_refreshed_api_key bails out for non-api-key auth, and the PR summary lists "subscription auth" as a case that must skip the refresh — but no test exercises it. I removed the guard and everything stayed green. This matters because subscription-mode LLMs (auth_type == "subscription", set in auth/openai.py) carry their own credential lifecycle; letting an api-key refresh hook clobber that key is exactly what the guard exists to prevent, and right now nothing holds the line.

Kill (unit-level on the resolver is enough and cheapest):

def test_non_api_key_auth_skips_refresh():
    llm = _make_llm(auth_type="subscription")
    llm.set_api_key_refresh_hook(lambda: "fresh_key")
    assert llm._resolve_refreshed_api_key(_auth_error()) is None

Verified: passes on the branch, fails with the guard removed.

M3 — the empty-key guard is unasserted

There is a test for a hook returning None and one for a hook returning the same key, but none for a hook returning an empty string. I deleted if not new_secret.get_secret_value(): return None and the suite stayed green — an empty refreshed key (which differs from the stale one) would sail through and drive a pointless retry with no credential.

Kill (parallels the existing returns_none / returns_same_key tests):

@patch("openhands.sdk.llm.llm.litellm_completion")
def test_empty_key_skips_retry(mock_litellm_completion):
    mock_litellm_completion.side_effect = _auth_error()
    llm = _make_llm()
    llm.set_api_key_refresh_hook(lambda: "")
    with pytest.raises(LLMAuthenticationError):
        llm.completion(messages=_message())
    assert mock_litellm_completion.call_count == 1

Verified: passes on the branch, fails with the guard removed.

Not a test gap

  • The auth_type != "api_key" guard does line up with reality — subscription login sets llm.auth_type = "subscription" in openhands/sdk/llm/auth/openai.py, so M2 is a genuine missing test, not an equivalent mutant.
  • The _api_key_refresh_hook is None guard is already covered indirectly (removing it turns the no-hook case into a TypeError instead of the mapped auth error), so I did not count it as a gap.

Order of priority: the Responses-API coverage (M6/M7) first — two shipped paths with zero assertions — then the subscription guard (M2), then the empty-key edge (M3).

This comment was generated by an AI assistant on behalf of the user.

@aivong-openhands

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough mutation review — all four survivors are now killed in 7bdd4be.

  • M6 / M7 (Responses paths): added test_responses_refreshes_key_and_retries_once / test_aresponses_refreshes_key_and_retries_once, plus repeat-401 loop-guard variants. The happy-path tests assert call_args_list[1].kwargs["api_key"] == "fresh_key" (via a new create_mock_responses_response helper), so they check the retry actually used the new key rather than merely that a second call happened — matching the completion tests' strength you highlighted.
  • M2 (subscription guard): added test_non_api_key_auth_skips_refresh, a unit test on _resolve_refreshed_api_key with auth_type="subscription".
  • M3 (empty-key guard): added test_completion_no_retry_when_hook_returns_empty_key.

I re-ran your mutants locally to confirm the kills: neutralizing the refresh-retry block in responses()/aresponses() fails the new M6/M7 tests, and dropping the auth_type != "api_key" / empty-key guards fails M2/M3 respectively. All 14 tests pass on the branch as-is; lint and format are clean.

This comment was created by an AI agent (OpenHands) on behalf of the user.

@aivong-openhands
aivong-openhands marked this pull request as ready for review September 22, 2026 14:31
aivong-openhands added a commit that referenced this pull request Sep 22, 2026
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>
@aivong-openhands
aivong-openhands force-pushed the fix/llm-refresh-on-401-5189 branch from 7bdd4be to 51bb808 Compare September 22, 2026 14:32
@aivong-openhands aivong-openhands changed the title feat(llm): refresh API key and retry once on a 401 feat(llm): OHE-3276 refresh API key and retry once on a 401 Sep 22, 2026

@juanmichelini juanmichelini left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@aivong-openhands

aivong-openhands commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks @juanmichelini — good catch. Fixed in 92d26e1: _resolve_refreshed_api_key now wraps the hook invocation in a try/except. If the hook raises, we log a warning and return None so the refresh is skipped and the original 401 surfaces instead of the hook's own exception. Added test_completion_raising_hook_surfaces_original_error to cover it.

This comment was created by an AI agent (OpenHands) on behalf of the user.

aivong-openhands added a commit that referenced this pull request Sep 22, 2026
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>
@aivong-openhands
aivong-openhands force-pushed the fix/llm-refresh-on-401-5189 branch from 92d26e1 to 915fc3d Compare September 22, 2026 16:42

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread openhands-sdk/openhands/sdk/llm/llm.py Resolved
Comment thread openhands-sdk/openhands/sdk/llm/llm.py Resolved
@aivong-openhands

Copy link
Copy Markdown
Contributor Author

Addressed the review finding in 779bb40.

Fix: both async refresh-on-401 retry branches now forward call_context=call_context, matching the sync completion/responses paths:

  • acompletion retry (was L1880)
  • aresponses retry (was L2257)

Regression tests (tests/sdk/llm/test_auth_refresh_retry.py): test_acompletion_retry_preserves_threaded_call_context and test_aresponses_retry_preserves_threaded_call_context. Each threads a distinct LLMCallContext(prompt_cache_key="threaded-pck", session_id="threaded-sid") into an LLM whose bound _call_context is the empty default, forces a 401 on the first attempt, and asserts the retried litellm call carries the same prompt_cache_key and x-litellm-session-id as the initial attempt.

Verified they are real regressions: with the source fix reverted, both fail with KeyError: 'prompt_cache_key' on the retry call (the threaded context is dropped); with the fix they pass. Full file: 17 passed. ruff + pyright clean.

This comment was posted by an AI agent (OpenHands) on behalf of the user.

@juanmichelini juanmichelini left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

aivong-openhands added a commit that referenced this pull request Sep 22, 2026
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>
@aivong-openhands
aivong-openhands force-pushed the fix/llm-refresh-on-401-5189 branch from 779bb40 to e27cfb4 Compare September 22, 2026 22:10
aivong-openhands added a commit that referenced this pull request Sep 24, 2026
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>
@aivong-openhands
aivong-openhands force-pushed the fix/llm-refresh-on-401-5189 branch from e27cfb4 to 0b98760 Compare September 24, 2026 15:51
@aivong-openhands

Copy link
Copy Markdown
Contributor Author

@juanmichelini can you assist with the merge?

aivong-openhands and others added 3 commits September 24, 2026 12:22
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>
aivong-openhands added a commit that referenced this pull request Sep 24, 2026
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>
@aivong-openhands
aivong-openhands force-pushed the fix/llm-refresh-on-401-5189 branch from 0b98760 to 7013f7c Compare September 24, 2026 17:22
@ak684
ak684 merged commit 1612a78 into main Sep 25, 2026
68 of 69 checks passed
@ak684
ak684 deleted the fix/llm-refresh-on-401-5189 branch September 25, 2026 02:48
ak684 pushed a commit that referenced this pull request Sep 25, 2026
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>
aivong-openhands added a commit that referenced this pull request Sep 28, 2026
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Hosted OpenHands Cloud returns 401 token_not_found_in_db after restoring default managed LLM profile

4 participants