Repository navigation
fix(backend): keep spent-BYOK provider failures out of ERROR counts and 500s - #23479
Conversation
…nd 500s 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]>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9f8beaa508
ℹ️ 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".
| if ( | ||
| _string_value(gateway_error.get('code')) == GATEWAY_CREDENTIAL_FAILURE_CODE | ||
| and _string_value(gateway_error.get('failure_class')) == 'byok_auth' | ||
| ): | ||
| return ByokProviderFailure(BYOK_INVALID_KEY_FAILURE_CLASS, 'gateway') |
There was a problem hiding this comment.
Parse gateway BYOK authentication envelopes on HTTP 401
When a rejected BYOK key reaches the gateway, _status_code_for_error in backend/llm_gateway/routers/openai_compatible.py returns HTTP 401, but this envelope-parsing block only runs for 429. Production OpenAI SDK exceptions do not expose the envelope's failure_class as a top-level attribute, so the earlier branch cannot recognize them either. In particular, an Anthropic-only BYOK context cannot match the subsequent direct OpenAI/OpenRouter checks, causing the gateway's explicit credential_failure/byok_auth response to become a generic 500 with ERROR logging. Accept the authentication status when parsing this envelope and cover an SDK-wrapped 401 without a synthetic top-level failure_class.
AGENTS.md reference: backend/AGENTS.md:L202-L202
Useful? React with 👍 / 👎.
Product invariants affected
process_conversation.pychange is aroute=label on the existing error-mapping call at the explicit-app boundary; no intake, promotion, or consolidation path is touched.Summary
BYOK users' own spent provider accounts kept looking like Omi server faults. In a 30-minute prod window (2026-10-24 03:51–04:21Z) the backend logged ~160
severity=ERRORtracebacks fromutils/conversations/process_conversation.py::_get_structuredand answered ~11 conversations withHTTPException 500: Error processing conversation— all rooted in the user's own key: Anthropic 400 "Your credit balance is too low" / "You have reached your specified API usage limits", OpenRouter 402 credits, gatewaybyok_quota. The prior fixes (#21779 and the OpenRouter 402 follow-up) covered three spellings; the rest still fell through to the generic 500, and every layer above logged them as server errors.This extends the existing single classifier (
backend/utils/llm/gateway_error_contract.py) — no parallel classifier:classify_byok_provider_failurenow also covers Anthropic's usage-limit 400 spelling, OpenAI's 429insufficient_quota, OpenRouter's 429limit_sourcerate limits, and rejected keys (byok_invalid_key, including the gateway'sbyok_auth). Direct provider errors classify only while the request runs on the user's validated key for that provider (contextvar gate), so the same provider error on Omi's server-paid key stays a loud ERROR/500.conversation_processing_http_exceptionboundary (both call sites, now labeledroute=conversation_processing/route=conversation_processing/app_result). Rejected keys also answer 429 withcode=byok_invalid_key(401 would read as an Omi session expiry to clients; the gateway's own byok_auth distinction is preserved in the typed detail).byok=true failure_class=byok_quota|byok_invalid_key|byok_rate_limit provider=... route=...— no traceback, no provider body, no key material, no new uid exposure. The executor background-failure funnel (utils/executors.py) stops printing ERROR tracebacks for these, the LangChain BYOK error callback logs WARNING instead of ERROR for actionable BYOK failures, and the pusher/Cloud-Tasks terminal dead-letter lines keep WARNING when the cause is BYOK.severity>=ERRORtherefore stops counting them.omi_capture_finalization_failures_totalgains a boundedreason="byok_provider"(zero-exported at startup) so dashboards/alerts can exclude them from server-fault counts.backend/docs/runbooks/byok-provider-failures.md(+ pointer inbackend/AGENTS.md): log shape, why these are not server faults, and the Cloud Logging exclusion filterseverity>=ERROR AND NOT textPayload:"byok=true"(backend serves text mode today; the JSON-mode variant is noted).backend/AGENTS.mdwas 11 bytes under its lean budget, so the stale "DG keepalive" gotcha (Deepgram, retired 2026-08-27) was dropped to make room for the pointer.Evidence
Unit tests (
BACKEND_UNIT_TEST_FILE_LIST=<list> bash test.sh, per file):tests/unit/test_conversation_structure_byok_quota.py— 19 passed. Extended with: Anthropic 400 usage-limit (the residual 500 path) → 429; OpenAI 429insufficient_quota→ 429; OpenRouter 429limit_source=requester_rates→ 429 rate-limit; gatewaybyok_authand direct Anthropic 401 → 429byok_invalid_key; server-paid negative (same credit/402 errors with no BYOK key in context → 500 + generic detail + ERROR log); log-severity assertions (exactly one WARNING containingbyok=true failure_class=byok_quota provider=anthropic route=conversation_processing, no ERROR records,exc_info is None, no provider body or key material in the line); executor funnel downgrade (WARNING/no traceback for byok detail, ERROR+traceback for real failures);byok_failure_class_ofcause-chain readback; finalization metric reason separation.tests/unit/test_byok_llm_logging.py(10),test_pusher_finalization_failure_severity.py(6),test_client_processing_finalize.py(56),test_action_item_date_validation.py(16),test_byok_llm_notifications.py(8),test_llm_error_handler_offload.py(3),test_finalization_failure_observability.py(4),test_structured_extraction_partial_content.py(14),test_reason_label_enums.py(19),test_process_conversation_free_tier_branch.py(44),test_llm_gateway_openai_compatible.py(32) — all pass.Static checks:
scan_async_blockers0 findings;check_module_stub_pollution --files <changed> --check-allowlist-monotonic origin/main0 violations;scan_import_time_side_effects0 violations.Testing scope
Backend-only change; no client contract additions beyond the existing typed-error family (
byok_invalid_keydetail follows the same{code, message}shape clients already handle forbyok_quota/byok_rate_limit).Failure-Class: new
🤖 Generated with Claude Code