Repository navigation
fix: heal stale org-level BYOR LLM key on conversation start (#421) - #437
Conversation
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>
Coverage reportClick to see where and how coverage changed
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>
35ef26a to
1ded7b8
Compare
Impact assessment: self-hosted / customer installs vs SaaSVerdict: behavior change that reaches customer self-hosted installs too — the What changed
Guards upstream of the new code (unchanged): Environment × interacting state (before → after)This is a host-independent change: the code branches on org/member DB state, not on
Validation level per source: the classifier rows are standalone-validated — I executed the real Behaviors that change, and for whom
Risks to customer installs
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 notePR is open (not merged), base
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. |
Mutation review of the tests in this PRI 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:
Mutants caught ❌ (your tests work)
Two things make this suite land. The store tests drive the real commit and re-read Survivor ✅ (a real gap)
Why it matters in production. That 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 NoneVerified: this passes on the PR branch unmodified, and fails ( Not a test gap
This comment was generated by an AI assistant on behalf of the user. |
Co-authored-by: openhands <openhands@all-hands.dev>
|
Mutation survivor addressed — added the idempotency test from your review.
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. |
|
I would also like to test this PR on a Replicated VM instance for some additional validation as the OHE surface is impacted |
Replicated VM verification — PASS, with one important caveat
|
| # 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(): |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
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>
|
🚀 Released in 1.63.0. |
Human
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.activepoints at the managedDefault, so the resolved model/base_url are correct, but……the effective api_key is stilldummymodel``, because_get_effective_llm_api_keychecks `org.llm_api_key` before the member slot:So any member with
has_custom=Falsekeeps sending the stale key → 401.The existing conversation-start heal (
_maybe_refresh_managed_llm_key) can't fix these users: bothget_current_managed_llm_keyandrotate_managed_llm_keyearly-out on a non-nullorg._llm_api_key(correctly, since it usually means a legit BYOR org):Fix
Restore the invariant #425 now enforces going forward:
Add
SaasSettingsStore.clear_stale_org_level_llm_key_if_managed(), called from_maybe_refresh_managed_llm_keybefore the verify path. On detecting the violation (active default managed +org._llm_api_keynon-null) it:org._llm_api_key;rotate_managed_llm_key(which now succeeds instead of returningBYOK);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
managed_llm_key_config_from_model; a real BYOR-active org returnsNone→ the field is left intact.rotate_managed_llm_keyalready returnsBYOKforhas_custom=Truemembers.org._llm_api_key is None→ the existing verify-and-skip takes over. No repeated rotation.Why separate from #425, not stacked
managed_llm_key_config_from_model+rotate_managed_llm_key, both already onmain. fix: replace stale custom LLM key when switching back to the managed default profile #425 changes_ensure_managed_llm_key_for_user/activate_profile, a path B never touches.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).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.pymanaged-key suite all green.ruff check+ruff formatclean.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 cleanmain(env-drivenllm-proxy.eval.all-hands.devdefault 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
ManagedLlmKeyOwnershipProcessor(fix: bulk-repair cross-user managed LLM key ownership #353) leaves cached views stale — that's option C, a distinct change to the processor + a cache-invalidation mechanism. B heals users who load the app; C would heal users who don't reload soon.This PR was created by an AI agent (OpenHands) on behalf of the repo maintainer.
Enterprise server image for this PR: