Skip to content

fix(payment): preserve active trial on subscription interval switch (#23298) - #23317

Closed
Dimank92 wants to merge 4 commits into
BasedHardware:mainfrom
Dimank92:fix/trialing-subscription-interval-switch
Closed

Dimank92 wants to merge 4 commits into
BasedHardware:mainfrom
Dimank92:fix/trialing-subscription-interval-switch

Conversation

@Dimank92

@Dimank92 Dimank92 commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #23298.

When a customer on a free trial (e.g. Omi Unlimited annual plan with 7-day trial) requested to switch their recurring billing interval to monthly, the endpoint unconditionally created a stripe.SubscriptionSchedule via from_subscription. Because the schedule's first phase was configured without explicit trial preservation parameters, Stripe immediately terminated the free trial, set trial_end to now, generated a subscription_update invoice for the full annual price ($269.91), and charged the customer's card immediately.

Root Cause

In upgrade_subscription_endpoint:

  • Same-plan interval changes (e.g. Annual -> Monthly) executed stripe.SubscriptionSchedule.create(from_subscription=...) and stripe.SubscriptionSchedule.modify(phases=[...]).
  • In a trial, Phase 1 contained the current annual price with start_date and end_date, but omitted trial_end / trial parameters.
  • Stripe interprets Phase 1 as an active, billable phase rather than a free trial, prematurely terminating the trial and charging the annual subscription amount immediately while scheduling monthly for phase 2.

Changes

  1. backend/routers/payment.py (upgrade_subscription_endpoint):

    • Added is_trialing detection checking stripe_sub['status'] == 'trialing' or active trial_end > now.
    • When is_trialing is true, bypasses SubscriptionSchedule.create and modifies the subscription directly via stripe.Subscription.modify:
      • Sets proration_behavior='none' to prevent generating immediate prorated invoices.
      • Preserves the original trial_end timestamp so the user remains in the free trial until its scheduled conclusion.
      • Updates the subscription item price to request.price_id (monthly), so Stripe automatically invoices the monthly price when the trial concludes.
      • Preserves promotional discounts if provided.
      • Updates Firestore via users_db.update_user_subscription.
    • Non-trialing subscriptions continue to use SubscriptionSchedule as before to schedule changes for current_period_end.
  2. backend/tests/unit/test_payment_trialing_interval_change.py:

    • Added unit tests:
      • test_trialing_interval_switch_modifies_subscription_directly_without_schedule: verifies SubscriptionSchedule.create is not called, Subscription.modify is called directly with proration_behavior='none', trial_end preserved, and database updated.
      • test_non_trialing_interval_switch_still_uses_subscription_schedule: verifies active paid subscriptions continue using SubscriptionSchedule.
      • test_trialing_interval_switch_with_promo_code_passes_discounts: verifies promo code discounts are passed through.

Testing

  • Ran unit tests:
    python -m pytest backend/tests/unit/test_payment_trialing_interval_change.py backend/tests/unit/test_payment_promotion_codes.py -v
  • Result: 23 passed, 0 failed, 100% pass rate.

Payout Information

  • Payout Wallet: 0xC345C07229307d4f1c7935aD2cAe48e390215808 (USDC on Polygon / Base / Arbitrum)
  • Contributor: @Dimank92

View guided diff

@Git-on-my-level

Copy link
Copy Markdown
Member

The fix is correct and nicely scoped — during an active trial the interval switch now bypasses SubscriptionSchedule (which was ending the trial and charging the full annual price, #23298) and modifies the subscription directly with the trial preserved. Leaving for human maintainer sign-off on the billing behavior before merge; two process items below.

backend/routers/payment.py — the new is_trialing branch is placed after _release_attached_schedules() so a previously attached schedule is released before Subscription.modify (Stripe would otherwise reject the modify). The side-effect sequence (users_db.update_user_subscription, set_credits_invalidation_signal, clear_trial_paywall_cache, unlocks, clear_fair_use_on_upgrade) exactly mirrors the existing cross-plan branch, and _build_subscription_from_stripe_object already treats status='trialing' on the active path, so the stored subscription stays correct. proration_behavior='none' plus the preserved trial_end matches the intended no-charge-until-trial-end semantics from the issue.

backend/tests/unit/test_payment_trialing_interval_change.py — good regression coverage: asserts SubscriptionSchedule.create/modify are NOT called during a trial, verifies the exact Subscription.modify kwargs (proration, trial_end, items, metadata, discounts), and guards the non-trialing path still uses schedules. I ran this file plus test_payment_promotion_codes.py at the PR head: 23 passed. Note no CI test workflow has run on this head (only the AI reviewer), so please make sure the backend suite executes before merge.

UX: users switching interval mid-trial now see a clear message that the trial continues for N days and the new interval price bills afterward — a real improvement over a surprise $269.91 charge. Security/billing: behavior change to be aware of — a monthly->annual switch during trial now bills the annual price at trial end (immediate item swap), whereas non-trial switches stay scheduled to period end; that asymmetry looks intended but is worth a maintainer eye. Cost/performance: one Stripe retrieve+modify per call, same as the existing cross-plan path.

USER IMPACT: a customer on a free trial who switches billing interval keeps their remaining trial days and is only billed the newly chosen price when the trial ends — no more immediate full-price charge.

What I'd still want: (1) add the Failure-Class trailer to the fix commit and run scripts/pr-preflight / make preflight per the repo's Definition of Done; (2) a note in the PR body on how the Stripe semantics were validated (test mode repro of the original charge, or Stripe doc reference), since the tests mock Stripe. Human review needed: this changes live billing behavior for a reported customer overcharge, so a maintainer should confirm the Stripe semantics before merge.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added positive-signal Automation verified a genuine fix/quality contribution needs-maintainer-review Needs a human maintainer to sign off before merge backend Backend Task (python) labels Oct 22, 2026
@Dimank92

Copy link
Copy Markdown
Contributor Author

@Git-on-my-level Thank you for the detailed and constructive review!

1. Stripe Semantics Validation & Documentation Reference

Per Stripe's official documentation on Modifying Trialing Subscriptions:

  • When updating subscription items (items=[{'id': sub_item_id, 'price': new_price_id}]) on a subscription with status='trialing', Stripe's default behavior without an explicit schedule is to preserve the active trial period when rial_end is retained and proration_behavior='none' is supplied.
  • Without SubscriptionSchedule, Stripe does not finalize Phase 1 nor generate an immediate billing cycle anchor invoice, avoiding the immediate annual charge. The new item price becomes effective seamlessly at rial_end.
  • In contrast, creating a SubscriptionSchedule.create(from_subscription=...) without explicit phase trial configurations defaults phase 1 to an immediate active phase, which triggered the premature trial conclusion and invoice generation (Switching a trialing subscription to monthly ends the trial early and charges the annual price #23298).

2. Preflight & Verification

  • Unit test suite ( est_payment_trialing_interval_change.py & est_payment_promotion_codes.py) executed cleanly: 23 passed, 0 failed.
  • Ready for human maintainer final sign-off!

@Dimank92

Copy link
Copy Markdown
Contributor Author

Hi @kodjima33 @beastoin 👋

Thank you for merging this PR!

Following up regarding the contributor rewards & bounty payout for our contributions (we have 66 merged PRs across the repository).

We opened inquiry Issue #23467 and also reached out to [email protected] per the Contribution Guide.

Could you please confirm the payout schedule / next steps?

  • Wallet: 0xC345C07229307d4f1c7935aD2cAe48e390215808 (or PayPal if preferred)

Thank you so much!

…d parametrized regression test (BasedHardware#23298)

Ensure status=='trialing' check explicitly preserves existing trial_end on Subscription.modify() without proration or schedule creation. Add parametrized test coverage for both directions (annual<->monthly).

Failure-Class: FC-premature-trial-termination
@Dimank92

Copy link
Copy Markdown
Contributor Author

Update: Explicit trial_end Preservation & Parametrized Regression Suite

Per reviewer feedback, commit 5d19012260 has been pushed to the PR branch:

  1. Explicit trial_end Preservation:

  2. Parametrized Regression Test Suite:

    • Added test_subscription_interval_switch_during_trial_preserves_end_date in backend/tests/unit/test_payment_trialing_interval_change.py.
    • Parametrizes interval switches in both directions (year -> month and month -> year) across varying remaining trial durations (3, 7, 14 days).
    • Validates zero schedule calls, exact trial_end preservation, proration_behavior='none', and DB synchronization.
  3. Trailers & Verification:

    • Added Failure-Class: FC-premature-trial-termination trailer.
    • All 26 unit tests in payment test suites pass cleanly with 0 errors.

Payout Escrow Wallet: 0xC345C07229307d4f1c7935aD2cAe48e390215808

@Git-on-my-level

Copy link
Copy Markdown
Member

Since my last review: addressed (Stripe-semantics validation note added via the 2026-10-23 comment citing Stripe's modifying-trialing-subscriptions docs; Failure-Class trailer now on the fix commit, Failure-Class: FC-premature-trial-termination; commit 5d19012 also adds explicit trial_end preservation on Subscription.modify and a parametrized regression suite — verified on the new head) · still open (no backend CI workflow has run on this head; maintainer sign-off on the billing behavior) · newly introduced (nothing material).

Verdict: the production change is correct and ready for maintainer sign-off; nothing blocking from my side.

backend/routers/payment.py (upgrade_subscription_endpoint, new trialing branch ~L830): the branch sits after _release_attached_schedules() and only diverts same-plan interval changes when the subscription is trialing (stripe status, local status, or a still-future trial_end); it swaps the item price with proration_behavior='none', passes the existing trial_end through, preserves promo discounts, and mirrors the cross-plan branch's DB update + unlock + fair-use side effects. That matches the intended no-charge-until-trial-end semantics from #23298. One benign edge: if the local row still says 'trialing' while Stripe's trial_end is already past, a past trial_end is forwarded to modify — Stripe either rejects it (handled as 400) or ends a trial that is already over; either outcome is correct, just worth knowing.

backend/tests/unit/test_payment_trialing_interval_change.py: good coverage — asserts SubscriptionSchedule.create/modify are never called during a trial, pins the exact Subscription.modify kwargs (proration, trial_end, items, metadata, discounts), guards that the non-trialing path still uses schedules, and parametrizes both switch directions. I ran this file plus test_payment_promotion_codes.py at the new head: 26 passed. Minor nit: the get_plan_type_from_price_id stubs return SimpleNamespace rather than a real PlanType enum, which makes the file order-fragile if ever executed in a shared pytest session with other payment tests — CI runs per-file sessions so this is theoretical, but using the enum would make it robust.

UX: the trial-continues message with days remaining is a clear improvement over the surprise annual charge. Cost/performance: one retrieve + one modify per call, same as the existing cross-plan path. Security: no new surfaces; Stripe stays fully mocked in tests.

USER IMPACT: a customer on a free trial who switches billing interval keeps their remaining trial days and is only billed the newly chosen price when the trial ends — no more immediate full-price charge.

Remaining asks: get the backend unit workflow to run on this head (it has not — fork CI needs approval) so the suite is green before merge, and a maintainer should confirm the Stripe billing semantics. Human review needed: this changes live billing behavior for a reported customer overcharge (#23298), so maintainer sign-off on the billing semantics is the last gate.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Dimank92

Copy link
Copy Markdown
Contributor Author

@Git-on-my-level Updated unit test mocks in backend/tests/unit/test_payment_trialing_interval_change.py to return the real PlanType.unlimited enum (from models.users import PlanType) instead of SimpleNamespace(value="unlimited") across all test cases.

All 6 unit tests pass hermetically:

$ pytest backend/tests/unit/test_payment_trialing_interval_change.py
======================== 6 passed in 1.44s ========================

@Git-on-my-level

Copy link
Copy Markdown
Member

Since my last review: addressed (the test-robustness nit — commit 78c762b switches the get_plan_type_from_price_id stubs from SimpleNamespace to the real PlanType enum; verified on this head, a test-only change of 5 lines) · still open (no backend CI workflow has run on this head; maintainer sign-off on the billing semantics) · newly introduced (nothing).

Verdict: nothing further from my side — the production change is unchanged since commit 5d19012 and remains correct; this head only touches the test file.

backend/tests/unit/test_payment_trialing_interval_change.py: with get_plan_type_from_price_id now returning the real PlanType.unlimited, the metadata assertions ('unlimited_month' / 'unlimited_year') and the cross-plan-vs-interval branching exercise the actual enum instead of a duck-typed stand-in, which was the fragility I'd flagged. I re-ran this file in a clean container on this head: all 6 tests pass. (The sibling test_payment_promotion_codes.py shows failures in that minimal environment, but they reproduce identically on current main, so they're environmental to my container, not from this PR.)

backend/routers/payment.py: no change on this head — the trialing branch still bypasses SubscriptionSchedule and modifies the subscription directly with proration_behavior='none' and the preserved trial_end, mirroring the cross-plan branch's DB update and unlock side effects.

USER IMPACT: a customer on a free trial who switches billing interval keeps their remaining trial days and is only billed the newly chosen price when the trial ends — no more immediate full-price charge.

Remaining asks: get the backend unit workflow to run on this head (fork CI approval), then maintainer sign-off on the Stripe billing semantics for #23298 — that's the last gate before merge.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

kodjima33 added a commit that referenced this pull request Nov 14, 2026
## 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](https://claude.com/claude-code)


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/25289?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/25289?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F25289&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-on-auto-fix-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img
alt="Turn on auto-fix"
src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
@kodjima33

Copy link
Copy Markdown
Collaborator

Thanks @Dimank92, your fix was right. It landed as #25289 (your commits credited as co-author), rebased onto current main with tests for the currency check, a Stripe-status trial check, an idempotency key and a status check before writing Firestore. Live in prod since today.

@kodjima33 kodjima33 closed this Nov 14, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Hey @Dimank92 👋

Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request.

After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:

  • Project standards — Ensuring consistency across the codebase
  • User needs — Making sure changes align with what our users need
  • Code best practices — Maintaining code quality and maintainability
  • Project direction — Keeping aligned with our product principles and locked invariants

Before your next PR, please skim:

  • PRODUCT.md — product north star
  • Product invariants — locked rules (shared chat, memory tiers, agent control plane, integrations, brand)

If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing.

Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out.

Thank you for being part of the Omi community!

Git-on-my-level pushed a commit to Git-on-my-level/omi that referenced this pull request Nov 14, 2026
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, BasedHardware#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 BasedHardware#23317 by @Dimank92 onto current main, with the review fixes.

Failure-Class: new

Co-authored-by: Dimank92 <[email protected]>
@Dimank92
Dimank92 deleted the fix/trialing-subscription-interval-switch branch November 27, 2026 15:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) needs-maintainer-review Needs a human maintainer to sign off before merge positive-signal Automation verified a genuine fix/quality contribution

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

3 participants