Repository navigation
Description
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)
-
The effective LLM config resolves to the managed OpenHands default for essentially every SaaS user (the
DB-backed default model is anopenhands/*model on the managed proxy, andbase_urlis normalized to the
managed proxy onload()). So the managed verify→rotate path is active on essentially every conversation
start:server/verified_models/default_profile.py:materialize_default_llm_profile(setsbase_url=None,
api_key=None).storage/saas_settings_store.py::load()opens a newa_session_maker()and setsmerged_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 inrotate_managed_llm_key, and reproduces on any OpenHands-proxy model. -
Because the effective config is now managed for every user,
_maybe_refresh_managed_llm_keyruns 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.
-
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.) -
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_dbimmediately, caching positive results only. So this is a real DB-visibility /
rotation race, not cache poisoning — which also rules out auser_api_key_cache_ttlnegative-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_keyis 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 workspaceUSER_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_modelshas 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'screated_atinLiteLLM_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, nouser_api_key_cache_ttl, no redis (confirms no
negative/shared cache is involved).
Reproduction
- On a ≥1.60.0 SaaS install with the OpenHands default model active, enable
LITELLM_LOG=DEBUG. - Force a rotation and overlap it: delete the managed key (LiteLLM
/key/deleteor DB) and immediately
fire two conversation starts for the same org (two tabs / two API calls / start+resume). - Observe interleaved
delete_key_by_alias//key/generateand atoken_not_found_in_dbfor the
earlier-minted key; correlate app-serverstale_key_detected/rotatedtimestamps with LiteLLM's
/key/generatecommit 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)
- Make rotation concurrency-safe. Serialize managed-key rotation per org (Postgres advisory lock /
SELECT … FOR UPDATEon 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 (notdelete_key_by_alias), with a short grace period so in-flight sandboxes
holding the previous key still authenticate. - Stop re-verifying+rotating on every start. Don't coerce the effective LLM into a managed
base_url=Nonerefresh for orgs that already have a valid managed key; make
_maybe_refresh_managed_llm_keyidempotent/cached (skip verify+rotate when validated recently), and
avoid running it twice per start. - Only rotate on a definitive key-invalid 401, not transient
verify_keyfailures (timeouts / 5xx /
allowed_fails); retry verify before rotating. - Make the sandbox path retryable: on
token_not_found401, 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:
- Bug: bulk managed-key ownership repair regenerates keys without invalidating cached UI/session view (stale-key errors) #421 / fix: heal stale org-level BYOR LLM key on conversation start (#421) #437 / fix: replace stale custom LLM key when switching back to the managed default profile #425 / test: simulate PR #353 managed-key rotation (DO NOT MERGE) #419 (and the merged fix: bulk-repair cross-user managed LLM key ownership #353 / chore(migrations): reconcile user_settings.llm_api_key mirror with org_member after #353 rotation #406): the bulk ownership-repair stale-key family — a
once-per-org regen that doesn't propagate to the cached UI/session view. Different trigger (ownership
processor, not per-start), different symptom (stale key), not a concurrency delete-by-alias race. - fix(llm): stop BYOR/custom key leaking into managed-proxy profiles on the read path #427: BYOR/custom key leaking into managed-proxy profiles — signature
LiteLLM Virtual Key expected. Received=dumm****odel, expected to start with 'sk-'(a non-sk-key), a read-path selection bug, not
token_not_found_in_dbfor a realsk-key. - UX: user can get stuck with a dead org-default LLM key and no way to fix it in the UI #296: "user stuck with a dead org-default LLM key" — related symptom, but permanent-stuck UX, not the
intermittent rotation race.
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
juanmichelini commentedon Sep 18, 2026
@aivong-openhands 191 does not touch keys only the allowed model list. did you reproduce it on d916135 exactly?
aivong-openhands commentedon Sep 18, 2026
@juanmichelini on the repro commit: yes,
d916135f9exactly. The reproduction ran against the deployedghcr.io/openhands/enterprise-server:1.60.0image on the KinD/Helm install, and that image's label is: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) thengenerate_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_keyis 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+generaterotation inrotate_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.
fix: rotate managed key delete-then-generate (LiteLLM unique-alias)
fix: clear managed-key alias under the lock (robust delete-then-gener…
fix: OHE-3276 make managed LLM key rotation concurrency-safe (enterpr…
fix(llm): pass only_if_current when refreshing a stale managed key
feat(llm): opt into SDK refresh-on-401 hook for managed proxy keys (#…