Repository navigation
fix(billing): prevent checkout-first duplicate subscriptions - #22552
Conversation
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
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Record the combined type gate, HTTP regressions and billing selection without claiming GitHub CI or deployment success. Failure-Class: none
|
Auto-fix isn't included in your plan ↗ |
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
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
* 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]>
|
The production change here is correct and nicely scoped — the fail-closed checkout admission in Correctness findings:
Security: fail-closed on uncertainty, no provider bodies in logs or responses, no secrets introduced — a positive change. 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:
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 |
…rst-protection # Conflicts: # backend/database/desktop_previews.py # backend/tests/unit/test_users_joan_followup_tombstone_guard.py # backend/utils/sync/pipeline.py
|
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
left a comment
There was a problem hiding this comment.
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]>
|
Pushed f079c67: merged current main and unstacked this PR. Its diff against main is now the checkout-first protection only.
|
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
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
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
…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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Pushed 06c51fa through 62c6a59: both review points fixed.
|
|
Auto-fix isn't included in your plan ↗ |
|
The production change here is correct and nicely scoped; nothing blocking from me — the failing checks trace to tests this PR doesn't touch.
CI: the four red checks reduce to two real failures — Dart 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 |
|
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
Still open before merge: the Dart 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 |
kodjima33
left a comment
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
💡 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); |
There was a problem hiding this comment.
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 👍 / 👎.
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.
Non-device verification follow-up — 2026-10-23All checks on current head 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. |
|
Since my last review: addressed (green Dart/Swift CI on the current head — Dart Analyze & Tests and Desktop Swift Build & Tests pass on Verdict: nothing blocking from me; the billing fix remains correct and well-guarded. What the final commit adds (verified): The backend substance is unchanged from my earlier review: Non-blocking note: 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 |
kodjima33
left a comment
There was a problem hiding this comment.
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.
|
I ran the checkout changes against a Stripe sandbox on
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. |
|
I ran the installed-client check on
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. |
|
Final merge review on 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 ( |
Summary
Refs #21869. Follow-up to #22193: protect users who go directly to checkout before subscription-read reconciliation has healed their stored paid plan.
resource_missing/404; preserve new-buyer, referral and one-time PaymentIntent-grant behavior.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
Nonefor active subscriptions and swallowed provider/modify/persistence errors, allowing fresh checkout.The shared primitive is that existing boundary:
Nonenow 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 preflightchecks passed on commit0e5f5f642c3ac64014b58b84ccf7e13a4bd80683. 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:
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 slowexpression (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):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.mdand the failure-class record.test.sh: 279 passed.routers/payment.pypasses the pinned type check (0 errors).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, webpurchaseErrorMessage(error, route), WindowsstartCheckoutreturningexisting_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
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.