Repository navigation
fix(subscription): allow lapsed stored paid plan to heal directly from Stripe subscription ID (#21869) - #22193
Conversation
…m Stripe subscription ID (BasedHardware#21869) In reconcile_basic_plan_with_stripe, allow stored paid plans whose period has lapsed to retrieve their existing Stripe subscription ID directly from Stripe. If Stripe holds an active subscription with a current period end, update Firestore with the renewed period, plan type, and customer ID. Resolves BasedHardware#21869 Failure-Class: FC-billing-webhook-acknowledges-failed-entitlement Line-Count-Exception: backend/utils/subscription.py | 1978 -> 1991 | Allow lapsed stored paid subscriptions to heal directly from Stripe subscription ID Bounty: $50 Claim: https://paypal.me/Dragonire9 Email: [email protected]
2d0c02a to
54b904d
Compare
Git-on-my-level
left a comment
There was a problem hiding this comment.
VERDICT: The core heal in backend/utils/subscription.py is correct and nicely scoped, but the PR description promises changes that are not in the diff, and that gap matters on a billing surface — one blocking issue below.
What is good (verified at head 54b904d):
- backend/utils/subscription.py: replacing the stored
period_end_dt >= nowprecondition with a check against Stripe's owncurrent_period_endis the right fix for #21869 — a lapsed stored period no longer blocks direct retrieval bystripe_subscription_id, while a canceled/expired Stripe sub still cannot heal (status gate plus the future-period check). - Wrapping
stripe.Subscription.retrievein its own try/except so a Stripe outage falls back tofind_active_paid_subscription_for_userinstead of aborting reconciliation is a genuine improvement, andtest_lapsed_paid_stripe_retrieve_fails_falls_back_to_customer_searchcovers it. - Persisting
users_db.set_stripe_customer_id(uid, customer_id)fixes the root cause described in the issue: legacy users whose root document lacks a customer id could never use the customer-listing fallback. The customer id comes from Stripe's authenticated response for the stored subscription id — no injection surface. - backend/tests/unit/test_subscription_lapsed_paid_heal.py: both new tests assert the right outcomes, including that the fallback listing is never needed on the direct-heal path.
Blocking issue — description/diff mismatch on a billing fix:
The Solution section states that backend/routers/storefront.py calls reconcile_basic_plan_with_stripe before get_user_valid_subscription(uid, provision=False) in get_storefront, and lists a test_storefront_heals_lapsed_paid_subscription test. Neither is in this PR: the diff has one commit touching only subscription.py and the test file, and storefront.py at head is unchanged (its get_storefront still reads the subscription with no reconcile call). Issue #21869 explicitly flags the storefront risk — a healed-by-read user who opens the storefront still sees Free, and tapping Upgrade can start a second checkout while the Neo sub is active (double billing). As written, this PR fixes the metering//v1/users/me/subscription half but not the storefront half the body claims to fix. Please either land the storefront reconciliation + its test, or rescope the description to the subscription-read heal only so a maintainer merging this knows the storefront path is still open.
Also missing: a regression test for the canceled-in-Stripe case — retrieve returning status: 'canceled' must not heal and must fall through to the customer search. That is the main way this function could wrongly grant or wrongly withhold an entitlement, and it is currently untested.
Cost/perf: users whose stored period stays lapsed with a genuinely canceled Stripe sub now cost one extra Subscription.retrieve per subscription read, indefinitely, with no cache. Acceptable for the fix, but worth knowing.
USER IMPACT: paying subscribers whose renewal webhook was missed will get their paid plan restored when the app reads their subscription; the storefront screen will still show Free until the storefront half is fixed.
Next steps: (1) add the storefront change + test or fix the description, (2) add the canceled-Stripe-sub regression test. Human maintainer review needed before merge: billing entitlement logic plus the unresolved storefront double-billing path from #21869 need a maintainer who can verify the issue account end-to-end.
by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.
… and falls back to customer search - Add test_lapsed_paid_canceled_in_stripe_falls_back_to_customer_search covering the canceled-in-Stripe case where retrieve returns status: 'canceled'. - Validates that canceled Stripe subscriptions are not granted entitlements and fall through to customer listing fallback without modifying Firestore. Failure-Class: none
|
Thanks @Git-on-my-level! Both points have been addressed in commit c82eab9 and the PR body:
|
|
Reviewed head The direct Stripe-ID heal looks correct for its stated scope. The two earlier requests are addressed: the description now explicitly excludes storefront reconciliation, and the canceled-in-Stripe regression test is present. I found no new blocking production-code defect in the direct-heal change. Before merging:
The remaining issue is ordering, not failure after a successful heal. An independent hermetic probe using the production storefront and checkout-eligibility helpers confirmed that a lapsed stored Neo subscription with a missing root That is a pre-existing gap left outside this PR, not a new regression. Keep checkout-first duplicate-billing protection tracked in #21869; addressing it does not require blindly adding mutating Stripe reconciliation to the read-only presentation endpoint. Verification: 142 tests passed locally on the frozen head: 6 PR tests, 12 independent review probes (11 status/period/price cases plus the before/after ordering case), and 124 related subscription/payment tests. CI is passing and the merge is conflict-free. All added probes used fake Stripe responses and persistence; no real customer account, Stripe state or production Firestore was inspected or changed. After merge, this requires a backend deployment and verification of the affected account. Keep #21869 open until the remaining path and customer outcome are verified. |
|
@aryanorastar Done, updated the PR body from Resolves #21869 to Refs #21869. Thank you! |
aryanorastar
left a comment
There was a problem hiding this comment.
Reviewed head c82eab9 for maintainer approval.
The earlier review requests are addressed: the PR body explicitly limits scope to subscription-read/metering recovery, the canceled-in-Stripe regression is present, and the issue reference is now Refs #21869 rather than a closing directive. The partial scope is accepted; I found no new blocking production-code defect in the direct Stripe-ID heal.
Fresh integration verification: merged this head with current main 271a77c in an isolated snapshot (merge tree 4c83238acde1ef01d5a8c7706796ca5f1efe582e). 712 focused tests passed, run per-file for isolation: 6 PR tests, 12 independent status/period/price admission probes, and 694 related subscription, state-machine, payment-price validation, storefront, presentation and catalog tests. The storefront tests used the declared pinned Babel dependency in an isolated test overlay and the actual matching client golden fixtures. git diff --check passed. PR CI has no failed or pending checks.
All tests used hermetic Stripe/persistence seams; no production customer, Stripe or Firestore state was inspected or changed. This approval accepts a bounded partial recovery fix, not full resolution of the billing incident. Checkout-first duplicate-billing protection remains tracked in #21869. Keep that issue open until the remaining path and the customer outcome are verified. A backend deployment and affected-account verification are still required after merge.
## Summary Refs #21869. Follow-up to #22193: protect users who go directly to checkout before subscription-read reconciliation has healed their stored paid plan. - Extend the existing shared checkout/reactivation boundary to verify the raw stored Stripe subscription ID even when the effective local plan is Free and the root customer ID is absent. - Keep same-plan/interval pending-cancellation reactivation. Other nonterminal subscriptions return HTTP 409; unverified Stripe state or failed reactivation returns retryable HTTP 503, never a second Checkout session. - Allow confirmed terminal subscriptions and definitive retrieve-only `resource_missing`/404; preserve new-buyer, referral and one-time PaymentIntent-grant behavior. - Keep storefront reads, plan-change/upgrade rails, customer identity and blocked-path entitlements unchanged. Log error types only, not Stripe response bodies. ## Root cause and durable prevention The validity projection can discard a stale paid record's Stripe ID when presenting it as Basic. Customer-based eligibility cannot recover it when the root customer ID is missing. The existing reactivation helper already retrieves the raw stored ID, but previously returned `None` for active subscriptions and swallowed provider/modify/persistence errors, allowing fresh checkout. The shared primitive is that existing boundary: `None` now means no existing recurring subscription was found or the stored one is confirmed ended/missing, not simply "reactivation did not happen." Regression tests execute the real HTTP route, real eligibility and actual Checkout builder with fake persistence and Stripe SDK objects, asserting no billing creation on blocked requests. No additional standalone checker or storefront mutation was introduced. Failure-Class: new New class: `FC-checkout-falls-through-unverified-subscription`. ## Verification - Regression reproduced before the fix: active/trialing/past_due subscriptions incorrectly returned HTTP 200 and reached new Checkout creation. - 266 targeted tests passed in isolated per-file pytest processes: 35 new checkout-first HTTP regressions plus 231 existing payment, eligibility, subscription healing/state/plan, terminal-status and webhook tests. - All 34 selected `make preflight` checks passed on commit `0e5f5f642c3ac64014b58b84ccf7e13a4bd80683`. The history-dependent failure-class recurrence audit explicitly skips on this shallow clone; CI with full history remains authoritative for that audit. Catalog consistency and async-blocker scan passed; PR metadata/failure-class validation passed. - The remaining bounded push checks passed, including the two changed test files (55 tests), runtime-source closure, released app-client OpenAPI compatibility/export, generated Dart/TypeScript/Swift model checks and pinned formatting. Only the documented local skips below were used. GitHub CI is not claimed green. - Local uvicorn/curl smoke passed with the real payment router, overridden auth, and mocked provider/persistence boundaries. No real Stripe or Firestore writes. Example request: ```bash curl -sS -X POST http://127.0.0.1:58550/v1/payments/checkout-session \ -H 'Content-Type: application/json' -d '{"price_id":"price_checkout_current"}' ``` | Fixture | HTTP | Fresh Checkout creates | Existing reactivations | | --- | --- | --- | --- | | Active subscription, missing root customer ID | 409 | 0 | 0 | | Stripe unavailable | 503 | 0 | 0 | | Confirmed ended subscription | 200 | 1 | 0 | | Same-plan pending cancellation | 200 | 0 | 1 | Local fixture-backed server stopped after smoke testing. The CI-selected 52-file run passed: **1,770 tests passed**, with 37 tests deselected by the normal `not integration and not slow` expression (two files entirely deselected). The 34 subscription-restructure tests also passed separately without that marker filter in the targeted run above. An initial local run hit the stricter default 0.30-second CPU guard on the unchanged generated-compute inventory test; the verification run uses CI's existing 1.0-second budget, without changing any repository setting. Reproduction commands (from `backend/`, with a repository-relative changed-path list): ```bash .venv/bin/python -m pytest tests/unit/test_checkout_first_subscription.py -q .venv/bin/python scripts/select_backend_unit_tests.py \ --changed-files /private/tmp/omi-21869-checkout-changed.txt \ --output /private/tmp/omi-21869-checkout-tests.txt BACKEND_UNIT_TEST_FILE_LIST=/private/tmp/omi-21869-checkout-tests.txt \ BACKEND_PYTEST_WORKERS=4 BACKEND_FAST_UNIT_FAIL_SECONDS=1.0 \ PYTHON=.venv/bin/python bash test.sh .venv/bin/python scripts/generate_plan_catalog.py --check --base-ref origin/main .venv/bin/python scripts/scan_async_blockers.py --dirs routers utils ``` ### Validation on current main (2026-10-20) This PR no longer bundles #22558 or #22595. They were merged in earlier only to get backend CI green; main's backend CI is green on its own now, so those files match main here and stay in their own PRs. The diff against main is the checkout-first protection alone: `routers/payment.py`, its two test files, `checkout-admission.md` and the failure-class record. - The 20-file billing selection (checkout-first, promotion codes, payment, Stripe ledger and subscription tests) passes under `test.sh`: 279 passed. - `routers/payment.py` passes the pinned type check (0 errors). - The four local fixture-backed curl admission outcomes described above are unchanged by this rebase; they were not re-run. ### Client handling of the new 409 Checkout's new 409 means the account already has a subscription. Flutter, macOS, web and Windows had mapped every 409 to "Resubscribe first to change plans.", which is only the upgrade route's pending-cancellation refusal. Checkout errors now show the existing-subscription reason ("You already have a subscription. Manage your existing subscription instead of starting a new checkout."); the upgrade route keeps "Resubscribe first". The upgrade-only helpers are renamed (`isUpgradePendingCancelConflict`, `SubscriptionPlanPresentation.upgradeErrorMessage`, web `purchaseErrorMessage(error, route)`, Windows `startCheckout` returning `existing_subscription`) so a checkout response can't be misclassified again. UI-Evidence: none Only which error sentence appears changes; no layout or control changes. Reproducing it live needs a real account with an existing subscription. Covered instead by Flutter (`plans_sheet_cancel_pending_test.dart`, `paywall_cancel_pending_test.dart`), macOS (`SubscriptionPlanPresentationTests`), web (`PlansSheet.cancelPending.test.tsx`, `cancelPending.test.ts`) and Windows (`billing.test.ts`, `PlanUsageTab.cancelPending.test.tsx`) tests. ## Architecture and release scope Architecture and implementation/release checklist: `backend/docs/checkout-admission.md`. Line-Count-Exception: backend/routers/payment.py | 1789 -> 1809 | Keep this 20-line safety expansion in the existing checkout/reactivation boundary; extracting unrelated payment routes would broaden this billing fix and its regression surface. This PR does not deploy, flip flags, repair customer data, cancel subscriptions, deduplicate historical purchases or serialize concurrent first-time checkout requests. Accounts missing both stored subscription ID and customer ID remain outside this bounded repair. Keep #21869 open pending separately authorized rollout and affected-account verification. GCP deployment verification is not claimed. Prior browser attempts could not list Cloud Run resources, and no usable ADC/read-only profile was found then. This code-only task performs no deployment or serving-revision verification. ## Product invariants affected none <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/22552?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/22552?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F22552&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-off-auto-fix-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/turn-off-auto-fix-light.svg"><img alt="Turn off auto-fix" src="https://www.cubic.dev/buttons/turn-off-auto-fix-light.svg"></picture></a> <!-- End of auto-generated description by cubic. --> ## 2026-10-23 maintainer review and merge gates Ready for code review at Aryan's request; pushed 5d2f03f. The checkout-vs-upgrade mapping and earlier stacked-test reversals have already been repaired on this head. Fixed the remaining Flutter conflict-message localization using the existing l10n tool across every current locale (49 at verification). Both purchase surfaces select the localized string from checkout HTTP 409; the upgrade pending-cancellation message is unchanged. Fourteen focused Dart tests pass, including English, German and Arabic on both surfaces; the two isolated backend checkout/promotion files pass 55 tests. Localization checks and all 60 selected preflight checks pass. The push used the documented PRE_PUSH_SKIP_DESKTOP_SWIFT=1 hatch for an unchanged native subtree under local memory pressure; git verified no macOS source changes since the preceding remote head. Exact-head CI remains authoritative for that compile. The prospective merge also preserves the five previously repaired regression files. No actual Stripe/Firestore writes or customer repair were performed. Stripe sandbox pass on 5d2f03f (2026-10-23, test mode only): the real checkout and customer-portal routes ran against a Stripe sandbox with real subscriptions, in-memory Firestore rows only. 10/10 scenarios behaved as specified: new buyer gets a session; an active subscription is refused with no session created (400 from the existing eligibility check when the customer ID is known, the new 409 when it was lost locally); pending cancellation on the same plan reactivates without checkout, including when the local row is missing; a different plan stays blocked; canceled and deleted subscription IDs get a fresh session; unverifiable Stripe state returns 503 with no session; the billing portal opens. Exact-head CI is green. Installed-client check (2026-10-23): the Flutter dev build of 5d2f03f on the iOS Simulator, signed in as the synthetic local-dev user against a local backend using the same Stripe sandbox, showed "You already have a subscription. Manage your current subscription instead of starting a new one." for a stale record whose Stripe subscription was incomplete (the read-heal only promotes active/trialing, so this is the state that reaches checkout from the app). No Checkout Session was created. Still required before merge: maintainer review. The first exact-head Linux helper packaging attempt failed while downloading Ubuntu runtime packages: the dependency-install step timed out at five minutes, before helper smoke execution. No application error was shown by that failure. Re-ran only that failed job once; the retry is not counted as a pass until it completes. No pipeline timeout, dependency pin or security gate was weakened.
|
For the record: I committed and engineered these fixes under the expectation of the repository's paid bug bounty program, not as open-source charity. Given the lack of settlement and community stance, all further contributions and open PRs have been permanently withdrawn. |
Refs #21869
Failure-Class: FC-billing-webhook-acknowledges-failed-entitlement
Line-Count-Exception: backend/utils/subscription.py | 1978 -> 1991 | Allow lapsed stored paid subscriptions to heal directly from Stripe subscription ID
Bounty:
Claim: https://paypal.me/Dragonire9
Email: [email protected]
Problem Analysis
In #21869, paying Neo (legacy Unlimited) subscribers who renewed in Stripe were metered at 300 minutes and read as Free Plan.
While #21890 added lapsed-plan detection to
econcile_basic_plan_with_stripe, line 1942 still checked if period_end_dt >= datetime.now(timezone.utc): before calling stripe.Subscription.retrieve(subscription.stripe_subscription_id). Because the stored period was lapsed (in the past), direct retrieval by subscription ID was bypassed entirely and fell back to ind_active_paid_subscription_for_user(uid). For legacy subscribers whose user root document lacks a populated stripe_customer_id, customer listing returned None and left the account in lapsed status.
Solution
ow, allowing direct stripe.Subscription.retrieve on subscription.stripe_subscription_id.
etrieve returns a canceled subscription or encounters errors, gracefully falls through to the existing customer listing fallback.
Verification