Repository navigation
fix(payment): reject declined cross-plan proration without mutating paid subscription (#23301) - #23416
Conversation
|
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.
Tests ( 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:
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 |
|
Thanks for the review @Git-on-my-level! I updated the PR description so the Verification list matches the exact 4 test functions in Ready for human maintainer sign-off whenever convenient ( |
…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]>
…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]>
…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.
…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.
Fixes #23301
Failure-Class: none
Summary
When an active paid subscriber switches across plans (e.g. Operator -> Architect) in
upgrade_subscription_endpoint,stripe.Subscription.modifypreviously ran withproration_behavior='always_invoice'and Stripe's defaultpayment_behavior='allow_incomplete'. When the immediate proration invoice charge was declined:open, and transitioned the subscription tostatus='past_due'._build_subscription_from_stripe_object(updated_sub)projectedstatus='past_due'toPlanType.basic(SubscriptionStatus.inactive), persisted that downgraded state to Firestore, and returned"plan": "upgraded"to the caller.Fix
'payment_behavior': 'error_if_incomplete'inmodify_paramsfor cross-planstripe.Subscription.modifycalls so Stripe rolls back the subscription item price update and raisesCardErrorwhenever the immediate proration invoice charge fails.stripe.error.CardErrorinupgrade_subscription_endpointand return HTTP402 Payment Requiredvia_stripe_client_error_detail(e, ...)without mutating Firestore.updated_subremains in('active', 'trialing')with nopending_updatebefore calling_build_subscription_from_stripe_objector writing to Firestore (raising HTTP402if incomplete/past_due).Verification
backend/tests/unit/test_payment_declined_proration.pycovering:test_upgrade_sets_error_if_incomplete_payment_behavior_in_sourcetest_cross_plan_upgrade_passes_error_if_incomplete_to_stripe_modifytest_declined_proration_card_error_returns_402_and_preserves_paid_plantest_declined_proration_past_due_snapshot_returns_402_and_never_projects_basicpytest 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)python3 backend/scripts/check_module_stub_pollution.py(0 violations)