Skip to content

fix(billing): prevent checkout-first duplicate subscriptions - #22552

Merged
aryanorastar merged 13 commits into
mainfrom
fix/21869-checkout-first-protection
Oct 23, 2026
Merged

aryanorastar merged 13 commits into
mainfrom
fix/21869-checkout-first-protection

Conversation

@aryanorastar

@aryanorastar aryanorastar commented Oct 19, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Refs #21869. Follow-up to #22193: protect users who go directly to checkout before subscription-read reconciliation has healed their stored paid plan.

  • Extend the existing shared checkout/reactivation boundary to verify the raw stored Stripe subscription ID even when the effective local plan is Free and the root customer ID is absent.
  • Keep same-plan/interval pending-cancellation reactivation. Other nonterminal subscriptions return HTTP 409; unverified Stripe state or failed reactivation returns retryable HTTP 503, never a second Checkout session.
  • Allow confirmed terminal subscriptions and definitive retrieve-only resource_missing/404; preserve new-buyer, referral and one-time PaymentIntent-grant behavior.
  • Keep storefront reads, plan-change/upgrade rails, customer identity and blocked-path entitlements unchanged. Log error types only, not Stripe response bodies.

Root cause and durable prevention

The validity projection can discard a stale paid record's Stripe ID when presenting it as Basic. Customer-based eligibility cannot recover it when the root customer ID is missing. The existing reactivation helper already retrieves the raw stored ID, but previously returned None for active subscriptions and swallowed provider/modify/persistence errors, allowing fresh checkout.

The shared primitive is that existing boundary: None now means no existing recurring subscription was found or the stored one is confirmed ended/missing, not simply "reactivation did not happen." Regression tests execute the real HTTP route, real eligibility and actual Checkout builder with fake persistence and Stripe SDK objects, asserting no billing creation on blocked requests. No additional standalone checker or storefront mutation was introduced.

Failure-Class: new

New class: FC-checkout-falls-through-unverified-subscription.

Verification

  • Regression reproduced before the fix: active/trialing/past_due subscriptions incorrectly returned HTTP 200 and reached new Checkout creation.

  • 266 targeted tests passed in isolated per-file pytest processes: 35 new checkout-first HTTP regressions plus 231 existing payment, eligibility, subscription healing/state/plan, terminal-status and webhook tests.

  • All 34 selected make preflight checks passed on commit 0e5f5f642c3ac64014b58b84ccf7e13a4bd80683. The history-dependent failure-class recurrence audit explicitly skips on this shallow clone; CI with full history remains authoritative for that audit. Catalog consistency and async-blocker scan passed; PR metadata/failure-class validation passed.

  • The remaining bounded push checks passed, including the two changed test files (55 tests), runtime-source closure, released app-client OpenAPI compatibility/export, generated Dart/TypeScript/Swift model checks and pinned formatting. Only the documented local skips below were used. GitHub CI is not claimed green.

  • Local uvicorn/curl smoke passed with the real payment router, overridden auth, and mocked provider/persistence boundaries. No real Stripe or Firestore writes. Example request:

    curl -sS -X POST http://127.0.0.1:58550/v1/payments/checkout-session \
      -H 'Content-Type: application/json' -d '{"price_id":"price_checkout_current"}'
    Fixture HTTP Fresh Checkout creates Existing reactivations
    Active subscription, missing root customer ID 409 0 0
    Stripe unavailable 503 0 0
    Confirmed ended subscription 200 1 0
    Same-plan pending cancellation 200 0 1

    Local fixture-backed server stopped after smoke testing.

The CI-selected 52-file run passed: 1,770 tests passed, with 37 tests deselected by the normal not integration and not slow expression (two files entirely deselected). The 34 subscription-restructure tests also passed separately without that marker filter in the targeted run above. An initial local run hit the stricter default 0.30-second CPU guard on the unchanged generated-compute inventory test; the verification run uses CI's existing 1.0-second budget, without changing any repository setting.

Reproduction commands (from backend/, with a repository-relative changed-path list):

.venv/bin/python -m pytest tests/unit/test_checkout_first_subscription.py -q
.venv/bin/python scripts/select_backend_unit_tests.py \
  --changed-files /private/tmp/omi-21869-checkout-changed.txt \
  --output /private/tmp/omi-21869-checkout-tests.txt
