Repository navigation
feat(analytics): measure the subscription funnel by tier and surface - #21337
Conversation
Paywall events carried the billing period instead of the tier, and Stripe webhook events omitted the catalog amount ARPMAU needs. Co-authored-by: Cursor <[email protected]>
The mobile changelog gate requires a fragment for app edits, and these analytics calls do not change what a user sees. Co-authored-by: Cursor <[email protected]>
Transcription settings and the unlimited deep link opened the sheet without Paywall Opened, and a successful paid-plan change never emitted Upgrade Succeeded. Co-authored-by: Cursor <[email protected]>
The matched-case force unwrap is rejected by the desktop lint gate. Co-authored-by: Cursor <[email protected]>
Webhook mrr_cents stays a USD list price, and web checkout continues when PostHog throws. Co-authored-by: Cursor <[email protected]>
The throwing-capture test forwarded an untyped rest list into createCheckoutSession, which tsc rejects in the web pre-push gate. Type the price id, and wrap the Windows year check so the classifier stays readable. Co-authored-by: Cursor <[email protected]>
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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ae759041cb
ℹ️ 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".
| WHERE snapshot_date = ( | ||
| SELECT MAX(snapshot_date) | ||
| FROM `based-hardware.omi_finops.plan_revenue_daily` |
There was a problem hiding this comment.
Bound the MRR snapshot to the selected week
The documented join requires the latest snapshot on or before the HogQL week_end, but this subquery always selects the table's all-time maximum. As soon as a newer snapshot exists, rerunning an earlier week pairs that week's MAU with future revenue and silently changes its ARPMAU. Pass the selected week end into this query and include it in the MAX(snapshot_date) predicate.
Useful? React with 👍 / 👎.
| case 'refresh_lagging': | ||
| toast('Payment received', { tone: 'warn', body: REFRESH_LAGGING_MSG }) | ||
| break | ||
| setSelectedPlanId(null) | ||
| await load() | ||
| return |
There was a problem hiding this comment.
Preserve completed checkouts when refresh is lagging
A refresh_lagging result is reached only after openCheckout returned success; the UI even reports “Payment received.” Returning here skips trackUpgradeSucceeded, and no later refresh emits it, so every successful checkout whose subscription projection takes more than eight seconds is permanently counted as selected but not completed. Emit the attributed success based on the checkout outcome before waiting for the entitlement refresh.
Useful? React with 👍 / 👎.
| case "pro": | ||
| return "unknown" |
There was a problem hiding this comment.
Canonicalize the legacy pro plan as architect
Legacy macOS subscription documents can still contain pro, and SubscriptionPlanType explicitly treats that value as the backward-compatible Architect plan. Mapping it to unknown causes settings and quota paywall impressions from those existing paid subscribers to lose their tier, skewing the newly added per-tier funnel; normalize pro to architect instead.
Useful? React with 👍 / 👎.
| WHERE event = 'Product Value' | ||
| AND timestamp >= {date_from} - INTERVAL 120 DAY | ||
| AND timestamp < {date_to} |
There was a problem hiding this comment.
Keep activation anchored to the actor's first-ever value event
The rolling 120-day lower bound makes min(timestamp) only the first event inside that lookback. Once Product Value history is older than 120 days, a previously activated user who emits another value event during the selected week will be counted as newly activated, inflating activated_users and corrupting the paid-conversion cohort. Use the event's fixed inception boundary or otherwise exclude actors with earlier Product Value events.
Useful? React with 👍 / 👎.
| // Stripe Checkout opens in a new tab. The parent page never sees the | ||
| // cancel URL Stripe returns to, so Upgrade Cancelled is not emitted | ||
| // here. trackUpgradeCancelled exists for a client that can observe it. |
There was a problem hiding this comment.
Record successful web checkout returns
For every new web subscription that uses Stripe Checkout, this branch only refreshes the parent when the browser regains focus and never emits trackUpgradeSucceeded, even if the refreshed subscription now matches the selected price. Consequently the predominant web purchase path always has a plan-selection event but no attributed completion, while only in-place upgrades and reactivations appear successful. On focus, fetch and verify the subscription before emitting the selected tier and interval.
Useful? React with 👍 / 👎.
| -- Closed properties only: source, current_plan, plan, billing_interval, previous_plan, new_plan, change_source, reason, has_details, step. | ||
| -- Upgrade Succeeded and Upgrade Cancelled are the property-less presence names. | ||
| -- Upgrade Succeeded Attributed is the checkout success that carries tier and interval. | ||
| SELECT event, COUNT(*) AS emitted |
There was a problem hiding this comment.
Project the funnel dimensions in the consumer query
The registered consumer asks for completion and abandonment by surface, tier, and billing interval, but this projection selects and groups only by event name. It therefore returns undifferentiated presence counts and cannot answer the question the new properties were added for; in particular, it cannot associate the property-less success/cancellation events with a preceding sourced selection. Project the relevant properties and implement the actor/sequence correlation needed for per-dimension conversion.
Useful? React with 👍 / 👎.
| func checkoutSelection(for priceId: String) -> (plan: String, interval: String) { | ||
| for plan in fallbackPlanCatalog { | ||
| if let price = plan.prices.first(where: { $0.id == priceId }) { | ||
| return (plan.id, SubscriptionFunnelWire.interval(price.title)) |
There was a problem hiding this comment.
Search the merged catalog for checkout attribution
The plan cards are built from mergedPlanCatalog, whose primary source is userSubscription.availablePlans, but this lookup searches only fallbackPlanCatalog. If the optional getAvailablePlans() request fails while the subscription response still contains its embedded catalog, checkout remains available and succeeds, yet every selection and completion is emitted with an unknown billing interval. Resolve the price from the same merged catalog used to render the selectable cards.
Useful? React with 👍 / 👎.
| WHERE event = 'Billing Subscription Cancellation Scheduled' | ||
| AND timestamp >= {date_from} | ||
| AND timestamp < {date_to} |
There was a problem hiding this comment.
Bucket billing movement by Stripe occurrence time
Backend billing events preserve Stripe's authoritative event time in properties.occurred_at, but these weekly predicates use PostHog ingestion timestamp. A delayed webhook delivery or retry that crosses a week boundary is therefore assigned to the wrong week, making the movement series change with delivery latency rather than billing activity. Parse and filter occurred_at, with ingestion time only as a fallback for older rows.
Useful? React with 👍 / 👎.
| ( | ||
| SELECT count() | ||
| FROM events | ||
| WHERE event = 'Billing Subscription Cancellation Scheduled' | ||
| AND timestamp >= {date_from} | ||
| AND timestamp < {date_to} |
There was a problem hiding this comment.
Deduplicate scheduled cancellations by billing event ID
This raw count() treats repeated delivery of the same Stripe event as multiple cancellations. Unlike start or churn, replaying a customer.subscription.updated cancellation payload still satisfies _cancellation_just_scheduled because its previous_attributes remain false-to-true, so an acknowledged-late or retried webhook can emit the same billing_event_id repeatedly. Count distinct billing_event_id values rather than PostHog rows.
Useful? React with 👍 / 👎.
What changed and why
The paywall funnel was not measurable by tier or surface: mobile
Upgrade Plan Selectedsent the billing period asplanand a hardcoded source, and several plans-sheet openers emitted nothing. This registers one closed vocabulary and emits it from mobile, macOS, Windows, and web. ARPMAU's numerator is the BigQueryplan_revenue_dailysnapshot (mrr_usd), joined to HogQL MAU as the latestsnapshot_dateon or before the exclusive week end. Webhook events measure movement. Theirmrr_centsis a USD list price and stays out of ARPMAU until a payer census exists.Upgrade SucceededandUpgrade Cancelledstay property-less because released wire shapes are immutable. A completed checkout also emitsUpgrade Succeeded Attributedwithplanandbilling_interval.Upgrade Modal ClickedandUpgrade Modal Dismissedstay the app-version update prompt; they are documented on theapp-update-promptconsumer and are not in the funnel query. Wire names are unchanged so existing presence dashboards keep counting them.Product invariants affected
app/lib/pages/chat/page.dartnow emitsPaywall Openedwhen the existing chat-quota sheet opens. No transcript, message store, or continuity change.app/lib/pages/memories/widgets/memory_item.dartlabels the locked-memory paywalllocked_memory. No tier, access policy, or memory content change.How it was verified
python3 scripts/check_event_registry.py— 159 events, consumers executable, generated Dart current.backend/.venv/bin/python -m pytest scripts/product-telemetry/test_scorecard.py::test_checked_in_posthog_queries_have_bounded_window_and_sentinel_limit --noconftest— 1 passed.BACKEND_UNIT_TEST_FILE_LISTcoveringtest_billing_product_events.py(9) andtest_jpy_price_recognition.py(13), viabash backend/test.sh— all passed. The changed-file selector falls back to the full suite becausesubscription_events.pyis unmapped; that full suite was not run locally.flutter test test/unit/analytics_manager_fail_open_test.dart— 28 passed. An earlier run of the analytics goldens, plans sheet, update prompt, usage page, and locked-conversation tests passed 61.bunx vitest runonsubscriptionFunnel.test.tsandPlansSheet.checkout.test.tsx— 3 passed. A throwing PostHog capture still starts checkout../node_modules/.bin/vitest run src/renderer/src/lib/analytics.test.ts— 7 passed.pnpm execwas not used: the machine's pnpm 11 tried to purgenode_moduleswith no TTY. This repo's Windows guide pins pnpm 10.xcrun swift test --package-path Desktop --filter SubscriptionFunnelTelemetryTests— 2 passed.subscription-baseline.hogqlagainst PostHog project 302298 for [2026-10-05, 2026-10-12) UTC finished in 6.22s: MAU 21977 (trailing 30 days [2026-09-12, 2026-10-12)), activated users 1247, billing movement 0, webhook MRR and paid conversion NULL.plan_revenue_daily(--maximum_bytes_billed=2147483648): snapshot_date 2026-10-12, mrr_usd 69240.78, paying_subs 2954, trialing_subs 26. ARPMAU = 69240.78 / 21977 = 3.150602 for that week.Tests
backend/tests/unit/test_billing_product_events.pycovers price id, USD round-half-upmrr_cents, trials omittingmrr_cents, andprice_generation.test_jpy_price_recognition.pycovers the JPY fixture omittingmrr_cents.app/test/utils/analytics/c8_slice4_goldens_test.dartandapp/test/unit/analytics_manager_fail_open_test.dartcover the mobile wire names.desktop/macos/Desktop/Tests/SubscriptionFunnelTelemetryTests.swift,desktop/windows/src/renderer/src/lib/analytics.test.ts, andweb/app/src/lib/analytics/__tests__/subscriptionFunnel.test.tscover the closed plan, interval, and source vocabulary.UI evidence
UI-Evidence: none -- telemetry only, no visible UI change
Failure class (fixes)
Failure-Class: none
Line-count exceptions
Line-Count-Exception: app/lib/pages/settings/transcription_settings_page.dart | 1547 -> 1554 | Paywall Opened stays beside the existing transcription-settings usage link.
Line-Count-Exception: app/lib/utils/analytics/analytics_manager.dart | 2918 -> 3059 | Closed funnel emitters stay on AnalyticsManager rather than a new wrapper.
Line-Count-Exception: backend/routers/payment.py | 1646 -> 1647 | Webhook forwards previous_attributes into the billing event.
Line-Count-Exception: desktop/macos/Desktop/Sources/AnalyticsManager.swift | 1651 -> 1740 | macOS funnel emitters stay on AnalyticsManager beside existing events.