Repository navigation
fix(payments): changing plan during a trial keeps the trial - #25289
Merged
Merged
Conversation
A same-plan monthly/annual switch went through SubscriptionSchedule.create. The schedule's first phase has no trial, so Stripe ended the trial at once and billed the full current price ($269.91 or $29.99, #23298). During a Stripe trial the endpoint now swaps the item price in place with proration_behavior none, the existing trial_end, payment_behavior error_if_incomplete and an idempotency key built from latest_invoice, so a retry replays but a later switch back cannot. The trial decision reads only Stripe's status; the stored status never says trialing. Both immediate branches now share one helper that refuses (402) an incomplete or pending_update result before writing Firestore. Ported from #23317 by @Dimank92 onto current main, with the review fixes. Failure-Class: new Co-authored-by: Dimank92 <[email protected]>
kodjima33
added a commit
that referenced
this pull request
Nov 14, 2026
…row (#25294) ## Problem First-year yearly plans renew at only 42% (22 of 52 anniversaries since Oct 1): 25% end on a failed card, 23% cancel, 10% pending. 58% of trial-end and renewal card failures are insufficient funds. 329 first-year yearly renewals come due in the next 75 days (about 147 between Dec 7 and 27), and half of those payers had no app session in 30 days. Source: `~/mobile-ux-agent/runs/2026-11-13/analysis/sessions.md` section 5 (Stripe, ACTUAL). #23953's declined-card row on Home already recovers some failed renewals, but it only offers updating the card for the same yearly charge. Someone who cannot pay $199.99 today has no smaller option and is lost after Stripe's retries. New fact from the same Stripe snapshot: **all 320 first-year yearly renewals due in the next 75 days are on the Neo yearly price** (`price_1RtJQ71F8wnoWYvwKMPaGlGY`, $199.99), not Omi Pro's $269.91. So the switch targets the subscription's own plan's catalog monthly price (Neo monthly $19.99, live and active; Omi Pro monthly $29.99), which `retired_plan_change_error` already allows ("may switch interval within it"). ## Change What the reader sees (only when the renewal that failed is yearly): - The declined row reads "Update it, or get Omi Pro back for US$29.99 a month" and adds **Switch to Monthly** (secondary) next to **Update** (primary, unchanged). - Switch to Monthly opens a confirm sheet laid out like the shipped yearly-switch sheet: Plan, **Due today** (the catalog monthly price), "Replaces the unpaid US$269.91 yearly charge. Renews monthly. Cancel anytime.", Confirm and Cancel. - Declined card: "Payment declined. Your plan didn't change." and the row stays. Success: "You're on monthly", the row leaves. - Monthly renewals, trials, discounted, non-USD, cancel-scheduled and unpaid subscriptions see exactly today's row. Backend: - `utils/monthly_switch.py`: offer rules and the switch. `GET /v1/users/me/subscription` adds `payment_issue.monthly_switch` (`price_id`, `amount`, `currency`, `yearly_amount`), omitted when not offered. - `POST /v1/payments/payment-issue/monthly-switch` (`routers/monthly_switch.py`, mounted next to `yearly_switch`). - `routers/payment.py`: `invoice.paid` retries a void the switch could not finish (+5 lines). - Kill switch `PAYMENT_ISSUE_MONTHLY_SWITCH_ENABLED` (default on, `ops_kill`, registered in `config/feature-flags.yaml`). App: `payment_issue_row.dart`, new `monthly_switch_sheet.dart`, model + API call, 8 strings in all 49 locales. At large text the stacked actions put Update (the primary) first, so it stays clear of Home's pinned Ask bar. `PlanSwitchFactRow` (shared with the yearly sheet) stacks label over value at large text so amounts never break mid-number. ## Money safety - **Pause, charge, then void.** 1. Before the charge, the unpaid yearly invoice's automatic collection is paused (`Invoice.modify(auto_advance=False)`), so no Stripe retry can collect it while the switch runs or while a failed void is being retried. 2. Then `Subscription.modify(items=[monthly], billing_cycle_anchor=now, proration_behavior=none, payment_behavior=error_if_incomplete)`. The unpaid yearly period earns no credit. 3. Only after the monthly charge succeeds is the yearly invoice voided. - **Any failure that did not switch restores dunning exactly as before:** - A decline (`card_error`, Stripe changed nothing) resumes collection. - An unclear Stripe error re-reads the subscription and resumes unless the switch landed. If it landed, collection stays paused and the retry voids. - A failed pause is undone before anything is charged. A failed resume is logged and reported (`record_fallback`); Update still pays the invoice. - **Double payment is reported, never silent:** if the superseded yearly invoice is found `paid` (amount_paid > 0), `void_superseded` logs an error and records `monthly_switch_superseded_invoice → paid_twice` (outcome exhausted) so someone refunds it. No automatic refund. - **Proven on the Stripe sandbox** ("Omi pricing qa", test mode, `livemode=false`, test clock; `runs/2026-11-14/y1/stripe-sandbox/proof2.log`). Three payers whose 19999 renewal was declined: - **A (switch works, void never runs):** paused (next attempt none), charged 1999. At +3, +8 and +20 days the yearly invoice is still open and never retried; charges stay 19999, 1999. - **B (switch declined):** `card_error`, collection resumed with the same next retry as before the pause, still past_due on yearly. Once the card works, dunning collects it: 19999, 19999 and no monthly charge. - **C (manual pay while paused, what Update does):** paid 19999. - Before the fix, the review's sandbox run without the pause charged 19999, 1999, 19999. - Earlier `proof.log`: a declined switch leaves no stray invoice, the preview equals the price, and the void with the same idempotency key replays. - **No double charge from taps or retries:** - A per-user Redis lock (no lock, no charge). - A replay check: a subscription already switched by us returns without a second modify. - An idempotency key bound to subscription, invoice and attempt. - **The charge is what the reader saw:** `expected_amount` must equal the live price and Stripe's preview for the same items, anchor and proration. No new prices, coupons or discounts. Only the plan's configured monthly price is accepted. - **Refused before any Stripe write:** anything not past_due (unpaid, active, trial), cancel scheduled, schedule attached, pending update, discount on the subscription or invoice, paused, invoiced billing, more than one item, non-USD, not on a consumer plan's configured yearly price, invoice not the open latest `subscription_cycle` invoice, wrong owner uid, kill switch off. - **A failed void is repaired:** `invoice.paid` for the new monthly invoice retries the void and returns 503 so Stripe redelivers. With the pause, nothing can collect the yearly invoice in the meantime. - **Compatibility** (`contracts/client-compat`, `check_app_client_openapi_compatibility.py` passes): the new field is additive and omitted when absent. - Old app + new backend: unchanged row (BEFORE run). - New app + old backend: no field, so the Update-only row (widget test). - **Cancel stays easy:** the sheet has Cancel and a close X, and nothing on the row or sheet blocks the existing cancel flow. ## Impact estimate > If a declined first-year yearly renewal can switch to the plan's monthly price from the Home row, first-year yearly renewal (any paid plan) goes 42% → 45% (44–48%); 30-day subscriber churn 11.21% → 11.06% (11.13–10.95%). Basis: - **A, ACTUAL:** - 42% (22/52) first-year yearly renewal (sessions.md section 5). - Churn 11.214% (`runs/2026-11-14/metrics.json`, `subscriber_churn`). - **Card failures that end, ACTUAL:** 25% of first-year yearly renewals (13/52). - **They rarely recover on their own, ACTUAL:** - 7 of 71 paid first-year yearly renewals paid after a failed first attempt, against 42 that ended on card failure (Stripe snapshot, paid-invoice lag). - So about 86% of failures are lost today, and the switch mostly reaches payers who would otherwise leave. - **Reach, MODELED 35–50% (42% central):** - Seeing the row needs an app session while past_due (up to 14 days of retries). - 50% of the 329 had a session in the last 30 days (ACTUAL). - The existing failed-renewal push sends people to Home. - **Take-up, MODELED 30% (20–45%) of row viewers who would otherwise end:** - 58% of failures are insufficient funds (ACTUAL). - The monthly charge is 10% of the yearly one for the Neo wave ($19.99 vs $199.99). - #23953's row: 4 of 6 tappers paid (ACTUAL, small n). - **Gain:** 25 × 0.42 × 0.30 ≈ +3.2 points (+1.8 to +5.6). - **Churn:** 329 × 3.2% ≈ 10 more payers kept over 75 days, about 4 per 30 days on ~2,800 active subscribers, so −0.15 points. - **Why not the brief's 55%:** that needs about half of all card failures to switch, but half of these payers never open the app. Reaching dormant payers needs the push or email to carry the offer (below). - **Revenue risk, MODELED:** someone who would have fixed the card and paid $199.99 now pays $19.99 a month instead. That is at most the ~14% of failures that recover today. ## At ship - Deploy backend first. The app shows nothing new until `payment_issue.monthly_switch` arrives, and `PAYMENT_ISSUE_MONTHLY_SWITCH_ENABLED=false` turns the offer and the endpoint off. - Events are unsampled (names contain "Subscri"), registered in `contracts/analytics/events.json`, consumer `subscription-payment-recovery`: - `Subscription Payment Issue Monthly Shown` / `Tapped` / `Switched` (after the server confirms) / `Failed` (reason: declined, refused, error). - Calibration read about 3 weeks after the Dec 7 wave: Monthly Switched ÷ Monthly Shown, and first-year yearly renewal (any paid plan) from Stripe. - **Dormant payers (not built, nothing sent):** the only Omi-owned path is the existing failed-renewal push (`_schedule_payment_recovery_notification` in `routers/payment.py`, "Payment declined / Update your payment method…", `navigate_to: /conversations` = Home, where this row is). - The same offer could ride it: when `billing_recovery.payment_issue_from_stripe` + `monthly_switch.offer()` return an offer at the past_due transition, append "Or keep <plan> for <price> a month." to the body. It needs copy approval and server-side l10n. - There is no Omi email for failed renewals. Stripe's own dunning emails (if enabled in the Stripe settings) link to the hosted invoice, which cannot switch plans. - Review follow-ups not in this PR: - The app re-reads the plan only on a lost answer, not on a 503. - The superseded-invoice metadata key is never cleared, so later monthly `invoice.paid` events do one extra invoice read. - Confirm the Stripe API version's invoice `subscription` field for the webhook gate. - Review follow-ups not in this PR: - The app re-reads the plan only on a lost answer, not on a 503. - The superseded-invoice metadata key is never cleared, so later monthly `invoice.paid` events do one extra invoice read. - Confirm the Stripe API version's invoice `subscription` field for the webhook gate. - Overlap: #25289 (open) extracts the upgrade path's store step. This PR leaves that path untouched and stores its own result with the same calls. Fold into that helper once it lands. ## Evidence Simulator (MUX pipeline, lane sim, iPhone 17 Pro iOS 26.2, local backend + Stripe stub). Same seed on main (BEFORE) and this branch (AFTER): Omi Pro yearly, first renewal declined, past_due with an open $269.91 invoice.      | check (same seed) | main | this branch | |---|---|---| | backend `payment_issue` | `{past_due, unlimited_v2}` | + `monthly_switch {2999 usd, yearly 26991}` | | row | Update only | offer line + Switch to Monthly + Update | | open sheet, Cancel | n/a | no Stripe write; still past_due, invoice open | | Confirm, card declined | n/a | "Payment declined. Your plan didn't change."; past_due, invoice open, 0 charges | | Confirm, card works | n/a | active monthly, 1 charge, yearly invoice void, plan unlimited_v2 | | replayed POST ×2 | n/a | HTTP 200, still 1 charge, 1 void | | relaunch | n/a | row stays gone | The full flow passed on the final backend tree (`runs/2026-11-14/y1/raw/after-light-final/checks.txt`): collection paused then resumed for the declined attempt, paused for the switch, yearly invoice void, 1 charge. Artifacts in `~/mobile-ux-agent/runs/2026-11-14/y1/`: - `before-after.png`, `demo.mp4` (28 s), `demo.gif`, `result.txt`, `stripe-sandbox/proof.log` - `before/` and `after/` (light, dark, largest text light and dark, de/ja/ar) - `stripe-sandbox/proof2.log`: the pause proof ## Tests - Backend: - `tests/unit/test_monthly_switch.py` (50): offer rules, pause, charge, void order; a decline resumes collection; an unclear failure resumes only if not switched; a failed pause never charges; a failed resume and a paid-twice invoice are reported; refusals before any write; replay; failed void; kill switch. - `tests/routers/test_payment_monthly_switch.py` (12): status codes, lock, store. - `tests/unit/test_monthly_switch_webhook.py` (3): void retry on `invoice.paid`, 503 on failure. - `tests/routers/test_users_payment_issue.py` (+2): offer on the subscription response. - Related suites green: billing_recovery, yearly_switch, declined_proration, promotion_codes, webhook_delivery, paid_app_renewal, stripe_event_ledger. - App: `test/pages/home/payment_issue_row_test.dart` (24): offer row, old-server row, sheet content, Cancel, single charge on double tap, declined, refused, lost answer, largest text (row with Update first, and the sheet), events. - Guards: mobile UX contract, UI isolate, brand UI, event registry, l10n check, OpenAPI export + Dart/TS/Swift generation, app-client compatibility, route-policy baseline, feature-flag registry. ## Not verified - Real take-up and reach: the estimate above is modeled. - The Neo yearly-to-monthly switch on live Stripe. The sandbox replica ($199.99 to $19.99) and the unit tests cover it, but the simulator shot uses Omi Pro prices (the stub has no Neo prices). - Live Smart Retry timing: the sandbox retried about 3 days after the declined renewal. The pause holds through +20 days there. - Pre-existing, not from this change: at the largest text the Home/Tasks header overflows on main too. One app test (`voice_recorder_test`) flaked once in a full run and passes alone on main and on this branch. Line-Count-Exception: backend/routers/payment.py | 2100 -> 2105 | the invoice.paid webhook is the durable retry point for voiding the superseded yearly invoice; the endpoint itself lives in routers/monthly_switch.py UI-Evidence: see the images above (.agent-artifacts/ui-evidence/mux-2026-11-14-yearly-renewal-save)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What changed and why
Fixes #23298. Takes over and supersedes #23317 by @Dimank92, who found the cause and wrote the first fix. Their commit authorship is kept with
Co-authored-by.A same-plan monthly/annual switch during a free trial went through
SubscriptionSchedule.create(from_subscription=...). The schedule's first phase has no trial, so Stripe ended the trial at once and billed the full current price on day one ($269.91 annual, $29.99 monthly). That matches the 14subscription_updatecharges in the trial cohort.POST /v1/payments/upgrade-subscriptionnow does this when Stripe says the subscription istrialing: it swaps the item price in place (proration_behavior=none, existingtrial_end). The trial continues, the change bills $0, and the trial end bills the price the user chose.Changes on top of #23317 (from the money-safety review):
currencyon the sub and on eachPrice. The old file failed on today's main with409 Could not verify the subscription currency.monkeypatchonly, with no_setup_payment_moduleand nosys.moduleschanges. Run first, it no longer breaks other payment tests.status == 'trialing'. The stored status can never betrialing, so that dead check is gone. Addedpayment_behavior='error_if_incomplete'and the idempotency keyomi-trial-interval-{sub}-{latest_invoice}-{price}-{trial_end}. Every swap issues a newlatest_invoice, so a retry replays the same change but a later switch back cannot (a key without it would replay annual→monthly after monthly→annual and leave Stripe on annual while Firestore says monthly)._store_modified_subscription. It runs the samestatus in (active, trialing)and no-pending_updatecheck (else 402) before any Firestore write.Dropped from #23317:
clear_trial_paywall_cache, which no longer exists on main.Product invariants affected
none
How it was verified
The real endpoint code ran against the Stripe sandbox "Omi pricing qa" (
livemode=false, asserted on every response). Stripe SDK requests went through thestripeCLI sandbox session; only Firestore and Redis were stubbed. Each sub ran on a test clock advanced to trial end + 25h, so the first charge is observed, not inferred. Script and logs:~/mobile-ux-agent/runs/2026-11-14/takeover-23317-sim/(run onb182d774ec; the head differs only by restoring the endpoint docstring so the published OpenAPI stays unchanged).pm_card_visa)a5125d8d8a, annual→monthlyactive, trial ended now,subscription_update$269.91subscription_updatepaidactive, trial ended now,subscription_update$29.99subscription_updatepaidtrialing, 7.00 days left, no schedule,subscription_update$0.00subscription_cyclepaidtrialing, 7.00 days left, no schedule,subscription_update$0.00subscription_cyclepaidtrialingon monthly, three $0.00 updatessubscription_cyclepaidA repeat tap of the same change returns the existing 400 "already subscribed" with no Stripe write. Stripe received exactly
items,proration_behavior=none,payment_behavior=error_if_incomplete,trial_end(unchanged),metadataand the idempotency key. Not exercised in the sandbox: a JPY trial sub (the sandbox has no JPY prices) and a realpending_update(unit-tested only).Tests
backend/tests/unit/test_payment_trial_interval_change.py(8 tests): both directions keep the trial with the exact Stripe params and key, schedule release runs before the swap and Firestore is written after it, the promo passes through,incomplete/pending_updatereturn 402 with no write, a switch back never reuses a key, and a paid (or ended-trial) sub still schedules.payment.py: 6 failed, 2 passed (the 2 paid-schedule guards).pytest-random-order, 8 seeds) across the new file and 11 other payment files: 102 passed each time.test_payment_promotion_codes.pywas left out: on main it already breaks other payment files when it runs before them (alone before them: 28 failed, without this PR's file). This PR does not touch it.upgrade-subscriptionoryearly_switchpasses in its own process, as CI runs them.Line-Count-Exception: backend/routers/payment.py | 2100 -> 2141 | trial branch of upgrade-subscription; the shared post-modify helper already removes the duplicated tail, and splitting payment.py is out of scope for a billing fix
UI evidence
UI-Evidence: none -- backend only; the app's request and response shape are unchanged.
Failure class (fixes)
Failure-Class: new
Failure-class transition narrative (only when needed)
Adds
FC-plan-change-ends-provider-trial. Violated contract: changing the price of a sub that Stripe reports as trialing must keep the trial and bill nothing until it ends. Guard:backend/tests/unit/test_payment_trial_interval_change.py. Evidence: #23298 and the sandbox runs above.🤖 Generated with Claude Code