BACKEND_UNIT_TEST_FILE_LIST=/private/tmp/omi-21869-checkout-tests.txt \
  BACKEND_PYTEST_WORKERS=4 BACKEND_FAST_UNIT_FAIL_SECONDS=1.0 \
  PYTHON=.venv/bin/python bash test.sh
.venv/bin/python scripts/generate_plan_catalog.py --check --base-ref origin/main
.venv/bin/python scripts/scan_async_blockers.py --dirs routers utils

Validation on current main (2026-10-20)

This PR no longer bundles #22558 or #22595. They were merged in earlier only to get backend CI green; main's backend CI is green on its own now, so those files match main here and stay in their own PRs. The diff against main is the checkout-first protection alone: routers/payment.py, its two test files, checkout-admission.md and the failure-class record.

  • The 20-file billing selection (checkout-first, promotion codes, payment, Stripe ledger and subscription tests) passes under test.sh: 279 passed.
  • routers/payment.py passes the pinned type check (0 errors).
  • The four local fixture-backed curl admission outcomes described above are unchanged by this rebase; they were not re-run.

Client handling of the new 409

Checkout's new 409 means the account already has a subscription. Flutter, macOS, web and Windows had mapped every 409 to "Resubscribe first to change plans.", which is only the upgrade route's pending-cancellation refusal. Checkout errors now show the existing-subscription reason ("You already have a subscription. Manage your existing subscription instead of starting a new checkout."); the upgrade route keeps "Resubscribe first". The upgrade-only helpers are renamed (isUpgradePendingCancelConflict, SubscriptionPlanPresentation.upgradeErrorMessage, web purchaseErrorMessage(error, route), Windows startCheckout returning existing_subscription) so a checkout response can't be misclassified again.

UI-Evidence: none

Only which error sentence appears changes; no layout or control changes. Reproducing it live needs a real account with an existing subscription. Covered instead by Flutter (plans_sheet_cancel_pending_test.dart, paywall_cancel_pending_test.dart), macOS (SubscriptionPlanPresentationTests), web (PlansSheet.cancelPending.test.tsx, cancelPending.test.ts) and Windows (billing.test.ts, PlanUsageTab.cancelPending.test.tsx) tests.

Architecture and release scope

Architecture and implementation/release checklist: backend/docs/checkout-admission.md.

Line-Count-Exception: backend/routers/payment.py | 1789 -> 1809 | Keep this 20-line safety expansion in the existing checkout/reactivation boundary; extracting unrelated payment routes would broaden this billing fix and its regression surface.

This PR does not deploy, flip flags, repair customer data, cancel subscriptions, deduplicate historical purchases or serialize concurrent first-time checkout requests. Accounts missing both stored subscription ID and customer ID remain outside this bounded repair. Keep #21869 open pending separately authorized rollout and affected-account verification.

GCP deployment verification is not claimed. Prior browser attempts could not list Cloud Run resources, and no usable ADC/read-only profile was found then. This code-only task performs no deployment or serving-revision verification.

Product invariants affected

none

View guided diff Turn on auto-fix

2026-10-23 maintainer review and merge gates

Ready for code review at Aryan's request; pushed 5d2f03f. The checkout-vs-upgrade mapping and earlier stacked-test reversals have already been repaired on this head. Fixed the remaining Flutter conflict-message localization using the existing l10n tool across every current locale (49 at verification). Both purchase surfaces select the localized string from checkout HTTP 409; the upgrade pending-cancellation message is unchanged. Fourteen focused Dart tests pass, including English, German and Arabic on both surfaces; the two isolated backend checkout/promotion files pass 55 tests. Localization checks and all 60 selected preflight checks pass. The push used the documented PRE_PUSH_SKIP_DESKTOP_SWIFT=1 hatch for an unchanged native subtree under local memory pressure; git verified no macOS source changes since the preceding remote head. Exact-head CI remains authoritative for that compile. The prospective merge also preserves the five previously repaired regression files. No actual Stripe/Firestore writes or customer repair were performed. Stripe sandbox pass on 5d2f03f (2026-10-23, test mode only): the real checkout and customer-portal routes ran against a Stripe sandbox with real subscriptions, in-memory Firestore rows only. 10/10 scenarios behaved as specified: new buyer gets a session; an active subscription is refused with no session created (400 from the existing eligibility check when the customer ID is known, the new 409 when it was lost locally); pending cancellation on the same plan reactivates without checkout, including when the local row is missing; a different plan stays blocked; canceled and deleted subscription IDs get a fresh session; unverifiable Stripe state returns 503 with no session; the billing portal opens. Exact-head CI is green. Installed-client check (2026-10-23): the Flutter dev build of 5d2f03f on the iOS Simulator, signed in as the synthetic local-dev user against a local backend using the same Stripe sandbox, showed "You already have a subscription. Manage your current subscription instead of starting a new one." for a stale record whose Stripe subscription was incomplete (the read-heal only promotes active/trialing, so this is the state that reaches checkout from the app). No Checkout Session was created. Still required before merge: maintainer review.

