Skip to content

Managed-key rotation race on conversation start → intermittent token_not_found_in_db 401 (enterprise-server 1.60.0 regression) #439

Closed

Description

@aivong-openhands

Summary

Since enterprise-server 1.60.0, conversations intermittently die with a non-retryable LiteLLM 401:

litellm.AuthenticationError: Invalid proxy server token passed. Received API Key = sk-...XXXX,
Key Hash (Token) =<hash>. Unable to find token in cache or `LiteLLM_VerificationTokenTable`
(token_not_found_in_db)

The key is a valid sk- managed key that is present in LiteLLM_VerificationToken and works for the
app's own server-side calls, yet a sandbox's completion call intermittently gets "not found." The 401 is
absent from the LiteLLM proxy request log (auth short-circuits before request logging).

Root cause is a rotation race on the managed LLM key. On every conversation start,
_maybe_refresh_managed_llm_key runs verify → rotate (delete-then-generate), and rotate_managed_llm_key
uses delete_key_by_alias on a per-org (shared) alias. When two rotations for the same org overlap, one
rotation's delete_key_by_alias deletes the other's freshly-minted key; the sandbox holding that key then
authenticates against a hash that no longer exists.

Status: root cause verified by live reproduction on a self-hosted Helm install (see
"Verified reproduction" below).

Affected versions

  • Clean: enterprise-server 1.59.1 (tag 0a1135682).
  • Broken: 1.60.0 (tag d916135f9) and 1.61.0. Bisection points at the enterprise-server image; the
    corresponding chart bump was only image tags (agent-server SDK exonerated via a decoupled test that
    pinned the old SDK against enterprise-server 1.60.0 and still flapped).
  • LiteLLM proxy 1.94.1, single replica / single worker, no redis / no cache (in-memory, positive-only
    auth cache).

It is model-independent (verified)

The error reproduces even after switching to a non-default model (e.g. claude-sonnet-4-5). This is
expected: "managed" is classified purely by provider + base_url, not the model name —

# storage/saas_settings_store.py  managed_llm_key_config_from_model(...)
openhands_type = is_openhands_model(llm_model)
uses_openhands_provider_proxy = openhands_type and (
    normalized_llm_base_url is None or 'all-hands.dev' in normalized_llm_base_url.lower())

So any OpenHands-proxy model takes the managed verify→rotate path. Only a true third-party BYOK base_url
skips it.

Root cause (code)

  1. The effective LLM config resolves to the managed OpenHands default for essentially every SaaS user (the
    DB-backed default model is an openhands/* model on the managed proxy, and base_url is normalized to the
    managed proxy on load()). So the managed verify→rotate path is active on essentially every conversation
    start:

    • server/verified_models/default_profile.py: materialize_default_llm_profile (sets base_url=None,
      api_key=None).
    • storage/saas_settings_store.py::load() opens a new a_session_maker() and sets merged_llm['base_url']=None.

    Note: this default-model selection is orthogonal to the bug — it only determines which model/base_url is the
    default. The race is entirely in rotate_managed_llm_key, and reproduces on any OpenHands-proxy model.

  2. Because the effective config is now managed for every user, _maybe_refresh_managed_llm_key runs on
    every conversation start — and from two call sites per start:

    • openhands/app_server/app_conversation/live_status_app_conversation_service.py:1089 (seed path from
      _start_app_conversation) and :1650 (_configure_llm_and_mcp).
    • Managed gate via managed_llm_key_config_from_model; on stale it rotates and returns the new key.
  3. rotate_managed_llm_key (storage/saas_settings_store.py) is delete-then-generate on a per-org
    (shared) alias
    :

    key_alias = get_openhands_cloud_key_alias(self.user_id, org_id_str)
    await LiteLlmManager.delete_key_by_alias(key_alias=key_alias)   # removes ALL keys under the alias
    new_key = await LiteLlmManager.generate_key(..., team_id=org_id) # mint new key, same alias
    org_member.llm_api_key = SecretStr(new_key); await session.commit()

    (The in-code comment says "delete the alias first so rotation never orphans a prior key" — this only
    holds for a single rotation; under concurrency it orphans the other rotation's key.)

  4. LiteLLM 1.94.x has no negative auth cache
    (litellm/proxy/auth/resolvers/store.py::_resolve_key, auth_checks.get_key_object): a DB miss raises
    token_not_found_in_db immediately, caching positive results only. So this is a real DB-visibility /
    rotation race, not cache poisoning — which also rules out a user_api_key_cache_ttl negative-cache
    theory.

The two calls within a single start are sequential (self-consistent), so the harmful race is across
overlapping starts
(two conversation starts, start+resume, or an extra rotate from a transient
verify_key failure under allowed_fails/timeouts).

Failing interleaving

Two conversation-start flows A and B for the same org (alias shared). k0 is stale (fresh state /
pre-epoch) or a transient verify flake fires:

A.read member=k0 ; B.read member=k0
A.verify(k0) invalid → A.delete_by_alias → tokens={} → A.generate k1 → tokens={k1} → A.commit member=k1 → A hands k1 to sandbox_A
B.verify(k0) invalid → B.delete_by_alias → tokens={}        ←  deletes k1
                       B.generate k2 → tokens={k2} → B.commit member=k2 → B hands k2 to sandbox_B
sandbox_A → POST /chat/completions with k1 → k1 ∉ tokens{k2} → 401 token_not_found_in_db  (non-retryable → conversation dies)

The survivor key (k2) is valid, so server-side calls and later inspection of LiteLLM_VerificationToken
look fine — matching the "key exists but sandbox says not found" symptom.

Verified reproduction (self-hosted Helm install)

Environment: enterprise-server 1.60.0, LiteLLM proxy 1.94.1 (single replica / single worker, no
redis/cache), shared Postgres. All identifiers below are placeholders.

Confirmed in the running image:

  • rotate_managed_llm_key = delete_key_by_alias(<shared per-org alias>) → generate_key(...).
  • _maybe_refresh_managed_llm_key is invoked from two call sites per start (see line refs above).
  • The managed key is team-scoped: team_id = <ORG_ID>, alias
    OpenHands Cloud - user <USER_ID> - org <ORG_ID> (for a personal workspace USER_ID == ORG_ID).

Test 1 — concurrent rotation storm (N=4 real rotate_managed_llm_key() for one org).
Log shows 4× _delete_key_by_alias:key_deleted followed by 4× _generate_key:key_created under the same
alias, and 4× rotate_managed_llm_key:rotated. Result: the "one managed key per alias" invariant is
violated (4 live keys under the alias), and all four deleted the pre-existing key k0 — so any sandbox
still holding k0 is now dead.

Test 2 — the documented interleaving (A.generate → B.delete), using the same primitives rotate() calls:

A: delete_by_alias + generate  -> k1   (handed to sandbox_A)
B: delete_by_alias (wipes k1) + generate -> k2   (survivor; app_member points here)

probe with k1 (sandbox_A) -> HTTP 401  token_not_found_in_db     ← orphaned
probe with k2 (server/app) -> HTTP 200  OK

This is the reported signature exactly: the sandbox's valid sk- key returns token_not_found_in_db
while the app's key works, because an overlapping rotation deleted the sandbox's key. Corroborating field
evidence: LiteLLM proxy logs during a real flap contained a key hash that was absent from
LiteLLM_VerificationToken (a minted-then-deleted orphan), alongside the surviving key.

Evidence

On an affected install (enterprise-server 1.60.0/1.61.0, shared Postgres):

  • verified_models has the OpenHands default row active (is_default=true, is_enabled=true) → the effective
    config resolves to the managed default, so the managed verify→rotate path is live.
  • App-server logs show the rotation happening on conversation start, in the same window as the newly-minted
    key's created_at in LiteLLM_VerificationToken:
    managed_llm_key_refresh:stale_key_detected   model=openhands/<default-model>
    LiteLlmManager:_delete_key_by_alias:key_deleted   key_alias="OpenHands Cloud - user <USER_ID> - org <ORG_ID>"
    LiteLlmManager:_lite_llm_generate_user_team_key:key_created   team_id=<ORG_ID>
    saas_settings_store:rotate_managed_llm_key:rotated
    
  • LiteLLM general_settings: no cache block, no user_api_key_cache_ttl, no redis (confirms no
    negative/shared cache is involved).

Reproduction

  1. On a ≥1.60.0 SaaS install with the OpenHands default model active, enable LITELLM_LOG=DEBUG.
  2. Force a rotation and overlap it: delete the managed key (LiteLLM /key/delete or DB) and immediately
    fire two conversation starts for the same org (two tabs / two API calls / start+resume).
  3. Observe interleaved delete_key_by_alias / /key/generate and a token_not_found_in_db for the
    earlier-minted key; correlate app-server stale_key_detected/rotated timestamps with LiteLLM's
    /key/generate commit and the failing auth.

Deterministic variant (no UI needed): invoke rotate_managed_llm_key() for the same org twice back to
back; the first rotation's key is the one a sandbox would already hold, and the second rotation's
delete_key_by_alias orphans it — probing that key returns token_not_found_in_db while the survivor
works. (A formal Quint model of the interleaving + fix verification is available on request.)

Proposed fix (priority order)

  1. Make rotation concurrency-safe. Serialize managed-key rotation per org (Postgres advisory lock /
    SELECT … FOR UPDATE on the org row, or a per-org Redis lock — cf. fix(enterprise): serialize provision-user via per-email Redis lock (OHE-2980) #132 "serialize provision-user via
    per-email Redis lock"). And/or generate-before-delete: mint + persist the new key, then delete only
    the specific previous hash (not delete_key_by_alias), with a short grace period so in-flight sandboxes
    holding the previous key still authenticate.
  2. Stop re-verifying+rotating on every start. Don't coerce the effective LLM into a managed
    base_url=None refresh for orgs that already have a valid managed key; make
    _maybe_refresh_managed_llm_key idempotent/cached (skip verify+rotate when validated recently), and
    avoid running it twice per start.
  3. Only rotate on a definitive key-invalid 401, not transient verify_key failures (timeouts / 5xx /
    allowed_fails); retry verify before rotating.
  4. Make the sandbox path retryable: on token_not_found 401, refetch the current managed key and
    retry once instead of failing the conversation.

Relationship to existing issues (distinct root cause)

Not covered by the current managed-key work:

Fixes here touch the same files as #427 / #437 (live_status_app_conversation_service.py,
saas_settings_store.py), so this should be coordinated with that in-flight work but tracked separately.


This issue was filed by an AI agent (OpenHands) on behalf of the repository maintainer.

Activity

  1. added
    bug
    on Sep 18, 2026
  2. juanmichelini commented on Sep 18, 2026

    @juanmichelini
    Contributor

    @aivong-openhands 191 does not touch keys only the allowed model list. did you reproduce it on d916135 exactly?

  3. aivong-openhands commented on Sep 18, 2026

    @aivong-openhands
    ContributorAuthor

    @juanmichelini on the repro commit: yes, d916135f9 exactly. The reproduction ran against the deployed ghcr.io/openhands/enterprise-server:1.60.0 image on the KinD/Helm install, and that image's label is:

    org.opencontainers.image.revision = d916135f966d89f825221421a4708519abf41a4f   # = d916135f9, "chore(main): release 1.60.0 (#345)"
    org.opencontainers.image.source   = https://github.com/OpenHands/enterprise
    

    The flawed primitive is present verbatim at that commit — git show d916135f9:storage/saas_settings_store.py:

    • rotate_managed_llm_key() (def L1063) → delete_key_by_alias(key_alias=...) (L1127) then generate_key(...) (L1128), with the comment "delete the alias first so rotation never orphans a prior key" (L1125) — which is the part that doesn't hold under overlap.
    • _maybe_refresh_managed_llm_key → rotate_managed_llm_key() (L1525), and _maybe_refresh_managed_llm_key is invoked from two sites per conversation start (L1089 and L1650).

    You're also right that the default/allowed-model plumbing is not part of this — I've removed that from the issue description. The root cause is entirely the delete_key_by_alias + generate rotation in rotate_managed_llm_key, driven per-start by _maybe_refresh_managed_llm_key, which races under concurrent starts and orphans a key already handed to a sandbox → token_not_found_in_db.


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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions