Skip to content

fix: heal stale org-level BYOR LLM key on conversation start (#421) - #437

Merged
juanmichelini merged 6 commits into
mainfrom
heal-stale-org-level-llm-key-421
Sep 22, 2026
Merged

juanmichelini merged 6 commits into
mainfrom
heal-stale-org-level-llm-key-421

Conversation

@juanmichelini

@juanmichelini juanmichelini commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Human

image

This is option B from the #421 remediation analysis — the lazy, cache-coherent healer for the already-broken cohort. It is a separate PR against main, intentionally not stacked on #425 (they're code-independent; see below).

Problem

PR #425 prevents new occurrences of the SaaS "stale default model" 401 (#421), but it does not restore already-broken orgs. For an affected org the persisted state is:

  • org._llm_api_key = a stale BYOR dummy (e.g. dummymodel) — written when a BYOR profile was saved as the org default, and never cleared on switch-back.
  • profiles.active points at the managed Default, so the resolved model/base_url are correct, but…
  • …the effective api_key is still dummymodel``, because _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          # ← stale dummy wins here
    ...

So any member with has_custom=False keeps sending the stale key → 401.

The existing conversation-start heal (_maybe_refresh_managed_llm_key) can't fix these users: 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):

# get_current_managed_llm_key / rotate_managed_llm_key
if org is None or org._llm_api_key:
    return None / BYOK        # ← broken org bails here

Fix

Restore the invariant #425 now enforces going forward:

org._llm_api_key must be None whenever the active default is managed.

Add SaasSettingsStore.clear_stale_org_level_llm_key_if_managed(), called from _maybe_refresh_managed_llm_key before the verify path. On detecting the violation (active default managed + org._llm_api_key non-null) it:

  1. clears org._llm_api_key;
  2. force-rotates a fresh managed key via rotate_managed_llm_key (which now succeeds instead of returning BYOK);
  3. invalidates the cached UI/session view via the existing invalidate_user_info_cache().

Reusing the conversation-start path means the DB state and the stale in-memory view heal together — no separate cache-invalidation mechanism (that's the work option C would require, and why B-alone is the proportional choice).

Safety

  • Never touches a legit BYOR org. Detection classifies off the resolved active LLM via managed_llm_key_config_from_model; a real BYOR-active org returns None → the field is left intact.
  • Never touches a member's own custom key. rotate_managed_llm_key already returns BYOK for has_custom=True members.
  • Self-stabilizing. Heals once per broken user on their next load; subsequent loads see org._llm_api_key is None → the existing verify-and-skip takes over. No repeated rotation.

Why separate from #425, not stacked

Testing

  • 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 (which would otherwise skip on the resulting key mismatch).
  • 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 the stale key on managed-active; leaves a real BYOR key intact on BYOR-active.
  • test_saas_settings_store.py, test_org_profiles.py (32), test_live_status_app_conversation_service.py managed-key suite all green. ruff check + ruff format clean.

The one failure in test_live_status_app_conversation_service.py (test_configure_llm_and_mcp_openhands_model_no_base_urls) is pre-existing on clean main (env-driven llm-proxy.eval.all-hands.dev default leaking into _configure_llm, which this PR does not touch) — verified by stashing the diff and reproducing the identical failure.

Scope / not in this PR

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-3925ffb

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

github-actions Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Coverage report

Click to see where and how coverage changed

FileStatementsMissingCoverageCoverage
(new stmts)
Lines missing
  openhands/app_server/app_conversation
  live_status_app_conversation_service.py 1533, 1544
  storage
  saas_settings_store.py 1060-1061, 1079, 1093
Project Total  

This report was generated by python-coverage-comment-action

…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>

Copy link
Copy Markdown
Contributor

Impact assessment: self-hosted / customer installs vs SaaS

Verdict: behavior change that reaches customer self-hosted installs too — the app_mode != 'saas' guard does not exclude OHE, because the openhands chart pins OPENHANDS_CONFIG_CLS=server.config.SaaSServerConfig and OH_APP_MODE=saas for every OHE install; every surface that resolves a managed/proxy LLM gets the new heal, there is no opt-out knob, and in a mixed org (org-level BYOR default + one member on a managed profile) the heal clears the org-wide org._llm_api_key off one member's resolved config, silently changing the effective credential for the org's other members — verified against a real DB below.

What changed

  1. SaasSettingsStore.clear_stale_org_level_llm_key_if_managed() — new (storage/saas_settings_store.py:1063). Classifies the acting member's resolved LLM via managed_llm_key_config_from_model(llm.model, llm.base_url); if managed and org._llm_api_key is non-null, nulls the org-wide encrypted column and commits. Returns True.
    Consumers: live_status_app_conversation_service.py:1487 (the only call site).

  2. LiveStatusAppConversationService._maybe_refresh_managed_llm_key() — new heal branch prepended before the existing verify path (live_status_app_conversation_service.py:1478-1530). On clear_* -> True: rotate_managed_llm_key(), else fall back to get_current_managed_llm_key(); on a key, invalidate_user_info_cache() and return the LLM with the new key.
    Consumers of the enclosing method (both reached on conversation start):

    • live_status_app_conversation_service.py:1704 — _configure_llm_and_mcp, the launch LLM.
    • live_status_app_conversation_service.py:1091 — _seed_sandbox_profiles, the sandbox profile-store fallback api-key.
      A near-duplicate of this path exists at openhands/app_server/settings/settings_router.py:149 and was not given the heal, so the two paths now diverge.

Guards upstream of the new code (unchanged): self.app_mode != 'saas', user.id and llm.api_key present, managed_llm_key_config_from_model(...) is not None, key not empty/**********, get_effective_org_id() non-null.

Environment × interacting state (before → after)

This is a host-independent change: the code branches on org/member DB state, not on WEB_HOST or a deployment flag. So the columns below are each surface's interacting state — what decides whether the new branch fires there.

Deployment app_mode (gate at :1388) LITE_LLM_API_URL (managed classifier input) Org-level _llm_api_key in play? Result
Customer self-hosted / OHE (Replicated) saas — pinned by chart OPENHANDS_CONFIG_CLS: "server.config.SaaSServerConfig" (values.yaml:25) + OH_APP_MODE: "saas" (_env.yaml:746). OH_DEPLOYMENT_MODE=self_hosted is a separate knob and does not gate this path → unchanged bundled litellm-helm: http://<release>-litellm.<ns>.svc.cluster.local:4000; else .Values.litellm.url → unchanged Yes, most likely here — org-level BYOR is the customer's own Anthropic/OpenAI key, set via PATCH /organizations/{id}/settings llm_api_key changed (in scope, incl. the mixed-org clear)
SaaS production saas → unchanged https://llm-proxy.app.all-hands.dev (code default) → unchanged Yes for BYOR orgs; the stale-dummy cohort this PR targets fixed for the #421 cohort; changed for mixed orgs
SaaS staging saas → unchanged staging proxy → unchanged same shape as prod fixed / changed
SaaS feature previews (e.g. pr-1085.staging) saas → unchanged staging proxy → unchanged same shape as prod fixed / changed (the author's manual test surface)
SaaS dev / eval saas → unchanged https://llm-proxy.eval.all-hands.dev → unchanged same shape fixed / changed
OSS / local OpenHands openhands → unchanged n/a n/a unchanged (app_mode != 'saas' returns early)

Validation level per source: the classifier rows are standalone-validated — I executed the real managed_llm_key_config_from_model source against each surface's LITE_LLM_API_URL; on every surface including both OHE variants, openhands/* with base_url=None and any model whose base_url equals that install's proxy URL classify as managed (a third-party BYOR base_url does not). The OHE app_mode / LITE_LLM_API_URL / OH_DEPLOYMENT_MODE rows are from chart templates and values at OpenHands/OpenHands-Cloud@main (charts/openhands/templates/_env.yaml, charts/openhands/values.yaml) — not verified against a live customer install, and a KOTS values.env override could in principle change them. The SaaS prod/staging/dev proxy URLs are not verified live (no access); they come from the code default in server/constants.py:106 / settings_router.py:63 and the URLs used in the repo's own tests.

Behaviors that change, and for whom

  • All SaaS-mode surfaces, including OHE — every conversation start whose resolved LLM is managed now performs an extra load() + a SELECT user/org before the verify path. Cheap, but it is on the hot launch path and runs for every such start, not just broken ones.
  • The Bug: bulk managed-key ownership repair regenerates keys without invalidating cached UI/session view (stale-key errors) #421 cohort (SaaS prod, and any OHE install that hit the same switch-back sequence) — heals on next conversation start: stale org._llm_api_key cleared, managed key rotated, cache invalidated, 401 gone in-flight. This is the intended fix and it works.
  • Mixed orgs on any surface — cross-member blast radius. clear_* decides off the acting member's resolved LLM but writes an org-wide column. Verified against a real Postgres DB using the repo's own org_with_multiple_members_fixture: org default anthropic/claude-3-5-sonnet + org-wide BYOR key, admin switched to openhands/... via their member diff (active profile a named org profile, so the diff survives load()), second member left on the org default. Result: cleared=True, org._llm_api_key -> None, and the second member's effective key silently changed from the org BYOR key to their own member-slot key while their model/base_url stayed on the BYOR endpoint — i.e. the wrong credential is now sent to a third-party provider. Neither new store test covers this: one clears the member diff so the org-level managed model resolves; the other makes org and member BYOR.
  • Exposure is state-dependent, and narrower than the above alone suggests. When the active profile is the materialized Default, load() overwrites model/base_url from that profile, so the member diff does not survive and the heal does not fire (I observed cleared=False in exactly that state). The clear reproduces when the active profile is a named org profile. That makes it a real but conditional path, not the common case.
  • Rotation side effects widen. The heal calls rotate_managed_llm_key(), which does delete_key_by_alias + generate_key against LiteLLM. Every heal is now two proxy mutations on the launch path. On OHE with the bundled in-cluster LiteLLM, a proxy blip makes _generate_key raise; the outer except Exception swallows it and returns the original LLM — but org._llm_api_key has already been committed as NULL in a separate session. Clearing and rotating are not atomic, so a failure here leaves the org key gone with no new key minted.
  • Paths that still diverge. settings_router.py:149 mirrors this refresh logic and did not get the heal, so healing depends on which entry point the user hits.

Risks to customer installs

  1. Customer installs are in scope, contrary to the usual "SaaS-only" reading. The guard is app_mode, and the chart pins app_mode=saas for OHE. OH_DEPLOYMENT_MODE=self_hosted — the flag that does say "this is a customer install" — is not consulted on this path. Argued from the config, not from intent: an OHE org whose members resolve an openhands/* model or the install's own proxy URL runs this heal.
  2. Org-level BYOR is the normal OHE shape, and it is exactly the field being nulled. Self-hosted customers commonly set one org-wide provider key. The blast radius is org-wide while the decision input is one member's config, so the "never touches a legit BYOR org" claim in the description holds only for a uniformly BYOR org. Verified counterexample above.
  3. Not atomic, and no opt-out. The DB clear commits in its own session before rotation is attempted; a LiteLLM failure leaves the org key cleared and unreplaced. There is no env var, chart value, or KOTS option to disable or scope the heal — shipping it is a fleet-wide decision, not a per-install one.
  4. Functionally, for the single-org / uniformly-managed case it is safe and self-limiting. After one heal org._llm_api_key is None, so subsequent loads take the existing verify-and-skip path; there is no rotation loop. Members with has_custom_llm_api_key=True are untouched (rotate_managed_llm_key returns BYOK). OSS/local is untouched.
  5. Separate from breakage: this is also a small credential-lifecycle change. It deletes and regenerates managed LiteLLM keys from an unauthenticated-by-the-user trigger (any conversation start), which is a different posture from healing only on an explicit settings action — worth stating even where nothing breaks.

Suggested narrowing, if useful: scope the clear to the case where no member of the org resolves a BYOR config, or move the clear into the same session/transaction as the rotation so the two cannot half-apply.

Rollout note

PR is open (not merged), base main, head 1ded7b8. It reaches surfaces as follows:

  • SaaS dev / staging / feature previews — on merge, via the normal enterprise-server image build; the PR image ghcr.io/openhands/enterprise-server:sha-1ded7b8 is already deployable to a preview (the author tested on pr-1085.staging).
  • SaaS production — next enterprise-server deploy after merge. No flag, so it cannot be staged or scoped per-org; the only staging lever is when the image ships.
  • Customer self-hosted / OHE — only once a chart release pins an enterprise-server image containing this commit and the customer takes that KOTS release. That lag is the real containment: it gives time to narrow the mixed-org clear before it reaches customer installs. Note that a KOTS values.env entry merges by name and wins, so a customer that has overridden OPENHANDS_CONFIG_CLS would fall outside this path — but nothing in the default chart does.

Because there is no opt-out knob, the practical rollback for any surface is reverting the image.


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

@aivong-openhands

Copy link
Copy Markdown
Contributor

Mutation review of the tests in this PR

I hand-wrote a small set of targeted mutants (reverting the fix + poking the machinery around it) and ran them against only the test files this PR touches. Baselines, green:

  • tests/unit/test_saas_settings_store.py -k clear_stale_org_level_key → 2 passed (~1.8s, real Postgres)
  • tests/unit/app_server/test_live_status_app_conversation_service.py -k maybe_refresh_managed_llm_key → 11 passed (~6.7s, mocked store)

Mutants caught ❌ (your tests work)

Mutant Result
CONTROL – skip the org._llm_api_key = None clear in clear_stale_org_level_llm_key_if_managed ❌ killed
Neutralise the managed-classifier guard so a BYOR-active org gets cleared too ❌ killed
CONTROL – disable the whole if await clear_stale_org_level_llm_key_if_managed(): heal branch ❌ killed
Drop the re-resolve fallback (healed_key = rotation.new_key only) ❌ killed

Two things make this suite land. The store tests drive the real commit and re-read org._llm_api_key from a fresh session (not a mock return), and the BYOR test plants a real key and asserts it survives untouched — so both the "must clear" and the "must not clobber a legit BYOR org" halves are pinned. The service tests assert the exact await fingerprint of each arm (get_key.assert_not_awaited() on the rotate path, get_key.assert_awaited_once_with() on the re-resolve path) plus the resolved api_key value, which is what kills the "drop the fallback" mutant via test_..._heals_via_re_resolve_when_rotation_skips.

Survivor ✅ (a real gap)

Mutant Result
In clear_stale_org_level_llm_key_if_managed, weaken the guard if org is None or not org._llm_api_key: → if org is None: ✅ 2 passed

Why it matters in production. That not org._llm_api_key clause is what makes the heal a one-shot. clear_stale_org_level_llm_key_if_managed() runs on every conversation start (via _maybe_refresh_managed_llm_key). Once an org has been healed, org._llm_api_key is already None, so the guard short-circuits to return False and the caller skips rotation — the "self-stabilizing / no repeated rotation" property the PR description promises. If that clause regresses, an already-healed, managed-active org would on every load (a) re-enter the write path and COMMIT a redundant org._llm_api_key = None, and (b) return True, driving the caller to force-rotate the managed LiteLLM key and invalidate the user-info cache on every single conversation start — unbounded key churn. Both new store tests seed a non-null stale key, so nothing exercises the already-healed path.

Fix — a real-DB test for the idempotent no-op:

@pytest.mark.asyncio
async def test_clear_stale_org_level_key_is_noop_when_already_healed(
    session_maker, async_session_maker, org_with_multiple_members_fixture
):
    """Idempotency: an already-healed org (active default managed AND
    org._llm_api_key already None) is a no-op — clear_* must return False so the
    caller does not re-rotate the managed key on every load."""
    from storage.org import Org

    fixture = org_with_multiple_members_fixture
    admin_user_id = fixture['admin_user_id']
    org_id = fixture['org_id']

    with session_maker() as session:
        org = session.get(Org, org_id)
        assert org is not None
        org.agent_settings = {'llm': {'model': 'openhands/claude-opus-4-5-20251101'}}
        org.llm_api_key = None
        admin_member = next(m for m in org.org_members if m.user_id == admin_user_id)
        admin_member.agent_settings_diff = {}
        admin_member.has_custom_llm_api_key = False
        session.commit()

    store = SaasSettingsStore(str(admin_user_id))
    with (
        patch('storage.saas_settings_store.a_session_maker', async_session_maker),
        patch('storage.user_store.a_session_maker', async_session_maker),
        patch('storage.org_store.a_session_maker', async_session_maker),
    ):
        cleared = await store.clear_stale_org_level_llm_key_if_managed()

    assert cleared is False
    with session_maker() as session:
        org = session.get(Org, org_id)
        assert org is not None
        assert org._llm_api_key is None

Verified: this passes on the PR branch unmodified, and fails (cleared comes back True) with the guard weakened to if org is None:.

Not a test gap

  • One more mutant survived — removing and rotation.new_key from the ROTATED arm of the healed_key conditional in _maybe_refresh_managed_llm_key. I think this is an equivalent mutant: it only changes behaviour when rotate_managed_llm_key() returns status == ROTATED with a falsy new_key, but ManagedLlmKeyStatus.ROTATED is only ever constructed alongside new_key=<generated key> from LiteLlmManager.generate_key(), so that self-inconsistent result isn't reachable through the current rotate path. The and rotation.new_key clause is defensive belt-and-suspenders, not an untested branch. If you want to pin the contract rather than leave it implicit, a one-line assert rotation.new_key in the ROTATED store test would do it — but I wouldn't add a test just to kill this mutant.

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

Co-authored-by: openhands <openhands@all-hands.dev>

Copy link
Copy Markdown
Contributor Author

Mutation survivor addressed — added the idempotency test from your review.

  • test_clear_stale_org_level_key_is_noop_when_already_healed — commit 14d52c520 (tests/unit/test_saas_settings_store.py): already-healed org (managed-active default + org._llm_api_key already None) is a no-op.
  • Verified against a real Postgres container: passes on the branch unmodified,and fails (cleared comes back True, assert True is False)with the guard weakened to if org is None: — exactly the mutant you identified.
  • Full set green: test_saas_settings_store.py -k clear_stale_org_level_key → 3 passed (+ the new idempotency test = 4 total), test_live_status_app_conversation_service.py -k maybe_refresh_managed_llm_key → 11 passed. ruff check and ruff format --check clean.
  • Skipped the equivalent-mutant test for and rotation.new_key as you recommended — no test added to kill it.

Author's note: I deliberately did not change any production code for this — the guard behaviour is pinned by the new test, not modified by it.

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

@aivong-openhands

Copy link
Copy Markdown
Contributor

I would also like to test this PR on a Replicated VM instance for some additional validation as the OHE surface is impacted

@aivong-openhands

Copy link
Copy Markdown
Contributor

Replicated VM verification — PASS, with one important caveat ⚠️

TL;DR: the healer works — already-broken orgs get their stale org-level key
cleared + a fresh managed key rotated on conversation start, and every
conversation after the trigger succeeds. But in a live UI run the
triggering conversation itself still 401s once
: the healed key does not reach
that conversation's sandbox runtime agent. The DB heal + in-flight model_copy
fix the app-server path, not the LLM the runtime agent actually uses. So the
real-world UX is "first conversation after the fix fails once, then self-heals."

Tested on a Replicated embedded-cluster VM. Control = the instance's baseline
enterprise-server:1.61.0 (healer absent); treatment = sha-14d52c5 (this PR's
head). The already-broken precondition was injected in-pod (stale
org._llm_api_key=dummymodel, managed active default, member has_custom=False),
and the heal was driven through the exact store-method sequence
_maybe_refresh_managed_llm_key runs on conversation start
(clear_stale_org_level_llm_key_if_managed() → rotate_managed_llm_key()),
against the real LiteLLM with real /chat/completions.

Control (no #437) — stays broken: healer method absent; effective key = stale
dummymodel, org._llm_api_key still set; /v1/models and a completion both
401 (Received=dumm****odel, expected to start with 'sk-').

Treatment (#437) — heals on conversation start:

  • clear_stale_org_level_llm_key_if_managed() → True, rotate_managed_llm_key()
    → rotated; org._llm_api_key cleared (None), member gets a fresh managed
    sk-… key, effective key flips off the dummy.
  • Real completion with the healed key → HTTP 200.
  • Idempotent: a second start is a no-op — clear… returns False, no
    re-rotation, key unchanged, org._llm_api_key stays None.

Safety (must NOT heal):

  • Legit BYOR-active org (org._llm_api_key = real key, BYOR active default):
    clear… returned False, org._llm_api_key left intact.
  • Member with has_custom=True: managed-key rotation did not touch the
    member's own key.

Live UI E2E (the caveat, with logs): re-injected the broken state and drove
real conversations. App-server + LiteLLM logs (UTC):

19:15:48.46  clear_stale_org_level_llm_key                       (heal fired)
19:15:48.60  managed_llm_key_refresh:healed_after_clear rotated
19:15:50.86  app_conversation_start:building_start_request  conv=4d4e6921…
19:15:51/52  litellm 401 Received=dumm****odel  <-- triggering convo runtime agent
             STILL used the stale key, AFTER the DB was healed
  • DB confirmed healed immediately after (org._llm_api_key=None, member sk-e…,
    direct completion 200), yet conversation 4d4e6921 (which triggered the heal)
    still 401'd because its sandbox runtime agent used the stale key.
  • The next conversation 41659260 → LiteLLM POST /chat/completions 200 OK,
    no stale 401 — subsequent conversations work.
  • Minor: at 19:15:43 LiteLLM logged KeyNotFoundError key=92ca… not found in db
    for a rotated managed key; transient here, but may be worth a look.

Suggestion: to truly heal in-flight, the refreshed key needs to reach the
conversation's runtime agent LLM (the sandbox), not just the app-server fallback
path — otherwise the first post-fix conversation for each broken user 401s once.

Notes:

  • The deterministic portion was exercised via the exact store calls the
    conversation-start hook makes (wiring into _maybe_refresh_managed_llm_key
    confirmed in source); the live UI run above exercises the full path.
  • Completions used the served (un-prefixed) model name; the resolved openhands/…
    prefixed string 400s via direct curl (a harness/prefix quirk after key auth
    passes — unrelated to this PR).
  • fix: heal stale org-level BYOR LLM key on conversation start (#421) #437 adds no migrations; forward-upgrading 1.61.0 (DB 161) → sha-14d52c5
    (DB 163, from the main merge) was schema-safe. Instance restored to baseline
    afterward.

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

# stale field flips the effective key off the dummy, then we
# force-rotate a fresh managed key so the returned LLM carries it
# (otherwise the existing verify path would skip on key mismatch).
if await settings_store.clear_stale_org_level_llm_key_if_managed():

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I'm pretty sure this will break org managed keys for enterprise...unless we wrap this all in a "if saas". I'm going to talk to an agent to see if this is true.

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.

hey @saurya it only triggers if SaaS because it's under

        if self.app_mode != 'saas':
            _logger.debug(
                'managed_llm_key_refresh:skip_non_saas',
                extra={'app_mode': self.app_mode, 'user_id': user.id},
            )
            return llm

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Yes unfortunately this is a bit of a misnomer, I think OHE uses saas mode. I think we might want to use DEPLOYMENT_MODE == 'cloud' instead.

Another fix would be to use OrgStore._uses_managed_default_llm(org) to see if the org the user is in uses a managed default - in which case we SHOULDN'T delete. I'm fine with either.

openhands-agent and others added 2 commits September 21, 2026 18:58
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>
@juanmichelini
juanmichelini enabled auto-merge (squash) September 22, 2026 04:44
@juanmichelini
juanmichelini merged commit 2cab630 into main Sep 22, 2026
14 checks passed
@juanmichelini
juanmichelini deleted the heal-stale-org-level-llm-key-421 branch September 22, 2026 04:51
@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