Skip to content

fix(backend): answer a spent BYOK provider account as a typed 429 - #21779

Merged
Git-on-my-level merged 1 commit into
mainfrom
fix/errfix-1015-gcp-process-conversation-py-632-fastapi
Oct 17, 2026
Merged

Git-on-my-level merged 1 commit into
mainfrom
fix/errfix-1015-gcp-process-conversation-py-632-fastapi

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 15, 2026 •

Copy link
Copy Markdown
Member

fix(backend): answer a spent BYOK provider account as a typed 429, not the generic 500

Error group

{"source": "gcp", "service": "backend", "group": "process_conversation.py:632 | fastapi.exceptions.HTTPException: 500: Error processing conversation, please try again later", "count": 8, "id": "gcp:backend-process-conversation-py-632-fastapi-exceptions-httpexception-500-error-processing-conversation-please-", "fingerprint": "fp:9dd85ca8e8f50576", "queued_pr": 21415, "queue_reason": "reopened"}

Root cause

_get_structured's composition boundary maps every unmapped failure to the generic 500. The recurrence is driven by the direct Anthropic BYOK notes lane (the lane #21415 repaired): when a user's own Anthropic account runs out of prepaid credit, every notes call fails before generation and retries can never succeed. Prod evidence (project based-hardware, 2026-10-15):

  • ERROR:utils.llm.gateway_error_contract:Conversation processing failed: BadRequestError recurring for the same uids/conversations while clients re-poll (get_conversation_by_id every minute for an hour).
  • Notes receipts at each failure: errors=1 latency_seconds≈0.5 words=13086 and errors=1 latency_seconds=0.470 words=16573 — instant provider rejection, no generation; successes run 5–13s at ≤3.3k words.
  • Full chained traceback for the exact group frame (/app/utils/conversations/process_conversation.py:632):
    File "/app/utils/conversations/process_conversation.py", line 611, in _get_structured
      structured = llm_input_dedupe.notes(
    File "/app/utils/llm/conversation_processing.py", line 466, in model_turn
      response = await call_model.ainvoke(messages)
    anthropic.BadRequestError: Error code: 400 - {'type': 'error', 'error': {'type': 'invalid_request_error',
      'message': 'Your credit balance is too low to access the Anthropic API. Please go to Plans &
      Billing to upgrade or purchase credits.'}, 'request_id': 'req_011Cg4rH8bexiFHHMid3brWg'}
    

This account state is the same class the platform already treats as "throttled BYOK, not a server bug": the gateway classifies it as byok_quota and answers 429 (_THROTTLED_FAILURE_CLASSES, because "answering 401 tells callers the key is invalid and makes a transient failure look permanent"), and the composition boundary already carries that typed contract for byok_rate_limit (#11112). Quota had no detection, so it fell into the generic 500 bucket — the user gets an unhelpful "try again later" for a state only they can fix, and this error group keeps reopening.

Fix

backend/utils/llm/gateway_error_contract.py:

  • Add BYOK_QUOTA_FAILURE_CLASS/BYOK_QUOTA_ERROR_DETAIL mirroring the rate-limit contract, and is_byok_quota_error(), which recognizes both forms of the failure: the gateway's credential_failure + byok_quota envelope (raised and SDK-unwrapped, HTTP 429) and direct Anthropic BYOK's BadRequestError 400 whose provider message carries Anthropic's stable "credit balance is too low" wording. Marker text is used only for classification — never logged or echoed.
  • conversation_processing_http_exception() now maps that class to 429 with {'code': 'byok_quota', 'message': ...}, logging a bounded warning like the rate-limit case. All other exceptions keep the existing generic 500 and privacy-safe log.

No fallback to the managed lane is introduced: the gateway's fallback policy deliberately never falls back on byok_quota-class account state.

Verification

  • py_compile on both touched files: OK.
  • New suite backend/tests/unit/test_conversation_structure_byok_quota.py (built from the live prod signature, real anthropic.BadRequestError instances):
    14 passed in 9.06s   (test_conversation_structure_byok_quota.py + test_conversation_structure_provider_timeout.py)
    
  • Contract consumers unchanged:
    82 passed (test_llm_gateway_openai_compatible.py + test_process_conversation_usage_context.py)
    
  • black --line-length 120 --skip-string-normalization --check: both files unchanged.

Failure-Class: none

View guided diff Turn on auto-fix

Direct Anthropic BYOK notes raise a plain 400 when the user's prepaid
balance runs out; the composition boundary mapped it to the generic
500, so retries could never succeed and the error group kept reopening.
Recognize the gateway byok_quota credential class and Anthropic's
stable credit-balance wording, and answer 429 with the typed
byok_quota detail like the existing rate-limit contract (#11112).
Provider error bodies stay out of logs and responses.

Failure-Class: none
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-15T23:32:29.321952Z ce88c67 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Git-on-my-level
Git-on-my-level merged commit 2391c05 into main Oct 17, 2026
62 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/errfix-1015-gcp-process-conversation-py-632-fastapi branch October 17, 2026 02:35
Git-on-my-level added a commit that referenced this pull request Oct 21, 2026
…typed 429, not the generic 500 (#22630)

# fix(backend): answer a credit-exhausted BYOK OpenRouter account as a
typed 429, not the generic 500

## Error group

```
{"source": "gcp", "service": "backend", "group": "process_conversation.py:633 | fastapi.exceptions.HTTPException: 500: Error processing conversation, please try again later", "count": 12, "id": "gcp:backend-process-conversation-py-633-fastapi-exceptions-httpexception-500-error-processing-conversation-please-", "fingerprint": "fp:9dd85ca8e8f50576"}
```

Same fingerprint family as the py-632 predecessor fixed by #21779
(direct Anthropic credit exhaustion). That fix deployed; the group
reopened on the new image (first line-633 event 2026-10-19T14:52Z, 68
events by 19:07Z).

## Root cause

`_get_structured`'s composition boundary maps every unmapped failure to
the generic 500. The recurrence is driven by the direct OpenRouter BYOK
notes lane: BYOK users whose key is OpenRouter's are routed to
`https://openrouter.ai/api/v1` (`_get_or_create_openrouter_llm`), and
when that account's credits cannot cover the request, OpenRouter answers
HTTP 402 and the openai SDK raises `APIStatusError` before generation.
Retries can never succeed, so clients re-poll into the same 500. Prod
evidence (project `based-hardware`, 2026-10-19):

- 19 of the 68 line-633 events since the current image deployed carry
this signature (69 occurrences since 2026-10-16); the remainder are
provider transport failures
(TimeoutError/APIConnectionError/InternalServerError, the family #22226
addresses) plus one interpreter-shutdown deploy artifact.
- Full chained traceback for the exact group frame
(`/app/utils/conversations/process_conversation.py:633`):
  ```
File "/app/utils/conversations/process_conversation.py", line 610, in
_get_structured
    structured = llm_input_dedupe.notes(
File "/app/utils/llm/conversation_processing.py", line 466, in
model_turn
    response = await call_model.ainvoke(messages)
  File "/opt/venv/.../openai/_base_client.py", line 1716, in request
    raise self._make_status_error_from_response(err.response) from None
openai.APIStatusError: Error code: 402 - {'error': {'message': 'This
request requires more
credits, or fewer max_tokens. You requested up to 65535 tokens, but can
only afford 65032.
To increase, visit https://openrouter.ai/settings/credits and upgrade to
a paid account',
'code': 402, 'metadata': {'limit_source': 'openrouter_credits', ...}}}
  ```

This is the same account state the platform already answers as
"throttled BYOK, not a server bug": the gateway classifies it
`byok_quota` and answers 429, and the composition boundary already types
the gateway envelope (#21779) and direct Anthropic's 400 "credit balance
is too low" (#21779). The direct OpenRouter 402 spelling had no
detection, so it fell into the generic 500 bucket — the user gets an
unhelpful "try again later" for a state only they can fix, and this
error group keeps reopening.

## Fix

`backend/utils/llm/gateway_error_contract.py`:

- Add `_OPENROUTER_CREDIT_EXHAUSTED_MARKERS` (`requires more credits`,
`openrouter_credits`): OpenRouter's stable spellings of the
credit-exhaustion account state, in the message and as the
`limit_source` metadata value. Marker text is used only for
classification — never logged or echoed.
- `is_byok_quota_error()` now also classifies HTTP 402 carrying either
marker as BYOK quota, mirroring the existing direct-Anthropic 400
branch. All other 402s and every other exception keep the privacy-safe
generic 500.
- `conversation_processing_http_exception()` is unchanged: the newly
classified errors now map to the existing typed 429 `{'code':
'byok_quota', ...}` detail, matching the contract the gateway lane
already enforces.

No fallback to the managed lane is introduced; the response only stops
misreporting a fixable account state as a server error.

## Verification

- `py_compile` on both touched files: OK.
- Extended the suite built from the live prod signature with real
`openai.APIStatusError` instances
(`backend/tests/unit/test_conversation_structure_byok_quota.py`):
  ```
  9 passed  (test_conversation_structure_byok_quota.py)
17 passed (test_conversation_structure_byok_quota.py +
test_conversation_structure_provider_timeout.py)
57 passed (test_process_conversation_usage_context.py — contract
consumers unchanged)
  ```
- `black --line-length 120 --skip-string-normalization --check`: both
files clean.

Failure-Class: none


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/22630?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<a
href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/22630?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F22630&source=description"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img
alt="Turn on auto-fix"
src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
1132dadf pushed a commit to 1132dadf/omi that referenced this pull request Oct 21, 2026
…typed 429

The direct OpenRouter BYOK notes lane answers a spent account with HTTP 402
('requires more credits' / limit_source openrouter_credits) before generation;
the composition boundary had no classifier for that spelling, so retries never
succeeded while clients re-polled the generic 500 at process_conversation.py:633
(same group family as the Anthropic credit fix in BasedHardware#21779). Classify 402 with
either OpenRouter credit marker as byok_quota so the boundary answers the
existing typed 429; every other 402 keeps the privacy-safe generic response.
Git-on-my-level added a commit that referenced this pull request Oct 24, 2026
…nd 500s (#23479)

Investigators kept mistaking BYOK users' own spent provider accounts for
Omi server faults (2026-10-24 03:51-04:21Z: ~160 severity=ERROR tracebacks
from _get_structured, 11 residual HTTPException 500s). The classifier
covered the gateway byok_quota envelope, Anthropic's credit-balance 400
(#21779) and OpenRouter's 402, but not Anthropic's usage-limit 400
spelling, OpenAI's 429 insufficient_quota, OpenRouter's 429 limit_source
rate limits, or rejected keys - those still answered the generic 500.

Extend the single classifier (utils/llm/gateway_error_contract.py), never
a parallel one: direct provider errors now classify only while the
request runs on the user's validated key for that provider, so the same
provider error on Omi's server-paid key stays a loud server fault.
Rejected keys answer the typed 429 byok_invalid_key (401 would look like
an Omi session expiry to clients; the throttled family matches the
gateway contract). The boundary logs exactly one structured WARNING
(byok=true failure_class=... provider=... route=...), the executor
background-failure funnel stops printing ERROR tracebacks for them, the
LangChain byok error callback and the terminal dead-letter lines keep
WARNING for byok causes, and finalization failures record a separate
byok_provider metric reason so dashboards can exclude them.

Investigator runbook: backend/docs/runbooks/byok-provider-failures.md
(exclusion filter severity>=ERROR NOT textPayload:"byok=true").

Failure-Class: new

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant