Skip to content

fix(payments): changing plan during a trial keeps the trial - #25289

Merged
kodjima33 merged 1 commit into
mainfrom
mux/2026-11-14-trial-plan-change
Nov 14, 2026
Merged

kodjima33 merged 1 commit into
mainfrom
mux/2026-11-14-trial-plan-change

Conversation

@kodjima33

@kodjima33 kodjima33 commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

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 14 subscription_update charges in the trial cohort.

POST /v1/payments/upgrade-subscription now does this when Stripe says the subscription is trialing: it swaps the item price in place (proration_behavior=none, existing trial_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):

  1. Tests rewritten on the real router with currency on the sub and on each Price. The old file failed on today's main with 409 Could not verify the subscription currency.
  2. Test isolation: the new file uses monkeypatch only, with no _setup_payment_module and no sys.modules changes. Run first, it no longer breaks other payment tests.
  3. The trial decision reads only Stripe's status == 'trialing'. The stored status can never be trialing, so that dead check is gone. Added payment_behavior='error_if_incomplete' and the idempotency key omi-trial-interval-{sub}-{latest_invoice}-{price}-{trial_end}. Every swap issues a new latest_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).
  4. Both immediate branches now share _store_modified_subscription. It runs the same status in (active, trialing) and no-pending_update check (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 the stripe CLI 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 on b182d774ec; the head differs only by restoring the endpoint docstring so the published OpenAPI stays unchanged).

Run (7-day trial, pm_card_visa) Right after the change First charge (clock past trial end)
main a5125d8d8a, annual→monthly status active, trial ended now, subscription_update $269.91 $269.91 subscription_update paid
main, monthly→annual status active, trial ended now, subscription_update $29.99 $29.99 subscription_update paid
this PR, annual→monthly trialing, 7.00 days left, no schedule, subscription_update $0.00 $29.99 subscription_cycle paid
this PR, monthly→annual trialing, 7.00 days left, no schedule, subscription_update $0.00 $269.91 subscription_cycle paid
this PR, annual→monthly→annual→monthly in one minute 3 distinct idempotency keys, ends trialing on monthly, three $0.00 updates $29.99 subscription_cycle paid

A 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), metadata and the idempotency key. Not exercised in the sandbox: a JPY trial sub (the sandbox has no JPY prices) and a real pending_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_update return 402 with no write, a switch back never reuses a key, and a paid (or ended-trial) sub still schedules.

  • On main's payment.py: 6 failed, 2 passed (the 2 paid-schedule guards).
  • On this branch: 8 passed.
  • Order independence: new file first, then the other 12 payment files: 142 passed. Global random order (pytest-random-order, 8 seeds) across the new file and 11 other payment files: 102 passed each time. test_payment_promotion_codes.py was 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.
  • Every test file that touches upgrade-subscription or yearly_switch passes 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

View guided diff Turn on auto-fix

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 kodjima33 added the mux-proposal Mobile UX improver (MUX) proposal; waits for Nik's ship label Nov 14, 2026
@kodjima33
kodjima33 merged commit 066363e into main Nov 14, 2026
69 of 70 checks passed
@kodjima33
kodjima33 deleted the mux/2026-11-14-trial-plan-change branch November 14, 2026 13:06
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.

![Home row before and after, and the confirm
sheet](https://raw.githubusercontent.com/BasedHardware/omi/34b1546d9f5c8aba02400c070690af7f3c8084c4/.agent-artifacts/ui-evidence/mux-2026-11-14-yearly-renewal-save/001-mobile-ios-home-row-before-after.png)
![Declined, switched, row gone, after
relaunch](https://raw.githubusercontent.com/BasedHardware/omi/34b1546d9f5c8aba02400c070690af7f3c8084c4/.agent-artifacts/ui-evidence/mux-2026-11-14-yearly-renewal-save/002-mobile-ios-declined-switched-row-gone.png)
![Dark before and
after](https://raw.githubusercontent.com/BasedHardware/omi/34b1546d9f5c8aba02400c070690af7f3c8084c4/.agent-artifacts/ui-evidence/mux-2026-11-14-yearly-renewal-save/003-mobile-ios-dark-before-after.png)
![Largest text before and after (light and
dark)](https://raw.githubusercontent.com/BasedHardware/omi/34b1546d9f5c8aba02400c070690af7f3c8084c4/.agent-artifacts/ui-evidence/mux-2026-11-14-yearly-renewal-save/004-mobile-ios-max-text-before-after.png)
![German, Japanese,
Arabic](https://raw.githubusercontent.com/BasedHardware/omi/34b1546d9f5c8aba02400c070690af7f3c8084c4/.agent-artifacts/ui-evidence/mux-2026-11-14-yearly-renewal-save/005-mobile-ios-locales-de-ja-ar.png)

| 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

mux-proposal Mobile UX improver (MUX) proposal; waits for Nik's ship

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Switching a trialing subscription to monthly ends the trial early and charges the annual price

1 participant