fix(backend): notify users about BYOK LLM key failures
Summary
- add rate-limited FCM notifications for actionable BYOK LLM failures: invalid key, permission denied, and quota exhaustion
- deduplicate notifications per user/provider/reason with a Redis SET NX lock
- remove permanently invalid FCM tokens returned by Firebase
Closes #7291
Stack note
This PR builds on the BYOK error-source plumbing from #7290. GitHub shows that base commit here because the upstream repo does not have the fork branch as a selectable base; after #7290 lands this can be rebased to show only the notification commit.
Verification
- PATH=/tmp/omi-backend-py311/bin:$PATH ./test-preflight.sh
- PATH=/tmp/omi-backend-py311/bin:$PATH pytest tests/unit/test_byok_llm_logging.py tests/unit/test_byok_llm_notifications.py -q
Greptile Summary
This PR adds end-to-end BYOK LLM failure notifications: a new _byok_uid_ctx ContextVar threads the authenticated user ID through LLM call stacks, a new byok_errors.py module classifies actionable errors (invalid key, permission denied, quota exhaustion) and dispatches FCM push notifications, and a Redis SET NX lock deduplicates notifications to at most one per user/provider/reason per 24 hours.
byok_errors.pyintroducesclassify_byok_llm_error,handle_llm_error/handle_llm_error_async, and_send_byok_llm_error_notification; the Redis lock is acquired before the FCM send, so a Firebase failure consumes the dedup window silently.clients.pyadds_LLMErrorCallback(a LangChainBaseCallbackHandler) and wires it into every LLM/embedding factory via_with_llm_callbacks.byok.py,pusher.py,sync.py, andagentic.pyare updated to propagate and reset the newbyok_uidcontext variable correctly.
Confidence Score: 3/5
Safe to merge after addressing the lock-before-send ordering in _send_byok_llm_error_notification; all other changes are additive and well-tested.
The core notification function acquires the 24-hour Redis dedup lock before attempting the FCM send. If Firebase throws, the lock is held but the user was never notified, defeating the feature's primary goal.
backend/utils/llm/byok_errors.py — specifically the lock-acquire-then-send ordering in _send_byok_llm_error_notification.
Important Files Changed
| Filename | Overview |
|---|---|
| backend/utils/llm/byok_errors.py | New module implementing BYOK LLM error classification, structured logging, and FCM notification delivery. Contains a logic bug where the Redis dedup lock is consumed before a successful FCM send, silencing notifications for 24h on any Firebase failure. Token fetch also occurs before the lock check, wasting Firestore reads on every suppressed duplicate. |
| backend/utils/llm/clients.py | Adds _LLMErrorCallback LangChain callback handler and wires it into all LLM client factories via _with_llm_callbacks. Embeddings proxy now wraps async/sync calls to catch and route errors. Changes are additive and non-breaking. |
| backend/utils/byok.py | Adds _byok_uid_ctx ContextVar and corresponding get/set helpers; properly reset in BYOKMiddleware and validate_byok_websocket. Change is minimal and well-scoped. |
| backend/database/redis_db.py | Adds try_acquire_byok_llm_error_notification_lock using Redis SET NX with a 24h default TTL. Implementation is correct. |
| backend/routers/sync.py | Adds set_byok_uid call at pipeline start and a matching reset in the finally block. |
| backend/routers/pusher.py | Adds set_byok_uid(uid) alongside the existing set_byok_keys call inside an async task. |
| backend/utils/retrieval/agentic.py | Replaces a plain logger.error with handle_llm_error_async in the Anthropic agent stream error handler. |
| backend/tests/unit/test_byok_llm_notifications.py | Unit tests covering successful send, deduplication, platform errors not notified, and bad-token cleanup. |
| backend/tests/unit/test_byok_llm_logging.py | Unit tests for error classification and the logging/callback plumbing. |
Sequence Diagram
sequenceDiagram
participant Router as Router (pusher/sync)
participant BYOK as byok.py
participant Handler as handle_llm_error
participant Redis as Redis
participant Firestore as Firestore
participant FCM as Firebase FCM
Router->>BYOK: set_byok_uid(uid)
Router->>Handler: LLM error triggers callback
Handler->>Firestore: get_all_tokens(uid)
Handler->>Redis: SET NX lock EX 86400
alt Lock acquired
Handler->>FCM: send_each(messages)
alt FCM success
FCM-->>Handler: BatchResponse
else FCM failure
Note over Handler,Redis: Lock held, no notification sent
end
else Lock not acquired
Handler-->>Router: return
end
Reviews (1): Last reviewed commit: "fix(backend): notify users about BYOK LL..." | Re-trigger Greptile
Thanks for this 🙏 — this is stacked on #7321, which itself needs a manual rebase (main rewrote _run_sync_pipeline to a semaphore + run_blocking async structure, conflicting with the BYOK-tagging changes). Please rebase #7321 onto latest main first, then rebase this one on top so it shows only the notification commit. Happy to review/land both once the base is clean. 🙏
@Git-on-my-level thanks — both correctness gaps fixed in 4e522bb0e.
1. Sync embedding failures now surface to the user. _OpenAIEmbeddingsProxy.embed_query/embed_documents are explicit methods, so the new __getattr__ wrapper never fired for them. They now route failures through handle_llm_error(...) (operation embed_query/embed_documents) before falling back to the platform key or re-raising — matching the async wrapper's behavior. Added a regression test asserting the sync path both notifies and still falls back to Omi's key.
2. Dedupe lock only kept after a successful send. Added release_byok_llm_error_notification_lock; the 24h lock is now released when messaging.send_each() raises or when no token send succeeds, so a transient FCM outage no longer silently suppresses the user for 24h. A partial success (≥1 delivered) keeps the lock as before. Added tests for the send-raises, all-sends-fail, and partial-success cases.
Note this is stacked on #7321 and still needs the manual rebase onto main (tracked separately). PTAL!
@Git-on-my-level thanks for the re-review — both items addressed in cc89ce76:
- FCM batching (blocker).
_send_byok_llm_error_notificationnow sends in batches of ≤500 (messaging.send_each's hard cap), matching the existingsend_bulk_notificationpath. Partial success keeps the dedupe lock; only a total delivery failure releases it for retry. Added a >500-token regression test (600 tokens → 500 + 100). - Async embedding fallback.
aembed_query/aembed_documentsnow notify viahandle_llm_errorand then fall back to Omi's key on a BYOK key failure, matching the sync methods. Added a test.
Re cubic's note on _PERMANENT_FAILURE_CODES: these (UNREGISTERED, INVALID_REGISTRATION_TOKEN, NOT_FOUND) are intentionally identical to the codebase's existing PERMANENT_FAILURE_CODES in utils/notifications.py, which is the main production FCM cleanup path — so they're consistent with how omi already prunes invalid tokens rather than a new/mismatched mapping.
Still stacked on #7321 and pending the rebase onto main.