Skip to content

fix(payment): reject declined cross-plan proration without mutating paid subscription (#23301) - #23416

Merged
kodjima33 merged 1 commit into
BasedHardware:mainfrom
martiindev710:fix/payment-declined-proration-23301
Oct 24, 2026
Merged

kodjima33 merged 1 commit into
BasedHardware:mainfrom
martiindev710:fix/payment-declined-proration-23301

Conversation

@martiindev710

@martiindev710 martiindev710 commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #23301

Failure-Class: none

Summary

When an active paid subscriber switches across plans (e.g. Operator -> Architect) in upgrade_subscription_endpoint, stripe.Subscription.modify previously ran with proration_behavior='always_invoice' and Stripe's default payment_behavior='allow_incomplete'. When the immediate proration invoice charge was declined:

  1. Stripe still moved the subscription item onto the new price, left the proration invoice open, and transitioned the subscription to status='past_due'.
  2. _build_subscription_from_stripe_object(updated_sub) projected status='past_due' to PlanType.basic (SubscriptionStatus.inactive), persisted that downgraded state to Firestore, and returned "plan": "upgraded" to the caller.

Fix

  1. Pass 'payment_behavior': 'error_if_incomplete' in modify_params for cross-plan stripe.Subscription.modify calls so Stripe rolls back the subscription item price update and raises CardError whenever the immediate proration invoice charge fails.
  2. Catch stripe.error.CardError in upgrade_subscription_endpoint and return HTTP 402 Payment Required via _stripe_client_error_detail(e, ...) without mutating Firestore.
  3. Add a defensive post-modify guard checking that updated_sub remains in ('active', 'trialing') with no pending_update before calling _build_subscription_from_stripe_object or writing to Firestore (raising HTTP 402 if incomplete/past_due).

Verification

  • Added backend/tests/unit/test_payment_declined_proration.py covering:
    • test_upgrade_sets_error_if_incomplete_payment_behavior_in_source
    • test_cross_plan_upgrade_passes_error_if_incomplete_to_stripe_modify
    • test_declined_proration_card_error_returns_402_and_preserves_paid_plan
    • test_declined_proration_past_due_snapshot_returns_402_and_never_projects_basic
  • Ran pytest tests/unit/test_payment_declined_proration.py tests/unit/test_payment_promotion_codes.py tests/unit/test_stripe_webhook_behavioral.py tests/unit/test_subscription_state_machine.py (90 passed)
  • Ran python3 backend/scripts/check_module_stub_pollution.py (0 violations)

@Git-on-my-level

Copy link
Copy Markdown
Member

Verdict: this fix is correct and well-targeted — it addresses the exact failure mode in #23301, and I verified it against the code and ran the new tests.

backend/routers/payment.py (+19/−1):

  • :789 — adding payment_behavior='error_if_incomplete' next to proration_behavior='always_invoice' is the right Stripe semantics here: a declined proration charge now rolls back the price change and raises CardError instead of leaving the item on the new price with the subscription past_due. I confirmed this is the only always_invoice Subscription.modify site in the file — the same-plan interval path goes through SubscriptionSchedule, and the other modify calls (:377, :949, :1120) are cancel/metadata-only — so the fix covers the whole affected surface.
  • :797-804 — the post-modify guard closes the second half of the bug. _build_subscription_from_stripe_object (:251→:275) projects any non-active/trialing status to Basic/Free, and previously that projected snapshot was written straight to Firestore. Rejecting with 402 before the projection prevents the paid-plan overwrite even if Stripe ever returns a past_due/pending_update snapshot.
  • :885-892 — the CardError handler is correctly ordered (after HTTPException, before InvalidRequestError/generic Exception) and routes through _stripe_client_error_detail, which only surfaces Stripe's user_message — no internal IDs leak into the response.

Tests (backend/tests/unit/test_payment_declined_proration.py): all 4 pass. I also ran them alongside the promotion-code and cancel-endpoint suites — the sys.modules restore fixture holds and no stubs leak into neighbors. (Two failures in test_payment_cancel_subscription_http_exception.py appear when certain pre-existing suites run together, but they reproduce identically on main without this PR — pre-existing test-isolation friction, not a regression here.)

USER IMPACT: subscribers whose card is declined during a plan change now stay on the plan they already paid for and see a clear "payment could not be completed" message, instead of being silently dropped to Free.

Two small follow-ups:

  • The PR description lists test_same_plan_interval_change_keeps_create_prorations_without_error_if_incomplete, which doesn't exist in the test file — please update the description so the verification claims match the diff.
  • The issue also mentions the subscription.updated webhook's past_due downgrade. This PR eliminates the plan-change trigger for it, but ordinary renewal-failure downgrades are unchanged — worth a separate issue if that path also needs grace handling.

Because this changes billing behavior on a customer-impacting payment flow, it needs a human maintainer's sign-off 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 23, 2026
@martiindev710

Copy link
Copy Markdown
Contributor Author

Thanks for the review @Git-on-my-level! I updated the PR description so the Verification list matches the exact 4 test functions in backend/tests/unit/test_payment_declined_proration.py (test_upgrade_sets_error_if_incomplete_payment_behavior_in_source, test_cross_plan_upgrade_passes_error_if_incomplete_to_stripe_modify, test_declined_proration_card_error_returns_402_and_preserves_paid_plan, and test_declined_proration_past_due_snapshot_returns_402_and_never_projects_basic).

Ready for human maintainer sign-off whenever convenient (need human response).

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fix(payment) 5/5: clear root cause (Stripe decline mutates paid sub to past_due), fixes #23301, scoped, test added, CI green, not already on main.

@kodjima33
kodjima33 merged commit 612b018 into BasedHardware:main Oct 24, 2026
1 check passed
Git-on-my-level added a commit that referenced this pull request Oct 24, 2026
…e CPU guard

test_payment_declined_proration lands 1.25-1.66s CPU per test on CI
runners (the subscription/Stripe module graph amortizes into the calls
under file isolation). The file never ran on main: every shard died at
the #23433 pyright errors first, so the guard had not flagged it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Oct 24, 2026
…c and legacy paths (#23512)

* fix(notes): stop persisting the 🧠 unset emoji default on deterministic and legacy paths

#23389 repaired the v2 NotesOutput boundary, but every other writer that
never received an emoji still persisted the Structured schema default 🧠:
the sync-intake deterministic minimum, the short-clip quiet minimum
(emoji=''), the media minimum, and the legacy StructuredExtraction /
AgentNotesSubmission submissions. A stored default is indistinguishable
from a chosen one, so users saw a deliberate brain badge no code chose.

- Move the category fallback (DEFAULT_EMOJI/CATEGORY_EMOJI/fallback_emoji)
  to models/conversation_emoji.py and map category `other` to the neutral
  💬, so every CategoryEnum member resolves to a non-brain emoji.
- Deterministic/minimum builders set the category fallback explicitly;
  quiet_minimum no longer blanks the emoji (blank renders as the client's
  random pick, which includes 🧠).
- StructuredExtraction/RichStructuredExtraction.to_structured apply the
  fallback, covering AgentNotesSubmission and EpisodeStructuredExtraction.
- The Structured model's own default (SDK + backend mirror), the share
  projection, and the client display projection change 🧠 → 💬, so a
  forgotten field lands on the neutral emoji. The deliberate
  relevance-discard placeholder (🧠/🎉 on discarded rows) is untouched.
- The app decodes a missing or blank emoji as 💬 and renders an empty
  emoji deterministically instead of a random pick containing 🧠; the
  app-client OpenAPI spec and generated dart wire schemas are regenerated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(retrieval): unblock the pyright lane and the isolation fallback #23433 left red

#23433 merged with all six backend unit shards failing, and every later
main push has failed the same way, so no PR can go green. This carries the
minimal repair; revert if the owning change lands its own fix.

- The defensive None/junk guards in result_bounds and omi_tools trip
  pyright's reportUnnecessary* rules. Keep the runtime hardening exactly
  as merged and suppress per-line with the codebase's established
  "# type: ignore[...] # defensive" idiom, as memories.py already does.
- generate_2025's seg.end None filter gets the same treatment instead of
  trusting the required-float annotation.
- The spec_from_file_location fallbacks did not register the module in
  sys.modules before exec, so model_text's dataclasses crashed with
  AttributeError under test_omi_tools_resilience's stub_modules harness
  (the test never ran in CI: the shards died at pyright first). Register
  before exec, matching the load_module_fresh recipe.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(payment): allowlist #23416's declined-proration cases against the CPU guard

test_payment_declined_proration lands 1.25-1.66s CPU per test on CI
runners (the subscription/Stripe module graph amortizes into the calls
under file isolation). The file never ran on main: every shard died at
the #23433 pyright errors first, so the guard had not flagged it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Oct 24, 2026
…12b018

test_payment_declined_proration.py landed on main by direct train push
(#23416) without the fast-unit CPU guard measuring it. On this PR's
shards it costs 1.29-1.95s CPU per 402-snapshot test vs the 1.00s fail
limit (runs 40118527240 and 40115474313, shard 6): the first test
amortizes the payment router/app import graph under file isolation and
the snapshots build full subscription/stripe objects. Assertions pass;
entries follow the allowlist's established boundary shape.
Git-on-my-level added a commit that referenced this pull request Oct 24, 2026
…23504)

* feat(subscriptions): new buyers get Omi Pro only on mobile and web

David's 2026-10-24 ruling: a buyer with no current paid subscription is
offered only unlimited_v2 (Omi Pro) on mobile, web, and unknown/missing
platforms, in the v1 catalog, the v2 ladder storefront (404) and checkout
enforcement. Desktop platforms and existing subscribers are unchanged.
Kill switch NEW_BUYER_SINGLE_PLAN_ENABLED (default on); rejections count
in omi_new_buyer_checkout_rejected_total{reason,plan}.

* chore(app): changelog none fragment for single-plan test-only app changes

* fix(subscriptions): zero-init rejection counter via function to satisfy pyright

* chore(api): regenerate app-client OpenAPI for the checkout platform header

* chore(desktop): regenerate Swift API DTOs for the checkout platform header

* chore(api): regenerate TS/Windows API clients for the checkout platform header

* fix(subscriptions): address review on new-buyer single-plan rule

Luna REQUEST-CHANGES follow-ups on #23504:

- P1: catalog filtering now keys off the period-valid plan lookup
  (get_user_valid_subscription) like checkout, so a lapsed
  Operator/Architect record on mobile is offered Omi Pro instead of
  their expired desktop SKU (backend/routers/payment.py).
- P1: a missing or unknown X-App-Platform keeps the pre-ruling
  behaviour everywhere (catalog, v2 storefront, checkout); the
  restriction follows the explicit first-party values (ios/android/web).
  Every desktop build ever shipped stamps the header on every request
  (macOS since d51d101, Windows since its platform-identity
  hardening), and the other desktop-identifying headers are all newer,
  so no reliable header-less desktop signal exists; desktop
  compatibility outranks closing the direct-API gap. Allowed legacy
  checkouts for those callers count in
  omi_new_buyer_checkout_rejected_total{reason="unknown_platform_allowed"}.
- P2: only a current recurring personal subscription exempts a buyer
  from the guard; an organization grant (pi_ PaymentIntent or no
  subscription id) is a new buyer for checkout.
- P2: /v2/payments/plans serves a new buyer on mobile/web a
  single-tier Omi Pro sheet (build_single_plan_storefront) instead of
  404, so the web plans panel never shows a dead 'Couldn't load plans'
  state; the web client ranks unlimited_v2 on its ladder so the card
  can check out. Golden fixture + web/backend tests included.
- P3: the trial test now exercises a configured Omi Pro monthly price
  with trial_days=7 through the real guard (not stubbed).

Copy: cta get_unlimited added to every storefront locale (locale
completeness contract). Docs and feature-flag registry updated.

* fix(typecheck): unblock CI — repair 5 pyright errors from main d39cae3/ac7939ac

origin/main moved under this PR and its merge ref now fails the
per-shard backend typecheck (scripts/typecheck.sh runs in every
shard when changed paths touch the typed boundary; the offending
commits landed on main by direct train push, so PR CI never saw
them). All five are annotation/guard mismatches; runtime behavior
is preserved:

- omi_tools.get_omi_product_info_tool: drop the redundant
  'query is None or' before the isinstance guard (isinstance
  already rejects None), keeping the non-str runtime defense.
- result_bounds.cap_items_for_llm: annotate items as
  List[T] | None so the existing None guard is type-honest.
- result_bounds.bounded_result: annotate result as object (the
  body already coerces None/non-str defensively) and bind the
  coerced value to a fresh local so narrowing survives to the
  return.
- generate_2025._compute_conversation_duration: filter falsy
  seg.end instead of 'is not None' (the model types end as
  float); zero ends were already irrelevant to the max_end > 0
  check.

Verified: pyright -p pyrightconfig.json -> 0 errors;
test_wrapped_* and test_goals_wrapped_firmware_hardening pass
through backend/test.sh. Note: test_omi_tools_resilience.py
errors at setup on pristine main content too (its importlib
fallback never registers sys.modules, so model_text's dataclass
lookup crashes) — pre-existing on main, not touched here.

* fix(retrieval): register fallback-loaded modules so dataclasses resolve — unblock CI

test_omi_tools_resilience.py (from main d39cae3) errors at setup in a
fresh interpreter: omi_tools' and result_bounds' importlib fallbacks
exec the modules without registering them in sys.modules, and
model_text.py uses 'from __future__ import annotations' with
@DataClass, whose string-annotation resolution does
sys.modules[cls.__module__].__dict__ -> AttributeError on None.

Register each fallback module in sys.modules before exec_module, as
importlib requires. The normal (non-fallback) import path is
unchanged. test_omi_tools_resilience.py (6 tests) and
test_retrieval_result_bounds.py (12) now pass through backend/test.sh;
pyright stays at 0 errors.

* test(backend): grandfather declined-proration CPU overruns from main 612b018

test_payment_declined_proration.py landed on main by direct train push
(#23416) without the fast-unit CPU guard measuring it. On this PR's
shards it costs 1.29-1.95s CPU per 402-snapshot test vs the 1.00s fail
limit (runs 40118527240 and 40115474313, shard 6): the first test
amortizes the payment router/app import graph under file isolation and
the snapshots build full subscription/stripe objects. Assertions pass;
entries follow the allowlist's established boundary shape.

* fix(observability): literal reasons at every guard-metric labels() call site

test_reason_label_enums (the reason-label contract) rejects
.labels(reason=<variable>): literals are closed by construction, a
variable needs a reviewed CLOSED_HELPERS helper or debt. The guard
recorder took the reason as a parameter and the zero-init loop iterated
the reasons tuple; both now pass literals at each call site
(record_new_buyer_checkout_rejection / record_new_buyer_unknown_platform_allowance
own their literal; zero-init spells both reasons per plan). No label
values change.

* fix(storefront): single-plan sheet carries a Free current card — client golden contracts

The Flutter storefront contract pins that every golden fixture has a
current tier with no bullets and an exact fixture count; the app and
backend fixture directories must also match byte for byte. The Omi Pro
sheet now appends the Free current card (same shape as the ladder
sheet's basic row: no bullets, no CTA, the $0 price), the golden is
regenerated and mirrored to app/test/fixtures, and the app fixture
count pin moves 16 -> 17.
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.

A declined proration on a plan change switches the plan anyway and drops a paid subscriber to Free

3 participants