Repository navigation
fix(backend): Stripe webhook 500s on deleted users - #7284
Conversation
…0s on deleted users (#7282) Root cause: Stripe sends subscription webhooks for users whose Firestore document no longer exists. The update_user_subscription() call uses Firestore .update() which requires the doc to exist — causing google.api_core.exceptions.NotFound → unhandled 500. Fixes: 1. Catch FirestoreNotFound at all three update_user_subscription call sites (subscription update, schedule completion, schedule cancellation) 2. Guard against None from _build_subscription_from_stripe_object in schedule handlers (unknown price ID → None → AttributeError) 3. Wrap notification stripe.Subscription.retrieve in try/except (was outside error handling, could crash on Stripe API errors) Co-Authored-By: Claude Opus 4.6 <[email protected]>
…ng (#7282) 9 tests verify: - FirestoreNotFound import and catches at all 3 update sites - None-guard for _build_subscription_from_stripe_object - Notification retrieve wrapped in try/except - Existing webhook behavior preserved Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Greptile SummaryThis PR fixes recurring Stripe webhook 500s caused by Firestore's
Confidence Score: 4/5Safe to merge; the fix is narrowly scoped to swallowing a well-understood Firestore NotFound on deleted users and does not touch subscription creation logic or auth paths. The backend/routers/payment.py — the customer.subscription.* try block (lines 714-728) could benefit from a general exception fallback to match the pattern used in both schedule handlers. Important Files Changed
Sequence DiagramsequenceDiagram
participant Stripe
participant WebhookHandler as stripe_webhook()
participant BuildSub as _build_subscription_from_stripe_object()
participant UsersDB as users_db.update_user_subscription()
participant Firestore
Stripe->>WebhookHandler: customer.subscription.updated/deleted/created
WebhookHandler->>BuildSub: subscription_obj
alt Unknown price ID
BuildSub-->>WebhookHandler: None (ValueError caught)
WebhookHandler-->>Stripe: 200 (None guard skips block)
else Valid price ID
BuildSub-->>WebhookHandler: Subscription object
WebhookHandler->>UsersDB: update_user_subscription(uid, ...)
UsersDB->>Firestore: .update(doc_ref)
alt User document exists
Firestore-->>UsersDB: OK
WebhookHandler-->>Stripe: 200
else User deleted
Firestore-->>UsersDB: NotFound (404)
UsersDB-->>WebhookHandler: raises FirestoreNotFound
WebhookHandler->>WebhookHandler: except FirestoreNotFound log warning
WebhookHandler-->>Stripe: 200
end
end
Stripe->>WebhookHandler: subscription_schedule.completed / canceled
WebhookHandler->>BuildSub: retrieved subscription dict
alt None returned
BuildSub-->>WebhookHandler: None
WebhookHandler->>WebhookHandler: log warning skip update
WebhookHandler-->>Stripe: 200
else Valid subscription
BuildSub-->>WebhookHandler: Subscription object
WebhookHandler->>UsersDB: update_user_subscription(uid, ...)
alt FirestoreNotFound
UsersDB-->>WebhookHandler: raises FirestoreNotFound
WebhookHandler->>WebhookHandler: log warning
else Other error
UsersDB-->>WebhookHandler: raises Exception
WebhookHandler->>WebhookHandler: log error
end
WebhookHandler-->>Stripe: 200
end
Reviews (1): Last reviewed commit: "chore(backend): add Stripe webhook test ..." | Re-trigger Greptile |
| try: | ||
| if new_subscription.status == SubscriptionStatus.active and is_paid_plan(new_subscription.plan): | ||
| conversations_db.unlock_all_conversations(uid) | ||
| memories_db.unlock_all_memories(uid) | ||
| action_items_db.unlock_all_action_items(uid) | ||
| users_db.update_user_subscription(uid, new_subscription.dict()) | ||
| set_credits_invalidation_signal(uid) | ||
| if new_subscription.status == SubscriptionStatus.active and is_paid_plan(new_subscription.plan): | ||
| clear_fair_use_on_upgrade(uid) | ||
| logger.info(f"Subscription for user {uid} updated from webhook event: {event['type']}.") | ||
| except FirestoreNotFound: | ||
| logger.warning( | ||
| f"Stripe webhook: user {uid} not found in Firestore, " | ||
| f"skipping subscription update for event {event['type']}" | ||
| ) |
There was a problem hiding this comment.
Missing general exception fallback in
customer.subscription.* handler
The schedule handlers (subscription_schedule.completed and subscription_schedule.canceled) both have a two-clause structure: except FirestoreNotFound followed by except Exception as e. The customer.subscription.* handler added here only has the FirestoreNotFound clause. If conversations_db.unlock_all_conversations, memories_db.unlock_all_memories, or action_items_db.unlock_all_action_items raise any other exception (e.g., a transient Firestore error, network timeout), it will propagate unhandled and produce a 500 — the same class of failure this PR is trying to prevent. The schedule handlers are already consistent with each other; this handler is the outlier.
| """Tests for Stripe webhook error handling fixes (#7282). | ||
|
|
||
| Root cause: Stripe webhooks crash with 500 when user doc doesn't exist in Firestore. | ||
| The update_user_subscription() call uses Firestore .update() which requires the doc | ||
| to exist — deleted or never-created users cause google.api_core.exceptions.NotFound. | ||
|
|
||
| Fixes verified via source-level analysis (no heavy imports needed): | ||
| 1. FirestoreNotFound catch at all update_user_subscription call sites | ||
| 2. None-guard for _build_subscription_from_stripe_object in schedule handlers | ||
| 3. try/except for notification stripe.Subscription.retrieve | ||
| """ | ||
|
|
||
| from pathlib import Path | ||
|
|
||
| PAYMENT_SOURCE = Path(__file__).resolve().parents[2] / "routers" / "payment.py" | ||
|
|
||
|
|
||
| def _read_source(): | ||
| return PAYMENT_SOURCE.read_text() | ||
|
|
||
|
|
||
| # ── Fix 1: FirestoreNotFound guard for deleted users ───────────────────────── | ||
|
|
||
|
|
||
| def test_imports_firestore_not_found(): | ||
| """payment.py must import FirestoreNotFound for the deleted-user guard.""" | ||
| source = _read_source() | ||
| assert 'from google.api_core.exceptions import NotFound as FirestoreNotFound' in source | ||
|
|
||
|
|
||
| def test_catches_firestore_not_found_at_all_update_sites(): | ||
| """All three webhook paths that call update_user_subscription must catch FirestoreNotFound. | ||
|
|
||
| Call sites: | ||
| 1. customer.subscription.* handler (the actual crash site from logs) | ||
| 2. subscription_schedule.completed handler | ||
| 3. subscription_schedule.canceled handler | ||
| """ | ||
| source = _read_source() | ||
| catches = source.count('except FirestoreNotFound:') | ||
| assert catches >= 3, ( | ||
| f"Expected at least 3 FirestoreNotFound catches " | ||
| f"(subscription update, schedule completion, schedule cancellation), " | ||
| f"found {catches}" | ||
| ) | ||
|
|
||
|
|
||
| def test_logs_uid_in_firestore_not_found_warning(): | ||
| """FirestoreNotFound catches must include 'not found in Firestore' for debugging.""" | ||
| source = _read_source() | ||
| # All three handlers should log a warning with the user context | ||
| assert source.count('not found in Firestore') >= 3 | ||
|
|
||
|
|
||
| # ── Fix 2: None-guard for _build_subscription_from_stripe_object ───────────── | ||
|
|
||
|
|
||
| def test_build_subscription_catches_unknown_price_id(): | ||
| """_build_subscription_from_stripe_object catches ValueError and returns None.""" | ||
| source = _read_source() | ||
| # Find the function definition | ||
| func_start = source.index('def _build_subscription_from_stripe_object') | ||
| # Find the next function definition to bound our search | ||
| next_func = source.index('\ndef ', func_start + 1) | ||
| func_body = source[func_start:next_func] | ||
|
|
||
| assert 'except ValueError:' in func_body | ||
| assert 'return None' in func_body | ||
|
|
||
|
|
||
| def test_schedule_completion_checks_none_subscription(): | ||
| """Schedule completion handler must check for None before .dict() call.""" | ||
| source = _read_source() | ||
| # The fix adds: if not new_subscription: ... else: update | ||
| assert 'if not new_subscription:' in source | ||
| assert 'unknown price ID' in source | ||
|
|
||
|
|
||
| def test_schedule_cancellation_checks_none_subscription(): | ||
| """Schedule cancellation handler must check for None before .cancel_at_period_end = True.""" | ||
| source = _read_source() | ||
| # Find the cancellation handler section | ||
| cancel_section_start = source.index("schedule_obj.get('status') == 'canceled'") | ||
| cancel_section = source[cancel_section_start : cancel_section_start + 1500] | ||
|
|
||
| # Must have the None guard before setting cancel_at_period_end | ||
| none_check_pos = cancel_section.index('if not new_subscription:') | ||
| cancel_attr_pos = cancel_section.index('cancel_at_period_end = True') | ||
| assert none_check_pos < cancel_attr_pos, "None check must appear before cancel_at_period_end assignment" | ||
|
|
||
|
|
||
| # ── Fix 3: Notification retrieve wrapped in try/except ────────────────────── | ||
|
|
||
|
|
||
| def test_notification_retrieve_wrapped(): | ||
| """The second stripe.Subscription.retrieve for notifications must be in try/except.""" | ||
| source = _read_source() | ||
| assert 'Error retrieving subscription for notification' in source | ||
|
|
||
|
|
||
| # ── Existing behavior preserved ────────────────────────────────────────────── | ||
|
|
||
|
|
||
| def test_customer_subscription_handler_still_guards_none(): | ||
| """customer.subscription.* handler already had 'if new_subscription:' guard — verify it's intact.""" | ||
| source = _read_source() | ||
| # Find the customer.subscription handler section | ||
| handler_start = source.index("'customer.subscription.updated'") | ||
| handler_section = source[handler_start : handler_start + 1500] | ||
|
|
||
| # Must still have the None guard from _build_subscription_from_stripe_object | ||
| assert 'if new_subscription:' in handler_section | ||
|
|
||
|
|
||
| def test_webhook_returns_success(): | ||
| """Webhook must always return {"status": "success"} at the end (Stripe expects 2xx).""" | ||
| source = _read_source() | ||
| # Find the stripe_webhook function | ||
| func_start = source.index("async def stripe_webhook(request: Request, stripe_signature: str = Header(None)):") | ||
| # Get to the return at the end of the function | ||
| func_section = source[func_start:] | ||
| # The function should end with return {"status": "success"} | ||
| assert 'return {"status": "success"}' in func_section |
There was a problem hiding this comment.
Source-text matching tests are brittle
All nine tests parse payment.py as a raw string and assert on the presence of exact substrings (e.g., 'except FirestoreNotFound:', 'not found in Firestore'). They provide zero runtime coverage: renaming the exception alias, rephrasing a log message, or reformatting the file with Black could break every test without changing any observable behavior — and conversely, a real regression that preserved the string literals would go undetected. For the critical users_db.update_user_subscription path, at least one parametrized test that mocks users_db.update_user_subscription to raise FirestoreNotFound and asserts the endpoint returns 200 would give real protection.
…nd log unknown price IDs (#7282) CODEx review identified unguarded _update_subscription_from_session() checkout path and silent None-subscription handling in customer.subscription.* handler. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…7282) Expand test coverage from 9 to 11 tests: checkout session FirestoreNotFound guard and customer.subscription.* None-subscription logging. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…checkout existence check (#7282) 1. Restructure _build_subscription_from_stripe_object to downgrade inactive subs to Basic BEFORE price ID resolution — prevents stale paid access on deletion 2. Add user existence check (get_user_profile) before checkout processing to prevent doc resurrection via get_user_valid_subscription's create-on-miss Co-Authored-By: Claude Opus 4.6 <[email protected]>
…tence check (#7282) Expand test coverage from 11 to 13 tests covering reviewer-requested fixes: inactive subscription downgrade ordering and checkout path user existence guard. Co-Authored-By: Claude Opus 4.6 <[email protected]>
…pe_object (#7282) 11 executable behavioral tests verifying function logic with controlled inputs: active/trialing/canceled/unpaid status handling, unknown price ID behavior, empty items, cancel_at_period_end propagation. Addresses tester coverage gaps. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Co-Authored-By: Claude Opus 4.6 <[email protected]>
🔄 Omi PR Workflow — Checkpoint StatusIssue: #7282 — Stripe webhook 500s on deleted/missing Firestore users Checkpoint Progress
CP9 Blocker Detail
Options to unblock:
Changes Summary
by AI for @beastoin |
✅ CP9A + CP9B — Live Testing CompleteEnvironment
CP9A: L1 Standalone Backend TestingHappy paths (all PASS):
Non-happy paths (all PASS):
CP9B: L2 Integration Testing (Backend Running)
Unit Test Suite (24/24 PASS)by AI for @beastoin |
|
lgtm |
Post-Deployment Monitoring — Initial CheckDeploy: Workflow run 25850911412 completed successfully Results (15 min post-deploy)
Notes
by AI for @beastoin |
Deploy Monitor Checkpoint (T+0) — 08:49 UTC
Next checkpoint: T+20m (~09:09 UTC) by AI for @beastoin |
Deploy Monitor Checkpoint (T+20m) — 09:09 UTC
Next checkpoint: T+30m (~09:19 UTC) by AI for @beastoin |
Deploy Monitor Checkpoint (T+30m) — 09:19 UTC
Next checkpoint: T+1h (~09:49 UTC) by AI for @beastoin |
Deploy Monitor Checkpoint (T+1h) — 09:49 UTC
Next checkpoint: T+2h (~10:49 UTC) by AI for @beastoin |
Deploy Monitor Checkpoint (T+2h) — 10:49 UTC
Full trend:
Next checkpoint: T+4h (~12:49 UTC) by AI for @beastoin |
Deploy Monitor — FINAL Checkpoint (T+4h) — 11:52 UTCFix Confirmed Working in ProductionThree
Before this fix: these would crash with Full Monitoring Summary
Final Stats (3h post-deploy)
Verdict: PASS — Monitoring CompleteIssue #7282 is resolved. The Stripe webhook 500s on deleted users are eliminated. by AI for @beastoin |
Summary
Fix Stripe webhook 500 errors caused by
Firestore .update()on deleted user documents (#7282).Root cause:
users_db.update_user_subscription()usesFirestore .update()which requires the document to exist. When a user is deleted but Stripe still sends webhook events (subscription updates, schedule completions/cancellations), the handler crashes withgoogle.api_core.exceptions.NotFound→ HTTP 500.Evidence: 4 occurrences in Cloud Run logs (confirmed by mon), all same deleted UID, crash at
payment.py:714.Changes
Fix 1: FirestoreNotFound guard at all 4 update sites
_update_subscription_from_session()— checkout.session.completed path (CODEx-identified gap)customer.subscription.*handler — the actual crash site from logssubscription_schedule.completedhandlersubscription_schedule.canceledhandlerFix 2: None-guard for
_build_subscription_from_stripe_object.dict()call.cancel_at_period_end = TrueFix 3: Notification retrieve wrapped
stripe.Subscription.retrievefor notifications wrapped in try/exceptFix 4: Inactive subscription downgrade (reviewer feedback)
_build_subscription_from_stripe_objectto check inactive status BEFORE price ID resolutionFix 5: Checkout user existence check (reviewer feedback)
get_user_profile(uid)check beforeget_user_valid_subscription()in checkout pathget_user_valid_subscription()'s create-on-miss behaviorDesign Decision
.update()+FirestoreNotFoundcatch is correct (not.set(merge=True)) —.set(merge=True)would create zombie/partial user documents from stale Stripe events. Confirmed by CODEx consultation.Testing
24 unit tests (13 source-level + 11 behavioral), all passing on Python 3.11.
Source-level tests (
test_stripe_webhook_none_guard.py— 13 tests):Behavioral tests (
test_stripe_webhook_behavioral.py— 11 tests):_build_subscription_from_stripe_objectextracted via exec + namespace injectionLive testing (CP9A — L1 standalone backend)
Backend started via
uvicorn main:app --port 18080with Python 3.11.15.Happy paths (all PASS):
_build_subscription_from_stripe_object(canceled)_build_subscription_from_stripe_object(unpaid)_build_subscription_from_stripe_object(empty items)payment.pyimport_update_subscription_from_sessionNon-happy paths (all PASS):
Live testing (CP9B — L2 integration, backend running)
Omi PR Workflow Checkpoints
Risks / Edge Cases
Exception(pre-existing) — could be tightened in follow-upReview Cycle
Closes #7282
by AI for @beastoin