Repository navigation
fix: replace stale custom LLM key when switching back to the managed default profile - #425
Conversation
…aged default Activating a keyless (managed) LLM profile — e.g. the live "Default" — after a custom-key (BYOR) profile left the previous profile's key in the encrypted ``_llm_api_key`` slot, which is shared by both custom and managed keys. The ``else`` branch only flipped ``has_custom_llm_api_key`` to False, so ``_get_effective_llm_api_key`` kept resolving the stale custom key (it falls back to ``_llm_api_key`` when no org-level key is set). New conversations then launched against the old, possibly-broken profile instead of the managed default — the SaaS "stale default model" bug. Mirror the canonical ``store()`` path: when the activated keyless profile uses a managed OpenHands key, re-ensure the member's managed key via ``OrgStore._ensure_managed_llm_key_for_user`` so the stale custom key is replaced with a fresh managed key. Co-authored-by: openhands <openhands@all-hands.dev>
Coverage reportClick to see where and how coverage changed
This report was generated by python-coverage-comment-action |
||||||||||||||||||||||||||||||||||||
…e custom key The previous fix called _ensure_managed_llm_key_for_user on switch-back to a managed/keyless profile, but that method's "reuse existing key if valid" fast-path can hand back the stale custom (BYOR) key as if it were a managed key: verify_existing_key returns True when LiteLLM's key-list call is inconclusive (keys is None), and verify_key returns True on anything that isn't an explicit auth failure. So the stale dummy key was trusted and reused, and new conversations still 401'd against the old profile. A custom key is never a valid managed key, so it must not be trusted here. Capture the member's prior has_custom_llm_api_key flag and pass it as force= to _ensure_managed_llm_key_for_user so the slot is unconditionally rotated (delete alias + mint fresh) when a custom key is being replaced. The normal reuse path still runs when switching between managed profiles. Add a force keyword to _ensure_managed_llm_key_for_user (defaults False; backward compatible with the store()/update_org caller). The regression test now mocks both LiteLLM verifications to return True (the inconclusive prod failure mode) and asserts the stale key is still replaced. Co-authored-by: openhands <openhands@all-hands.dev>
…itch-back End-to-end test mirroring the real SaaS repro (enterprise#421): activate a BYOR TestModel with a dummy key, switch back to the managed Default, then resolve the effective launch key via _get_effective_llm_api_key and assert it is the fresh managed key — never the stale dummy. Confirms the force-rotate fix covers the full activate→launch path.
…ed profile, not the stale org default enterprise#421: switching from a custom-key BYOR profile back to the managed Default left the stale custom key (e.g. dummymodel) in the member shared _llm_api_key slot. At conversation launch _get_effective_llm_api_key returned that stale key -> 401. c1990f1 attempted to fix this by force-rotating via _ensure_managed_llm_key_for_user(force=True) on switch-back, but that method classifies managed-ness from the org persisted default agent_settings.llm. A profile switch only advances profiles.active and the member diff; it never rewrites the org default, so the org default stays pinned to the prior BYOR config (dummymodel). uses_managed_llm_key was therefore False and the method returned early WITHOUT rotating, so the stale custom key survived. Live repro on pr-1069 staging confirmed it: after activating Default, has_custom=False but _llm_api_key decrypted to dummymodel. Fix: _ensure_managed_llm_key_for_user now accepts an optional llm override; activate_profile passes the activated profile LLM so the classification reflects the profile being switched to (the managed Default), not the stale org default. The force-rotate then runs and replaces the stale custom key with a fresh managed key. Regression test test_switch_back_rotates_when_org_default_is_stale_byor mirrors prod (org default pinned to the stale BYOR config) and fails on c1990f1 / passes with this fix. The prior tests set the org default to the managed model beforehand, which is why c1990f1 passed locally but failed in prod. Co-authored-by: openhands <openhands@all-hands.dev>
…ack repairs the key enterprise#421: after activating a custom-key BYOR profile (e.g. a "TestModel" with a broken key) and switching back to the managed Default, new conversations kept failing with 401 — the stale custom key was never rotated out of the shared ``_llm_api_key`` slot. PR #425 added a force-rotate on switch-back, but it was gated on a hand-rolled ``base_url == LITE_LLM_API_URL`` exact-match check in BOTH ``activate_profile`` and ``OrgStore._ensure_managed_llm_key_for_user``. That check fails for a managed OpenHands model whose ``base_url`` is an ``all-hands.dev`` proxy URL that differs from ``LITE_LLM_API_URL`` by a trailing slash or an app-vs-staging subdomain (or a profile created in one environment and activated in another). ``_ensure_managed_llm_key_for_user`` then bailed out before rotating and the broken key stayed effective — every time, even across repeated switches. Fix: replace both hand-rolled checks with the canonical ``managed_llm_key_config_from_model`` detector that ``SaasSettingsStore.store()`` already uses. It classifies any OpenHands model pointing at an ``all-hands.dev`` proxy (or with ``base_url=None``) as managed, so the stale custom key is force-rotated for every genuinely-managed profile, not just the one whose ``base_url`` is byte-identical to ``LITE_LLM_API_URL``. Regression test ``test_managed_profile_with_non_default_proxy_url_rotates_stale_key`` activates a BYOR profile with a dummy key, then activates a keyless managed profile whose ``base_url`` is an ``all-hands.dev`` URL != ``LITE_LLM_API_URL`` and asserts the stale dummy is replaced with a fresh managed key. It fails on PR #425 and passes with this change. Co-authored-by: openhands <openhands@all-hands.dev>
…ged profile (#421) PR #425 only rotated the *member* LLM key slot when switching from a custom-key BYOR profile back to the managed Default. It never touched `org._llm_api_key`, which holds the BYOR key written when that profile was saved as the org default via POST /orgs/app. `_get_effective_llm_api_key` checks `org.llm_api_key` *before* the member slot, so the stale dummy there (`dummymodel`) won over the freshly-rotated member managed key — every new conversation launched against the dummy and 401'd (`Received=dumm****odel`), even after the member row was repaired. Confirmed against the live staging pod via a settings-load probe (resolve_agent_profile=True): resolved llm.model=openhands/deepseek-v4-flash but resolved llm.api_key=dummymodel (len 10), while the member slot held the fresh `sk-...` managed key and `org.llm_api_key` decrypted to `dummymodel`. Fix: in `_ensure_managed_llm_key_for_user` (the shared chokepoint called from both `activate_profile` and `update_org`), clear `org._llm_api_key` when the target LLM is managed. The org-level column only ever holds a BYOR/org-custom key (managed keys are minted per-member), so clearing it when the active default becomes managed is always safe and lets the effective key fall through to the rotated member key. Regression test pins `org._llm_api_key` to the dummy (the exact prod state the prior tests missed — they only set `org.agent_settings.llm`) and asserts it is cleared on switch-back, with the effective key resolving to the fresh managed key. Co-authored-by: openhands <openhands@all-hands.dev>
Remove the multi-line comment/docstring narration that bloated the PR diff (bug/commit history belongs in the PR description, not inline). No logic changes; all org_profiles/org_store tests still pass (90 passed, 3 skipped). Co-authored-by: openhands <openhands@all-hands.dev>
…ged profile (#421) PR #425 only rotated the *member* LLM key slot when switching from a custom-key BYOR profile back to the managed Default. It never touched `org._llm_api_key`, which holds the BYOR key written when that profile was saved as the org default via POST /orgs/app. `_get_effective_llm_api_key` checks `org.llm_api_key` *before* the member slot, so the stale dummy there (`dummymodel`) won over the freshly-rotated member managed key — every new conversation launched against the dummy and 401'd (`Received=dumm****odel`), even after the member row was repaired. Confirmed against the live staging pod via a settings-load probe (resolve_agent_profile=True): resolved llm.model=openhands/deepseek-v4-flash but resolved llm.api_key=dummymodel (len 10), while the member slot held the fresh `sk-...` managed key and `org.llm_api_key` decrypted to `dummymodel`. Fix: in `_ensure_managed_llm_key_for_user` (the shared chokepoint called from both `activate_profile` and `update_org`), clear `org._llm_api_key` when the target LLM is managed. The org-level column only ever holds a BYOR/org-custom key (managed keys are minted per-member), so clearing it when the active default becomes managed is always safe and lets the effective key fall through to the rotated member key. Regression test pins `org._llm_api_key` to the dummy (the exact prod state the prior tests missed — they only set `org.agent_settings.llm`) and asserts it is cleared on switch-back, with the effective key resolving to the fresh managed key. Co-authored-by: openhands <openhands@all-hands.dev>
d124647 to
9799005
Compare
Remove the multi-line comment/docstring narration that bloated the PR diff (bug/commit history belongs in the PR description, not inline). No logic changes; all org_profiles/org_store tests still pass (90 passed, 3 skipped). Co-authored-by: openhands <openhands@all-hands.dev>
Impact assessment: self-hosted / customer installs vs SaaSVerdict: Behavior change on every surface, not additive-inert — the fix itself (clearing What changed
Environment × flag matrix (before → after)The change is host-independent in the usual sense — no behavior branches on
Third-party BYOR rows ( Validation level per source: the classifier columns are standalone-validated — I extracted the real Behaviors that change, and for whom
Risks to customer installs
Rollout noteThe PR is open, not a draft, CI fully green,
Suggested sequencing: land the Two caveats on confidence, stated plainly: the classifier transitions are standalone-validated against the real classifier source, so every Edited after posting, on two points. The matrix originally listed some surfaces twice (one row per surface × model-prefix pair) without saying so, which obscured that the prefix — not the surface — is what determines breakage; surfaces are now unique with the prefix as a column. And the original claimed SaaS was less exposed because those rows "canonicalize at load." That mitigation was wrong and is retracted: load-time canonicalization is in-memory only and never written back to This analysis was produced by an AI agent (OpenHands) on behalf of @aivong-openhands. |
|
Since the OHE impact analysis shows regression risk for OHE, i'd like to test this on a Replicated VM instance |
Replicated VM verification — PASS ✅Tested this PR end-to-end on a Replicated embedded-cluster VM (Unstable 0.68.0 / Control (no #425) — bug reproduced: after activating a BYOR profile and
Treatment (#425) — fixed:
Notes:
This comment was created by an AI agent (OpenHands) on behalf of @aivong-openhands. |
|
Just adding my 2 cents here - shifting away from is_openhands_model to the new way of doing things cleans things up significantly, so this change has my approval. |
…437) * fix: heal stale org-level BYOR LLM key on conversation start (#421) PR #425 stops new occurrences of the SaaS "stale default model" 401 but leaves already-broken orgs unhealed: their ``org._llm_api_key`` still holds a stale BYOR dummy that shadows the rotated member managed key at launch (``_get_effective_llm_api_key`` checks ``org.llm_api_key`` before the member slot). The existing conversation-start heal can't fix them because both ``get_current_managed_llm_key`` and ``rotate_managed_llm_key`` early-out on a non-null ``org._llm_api_key`` (correctly, since it usually means a legit BYOR org). Add ``SaasSettingsStore.clear_stale_org_level_llm_key_if_managed()``, which restores the invariant — ``org._llm_api_key`` must be ``None`` when the active default is managed — and call it from ``_maybe_refresh_managed_llm_key`` before the verify path. On detecting the violation it clears the stale field and force-rotates a fresh managed key, then invalidates the cached UI/session view (reusing the existing ``invalidate_user_info_cache()`` path, so the DB state and the stale in-memory view (#421) heal together). Detection classifies off the resolved active LLM, so legit BYOR-active orgs and members with their own custom keys are never touched. Self-stabilizing: heals once per broken user on their next load, then the existing verify-and-skip takes over. This is the lazy option B from the #421 analysis; it is cache-coherent out of the box and proportional to restoring the broken cohort without the bulk-processor cache-invalidation work that option C would require. Tests: - ``test_maybe_refresh_managed_llm_key_heals_stale_org_level_key`` pins the broken effective key (``dummymodel``) and asserts the heal branch clears + force-rotates + invalidates, bypassing the verify path. - Real-DB ``test_clear_stale_org_level_key_when_active_default_is_managed`` / ``..._skips_when_active_default_is_byor`` cover the store helper directly: clears on managed-active, leaves a real BYOR key intact. Co-authored-by: openhands <openhands@all-hands.dev> * fix: heal in-flight LLM key when rotation skips after clearing stale org key Candidate-2 fix for the #421 self-heal. clear_stale_org_level_llm_key_if_managed() clears the stale org-level BYOR shadow from the DB, but the heal only restored the *in-flight* LLM when rotate_managed_llm_key() returned a new key. If rotation yielded none (MISSING_MEMBER / already-current / LiteLLM transient), execution fell through to the mismatch bail and returned the original stale llm — the DB was healed but the request still 401'd until the next load. Now, after a successful clear, prefer the rotated key but fall back to re-resolving the effective managed key off the now-healed DB, invalidate the cached user view, and return that. The heal lands on the same request that triggered it. Adds a regression test for the rotation-skips re-resolve path. Co-authored-by: openhands <openhands@all-hands.dev> * test: pin idempotency of stale org-level key heal Co-authored-by: openhands <openhands@all-hands.dev> * fix: gate stale org-level LLM key heal to cloud deployment app_mode == 'saas' is true on self-hosted OHE too, so the #421 heal cleared a legitimately managed enterprise org's org-level key. Gate the clear_stale_org_level_llm_key_if_managed call on DEPLOYMENT_MODE == 'cloud' (the axis that actually separates the All-Hands managed proxy from self-hosted). The rest of the refresh path is untouched. Co-authored-by: openhands <openhands@all-hands.dev> --------- Co-authored-by: openhands <openhands@all-hands.dev> Co-authored-by: aivong-openhands <ai.vong@openhands.dev>
|
🚀 Released in 1.63.0. |
Human
Notice this prevents the error from happening again but does not restore already broken users.
Problem
SaaS-only "stale default model" 401 (enterprise#421), reported from
saas-deployprod:TestModelwith a dummy/broken config, set it as the default.TestModel— fails (expected, bad config).Defaultprofile) back as the default.TestModelkey is still being used (Received=dumm****odel).Root cause
A live settings-load probe (
SaasSettingsStore.load(resolve_agent_profile=True)) against thepr-1069staging pod showed:The model/base_url were correctly resolved to the managed
Default, but the effective api_key wasdummymodel— fromorg._llm_api_key, not the member slot.org._llm_api_keyis the org-level BYOR key written whenTestModelwas saved as the org default viaPOST /orgs/app. It is never cleared on a profile switch —activate_profileonly touches the member row andprofiles.active. And_get_effective_llm_api_keychecksorg.llm_api_keybefore the member slot:So with
has_custom=False,org.llm_api_key(dummymodel) shadows the freshly-rotated member managed key. The prior unit tests missed this because they setorg.agent_settings.llmto the BYOR model/base_url but never persisted a BYOR key intoorg._llm_api_key.Two related gaps were fixed along the way:
activate_profileclassified managed-ness from the stale org defaultagent_settings.llm(still pointing at the BYOR profile) instead of the activated profile, so the member-slot force-rotation was skipped. Now it passes the activated profile's LLM and uses the canonicalmanaged_llm_key_config_from_modeldetector (handlesall-hands.devproxy URLs that differ fromLITE_LLM_API_URL).org._llm_api_keystale — the actual prod 401.Fix
In
_ensure_managed_llm_key_for_user— the shared chokepoint called from bothactivate_profileandupdate_org— clearorg._llm_api_keywhen the target LLM is managed. The org-level column only ever holds a BYOR/org-custom key (managed keys are minted per-member), so clearing it when the active default becomes managed is always safe, and the effective key then falls through to the rotated member key.Testing
TestSwitchBackClearsStaleOrgLevelKeypinsorg._llm_api_keyto the dummy (the exact prod state the prior tests missed) and asserts it is cleared on switch-back, with the effective key resolving to the fresh managed key. Fails without this fix, passes with it.TestE2EStaleDefault401Repro,TestSwitchBackWithStaleOrgDefault,TestSwitchBackManagedProfileWithNonDefaultProxyUrl) still pass.test_org_profiles.py(37),test_org_store.py,test_saas_settings_store.py(137 passed, 3 skipped).ruff check+ruff formatclean.This PR was created by an AI agent (OpenHands) on behalf of the repo maintainer.
Enterprise server image for this PR: