From 747a1d5f954dbea15b56b9f492625d041eedd783 Mon Sep 17 00:00:00 2001 From: "victormanuel.caverogracia" <> Date: Sat, 18 Jul 2026 23:42:20 +0200 Subject: [PATCH] fix(billing): don't let a non-current subscription clobber the live row subscriptions keeps one row per user, keyed on user_id in _upsert. An event for a *different* sub of the same user (e.g. canceling a dangling past_due annual while a monthly trial is live) would overwrite the good row. Add a cross-subscription guard: another sub only takes over the row when the stored one is no longer live. --- cloud/billing.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/cloud/billing.py b/cloud/billing.py index 5e30c2a..130a09d 100644 --- a/cloud/billing.py +++ b/cloud/billing.py @@ -328,6 +328,18 @@ async def _upsert_subscription(sub_obj: dict, event_created: datetime): # Order guard: ignore events older than what we've already applied. if row and row.last_event_at and event_created < row.last_event_at: return + # Cross-subscription guard: the table keeps one row per user, so an + # event for a *different* subscription of the same user must not clobber + # the row that represents their live plan. This is exactly what happens + # when a user has a dangling sub (e.g. a past_due annual that gets + # canceled) alongside a live one (a trialing monthly): the canceled + # sub's update would otherwise overwrite the good row. Only let another + # subscription take over when the stored one is no longer live. + if row and row.stripe_subscription_id != sub_obj["id"]: + stored_live = row.status in ("active", "trialing", "past_due", "unpaid") + incoming_live = sub_obj.get("status") in ("active", "trialing", "past_due") + if stored_live and not incoming_live: + return start, end = _sub_period(sub_obj) now_canceling = bool(sub_obj.get("cancel_at_period_end")) # Detect the moment the user hits "cancel" (False -> True).