The first exact-head Linux helper packaging attempt failed while downloading Ubuntu runtime packages: the dependency-install step timed out at five minutes, before helper smoke execution. No application error was shown by that failure. Re-ran only that failed job once; the retry is not counted as a pass until it completes. No pipeline timeout, dependency pin or security gate was weakened.

Refs #21869. Verify the raw stored Stripe ID at checkout admission before any fresh subscription session. Preserve same-plan reactivation and confirmed-ended/new-buyer flows; fail closed on uncertainty.

Failure-Class: new
@aryanorastar
aryanorastar marked this pull request as ready for review October 19, 2026 16:40
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-23T14:15:33.766266Z 5d2f03f Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@cubic-dev-ai

cubic-dev-ai Bot commented Oct 19, 2026

Copy link
Copy Markdown

Auto-fix isn't included in your plan ↗

Upgrade to Team

aryanorastar added a commit that referenced this pull request Oct 19, 2026
Keep denied-provider fallback coverage explicit and add current hosted streaming selection cases. Preserve prerecorded/PTT restrictions, retry behavior and all serving/deployment configuration. Refs #22552. Failure-Class: none
aryanorastar added a commit that referenced this pull request Oct 19, 2026
Run all six Joan privacy cases through their real URL instead of the unrelated renamed person handler. Keep fresh from-segments router/auth construction in fixture setup without changing CPU limits or request assertions. Refs #22552. Failure-Class: none
Git-on-my-level added a commit that referenced this pull request Oct 19, 2026
* fix(backend): scope STT cap dispatch to cohorts and lanes

* fix(backend): fence scoped budget shortcuts and backlog refunds

* fix(backend): retain claim history and restore listen bypasses

* fix(backend): default cap scope to live and fence batch admission

* test(backend): make legacy cap regression scope explicit

* test(backend): use explicit cap scope in legacy review suites

* fix(sync): preserve the scoped recovery triple-return signature

* docs(backend): align cap lane catalog with live-only policy

* fix(backend): type preview validation boundaries as untrusted inputs

* fix(tests): align gateway and batch fixtures with current APIs

Replace retired JIT-budget imports with current request-ID behavioral coverage. Refresh the audio-copy fixture's vector cleanup dependency without changing production code or test gates. Refs #22552. Failure-Class: none

* fix(tests): repair transcript processor and real tool contracts

Assert CLIENT_FINALIZE in processor fakes. Replace collection-time package mutation with real tool imports, current async invocation and valid caller context; retain all sanitization assertions. Refs #22552. Failure-Class: none

* fix(tests): bind Joan access guards to the registered followup route

Failure-Class: none

---------

Co-authored-by: Aryan <[email protected]>
@Git-on-my-level

Copy link
Copy Markdown
Member

The production change here is correct and nicely scoped — the fail-closed checkout admission in _try_reactivate_subscription genuinely closes the #21869 duplicate-subscription hole — and formal merge sign-off is left to a human maintainer since this changes billing admission behavior.

