Skip to content

fix: replace stale custom LLM key when switching back to the managed default profile - #425

Merged
juanmichelini merged 8 commits into
mainfrom
fix/stale-llm-key-on-profile-switch
Sep 21, 2026
Merged

juanmichelini merged 8 commits into
mainfrom
fix/stale-llm-key-on-profile-switch

Conversation

@juanmichelini

@juanmichelini juanmichelini commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

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-deploy prod:

  1. Start a conversation with the free DeepSeek (default) model — works.
  2. In LLM profiles, add a profile TestModel with a dummy/broken config, set it as the default.
  3. Start a conversation with TestModel — fails (expected, bad config).
  4. Set DeepSeek (the managed Default profile) back as the default.
  5. Start a conversation with the default model (DeepSeek) — still fails. The TestModel key is still being used (Received=dumm****odel).

Root cause

A live settings-load probe (SaasSettingsStore.load(resolve_agent_profile=True)) against the pr-1069 staging pod showed:

resolved llm.model    : openhands/deepseek-v4-flash   ← correct
resolved llm.api_key  : dummymodel  (len 10)          ← stale dummy → 401
member.llm_api_key    : sk-aVsi87H_w... (len 25)      ← fresh managed key (rotation worked)
org.llm_api_key       : dummymodel  (len 10)          ← stale, never cleared

The model/base_url were correctly resolved to the managed Default, but the effective api_key was dummymodel — from org._llm_api_key, not the member slot.

org._llm_api_key is the org-level BYOR key written when TestModel was saved as the org default via POST /orgs/app. It is never cleared on a profile switch — activate_profile only touches the member row and profiles.active. And _get_effective_llm_api_key checks org.llm_api_key before the member slot:

def _get_effective_llm_api_key(org, org_member):
    if org_member.has_custom_llm_api_key: return org_member.llm_api_key
    if org.llm_api_key: return org.llm_api_key          # ← dummymodel wins here
    if org_member._llm_api_key: return org_member.llm_api_key
    return None

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 set org.agent_settings.llm to the BYOR model/base_url but never persisted a BYOR key into org._llm_api_key.

Two related gaps were fixed along the way:

  • activate_profile classified managed-ness from the stale org default agent_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 canonical managed_llm_key_config_from_model detector (handles all-hands.dev proxy URLs that differ from LITE_LLM_API_URL).
  • The above still left org._llm_api_key stale — the actual prod 401.

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 the effective key then falls through to the rotated member key.

Testing

  • New regression TestSwitchBackClearsStaleOrgLevelKey pins org._llm_api_key to 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.
  • Existing switch-back regressions (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 format clean.

This PR was created by an AI agent (OpenHands) on behalf of the repo maintainer.


Enterprise server image for this PR:

ghcr.io/openhands/enterprise-server:sha-89e850f

…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>
@github-actions github-actions Bot added the type: fix A bug fix label Sep 16, 2026
@github-actions

github-actions Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Coverage report

Click to see where and how coverage changed

FileStatementsMissingCoverageCoverage
(new stmts)
Lines missing
  server/routes
  org_profiles.py
  storage
  org_store.py
Project Total  

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>
juanmichelini pushed a commit that referenced this pull request Sep 17, 2026
…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>
juanmichelini pushed a commit that referenced this pull request Sep 17, 2026
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>
@juanmichelini
juanmichelini force-pushed the fix/stale-llm-key-on-profile-switch branch from d124647 to 9799005 Compare September 17, 2026 18:08
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>

aivong-openhands commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Impact assessment: self-hosted / customer installs vs SaaS

Verdict: Behavior change on every surface, not additive-inert — the fix itself (clearing org._llm_api_key on switch-back to a managed profile) is functionally correct for the reported SaaS 401, but it is also (a) a destructive org-level write triggered by one member's per-member profile activation, and (b) the swap to managed_llm_key_config_from_model silently narrows the update_org path by newly requiring an openhands/-prefixed model, so orgs whose persisted default is the seeded litellm_proxy/<name> + base_url == LITE_LLM_API_URL lose managed-key rotation and the org-wide has_custom_llm_api_key reset they get today. The variable that decides breakage is the persisted model prefix, not the deployment surface — every surface, SaaS included, holds affected rows. There is no opt-out knob (no env var, chart value, or KOTS option), so both changes are fleet-wide posture decisions the moment the image ships.

What changed

  1. OrgStore._ensure_managed_llm_key_for_user (storage/org_store.py:996) — four distinct changes:
    • New force: bool = False kwarg; the "reuse existing key" fast-path is now gated on not force (org_store.py:1057-1066).
    • New llm: LLM | None = None kwarg overriding managed-ness classification away from the org's persisted default (org_store.py:1015-1021).
    • Hand-rolled base_url == LITE_LLM_API_URL check replaced with managed_llm_key_config_from_model(...) plus a new config.openhands_type requirement (org_store.py:1022-1028).
    • New side effect: updated_org.llm_api_key = None whenever the target LLM classifies as managed (org_store.py:1031-1039).
    • Consumer sites (complete, non-test): storage/org_store.py:607 (update_org, called with no new kwargs → inherits the classifier narrowing and the org-key clear) and server/routes/org_profiles.py:462 (activate_profile, passes force=had_custom_key, llm=llm).
  2. activate_profile (server/routes/org_profiles.py:434-465) — keyed branch now classifies via managed_llm_key_config_from_model instead of base_url-exact-match + is_openhands_model; keyless branch captures the prior has_custom_llm_api_key and force-rotates through the chokepoint. Reached via POST /api/organizations/{org_id}/profiles/{name}/activate (saas_server.py:185), gated on Permission.EDIT_ORG_SETTINGS.
  3. Unchanged but load-bearing: SaasSettingsStore._get_effective_llm_api_key (storage/saas_settings_store.py:189) precedence is member.has_custom → org.llm_api_key → member._llm_api_key. This is the precedence the fix exploits, and it is what makes the org-level clear safe for co-members (point 3 below).

Environment × flag matrix (before → after)

The change is host-independent in the usual sense — no behavior branches on WEB_HOST or OH_DEPLOYMENT_MODE. What it branches on is each surface's interacting state: the LITE_LLM_API_URL it runs with, and the model prefix its org rows actually hold. Both prefix shapes occur on every surface, so the classifier columns are split by prefix and each surface appears once.

Deployment LITE_LLM_API_URL openhands/<name> rows litellm_proxy/<name> + managed base_url rows Result
Customer self-hosted (OHE / Replicated), bundled litellm http://<release>-litellm.<ns>.svc.cluster.local:4000 True → True True → False mixed: openhands/ unchanged (org BYOR key now cleared — posture); litellm_proxy/ changed (regression risk)
Customer self-hosted, external proxy .Values.litellm.url (placeholder https://llm-proxy.example.com) True → True True → False mixed, as above
SaaS production https://llm-proxy.app.all-hands.dev False → True where the proxy URL is not byte-identical True → False mixed: openhands/ fixed (the #421 repro); litellm_proxy/ changed (regression risk)
SaaS staging / dev / feature previews per-env llm-proxy.*.all-hands.dev False → True for a profile created in one env, activated in another True → False mixed, as above

Third-party BYOR rows (anthropic/… + api.anthropic.com) classify False → False on every surface — unchanged, org BYOR key preserved.

Validation level per source: the classifier columns are standalone-validated — I extracted the real managed_llm_key_config_from_model and is_openhands_model bodies verbatim from this PR's head and executed them against each surface's LITE_LLM_API_URL, diffing main's guard against this PR's guard; every → transition above is a confirmed divergence, not an inference. The self-hosted LITE_LLM_API_URL, OH_DEPLOYMENT_MODE=self_hosted pin, commented-out LITELLM_DEFAULT_MODEL, and image.tag are from chart/template defaults (OpenHands-Cloud charts/openhands/templates/_env.yaml:353-377,749, charts/openhands/values.yaml:15,127,329-337). SaaS per-env values and the live distribution of litellm_proxy/ vs openhands/ org rows are not verified (no access) — I could not read the SaaS values files or query any database, so the population size of the affected rows is unquantified on every surface.

Behaviors that change, and for whom

  • Every surface: switching the active default to a managed profile now deletes the org's BYOR key from org._llm_api_key rather than shadowing it. OrgAppSettingsResponse.llm_api_key_set (server/routes/org_models.py:494) flips to False, and an admin switching back to BYOR must re-enter the credential — there is no undo. The trigger is activate_profile, which is per-member for the key and diff but org-level for profiles.active and now for this column: any member holding EDIT_ORG_SETTINGS activating a managed profile destroys the org-wide credential for everyone.
  • Every surface: update_org (POST /orgs/app) inherits the org-key clear too, since it calls the same chokepoint with default kwargs. That path is the one that wrote the key, so it is more defensible there, but it is still new destructive behavior on a save that only touches agent_settings_diff.llm.
  • Every surface, orgs on a litellm_proxy/-prefixed default: _ensure_managed_llm_key_for_user now early-returns. Two knock-on effects: the acting member's managed key is no longer minted/refreshed, and — because effective_managed_key is None — should_reset_custom_key_flag is False (org_store.py:615-621), so no member's has_custom_llm_api_key is reset. A member who previously held a BYOR key keeps has_custom=True, so _get_effective_llm_api_key keeps returning their third-party key while the model now points at the managed proxy → a 401 with the same signature as Bug: bulk managed-key ownership repair regenerates keys without invalidating cached UI/session view (stale-key errors) #421, just reached from the other direction. This shape is not exotic: get_default_llm_model() returns litellm_proxy/<name> via build_litellm_proxy_model_path and get_default_llm_base_url() returns LITE_LLM_API_URL, which is exactly what create_org seeds (org_store.py:128-130) and what create_base_org_agent_settings produces (storage/org_default_settings.py:25-26).
  • The litellm_proxy/ shape is not transitional, and not self-hosted-specific. Two verified reasons. First, canonicalize_openhands_llm_payload runs in load() on merged_agent_settings (saas_settings_store.py:449) and is assigned only to the in-memory kwargs['agent_settings']; there is no write-back to org.agent_settings. _ensure_managed_llm_key_for_user, when called from update_org without the new llm= override, reads OrgStore.get_agent_settings_from_org(updated_org) — the raw persisted row, which never saw that canonicalization. Second, _validate_org_version (org_store.py:415-425) rewrites managed orgs' models back to get_default_llm_model(), i.e. the litellm_proxy/-prefixed value, and calls _update_org_kwargs with no update_data, bypassing the classification block entirely — so org rows are pushed toward the narrowed shape on every version bump. Additionally, on self-hosted the SDK's rewrite predicate only matches the two hard-coded managed-proxy URLs, so an in-cluster or customer-proxy base_url can never canonicalize even in memory.
  • SaaS (the intended fix): the Bug: bulk managed-key ownership repair regenerates keys without invalidating cached UI/session view (stale-key errors) #421 switch-back path is repaired for openhands/-prefixed rows, and the cross-environment case (an openhands/ model carrying a staging/app proxy URL that differs from LITE_LLM_API_URL by subdomain or trailing slash) now rotates where main silently bailed. Standalone-confirmed.
  • Interplay: force=True bypasses the verify_existing_key / verify_key fast-path, so switch-back now always calls delete_key_by_alias + generate_key. That exercises the LiteLLM write path on every BYOR→managed switch instead of occasionally. _generate_key raises ValueError when LITE_LLM_API_KEY/LITE_LLM_API_URL are unset, and it is called inside the _org_profiles_transaction context — so on an install with LiteLLM unconfigured, activating a managed profile now raises where it previously returned early, and the exception skips the commit (the context manager commits only on normal exit), rolling back profiles.active. Not verified against a real LiteLLM-disabled install.

Risks to customer installs

  1. The openhands_type narrowing is a functional regression, not a no-op, and it is surface-independent. The chart leaves LITELLM_DEFAULT_MODEL commented out, so the seeded default is litellm_proxy/<version-map-model> + base_url == LITE_LLM_API_URL — the exact shape main treats as managed and this PR does not. Per the bullet above, neither load-time canonicalization nor the org version bump moves rows out of that shape; the bump moves them in. Mitigating factor I verified: update_org merges agent_settings_diff into the org row before the classification block runs (org_store.py:585-599), so an admin saving a model through the UI classifies on the new openhands/-prefixed value and is unaffected. The exposure is therefore API clients, any path posting a litellm_proxy/-prefixed model, and freshly seeded or version-bumped orgs that no admin has re-saved — unquantified, and the failure is a silent 401 rather than an error.
  2. Destroying the org BYOR key is a posture change, separate from any breakage. Self-hosted installs are the population most likely to run BYOR against their own proxy (ENABLE_BYOR_EXPORT exists specifically for deployments with no Stripe flow), so they carry the most value in org._llm_api_key. A per-member profile activation is a weak authorization story for an irreversible org-wide credential deletion, even with EDIT_ORG_SETTINGS gating.
  3. Co-members are functionally safe, and this can be argued from mechanism. When a BYOR key is set via POST /orgs/app, get_member_updates() broadcasts it into every member row and resets has_custom_llm_api_key=False (org_models.py:438-453, org_member_store.py:297-314); members joining later are seeded from their loaded effective settings (org_invitation_service.py:370-385, user_provisioning.py:753). So after org._llm_api_key is cleared, _get_effective_llm_api_key falls through to member._llm_api_key, which holds the same value — the effective key is unchanged. This is why the PR's "always safe" claim holds for the common case.
  4. But the fall-through is not total, and this is the gap worth closing before merge. add_user_to_org is called with llm_api_key='' whenever the loaded settings carry no key — both org_invitation_service.py:370-372 and user_provisioning.py:740-746 do this explicitly, the latter commented as letting "LiteLLM-disabled deployments still create memberships." For such a member, org_member._llm_api_key is falsy, so _get_effective_llm_api_key returns None and the launch proceeds with no credential (a logger.warning, not an error, at saas_settings_store.py:439). Before this PR those members resolved to org.llm_api_key. Not verified (no access) — I cannot tell how many such rows exist, and they are most likely on LiteLLM-disabled self-hosted installs, which is precisely the population least able to self-diagnose it.
  5. No opt-out. Neither behavior is gated by an env var, chart value, or KOTS ConfigOption, and both live below the route layer, so an operator cannot scope or disable them. Whatever ships, ships to the whole fleet at once.
  6. Test coverage matches the fix, not the narrowing. TestSwitchBackClearsStaleOrgLevelKey genuinely pins the prod state the prior tests missed (org.llm_api_key = 'dummymodel') and asserts the effective key resolves to the fresh managed key — a real regression test. But no test covers a litellm_proxy/-prefixed org default through update_org, which is exactly where the classifier swap changes behavior, and none covers a member whose _llm_api_key is empty. CI is green (Python Tests on Linux (3.12) SUCCESS), so the narrowing is invisible to the suite.

Rollout note

The PR is open, not a draft, CI fully green, mergeStateStatus: BLOCKED on REVIEW_REQUIRED; the author reports manual verification on a staging preview. It is app-code only — server/routes/org_profiles.py, storage/org_store.py, plus tests — with no chart or migration component, so it reaches surfaces purely through the ghcr.io/openhands/enterprise-server image:

  • SaaS prod/staging/dev/feature pick it up on the normal merge → image build → deploy path, immediately and fleet-wide. Feature previews already run it via the PR image (sha-f5ec3e2).
  • Customer self-hosted / OHE only see it when charts/openhands/values.yaml image.tag is bumped off 1.61.0 and a KOTS release ships, so there is a natural staging window — the one place rollout can be sequenced. Nothing else can be: with no flag, the behavior cannot be scoped to SaaS or dark-launched.
  • Because both changes are code-level with no config bypass, and because the chart's own OH_DEPLOYMENT_MODE=self_hosted pin does not gate either one, the risks in points 1 and 4 cannot be mitigated post-deploy except by rolling the image back.

Suggested sequencing: land the org._llm_api_key clear (the actual #421 fix) and keep the classifier swap's openhands_type requirement out of the shared update_org path — e.g. preserve main's base_url == LITE_LLM_API_URL arm alongside the canonical detector, so this PR strictly widens rather than trades one classification gap for another. That removes the regression surface on every deployment, not just self-hosted.

Two caveats on confidence, stated plainly: the classifier transitions are standalone-validated against the real classifier source, so every → above is a confirmed divergence from main. But the blast radius of risks 1 and 4 (how many org rows hold a litellm_proxy/ default, how many member rows have an empty _llm_api_key) is unverified for lack of database access — those two numbers decide whether they are footnotes or blockers, and a prod read-replica check would settle it.


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 org.agent_settings, while _validate_org_version actively rewrites rows back to the litellm_proxy/ prefix and bypasses the classification block. The regression risk is surface-independent, SaaS included. Code references for both are in the "not transitional" bullet above.

This analysis was produced by an AI agent (OpenHands) on behalf of @aivong-openhands.

@aivong-openhands

Copy link
Copy Markdown
Contributor

Since the OHE impact analysis shows regression risk for OHE, i'd like to test this on a Replicated VM instance

@aivong-openhands

Copy link
Copy Markdown
Contributor

Replicated VM verification — PASS ✅

Tested this PR end-to-end on a Replicated embedded-cluster VM (Unstable 0.68.0 /
enterprise-server:1.61.0 as control, sha-f5ec3e2 as the fix build). Repro
mirrors this PR's own unit test (test_switching_to_managed_default_replaces_stale_custom_key)
but runs against the real LiteLLM (no mocks) with real /chat/completions
calls, and covers both stale-key vectors (org-level org._llm_api_key and the
member slot).

Control (no #425) — bug reproduced: after activating a BYOR profile and
switching the org default back to the managed Default:

Treatment (#425) — fixed:

  • Fresh cycle: after switch-back, org._llm_api_key is cleared (None) and
    the member slot is force-rotated to a fresh managed sk-… key; the
    effective key is the managed key (stale=False).
  • Heal-forward: a principal left broken on the control build heals after a
    single switch-back on the fixed build (org key cleared + member rotated).
  • E2E: with the fresh managed key, /v1/models → 200 and a real completion
    against a served model (claude-sonnet-4-5-20250929) → HTTP 200.
  • Live UI: logged into the fix build and drove the whole flow in the browser
    (BYOR profile as org default → switch back to managed → start conversation);
    the conversation succeeded end-to-end with no stale-key 401.

Notes:

  • Completions that used the resolved model string (openhands/deepseek-v4-flash
    / openhands/claude-…) returned 400 "invalid model" — a test-instance data
    quirk (the DB default verified model isn't served on this proxy, and the raw
    openhands/ prefix isn't LiteLLM's registered name). This is a post-auth model
    routing 400, not a 401, so it's unrelated to this PR; key auth is proven by the
    401→200 transition.
  • The "valid third-party BYOR retained + 200" regression wasn't fully exercised
    (no spare valid provider key), but activating a BYOR profile still sets
    has_custom=True and keeps the custom key — the fix only clears/rotates when
    switching to a managed profile, so BYOR activation is undisturbed.
  • Instance restored to baseline afterwards (image 1.61.0, DB rev 161,
    throwaway profile deleted, state verified == original).

This comment was created by an AI agent (OpenHands) on behalf of @aivong-openhands.

@juanmichelini
juanmichelini merged commit bfd4e15 into main Sep 21, 2026
16 checks passed
@juanmichelini
juanmichelini deleted the fix/stale-llm-key-on-profile-switch branch September 21, 2026 19:20
@saurya

saurya commented Sep 21, 2026

Copy link
Copy Markdown
Contributor

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.

juanmichelini added a commit that referenced this pull request Sep 22, 2026
…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>
@openhands-release-bot openhands-release-bot Bot added the released: 1.63.0 Shipped in 1.63.0 label Sep 22, 2026
@openhands-release-bot

Copy link
Copy Markdown
Contributor

🚀 Released in 1.63.0.

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

Labels

released: 1.63.0 Shipped in 1.63.0 type: fix A bug fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants