Repository navigation
Play Billing follow-up: money fixes (deletion retry, refund-only periods, keyed account id), Play reviewer app fixes (trial disclosure, hardware-only store, paywall Retry, Play prices), prod deploy config - #26129
Merged
Conversation
…nt ids Account deletion re-reads Google before and after a Play cancel, accepts any state that can no longer charge, and raises a retryable error (status code and token hash only) that the wipe retries instead of parking. A refund or revoke records the period it removed; only a later paid period grants again. The Play obfuscated account id is an HMAC under PLAY_ACCOUNT_ID_HMAC_KEY; without the key no Play config is issued, and the account map only binds ids issued to that uid. Failure-Class: none
RTDN and reconcile audiences and caller identities, the account-id HMAC key from Secret Manager, and empty ANDROID_PLAY_BILLING_MIN_BUILD/COHORT. Play stays off: ANDROID_BILLING is not set and no build qualifies until MIN_BUILD is set. Staging keeps the Play routes closed.
…e for Play readers The trial paywall shows the Play renewal and Google Play management line, Play's own price strings (no computed was/save or zero), and the plans sheet's Retry when Play's plans or the subscription read fail, on the trial and outline pages. On Android Play-billing builds the store opens on the Omi device page with a navigation allow-list (that product, its cart and checkout), also from Connect.
…t a stubbable exception class
…, min build 1617 Backend: build the Play publisher only for users with a Play purchase; a failed Play cancel at deletion admission propagates like Stripe so grace actions stay incomplete and the reconciler retries; RTDN transport errors become 503 with no token; user-cancelled subscriptions with time left get a best-effort developer cancel; a voided notification without order ids revokes; constant-time account id comparisons; verify route rate limit stated in the route manifest; the Firestore wipe drops the user's Play purchase records and account-map entries. App: the hardware-only store opens the app-hardware template, forces it on every device page and shows the page only when its marker element is present; off-site pages open only from checkout; blocked pages say so; a post-purchase hop closes the store with an order-placed message; the trial page uses Play's trial length and sends plans without a Play trial phase to the plain Play plans; paid apps hide payment links while the billing provider is unknown; Play queries time out after 10 s. Config: ANDROID_PLAY_BILLING_MIN_BUILD=1617 on prod backend (1616 predates these fixes); ANDROID_BILLING stays stripe and the cohort env stays empty.
…changed People writer
kodjima33
marked this pull request as ready for review
November 23, 2026 16:56
kodjima33
added a commit
that referenced
this pull request
Nov 23, 2026
Git-on-my-level
added a commit
that referenced
this pull request
Nov 23, 2026
…n red, shard 7) (#26161) ## What changed and why Main has been red on Backend unit shard 7 since #26135 (`4729587c`). Every case in `tests/unit/test_merge_validation.py` errors at setup: ``` ImportError: cannot import name 'get_firestore_client' from 'database._client' ``` #26135 added `from database.record_audio import fence_record_audio_removal` to `utils/conversations/merge_conversations.py`. That fixture loads the module against a stubbed `database._client` that carries only `db`, so the real `database.record_audio` → `pipeline_ledger` chain can't import. The pure validation functions under test never call the fence, so the fixture now stubs `database.record_audio` the same way it stubs the other persistence modules. Test-only; no production code changes. This blocks the backend roll that carries #26129 (Play Billing server side), which is needed today for the Android test purchase before the Google resubmission. ## Verification From `backend/`, each file in its own process, as CI runs them: - `tests/unit/test_merge_validation.py`: 50 passed. The unfixed file gives 50 errors. - `tests/unit/test_merge_conversations_canonical_delete.py`: 18 passed. - `tests/unit/test_conversation_smart_merge_flatten.py`: 103 passed. Rollback: revert this PR. ## Failure class (fixes) Failure-Class: none 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/26161?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a> <a href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/26161?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F26161&source=description" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img alt="Turn on auto-fix" src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
kodjima33
added a commit
that referenced
this pull request
Nov 23, 2026
… (follow-up to #26129) (#26159) ## What changed and why Follow-up to #26129 (merged as fca9009 with Play Billing off for everyone: `ANDROID_BILLING=stripe`, min build 1617, empty cohort). Fixes the round-2 review findings that must land before Play Billing is switched on or the Android build is shown to a Google Play reviewer. No prod switch values change. ## Backend (money) 1. **Stale cancel flag.** `cancel_for_account_deletion` no longer skips a purchase because an earlier deletion marked it cancelled. It re-reads Google for every purchase on every run. A purchase the developer already cancelled is recognized from Google's own `canceledStateContext.developerInitiatedCancellation`, so repeats stay cheap. Sequence tested: grace deletion cancels, restore, the user resubscribes the same purchase (RTDN `SUBSCRIPTION_RESTARTED`, Google ACTIVE), delete again: cancelled a second time. 2. **Purge wider than cancel.** The cancel now walks the user's pointers plus every purchase document with the uid (`purchase_keys_for_uid`, the same uid equality query the purge uses). Each settled purchase gets `account_deletion_confirmed_at`. The wipe records the time just before its billing step, and `purge_account_records` refuses (raises, wipe retries) if any purchase doc lacks a confirmation at or after that time. Nothing is deleted in that case. Tested: a uid-bound purchase with no pointer is cancelled before deletion; a doc confirmed only by an earlier deletion, or never, blocks the purge. 3. **Stuck grace-mode cancel.** Every failed grace admission retry in the reconciler now logs with attempt count, age and overdue state (`logger.critical` once past the due date), emits the existing `Account Deletion Wipe Failed` deletion telemetry (`failed_operations=['grace_immediate_actions']`, `retry_count`, `age_seconds`, `overdue`, no token, uid only where existing deletion logs already use it), and records `grace_actions_failed_attempts` / `grace_actions_last_failed_at` / `grace_actions_overdue` on the deletion marker. The wipe is still never dispatched while Google can charge. This is a hard failure, so it uses the deletion error telemetry rather than `record_fallback` (per `.github/agent-docs/fallback-telemetry.md`). 4. **Cohort lookup on the subscription route.** No code change needed: the route is a sync handler (thread pool), the membership read is `get(timeout=1.0, retry=None)`, read errors become `None` in `_TTLReads._refresh`, and `user_in_play_cohort` catches anything else and returns False. Added tests pinning both: a timed-out read through the real resolver chain returns "not Play" without raising (and the same chain admits a member when the read answers), and the read stays bounded at 1 s with no retry. ## App (reviewer-facing, Android hardware-only store) 5. **"Order placed" only on the store's own checkout.** A post-purchase path closes the store only on `www.omi.me` / `omi.me` under a checkout path, or on `checkout.shopify.com`. The same words anywhere else go through the normal rules, so a blocked page gets "This page isn't available in the app." 6. **Every `*.omi.me` host is a store host.** `app.omi.me` (sells Omi Pro), `h.omi.me` and any other subdomain are blocked from every page, including checkout and off-site payment hops. Only `www.omi.me` / `omi.me` with the path allow-list load. 7. **Trial page while Play's offers load or failed.** For a Play-billed reader with no loaded Play offer, the timeline card (trial length, date, rows) is replaced by a skeleton while loading and by nothing in the error / Retry state. Stripe-billed and iOS readers keep the 7-day timeline (tested on both platforms). 8. **Web view wiring under test.** New `test/pages/shop/omi_shop_web_page_test.dart` drives `OmiWebPage` with a fake `WebViewPlatform`: (a) the device page stays behind the loading state until the marker check returns true; (b) missing marker shows the message with Close, never the page; (c) a throwing script and a script that never answers (new 5 s `WebPageCheck.timeout`) give the same blocked state; (d) a blocked navigation is prevented and shows the message. 9. **Paid Marketplace apps while the provider is unknown.** The paid button now shows the loading state until the first subscription read lands, then Subscribe (Stripe) or "Not available on Android" (Play). The test also caught that the old read used the State's context; it now selects from the build context so the button updates when the read lands. ## Product invariants affected - INV-MEM-3: `backend/services/users/account_deletion.py`. The wipe purges Play purchase records only after this run's billing step confirmed each one, and the grace reconciler reports a stuck admission cancel instead of failing silently. Memory and privacy deletion order are unchanged; deletion is never blocked by memory intake state. ## How it was verified - Backend (one process per file): `test_play_billing_money` 57, `test_play_billing` 62, `tests/services/users/test_account_deletion` 114, `tests/routers/test_users` 330, `test_batch_account_authority_writers` 652, `test_claim_deletion_wipe_txn` 41, `test_lake_wipe_step` 72, Firestore query guards (`test_firestore_query_shapes` 633, `test_firestore_index_oracle` 132, `test_firestore_outside_query_contract` 31, `test_firestore_runtime_witnesses` 25, `test_port_surface_parity` 51), plus the other deletion and billing suites: all passed. - App (Flutter 3.44.5): `omi_shop_hardware_test`, `omi_shop_web_page_test`, `app_detail_paid_billing_test`, `play_billing_plans_sheet_test` and the 22 other paywall, plans sheet, app detail and shop test files: all passed. `flutter analyze` on the changed files: no new issues. - `make preflight` and `scripts/pr-preflight --pr-body-file` on this body. - Not run: any device or emulator build. The web view tests use a fake platform; the real post-purchase URL and the device proofs listed in the review are still UNVERIFIED. ## UI evidence UI-Evidence: none -- these states only render on Android with Play config or an unknown billing provider; widget tests cover each state (no device build in this change). ## Failure class (fixes) Failure-Class: none <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/26159?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a> <a href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/26159?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F26159&source=description" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img alt="Turn on auto-fix" src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
kodjima33
added a commit
that referenced
this pull request
Nov 23, 2026
…M (default off) (#26146) ## What changed and why People who bought Omi with "12 months included" (Shopify bundle), or who hold a prepaid or creator code, can only use it through Stripe Checkout today. Checkout asks for a card even at US$0, and in-app redemption needs an existing paid plan. 31 people wrote to support in 7 days because their prepaid Pro "doesn't land". This adds a way to redeem a **fully prepaid** code in the app, with no card and no payment screen. It sits behind `PREPAID_CODE_REDEEM`: - `off` (default, prod value): nobody, no cohort read. - `cohort`: members of the `prepaid-code-redeem` rollout cohort, for a test account. - `on`: everyone, no read. **Google Play-billed Android readers keep main's behaviour.** For them, and while Android doesn't yet know its billing provider, no code entry is shown anywhere. Opening it for Play is a later decision. ## Which codes are in scope Scope comes from the code itself (live Stripe objects), not from a list of names: - **Single-use** promotion code (`max_redemptions == 1`): something one person prepaid, not a shared discount. - Its coupon makes the **Omi Pro monthly price exactly $0 for a fixed term**: - 100% off, `repeating` N months (1–24): the bundle "Omi Pro: 12 months included", prepaid-year codes, creator codes `OMI-TRYBE-…` (3 months) and support grants. - An amount off at least the monthly price, in the same currency: `repeating` N months, or `once` = 1 month when the amount is below the yearly price ("Omi Monthly: first month included", $29.99 once). - It must also pass the coupon's `applies_to` product restriction. - **Out of scope; checkout keeps today's behaviour:** percent-off or amount-off below the price, `forever`, `once` 100% (its term depends on which price it lands on, so it isn't knowable), and shared codes. The sheet says "This code can't be redeemed here. Use it when you choose a plan." The code is not consumed. ## Screenshots (iPhone 17 Pro simulator, real backend + Stripe stub) | Switch off (today) | Switch on | Sheet | Refusal | Success | After redeem | |---|---|---|---|---|---| | <img src="https://raw.githubusercontent.com/BasedHardware/omi/5efe39720d0e425fb95b4d9b7dbc45f344111edb/.agent-artifacts/ui-evidence/feat-prepaid-code-no-card/003-mobile-ios-plans-switch-off.png" width="150"> | (removed, see note) | <img src="https://raw.githubusercontent.com/BasedHardware/omi/5efe39720d0e425fb95b4d9b7dbc45f344111edb/.agent-artifacts/ui-evidence/feat-prepaid-code-no-card/007-mobile-ios-error-used.png" width="150"> | <img src="https://raw.githubusercontent.com/BasedHardware/omi/5efe39720d0e425fb95b4d9b7dbc45f344111edb/.agent-artifacts/ui-evidence/feat-prepaid-code-no-card/009-mobile-ios-error-not-prepaid.png" width="150"> | <img src="https://raw.githubusercontent.com/BasedHardware/omi/5efe39720d0e425fb95b4d9b7dbc45f344111edb/.agent-artifacts/ui-evidence/feat-prepaid-code-no-card/010-mobile-ios-success.png" width="150"> | (removed, see note) | | <img src="https://raw.githubusercontent.com/BasedHardware/omi/5efe39720d0e425fb95b4d9b7dbc45f344111edb/.agent-artifacts/ui-evidence/feat-prepaid-code-no-card/001-mobile-ios-paywall-switch-off.png" width="150"> | <img src="https://raw.githubusercontent.com/BasedHardware/omi/5efe39720d0e425fb95b4d9b7dbc45f344111edb/.agent-artifacts/ui-evidence/feat-prepaid-code-no-card/002-mobile-ios-paywall-have-a-code.png" width="150"> | <img src="https://raw.githubusercontent.com/BasedHardware/omi/5efe39720d0e425fb95b4d9b7dbc45f344111edb/.agent-artifacts/ui-evidence/feat-prepaid-code-no-card/005-mobile-ios-sheet-empty.png" width="150"> | <img src="https://raw.githubusercontent.com/BasedHardware/omi/5efe39720d0e425fb95b4d9b7dbc45f344111edb/.agent-artifacts/ui-evidence/feat-prepaid-code-no-card/006-mobile-ios-error-invalid.png" width="150"> | <img src="https://raw.githubusercontent.com/BasedHardware/omi/5efe39720d0e425fb95b4d9b7dbc45f344111edb/.agent-artifacts/ui-evidence/feat-prepaid-code-no-card/012-mobile-ios-success-dark.png" width="150"> | <img src="https://raw.githubusercontent.com/BasedHardware/omi/5efe39720d0e425fb95b4d9b7dbc45f344111edb/.agent-artifacts/ui-evidence/feat-prepaid-code-no-card/008-mobile-ios-error-expired.png" width="150"> | Note: these frames are from the first round. The plans-sheet frames with two code rows and "Resubscribe" after redeeming are removed because this round changed both. The new plans-sheet states are covered by widget tests only. Free disk was below the 30 GB floor, so no simulator build was made this round. ## App behaviour this round - **One code entry on the plans sheet** (merged, not stacked). When the switch admits a free reader, "Have a code?" replaces the "Promo code" row. A fully prepaid code redeems with no card. A valid discount code (`not_prepaid`) closes the sheet, opens today's promo field with the code filled in, and goes through today's checkout. Paid readers and switch-off readers see only today's "Promo code" row. - **The paywall closes after a redeem.** `showPrepaidCodeSheet` returns `bool`. On Done after a redeem, the trial paywall pops with `true`, the same way Restore does. - **Where the sheet opens:** only from the trial paywall and the Stripe plans sheet. The outline paywall and the Play plans screen have no entry. - **Copy:** the rate-limit message is now "Too many tries. Try again later." in all 49 locales. - **Android:** not exercised on a device or emulator; the MUX pipeline has no Android lane. Covered by widget tests run as `TargetPlatform.android`: - entry shown for a Stripe Android reader; - success, and every refusal message; - paywall closes on success and stays up on a refused code; - one code row, and a discount code handed to the promo field; - Play-billed reader sees no entry on the plans sheet, trial paywall or outline paywall; - provider unknown hides the entry. ## Grant model (Stripe stays the record) 1. `POST /v1/payments/prepaid-code/redeem` creates or reuses the Stripe customer, then calls `Subscription.create` on Omi Pro monthly with `discounts=[{promotion_code}]` and no payment method. It sets `payment_behavior=error_if_incomplete`, `proration_behavior=none`, and `cancel_at` = N calendar months minus 1 hour. Stripe enforces max redemptions, expiry and first-time restrictions, and counts the redemption. 2. The existing `customer.subscription.created`/`updated` webhook grants Pro unchanged, with metadata `uid`, `redeemed_promotion_code_id`, `prepaid_code_redemption=1` and Shopify attribution. 3. Single use and idempotency: a Firestore claim on `promotion_code_redemptions/{promo_id}` (the same ledger as `/redeem-code`, so the two paths exclude each other) plus Stripe idempotency keys. A double tap or retry by the same user returns the first result and never creates a second subscription. A definitive Stripe refusal releases the claim. An unknown outcome keeps it, so a retry replays the same idempotent create. **Stripe sandbox test clocks (`livemode=false`, `~/mobile-ux-agent/runs/2026-11-23/p1/sandbox/`):** - 3 months: active with no card, 3 × $0 paid invoices, ended exactly at `cancel_at`, 0 charge attempts. - 12 months: 12 × $0 paid invoices, ended at `cancel_at`, 0 charge attempts. - Reusing the single-use code was refused ("used up"). The production path adds a 1-hour margin before the boundary. ## End of term - At `cancel_at` Stripe ends the subscription. The `deleted` webhook projects Free at once: the paid-through grace is skipped for prepaid subscriptions (`routers/payment.py`, `_build_subscription_from_stripe_object`), so the normal downgrade and ended event fire once. The user then sees their platform's normal purchase options. No renewal is attempted and no dunning email is sent. - **Before the end:** the success sheet says "Your Omi Pro plan ends {date}." The subscription response carries `subscription.prepaid: true`, only for users the switch admits; it is omitted otherwise, so switch-off responses are byte-identical. With that marker, Plans & Billing shows only the plan name and "Your Omi Pro plan ends {date}.", with no Resubscribe, Upgrade, Cancel or Manage payment method control. - No existing reminder fits: `trial_will_end` skips subscriptions with `cancel_at` (`utils/trial_reminder.py:40`). A pre-expiry nudge is a follow-up. ## Money-safety: every changed line near code validation, subscription creation and entitlement - `backend/utils/prepaid_code_redemption.py` - `prepaid_months`: the scope rule. - Lookup and classification: expired, used, inactive, shared, customer-locked, `applies_to`, not prepaid. - `_has_live_plan` / `_has_open_stripe_subscription`: refuses with `has_plan` for a live Stripe row, a live Play row, or **any Stripe subscription that can still bill** (active, trialing, past_due, unpaid, incomplete, paused). The code is not consumed. - Customer creation and `Subscription.create`. - Stripe error mapping. - `_resume`: idempotent retry. - Claim, create and release ordering. - `backend/database/promotion_redemptions.py`: `claim(extra=)`, `get`, `set_subscription`. - `backend/routers/redeem_code.py`: switch gate (404 when not admitted), per-uid rate limit, error to reason-code mapping. - `backend/routers/payment.py`, each returning 409 "Your prepaid plan ends on its own…" before any Stripe change: - cancel (`DELETE /v1/payments/subscription`); - customer portal (`POST /v1/payments/customer-portal`); - upgrade (`POST /v1/payments/upgrade-subscription`); - reactivation inside checkout (`POST /v1/payments/checkout-session`); - plus no paid-through grace at term end. - `backend/utils/subscription_state_machine.py`, `backend/utils/subscription.py`: projection of end date, "ends" state and the `prepaid` marker, for the prepaid metadata marker only. - `backend/config/prepaid_code_redeem.py`: the three-state switch, marker and `prepaid_end`. **Endpoints audited for a guard on a prepaid subscription:** - Cancel: guarded (new). - Un-cancel: only through checkout reactivation; guarded, falls through to 409. - Upgrade and plan change: guarded. - Customer portal: guarded (new). The app hides it too. - Stay offer (`utils/retention_offer.py`): refused, the subscription already has a discount. - Yearly switch (`utils/yearly_switch.py:111,117`) and monthly switch / downsell (`utils/monthly_switch.py:124,130`): refused for `cancel_at` or a discount. - Redeem-code onto a plan (`utils/promotion_redemption.py`): refused, already discounted. - Pause: no endpoint exists. Both switches refuse `pause_collection`. - Checkout while a non-terminal subscription exists: existing 409. - These end the subscription immediately with no charge, which is fine: account-deletion cancel, the Play-conflict cancel and refund (`utils/stripe.py:577`), and the old-subscription cancel after a new checkout (`payment.py`). - Admin or support: the web admin calls no Stripe subscription mutation (searched `web/admin`). The Stripe dashboard itself is not guarded. ## Switch off = today - **Reads:** with `PREPAID_CODE_REDEEM=off` there is **no cohort read** on `GET /v1/users/me/subscription` for any user. A test exercises the real `enabled_for` against a counting cohort resolver. With `cohort` it reads the `prepaid-code-redeem` cohort document; with `on` it reads nothing. The first round of this PR read the cohort on every request even when off; that is fixed. - **Response:** byte-identical with the switch off. `prepaid_code_redeem` and `subscription.prepaid` are omitted (tested). - **Route:** answers `404 Not Found` and reads no rate-limit bucket (tested). - **App:** shows today's paywall hint and today's single "Promo code" row (widget tests; simulator `before-light/`). - **Deploy config:** declared in `backend/deploy/runtime_env/{prod,dev}.overlay.yaml` → `runtime_env.yaml` (`PREPAID_CODE_REDEEM: 'off'`, rollout), plus `config/feature-flags.yaml`. - **Test account:** set `cohort` and add a member doc to `rollout_cohorts/prepaid-code-redeem`. No uid is in source. ## Rate limits - `payments:prepaid_code`: 10 per hour per uid. Fail-open on a Redis outage, like `/redeem-code`. - The per-IP limiter is removed. The repo has no trusted client-IP helper; the connection peer and `X-Forwarded-For` hops behind the load balancer don't identify the client. ## Analytics - No new events. The three funnel events from the first round are removed: no existing funnel needs them, and the metric below is measured from Stripe (`prepaid_code_redemption` metadata) and support contacts. **Will miscount these $0 subscriptions (listed, not rewritten):** - `web/admin/lib/stripe-subscriptions.ts:105-134,255,275-352`: MRR from `unit_amount`, ignores discounts. Feeds `web/admin/lib/wall-metrics.ts:747`. - `web/admin/app/api/omi/stats/revenue/route.ts:40-47`, `.../mrr-trends/route.ts:110-119`, `.../profitability/route.ts:552-570`, `.../subscription-trends/route.ts:60-68`, `web/admin/app/api/omi/subscriptions/route.ts:93-94`. - `backend/scripts/finops/pull_stripe.py:281,318-319`: counts them as paying subscribers. `:139-148` reads only legacy `discount`. `:329` ignores `cancel_at`. - `backend/utils/observability/subscription_events.py:74-93,139-168`: `Billing Subscription Started` with full-price `mrr_cents`. ## Merged with #26129 (Play Billing follow-up) - Merged current `origin/main` (with #26129) into this branch. - `trial_paywall_page.dart`: two hunks, both sides kept (`if (canRedeemCode) … else if (!playBilled) …`). - l10n: took main's files and re-added this PR's six keys with `scripts/l10n.py`. - The redeem entry is never shown to a Play-billed or provider-unknown reader (`UsageProvider.canRedeemPrepaidCode`), which matches #26129's Play trial page. ## How it was verified - **Backend:** `tests/unit/test_prepaid_code_redemption.py` (46 tests, Stripe mocked). Covers: - in-scope and refused code kinds; expired, used, case and whitespace; second tap and retries; - live Stripe and Play plans, and past_due / unpaid / incomplete / trialing / paused subscriptions blocking redeem; - three-state switch with zero reads when off; route per-uid limit; - cancel, portal, upgrade and reactivation 409s; no grace at term end; the `prepaid` marker only when admitted. Also passing: 191 neighbouring files one by one, including `tests/routers/test_users.py`, the Stripe webhook behaviour tests, lifecycle writer inventory, runtime-env validator, route policy and app-client schema inventory. `test.sh` timing guard passes. `backend/scripts/typecheck.sh`: 0 errors. OpenAPI and the Dart, TS and Swift clients are regenerated and checked. - **App:** `test/widgets/prepaid_code_sheet_test.dart` (18) and `test/widgets/play_billing_plans_sheet_test.dart` (27, including 5 new). 777 tests across 68 neighbouring files pass. `l10n.py check` passes. - **Simulator (first round):** iPhone 17 Pro, real backend plus loopback Stripe stub, `~/mobile-ux-agent/runs/2026-11-23/p1/`. ## Not verified - Live Stripe and the production webhook grant (sandbox and stub only). - Whether Stripe emails anything for $0 invoices. New customers are created with no email; an existing customer may have one. - 24-month terms from a month-end start. The money reviewer ran 3 and 6 months from month-end starts in the sandbox; I ran 3 and 12 months from the 23rd. - A Checkout session already open with the code applied when the code is redeemed here. - The Stripe customer portal configuration. It is refused server-side for prepaid plans, but its live settings were not read. - Android on a device or emulator (widget tests only). - This round's plans-sheet UI on the simulator (widget tests only; disk below the floor). - Largest text on the simulator: Plans & Billing already overflows on main. - **CI:** `test_people_generation_inventory` failed on main itself; `ccb96700f4` was already in the old base, so rebasing alone would not have fixed it. Main now carries the `people-generation-writers.json` pin from #26129, and the test passes on this merged branch. No pin was added here. `tests/unit/test_merge_validation.py` (backend unit shard 6/8) fails with 50 `ImportError` errors on current origin/main too (reproduced on a clean origin/main checkout). It comes from main's recent `pipeline_ledger` import changes, not this PR. `test_conversations_v3_stream` and `test_batch_result_protocol` hit the 1.00 s CPU guard once (1.01–1.20 s) and passed on re-run. ## Metric Support contacts about codes: 31 a week → near 0. Android code upgrades kept after Play Billing: about 23 a week (MODELED from 99 in 30 days). ## Product invariants affected INV-MEM-4 is selected by changed paths. No memory intake, consolidation or promotion code changes. This PR touches billing, subscription projection and app paywall code only. ## Line-count exceptions Line-Count-Exception: backend/routers/payment.py | 2395 -> 2418 | prepaid guards must sit inside the cancel, portal, upgrade, reactivation and term-end grace paths they protect Line-Count-Exception: backend/routers/users.py | 2875 -> 2885 | the prepaid switch fields sit beside play_billing on the subscription response Line-Count-Exception: backend/utils/subscription.py | 1880 -> 1882 | the Stripe self-heal projection shows the prepaid end date like project_subscription
Git-on-my-level
pushed a commit
to Git-on-my-level/omi
that referenced
this pull request
Nov 23, 2026
… (follow-up to BasedHardware#26129) Backend: - Account deletion re-reads Google for every purchase instead of trusting a stored cancel flag, so a purchase resubscribed after a restore is cancelled again. - The cancel covers every purchase document bound to the uid (the exact set the purge deletes), stamps a confirmation time, and the purge refuses any purchase not confirmed in this wipe. - A failing grace admission cancel logs (critical once overdue), emits deletion telemetry with attempt count and age, and records attempts/overdue on the marker; the wipe stays blocked. - Tests pin the cohort lookup's bounded read and its fail-closed result. App: - Post-purchase close only on the store's own checkout; every other *.omi.me host is blocked. - Trial page shows no trial length, date or timeline for a Play reader until Play's offer loads. - Marker check times out after 5 s into the blocked state; widget tests drive the web view. - Paid Marketplace apps wait (loading) while the billing provider is unknown.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What changed and why
Follow-up to #26078 (merged as 4fa06e2), based on
main. Money review round 2 made three fixes conditions for turning Play Billing on for all Android users. The general review said the build is not ready for a Play reviewer without four app fixes. Nothing can be turned on in prod until the Play settings are declared in the deploy config. Play Billing stays off for every user:ANDROID_BILLING=stripe, empty cohort env, and the minimum build is 1617. Only a uid in theandroid-play-billingrollout cohort, on Android build 1617 or later, uses Play.Round 2 (review of 77f0481)
Backend (money):
backend/utils/play_publisher.py:161). A Stripe or iOS user's deletion never callsgoogle.auth.default.backend/services/users/account_deletion.py:706); the round-1defer_play_failurepath is gone. In grace mode the delete request fails andgrace_actions_completeis never written, so the reconciler re-runs the admission steps every cycle until Google confirms (:938-946, unchanged). In immediate mode the request fails the same way a Stripe failure does. I picked propagation because it is what Stripe already does; a separateplay_cancel_pendingmarker field would be new schema.apply_tokenwraps every non-PurchaseNotFoundread error asPlayBillingError(503, 'play_unavailable')with only the type name logged,from None(backend/utils/play_billing.py:432). Pub/Sub retries on the 503.play_publisher.py:118,:173). This stops the user un-cancelling in Google Play after the account is gone._latest_order_idsreturns an empty set,play_billing.py:406,:439).hmac.compare_digeston bytes atplay_billing.py:354and:394;route_policy_manifest.yaml:116now states the verify route's real limiter (payments:play_verify, uid, fail-open, dependency; 30/h inutils/rate_limit_config.py).play_billing_records, after the billing step confirmed Google stopped charging and before the Firestore user-data wipe (backend/services/users/account_deletion.py:525). It deletes everyplay_subscription_purchasesdoc andplay_billing_accountsentry whoseuidis the user (backend/database/play_subscriptions.py:136, throughbackend/utils/play_publisher.py:190); a failure keeps the wipe retryable. No uid + purchase token is left behind. A later notification for a dropped token finds no owner and is recorded unbound (token-hash id, token, no uid), never granted. The query is registered in the Firestore query driver registry (single-fielduidequality, built-in index). About 20 lines of code, no schema change. The grace admission path never purges, so Restore during grace keeps the subscription.App (reviewer-facing):
8. Shop on the
app-hardwaretemplate, fail closed. The store openshttps://www.omi.me/products/omi?view=app-hardware&_ref=<source>(app/lib/pages/shop/omi_shop.dart:24). Any allowed main-frame navigation to/products/omiwithoutview=app-hardware(or with another view) is replaced by the same URL with it. After a device page finishes loading in the restricted view, the app runsdocument.getElementById('omi-app-hardware') !== null; the page stays behind the loading state until it passes, and if the marker is missing (template removed, Shopify fell back to the normal page) the reader sees "This page isn't available in the app." with Close instead (omi_shop.dart:74-81,app/lib/pages/apps/widgets/omi_web_page.dart:136,:149,:219). iOS and non-restricted readers are untouched (no policy, no check).9. Allow-list shape (
omiHardwareNavigation,omi_shop.dart:48):www.omi.me/omi.me:/products/omi(forced to the template),/cart,/cart/*(permalinks such as/cart/<variant>:<qty>, used by the page's own Get Omi button),/checkout,/checkouts/*,/<digits>/checkouts/*,/policies/*. Everything else is blocked (home,/pages/*, other products, collections, search)./checkouts/page (any host) or already an off-site page reached that way. That covers Shop Pay (accounts.shop.appetc.), PayPal, Klarna, Afterpay, Amazon Pay, bank redirects and top-level 3-D Secure without a host list. From the product, cart and policy pages, off-site navigation stays blocked. A return to omi.me goes through the path allow-list again.pageNotAvailableInApp, 49 locales). Apost-purchase/post_purchasehop (payment already taken) closes the web view and shows "Order placed. Check your email for the confirmation." (shopOrderPlacedCheckEmail,omi_shop.dart:119). I did not try to derive the thank-you URL: Shopify's new checkout paths are not documented enough to build one safely. UNVERIFIED against a live order.PaywallPrice.trialDaysfromPlayPlanOffer.trialDays) for the "In N days" row, its date, the price terms and the monthly fallback sheet (trial_paywall_page.dart:310,:130,:164). If any listed Play plan has no free-trial phase for this account (trial used, or not eligible), the reader gets the plain Play plans instead: price, Subscribe, renewal disclosure, no trial promise and no "free until" row (:276). The plans sheet and the outline paywall already usedPlayPlanOffer.trialDaysper plan and show no trial when it is null; unchanged.app_detail.dart:867hides the app's own payment link forplayBilledPurchaser || billingProviderUnknown(Android-only getter), as the store does.isAvailable()andqueryProductDetailstime out after 10 s (app/lib/services/billing/play_billing.dart:158-159); the provider's catch ends loading and the paywalls show Retry.CI note:
backend/docs/people-generation-writers.jsonre-pinschat_edits.py:apply_update. Main has failedtest_people_generation_inventorysince ccb9670 (David Zhang, today), which changed only whichValueErrorsubclassapply_updateraises for an unsupported field, before any write. The People write and generation bump path is unchanged;test_chat_edits_firestoreandtest_chat_edit_toolspass.Not changed, as agreed: the shop restriction while the provider is unknown, Android creators pricing apps, and
apply_token's read-then-write without a transaction.Money fixes
backend/utils/play_publisher.py:130re-readssubscriptionsv2first. Not found, or any state that can no longer charge (EXPIRED, CANCELED, PENDING_PURCHASE_CANCELED), is already done.:117) and accepts a state that can no longer charge.PlayCancelPending(:44). It is not aDeletionBillingError, so the wipe marks the markerfailed, which the deletion reconciler retries with backoff (max 1 h, no terminal state) instead ofbilling_failed(services/users/account_deletion.py:706). Admission no longer fails the delete request on it; the wipe repeats the cancel at its irreversible boundary (:725).database/account_deletion_policy.py:53).PublisherHTTPError(status)(:36). No exception text, log or storedbilling_errorcarries a request URL or the purchase token: only the HTTP status and the first 12 characters of the token's SHA-256.revoked_through= the expiry Google showed at that moment (backend/utils/play_billing.py:438) and removes access.revoked_through(:171,:367). Grace is a failed charge, so it never re-grants.orderIdis not the latest order) keeps the current paid period (:430).revoked: trueflag keep never re-granting (:163).obfuscated_account_id = HMAC-SHA256(PLAY_ACCOUNT_ID_HMAC_KEY, uid)(backend/config/play_billing.py:132). The key comes from Secret Manager (secretPLAY_ACCOUNT_ID_HMAC_KEY, at least 32 characters). Without it no Play config is issued (:75) and verify answers503 play_not_configured.HMAC(uid) == id(backend/utils/play_billing.py:391) and never moves an existing binding.Play reviewer build
PlayBillingDisclosure(renewal at the shown price until cancelled, managed and cancelled in Google Play, Billed by Google Play) replaces "Cancel anytime" for Play-billed readers (app/lib/pages/paywall/trial_paywall_page.dart:221). Terms and Privacy stay in the page footer.app/lib/pages/capture/connect.dart:30). Everyone else keeps the browser.PlayPlansError(the plans sheet'sOmiErrorStatewith Retry,play_plans_content.dart:267) replaces the dead "Unable to load plans" on the trial (trial_paywall_page.dart:380) and outline (outline_paywall_page.dart:240) paywalls. Retry re-reads the subscription when that failed, otherwise reloads Play's offers. A failed subscription read ends the outline skeleton (UsageProvider.billingProviderFailed).price.formatted, which is Play's string for Play readers and the same string as before for Stripe (trial_paywall_page.dart:397,:409). The computed "was" (12 × monthly) and "Save" amounts are hidden for Play readers. The CTA uses Play's own trial-phase string ("Try for Free" / "Try for ₹0.00") instead of an app-formatted zero (:457). The outline yearly card's computed per-month is replaced by "Billed yearly" for Play readers (outline_paywall_page.dart:251); its "Save N%" is computed from Play's two prices in the same currency.Deployment configuration (item 8)
Declared on the prod Cloud Run
backendservice (backend/deploy/runtime_env/prod.overlay.yaml, composed intobackend/deploy/runtime_env.yaml):PLAY_RTDN_OIDC_AUDIENCEhttps://api.omi.me/v2/internal/play-billing/rtdnPLAY_RTDN_PUSH_SA[email protected]PLAY_RECONCILE_OIDC_AUDIENCEhttps://api.omi.me/v2/internal/play-billing/reconcilePLAY_RECONCILE_INVOKER_SA[email protected]PLAY_ACCOUNT_ID_HMAC_KEYPLAY_ACCOUNT_ID_HMAC_KEY, versionlatestANDROID_PLAY_BILLING_MIN_BUILD'1617'(prod.overlay.yaml:655): the last internal build, 1616, predates these fixes; every later build is cut from main after this PRANDROID_PLAY_BILLING_COHORT''(members come from the rollout cohort below)ANDROID_BILLINGstripe(onlyplaysends every new Android purchase to Google)PLAY_ACCOUNT_ID_HMAC_KEYin projectbased-hardware(for exampleopenssl rand -hex 32) and grant[email protected]roles/secretmanager.secretAccessoron it before the first backend deploy that includes this PR. Cloud Run refuses a revision whose secret does not exist.gcloud compute url-maps describe custom-domains-49a4sendsapi.omi.me/*(so/v1/payments/play/*and/v2/internal/play-billing/*) to backend servicecustom-domains-api-omi-me-backend-49a4-be. That is the serverless NEGcustom-domains-api-omi-me-backend-49a4-neg, i.e. Cloud Runbackend. Only/v1/sync-local-files,/v2/sync-local-files,/v1/users/migration/batch-requestsand/v1/sync/audio/*go to backend-sync,/v3|v4/listento backend-listen, and/v2/integrations/*and/v1/mcp*to backend-integration.backendhas noOMI_ROLE, so it mounts every router. No other service needs these keys.backend(routes answer 403) and drops the secret (unmapped).PLAY_RTDN_PUSH_SAis added to the staging diff allow-list next to*_INVOKER_SA.config/deployment-setting-classification.json(secret / config), and the flag registry doc is regenerated.scripts/pre-deploy-check.sh(704 passed);test_render_backend_runtime_env.py(the approved prod secret bindings now includePLAY_ACCOUNT_ID_HMAC_KEYonbackend);test_runtime_env_sources.py;test_backend_runtime_env_validator.py;cross_service_contract.py --all(0 new violations).Putting the test account on Play Billing (no uid in Git):
/tmp/play-tester-uid. The tool never prints it.GCP_AGENT_TIER=prod-operator,GOOGLE_APPLICATION_CREDENTIALSset), frombackend/:python scripts/rollout_cohort.py --uid-file /tmp/play-tester-uid --cohort android-play-billing --project based-hardware --environment prod --add --applyThis merges
cohorts.prod["android-play-billing"] = trueintorollout_cohorts/{uid}in the default Firestore database ofbased-hardware(the customer data plane,docs/runbooks/rollout-cohorts.md). It is not theomi-flagsdatabase:OMI_FLAGS_SOURCE=omi/omi-flagsis the separate flag store used by the LLM gateway and does not hold cohorts.--remove --apply.ANDROID_PLAY_BILLING_MIN_BUILDis read from the environment only (not from Firestore), so it is set here to1617to save a second config deploy. WithANDROID_BILLING=stripeand an empty cohort env,client_uses_playis still False for every client; a test uid is then enabled by theandroid-play-billingrollout cohort alone, with no redeploy.test_deployed_prod_values_send_nobody_to_play_without_the_rollout_cohort(backend/tests/unit/test_play_billing.py:654) reads the rendered prod values and proves: False on Android 1617 and 9999 without the cohort; True for the cohort uid on 1617, False on 1616; the switch-off subscription response is byte-identical on 1617 and 9999.Correction to #26078's description
macOS and Windows desktop changed only generated files in #26078. They do not show "Billed by Google Play"; their Manage billing button calls the portal endpoint, which now returns Google Play's subscriptions URL, and that opens in the browser. Flutter (iOS) and the web app show "Billed by Google Play" with the Play link.
Product invariants affected
INV-MEM-3 —
backend/services/users/account_deletion.py: the Play cancel moves out of the Stripe billing wrapper and fails as a retryable wipe error instead of a parked billing failure, and a failed admission cancel keeps grace actions incomplete. The wipe also drops the user's Play purchase records and account-map entries (newplay_billing_recordsstep). Memory and privacy deletion order are unchanged; the wipe never reports success while Google can still charge.INV-MEM-4 — named because
account_deletion.pyis under its glob. Memory intake, consolidation and promotion are untouched.How it was verified
test_play_billing.py(62) andtest_play_billing_money.py(49).purge_user_subtree, the Firestore query shape and outside-query guards, route policy inventory and preflight: 3802 + 663 passed.test_*account_deletion*,test_delete_account*andtest_rollout_cohort*suite.tests/routers/test_users.py(330), checkout, webhook and trial suites.pre-deploy-check.sh(704) and the runtime-env, render, validator and cross-service checks: all pass.play_billing_plans_sheet_test.dart,play_billing_test.dart,play_billing_platform_test.dart,omi_shop_hardware_test.dartandconnect_device_get_omi_test.dartpass.scripts/l10n.py checkok; analyzer clean on the changed files.subscriptionsv2:cancel, including which error Google returns for an already-ended subscription (handled either way by the re-read);app-hardwaremarker check, the off-site rule with Shop Pay, PayPal and a 3-D Secure card, and the post-purchase close, against a live order;Tests
backend/tests/unit/test_play_billing_money.py(deletion re-read, failed-cancel re-read, 400/403/503 retryable without the token, wipe-not-parked, legacy re-claim; refund then renewal, refund and revoke, refund then re-post, grace after refund, earlier-order refund; forged id, tampered map, missing key, write-once map),backend/tests/unit/test_play_billing.py(HMAC id, key-gated switch),backend/tests/unit/test_render_backend_runtime_env.py.test_play_billing_money.py): deletion without ADC for a user with no Play fields; grace admission with Google 503 then a reconciler run that cancels and completes; RTDN transport error whose message holds the token (absent fromstr(e)and the traceback); cancelled-with-time-left is cancelled, its failure does not park, an ended one needs no cancel; voided without order ids revokes; the wipe drops purchase docs and map entries.test_play_billing.py: deployed prod values.app/test/widgets/play_billing_plans_sheet_test.dart(trial disclosure, Play price strings, no computed was/save, Play trial CTA, Retry on outline and trial, failed subscription read recovers; round 2: 3-day Play trial, a plan with no trial phase, a Play client that never answers ends in Retry),app/test/unit/omi_shop_hardware_test.dart(template forcing, allowed and blocked URLs, off-site only from checkout, post-purchase closes, marker present shows / missing blocks).UI evidence
UI-Evidence: none -- these Play screens only render with Play config from the server; widget tests cover each state.
Failure class (fixes)
Failure-Class: none