Correctness findings:

  • backend/routers/payment.py — the new admission logic is right in every branch I traced: the pi_ one-time-grant guard runs before retrieve (retrieving a PaymentIntent as a Subscription would always error); terminal statuses via stripe_utils.TERMINAL_SUBSCRIPTION_STATUSES allow fresh checkout; resource_missing + HTTP 404 from retrieve-only is the sole definitive-absence exception; every other nonterminal state — including unknown future Stripe statuses — raises 409; and the old except Exception that silently swallowed provider errors now becomes a retryable 503 that logs only the exception type. The record_fallback(..., 'exhausted') telemetry is preserved on the no-subscription path. One subtlety worth knowing: after a successful Subscription.modify, a local persistence failure now surfaces as 503 even though cancellation was already removed in Stripe — safe (the retry is idempotent), just a new response shape.
  • backend/tests/unit/test_checkout_first_subscription.py — the strongest part of the PR: real HTTP route, real eligibility path, Stripe SDK objects, and assertions that blocked paths create no Checkout session, write no entitlements, and leak no provider bodies (including the modify-time resource_missing case, which the doc correctly says must not fall through).
  • backend/utils/sync/pipeline.py — _record_sync_segment_exception is a verbatim extraction of the old inline handler; destructive-operation re-raise stays in the coordinator and turnstile completion in finally, and the new parametrized tests pin retry labels, fence propagation, and bounded logging.
  • backend/database/desktop_previews.py — signatures widened to object with cast applied only after isinstance guards; runtime behavior unchanged, and the new tests confirm untyped payloads reject before any Firestore access.
  • Commits 4/6/7/8 (request-context, batch-upload, external-tools, from-segments, Deepgram/STT, Joan tombstone tests) are test-suite repairs aligning tests with current APIs — no production code touched.
  • backend/docs/checkout-admission.md and the new failure-class JSON match the implemented behavior, including the honest non-goals checklist.

Security: fail-closed on uncertainty, no provider bodies in logs or responses, no secrets introduced — a positive change.
UX: users with a stale-but-nonterminal stored subscription now get a clear 409 ("manage your existing subscription") or a retryable 503 instead of silently being double-subscribed — that is the point of the fix, but see action item 1 below.
Blast radius: the shared /v1/payments/checkout-session route for all clients; if the 409/503 paths misfire, the failure mode is a blocked checkout (safe), not a duplicate charge.

USER IMPACT: A user whose account still has a live or unverified Stripe subscription can no longer start a second checkout that would double-bill them — they'll be told to manage their existing subscription or retry.

What I'd still want:

  1. Confirm the apps/clients calling POST /v1/payments/checkout-session render the new 409/503 detail messages gracefully (this path previously almost never returned them).
  2. A maintainer pass on the intended 409-for-plan-change semantics: users trying to switch plans at checkout are now directed to the upgrade rail — correct per the docs, but it is a product-behavior decision worth explicit sign-off.
  3. If the test repairs in commits 4/6/7/8 were fixing failures that also exist on main, consider landing them separately so main gets the green suite too.

Billing checkout-admission semantics on the payments surface need maintainer sign-off before merge; leaving this for human maintainer review.


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 needs-maintainer-review Needs a human maintainer to sign off before merge backend Backend Task (python) labels Oct 19, 2026
…rst-protection

# Conflicts:
#	backend/database/desktop_previews.py
#	backend/tests/unit/test_users_joan_followup_tombstone_guard.py
#	backend/utils/sync/pipeline.py
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Pushed 9d0bee2: merged current main (8edd56d). The three conflicts came from this PR's prerequisite merges (#22558, #22595), so they're resolved the same way as on those PRs.

@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.

Backend payment/billing change (checkout-first duplicate-subscription guard) explicitly labelled needs-maintainer-review; diff also bundles other PRs' test files (stacked branch). High financial-impact surface -> approve only, flagging for Nik's direct sign-off rather than autonomous merge despite otherwise solid root-cause/test coverage.

…sites

