Skip to content

fix(backend): return actionable 429 for BYOK rate limits - #11112

Merged
kodjima33 merged 4 commits into
mainfrom
agent/m1-studio-nik-codex-terra-xhig/374b278a
Aug 5, 2026
Merged

kodjima33 merged 4 commits into
mainfrom
agent/m1-studio-nik-codex-terra-xhig/374b278a

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Aug 4, 2026 •

Copy link
Copy Markdown
Member

Closes SCA-295

Summary

  • Preserve the gateway's typed byok_rate_limit classification in its safe OpenAI-compatible error envelope.
  • Translate only that credential failure at the conversation-processing composition boundary into HTTP 429 with the stable detail.code=byok_rate_limit contract.
  • Keep BYOK no-fallback behavior and idempotent /v1/conversations/from-segments cleanup unchanged; BYOK quota and Omi-paid provider 429s retain the existing generic processing error behavior.

Verification

  • backend/.venv/bin/python -m pytest -q backend/tests/unit/test_llm_gateway_openai_compatible.py backend/tests/unit/test_process_conversation_usage_context.py backend/tests/unit/test_developer_from_segments_idempotency.py — 70 passed.
  • black --check --line-length 120 --skip-string-normalization ... — passed.
  • backend/.venv/bin/python backend/scripts/scan_async_blockers.py --dirs backend/utils/conversations backend/utils/llm backend/llm_gateway — passed, 0 selected findings.
  • The focused TestClient /v1/conversations/from-segments path returned 429 with the bounded BYOK rate-limit contract and released its idempotent processing claim.

Product invariants affected

None.

Failure-Class: FC-recoverable-provider-failure-terminal

Review in cubic

Carry the gateway's bounded BYOK rate-limit classification to the conversation-processing composition boundary, where it becomes a safe actionable 429 without changing fallback policy.

Failure-Class: FC-recoverable-provider-failure-terminal
Co-authored-by: multica-agent <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: dfb895852b

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

All reported issues were addressed across 6 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Accept unwrapped OpenAI gateway errors, sanitize generic processing logs, and preserve import-isolated conversation tests.

Failure-Class: FC-recoverable-provider-failure-terminal
Co-authored-by: multica-agent <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bbe2cea52f

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

extract_action_items() swallows all exceptions and returns []. A BYOK
rate-limit during this step was silently lost, persisting an incomplete
conversation without the actionable 429/retry contract this PR adds.

Let typed BYOK rate-limit errors escape the catch-all so they reach the
composition boundary (_get_structured) which maps them to the 429.

Addresses Codex review thread PRRT_kwDOLkKqys6Wg3b6.

Failure-Class: FC-recoverable-provider-failure-terminal
Two unrelated backend unit test files (test_action_item_date_validation.py
and test_conversation_structure_timezone.py) load the real
conversation_processing.py from file after stubbing heavy dependencies.
Since conversation_processing now imports gateway_error_contract, both
must stub it too or collection fails with ModuleNotFoundError.

Verified: test.sh runner passes for both files (40 tests) plus PR-focused
tests (72 tests).
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Monitor pass — CI fix + review thread resolution

  • Fixed Backend unit suite collection failure: two unrelated test files (test_action_item_date_validation.py, test_conversation_structure_timezone.py) that load conversation_processing.py via file-based isolation harnesses needed a stub for the new gateway_error_contract import. Added the same _stub_module("utils.llm.gateway_error_contract") pattern used by neighboring harnesses.
  • Resolved P1 thread (unwrapped OpenAI error bodies): is_byok_rate_limit_gateway_error already handles both {\"error\": {...}} and unwrapped {code, failure_class} body shapes via body.get('error', body) (gateway_error_contract.py:43). Covered by test_byok_throttling_is_not_reported_as_a_credential_rejection which iterates both shapes.
  • Resolved P2 thread (action-item extraction propagation): extract_action_items re-raises typed BYOK rate-limit errors before the catch-all fallback (conversation_processing.py:1049-1051), so they reach the composition boundary and the user gets the actionable 429/retry contract.

Backend unit suite is now green. No unresolved review threads remain.

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Typed BYOK rate-limit failure now survives to the composition boundary and returns an actionable 429; bounded classifier, no upstream body leakage, unit-tested, CI green.

@kodjima33
kodjima33 merged commit 6cf8d0c into main Aug 5, 2026
37 checks passed
@kodjima33
kodjima33 deleted the agent/m1-studio-nik-codex-terra-xhig/374b278a branch August 5, 2026 14:36
Git-on-my-level added a commit that referenced this pull request Oct 17, 2026
…1779)

# 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


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/21779?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/21779?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F21779&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. -->
tivince82 pushed a commit to tivince82/omi that referenced this pull request Oct 17, 2026
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 (BasedHardware#11112).
Provider error bodies stay out of logs and responses.

Failure-Class: none
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.

2 participants