Main's backend CI is green on its own, so the preview/sync and backend
test repairs merged in for validation (#22558, #22595) are no longer
needed here; those files now match main and remain in their own PRs.
This branch's diff against main is the checkout-first protection only.

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

Copy link
Copy Markdown
Collaborator Author

Pushed f079c67: merged current main and unstacked this PR. Its diff against main is now the checkout-first protection only.

  • Why: this branch had merged in test(backend): regression coverage for preview validation and sync segment outcomes #22558 (preview/sync typing) and test(backend): decouple STT and from-segments tests from deployment state #22595 (backend test repairs) to get backend CI green, so the diff carried their test files and a docs note. Main's backend CI is green on its own now, so those six files (test_database_desktop_previews_resilience.py, test_developer_from_segments_idempotency.py, test_modulate_stt.py, test_streaming_deepgram_backoff.py, test_sync_capture_pipeline.py, listen_pusher_pipeline.mdx) are reset to main and stay in their own PRs.
  • Remaining diff (5 files): backend/routers/payment.py, test_checkout_first_subscription.py, test_payment_promotion_codes.py, backend/docs/checkout-admission.md, and the FC-checkout-falls-through-unverified-subscription record. The billing change itself is untouched.
  • Checks on this head: 20-file billing selection under test.sh, 279 passed. routers/payment.py pinned type check, 0 errors. make preflight: 34 checks passed.
  • Description: the prerequisite/recheck section is replaced with validation on current main, and the pipeline.py line-count exception is dropped since this PR no longer touches that file. checkout-admission.md's checklist is updated the same way.

MichaelC001 pushed a commit to MichaelC001/omi that referenced this pull request Oct 21, 2026
Accept unknown preview inputs at the validation boundary while preserving runtime guards. Extract sync segment failure reporting without changing retry, custody, fence or cleanup behavior.

Refs BasedHardware#22552. Failure-Class: none
MichaelC001 pushed a commit to MichaelC001/omi that referenced this pull request Oct 21, 2026
Replace retired JIT-budget imports with current request-ID behavioral coverage. Refresh the audio-copy fixture's vector cleanup dependency without changing production code or test gates. Refs BasedHardware#22552. Failure-Class: none
MichaelC001 pushed a commit to MichaelC001/omi that referenced this pull request Oct 21, 2026
Assert CLIENT_FINALIZE in processor fakes. Replace collection-time package mutation with real tool imports, current async invocation and valid caller context; retain all sanitization assertions. Refs BasedHardware#22552. Failure-Class: none
aryanorastar and others added 3 commits October 21, 2026 08:38
…from upgrade's

Merging main kept this branch's earlier reverts of #22558 and #22595's
test files, which would have undone their now-merged coverage; those
files now match main. The branch's diff is the checkout protection plus
the client fix below.

The new checkout 409 means an existing subscription, but Flutter, macOS,
web and Windows mapped every 409 to "Resubscribe first", which is only
the upgrade route's pending-cancellation refusal. Checkout errors now
show the existing-subscription reason; the upgrade mapping is renamed so
it cannot classify checkout responses again.

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

Copy link
Copy Markdown
Collaborator Author

Pushed 06c51fa through 62c6a59: both review points fixed.

  • Merged test coverage preserved: merging current main kept this branch's earlier reverts of test(backend): regression coverage for preview validation and sync segment outcomes #22558's and test(backend): decouple STT and from-segments tests from deployment state #22595's test files. Now that both are merged, those reverts would have undone their coverage. The five files (test_database_desktop_previews_resilience.py, test_developer_from_segments_idempotency.py, test_modulate_stt.py, test_streaming_deepgram_backoff.py, test_sync_capture_pipeline.py) now match main exactly, and none of them is in this PR's diff.
  • Clients no longer read the checkout 409 as "Resubscribe first": checkout's new 409 means an existing subscription, but every client mapped any 409 to the upgrade route's pending-cancellation copy. Checkout errors now show the existing-subscription reason, and only an upgrade 409 says "Resubscribe first".
    • Flutter: plans_sheet.dart and paywall_checkout.dart show the server detail for checkout errors. The helper is now isUpgradePendingCancelConflict and is used only on the upgrade path.
    • macOS: SubscriptionPlanPresentation.checkoutErrorMessage / upgradeErrorMessage replace the shared mapper.
    • Web: purchaseErrorMessage(error, route); SettingsPage and PlansSheet record which route they called.
    • Windows: startCheckout returns blocked for an upgrade 409 and a new existing_subscription for a checkout 409; PlanUsageTab shows each.
  • Tests: the existing Flutter and web tests that asserted "a checkout 409 says resubscribe first" pinned the bug; they now assert the existing-subscription message. New coverage: Flutter paywall checkout 409; macOS presentation mapping; web route-aware helper; Windows startCheckout route classification and both tab outcomes.
  • Checks: Flutter paywall/plans/cancel-pending 61 passed; macOS SubscriptionPlanPresentationTests 5 passed (xcrun); web 39 passed, typecheck clean (Bun); Windows billing and PlanUsageTab 78 passed, web typecheck clean (pnpm); backend billing selection 279 passed earlier on this change, unchanged here. make preflight: 59 checks passed.
  • Also: UI-Evidence: none (only the error sentence changes), changelog fragments for mobile, macOS and Windows, and a client checklist line in checkout-admission.md.

@cubic-dev-ai

cubic-dev-ai Bot commented Oct 21, 2026

Copy link
Copy Markdown

Auto-fix isn't included in your plan ↗

Upgrade to Team

@Git-on-my-level

Copy link
Copy Markdown
Member

The production change here is correct and nicely scoped; nothing blocking from me — the failing checks trace to tests this PR doesn't touch.

  • backend/routers/payment.py _try_reactivate_subscription: verified the fail-closed logic — only a retrieve-only resource_missing/404 or a confirmed terminal status (canceled/incomplete_expired, via TERMINAL_SUBSCRIPTION_STATUSES in utils/stripe.py:122) admits fresh checkout; every other nonterminal state returns 409, and any provider/persistence error now returns 503 instead of the old swallow-all except that fell through to a second Checkout session. The pi_ guard correctly keeps one-time grants out of Subscription.retrieve. I confirmed this helper has a single caller (the checkout-session route), so the 409/503 semantics can't leak into other routes. One nit: the old record_fallback(..., outcome='exhausted') telemetry is gone and the 503 path logs only the exception type — if that fed reconciliation dashboards, consider recording block/503 outcomes too.
  • backend/tests/unit/test_checkout_first_subscription.py drives the real HTTP route and covers the matrix well (nonterminal incl. unknown statuses, terminal, new buyer, referral, pi_ grant, resource_missing, uncertainty→503, failed reactivation→503, same-price reactivation, different-price 409). The TERMINAL_SUBSCRIPTION_STATUSES line added to test_payment_promotion_codes.py is harness isolation for its fake utils.stripe module — the production symbol exists, so no gap.
  • Clients all disambiguate the two 409 meanings, with tests: Flutter renames to isUpgradePendingCancelConflict and stops mapping checkout 409s (paywall_checkout.dart, plans_sheet.dart); Windows returns a structured existing_subscription result instead of sniffing status codes in the toast (billing.ts, PlanUsageTab.tsx); macOS splits upgradeErrorMessage/checkoutErrorMessage (SettingsContentView+BillingHelpers.swift); web adds route-aware purchaseErrorMessage (cancelPending.ts, PlansSheet.tsx, SettingsPage.tsx). Note web still detects 409 by regexing the error message — pre-existing pattern, unchanged; a future cleanup could use the structured status like Windows does.
  • backend/docs/checkout-admission.md matches the implemented decision table, and changelog fragments are present on all surfaces.

CI: the four red checks reduce to two real failures — Dart capture_live_recovery_test.dart (#20837 BLE durability guard, expected 210 got 200) and Swift MeetingMemoryBriefRenderingTests (19 vs 25). Neither subsystem is touched by this diff and other PRs' runs of both suites pass today, so they look flaky/unrelated — but a green re-run on this head is needed before merge.

USER IMPACT: someone who already has a subscription and hits checkout directly now sees "you already have a subscription" (or a retry prompt when Stripe can't be reached) instead of being allowed to buy a second subscription.

Still wanted before merge: green (or re-run) Dart/Swift suites on this head, confirmation of the #21869 customer reconciliation checklist in the doc, and optionally restored fallback telemetry. Leaving for human maintainer review: the existing approval predates the latest push and this sits on the payments admission boundary, so a fresh sign-off on this head is warranted.


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

Copy link
Copy Markdown
Member

Since my last review: addressed (both open items, verified on the new head) · still open (green Dart/Swift CI re-run; maintainer sign-off on this head) · newly introduced (none).

Addressed, verified on 62c6a59:

  • Clients no longer read a checkout 409 as "Resubscribe first": confirmed on all four surfaces — Flutter's helper is now isUpgradePendingCancelConflict and is used only on the upgrade path (plans_sheet.dart, paywall_checkout.dart); macOS splits checkoutErrorMessage/upgradeErrorMessage (SettingsContentView+BillingHelpers.swift); web's purchaseErrorMessage(err, route) records which route was called (cancelPending.ts, SettingsPage.tsx, PlansSheet.tsx); Windows' startCheckout returns a structured existing_subscription for a checkout 409 (billing.ts, PlanUsageTab.tsx). The earlier tests that pinned the buggy mapping now assert the existing-subscription copy, with new coverage on each surface.
  • The stacked test-repair files from the earlier revisions (test_modulate_stt.py, test_streaming_deepgram_backoff.py, and the other three) are no longer in this PR's diff at all, and the backend unit, guardrails, and hermetic merge gate suites are green on the head.

Still open before merge: the Dart capture_live_recovery_test and Swift MeetingMemoryBriefRenderingTests failures are in subsystems this diff doesn't touch and pass on other PRs today — likely flake, but this head needs a green re-run — and the existing approval predates the latest pushes, so a fresh maintainer sign-off on this head is warranted.

USER IMPACT: unchanged from my note above — a user who already has a subscription is told so at checkout instead of being able to buy a second one.


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 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.

Trusted contributor bug fix for checkout-first duplicate subscriptions with tests across all 3 clients, but required CI checks (Desktop Swift Build/Tests, Mobile Release Eligibility, Dart Analyze) are failing — holding at approve per hard floor until green.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 86c9c7ae59

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

error: true,
);
// Checkout's 409 is an existing subscription, not a pending cancellation.
report(session['detail'] as String? ?? l10n.couldNotProcessSubscription, error: true);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Localize the new checkout conflict message

For every non-English Flutter locale, a checkout 409 now displays the backend's English detail verbatim; the same new behavior also appears in PlansSheet. Add a localized existing-subscription key and select it from status_code == 409, while reserving the server detail for logging or non-user-facing diagnostics. The app requires all user-facing strings to come from context.l10n.

AGENTS.md reference: app/AGENTS.md:L116-L119

Useful? React with 👍 / 👎.

@aryanorastar
aryanorastar marked this pull request as draft October 23, 2026 05:55
Failure-Class: FC-checkout-falls-through-unverified-subscription

Use typed checkout 409 to select localized copy on both purchase surfaces; retain upgrade-only pending-cancellation copy. Update every current locale with the l10n tool and regenerate delegates. Verified: l10n check (49 locales), 14 focused Dart tests including en/de/ar, and 55 isolated checkout/promotion backend tests. Keep draft: real sandbox checkout/client flow and final-head CI remain gates. No Stripe, Firestore or deployment mutations.
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Non-device verification follow-up — 2026-10-23

All checks on current head 5d2f03f7a3547518c0a3dce66884a629b67b50b7 are now successful or intentionally skipped. The Linux helper rerun passed after the earlier Ubuntu dependency-download timeout; no CI gate was weakened.

The existing focused evidence remains 14 Dart tests, 55 backend checkout/promotion tests, all current locale checks and 60 selected preflight checks. These are not live Stripe sandbox acceptance.

The checked local environment has no configured test-only Stripe key, and the existing company-email browser sign-in reaches account-creation onboarding rather than an approved Omi sandbox. Stopped before creating an account or key. This is not proof that no other authorized sandbox exists. No production Stripe/Firestore/customer writes were made.

Still draft: need the approved sandbox configuration and an actual client-to-backend-to-Stripe pass covering checkout refusal without a second subscription, same-plan reactivation and manage-existing recovery. No merge or deployment performed.

@Git-on-my-level

Copy link
Copy Markdown
Member

Since my last review: addressed (green Dart/Swift CI on the current head — Dart Analyze & Tests and Desktop Swift Build & Tests pass on 5d2f03f; maintainer approval also landed on 86c9c7a) · still open (sign-off on the final commit — 5d2f03f is one l10n-only commit past the approved head) · newly introduced (none that I can find — the last commit is mechanical localization).

Verdict: nothing blocking from me; the billing fix remains correct and well-guarded.

What the final commit adds (verified): checkoutExistingSubscription added to every app/lib/l10n/app_*.arb plus the regenerated app_localizations*.dart files (Generated Files check passes), and the checkout-409 widget tests now pin the localized string in en/de/ar (app/test/widgets/paywall_cancel_pending_test.dart, plans_sheet_cancel_pending_test.dart) — the app shows a properly localized "You already have a subscription…" instead of raw server English.

The backend substance is unchanged from my earlier review: backend/routers/payment.py _try_reactivate_subscription admits fresh checkout only on a retrieve-only resource_missing/404 or a confirmed terminal status (TERMINAL_SUBSCRIPTION_STATUSES, backend/utils/stripe.py:122); every other nonterminal state returns 409 and provider/persistence failures return 503, with logs carrying only the exception type. backend/tests/unit/test_checkout_first_subscription.py covers the nonterminal matrix (including an unknown future status), terminal pass-through, new-buyer/referral/pi_-grant paths, and asserts no billing writes on any blocked path. All four client surfaces keep checkout-409 and upgrade-409 apart (app/lib/utils/cancel_pending_purchase.dart, desktop/windows billing.ts, web cancelPending.ts, macOS BillingHelpers.swift).

Non-blocking note: web/app/src/lib/cancelPending.ts still classifies 409 by regex over the error message (/\b409\b/) — pre-existing and now route-scoped, but an error detail that happens to contain "409" would still misroute the copy; exposing the status from the API client would harden it.

USER IMPACT: users who already have a subscription and hit checkout directly now see a localized "You already have a subscription — manage it instead" message instead of being let into a second (double-billed) purchase; if Stripe can't be reached, checkout asks them to retry rather than risking a duplicate.

Billing admission-gate change needs maintainer sign-off on the final head before merge — the existing approval is one commit behind (l10n-only).


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

@aryanorastar
aryanorastar marked this pull request as ready for review October 23, 2026 14:11

@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.

Billing/checkout fix with good test coverage, CI green. Approve-only given financial blast radius and diff size (900+ lines touching Stripe checkout/subscription logic) — flagging for Nik's own look before merge rather than owner-override.

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

I ran the checkout changes against a Stripe sandbox on 5d2f03f7a3, test mode only. The real /v1/payments/checkout-session and /v1/payments/customer-portal routes made live calls to the sandbox, with real customers, test cards and subscriptions. Only the Firestore user rows were in memory. All 10 cases behaved as specified:

Case Result
New buyer 200, real cs_test_ session in subscription mode
Active subscription, customer ID known 400 from the existing eligibility check; no session created
Active subscription, local customer ID lost 409 (new); no session created
Pending cancellation, same plan 200 reactivated; Stripe cancel_at_period_end is false; no session
Pending cancellation, local row missing Recovered from Stripe and reactivated; no session
Pending cancellation, other plan 400; still scheduled to cancel; no session
Canceled subscription 200, fresh session
Deleted subscription ID (resource_missing) 200, fresh session
Stripe state unverifiable (invalid key) 503; no session
Manage existing (customer portal) 200, real billing-portal URL

Still needed before merge: checking the client 409 messages on an installed client against the sandbox, and maintainer review. The PR description's merge-gate note is updated to match.

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

I ran the installed-client check on 5d2f03f7a3: the Flutter dev build on the iOS Simulator (iPhone 16 Pro), against a local backend that uses the same Stripe sandbox. It was signed in as the synthetic local-dev user, and all data is synthetic.

  • Setup: the Firestore subscription row is stale. It has expired, so the app shows Free, but it still points at a real sandbox subscription that is incomplete (payment failed on a test card). The subscription read only heals active/trialing subscriptions, so this is a state where the app genuinely reaches checkout. An active subscription is healed to paid first, so the app routes it to upgrade, not checkout.
  • Action: Plans & Billing → Plus annual → Upgrade.
  • Result: the backend returned 409 for POST /v1/payments/checkout-session. The sheet showed "You already have a subscription. Manage your current subscription instead of starting a new one." It did not show "Resubscribe first". Stripe has 0 Checkout Sessions for that customer, and the incomplete subscription is unchanged.

Side note, not changed by this PR: on mobile, Operator and Architect are manage-only. A user whose stale row points at an Operator price sees Operator in the storefront, but the app's own price lookup blocks the purchase with "Selected plan is not available" before any request is sent. I worked around it by seeding a Plus subscription instead.

The merge-gate note in the PR description now lists only maintainer review as outstanding.

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Final merge review on 5d2f03f7a3547518c0a3dce66884a629b67b50b7 (2026-10-23): no blocking finding in the final backend/client error-mapping diff. Fresh focused regressions pass: 35 checkout-first HTTP tests, 20 promotion-code tests and 14 Flutter purchase/localization tests. The earlier localization review finding is fixed on this head.

Reused the same-head recorded runtime evidence: 10/10 Stripe test-mode checkout/reactivation/portal scenarios, with real sandbox Stripe objects and in-memory user rows; the installed iOS Simulator flow displayed the localized checkout 409 message and created no duplicate Checkout Session. No claim of production Firestore, production billing or customer repair. Existing current-head approval and required Mobile Release Eligibility pass; no failed or pending PR checks at the final snapshot.

Aryan explicitly authorized this merge. This is code merge only: no deployment, live billing operation, production-data change or issue closure is authorized/performed. Keep #21869 open for separately authorized rollout and affected-account verification. The main backend deployment workflow is manual (workflow_dispatch) at the reviewed base.

@aryanorastar
aryanorastar merged commit 416813d into main Oct 23, 2026
78 of 79 checks passed
@aryanorastar
aryanorastar deleted the fix/21869-checkout-first-protection branch October 23, 2026 16:37
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants