Skip to content

feat(billing): lazy reconcile on certification paywall hit (#3623 step 3) - #3663

Merged
bokelley merged 1 commit into
mainfrom
bokelley/lazy-reconcile
Apr 30, 2026
Merged

bokelley merged 1 commit into
mainfrom
bokelley/lazy-reconcile

Conversation

@bokelley

Copy link
Copy Markdown
Contributor

Summary

When a Stripe customer is re-linked between orgs (admin audit, support fix-up) without subscription state being transferred to the new org row, the user appears as a non-member at the next paywall hit despite holding an active membership in Stripe. The four certification gates now lazy-heal from Stripe before denying. The user clicking the paywall is the trigger; they never see the drift.

Diagnosis

Three real cases observed in production: Lina (cus_UF4bV…), HYPD (cus_TajjN…), Yoshihiko (cus_Tpzj…). All three already manually fixed during the investigation that motivated this work (see #3627 and #3643 PR descriptions).

The Stripe-side investigation revealed these are not missed-webhook bugs. Stripe customer metadata explicitly records relinked_at / previous_workos_organization_id for at least one (Lina). The original customer.subscription.created webhook fired correctly against the original org. Some later admin process re-linked the customer to a different org but didn't transfer subscription state to the new org's row.

This makes lazy reconciliation the right shape (instead of the cron auto-remediation we were originally scoping):

Failure mode Cron auto-remediate Lazy reconcile on paywall
Missed webhook ✅ catches ✅ catches
Customer relinked, state not transferred ✅ catches ✅ catches
Customer-impact latency up to 1 hour < 1 second
Notification cascade misfires (welcome DM weeks late) risk none — no welcome cascade
Legal: backfilled attestation without click-through risk n/a — no attestation written

Lazy reconcile dominates on every axis at AAO's scale.

What changed

  1. New module server/src/billing/lazy-reconcile.ts exporting attemptStripeReconciliation(orgId, deps).

    • Reads org row; skips if already entitled or no stripe_customer_id
    • Pulls customer + active subs from Stripe, filters via pickMembershipSub (from fix(billing): /sync picks membership sub, not subscriptions.data[0] (#3623 step 2) #3646)
    • UPDATE … WHERE subscription_status IS NULL OR = 'none' — concurrent webhook writes always win
    • Returns { healed, reason } for caller logging
    • Only writes the subscription_* columns; deliberately not attestation/audit/activity rows
  2. server/src/addie/mcp/certification-tools.ts:

    • memberContext is now a let so successful heals are visible to subsequent calls in the same handler turn
    • New ensureMembership() helper wraps the heal call
    • Four gates (get_certification_module, start_certification_module, test_out_modules, start_certification_exam) call ensureMembership() before denying
  3. .gitignore: adds .stripe-key (live Stripe key file).

What it deliberately doesn't do

  • No attestation/audit/activity writes. The webhook handler (handle-subscription-created.ts) is the canonical place for those side effects, keyed off pending_agreement_user_id from checkbox-click time. A paywall click is action-signal but not fresh consent. Lazy reconcile heals the entitlement gate; legal records remain a webhook concern.
  • No reverse direction. (NULL|none) → entitled only; never overwrites an existing active/canceled/etc. status.
  • No cron. Per the diagnosis above and expert review converged in this thread, the cron design was overengineering — lazy reconcile delivers the customer-impact fix without the architectural lift.

Verification

End-to-end against the sandbox lina_class fixture (#3643):

=== Before heal ===
{ subscription_status: null, stripe_subscription_id: null }

=== Running heal ===
result: { healed: true, reason: 'healed_from_stripe', subscriptionStatus: 'trialing' }

=== After heal ===
{ subscription_status: 'trialing', stripe_subscription_id: 'sub_…', amount: 25000, lookup_key: 'aao_membership_professional_250' }

=== Re-run on healed row (idempotency) ===
result: { healed: false, reason: 'already_entitled' }

Test plan

  • 11-case unit test for attemptStripeReconciliation: happy path, all skip reasons, multi-sub correct picking (the data[0] regression class), concurrent-webhook race, transient Stripe error, trialing-as-entitled
  • Existing 67 tests in tests/unit/integrity/ and tests/unit/billing/ still pass
  • npx tsc --noEmit clean
  • Pre-commit hook passes (unit + dynamic imports + typecheck)
  • End-to-end manual test against sandbox lina_class fixture
  • Reviewer: pull a recent membership-required Addie escalation; if the org has stripe_customer_id IS NOT NULL, the heal would fire on the next gate hit

Refs

🤖 Generated with Claude Code

…p 3)

When a Stripe customer is re-linked between orgs (admin audit, support
fix-up) without subscription state being transferred to the new org
row, the user appears as a non-member at the next paywall hit despite
holding an active membership in Stripe. Three real cases observed in
production (Lina/HYPD/Yoshihiko, manually fixed via /sync). Diagnosis
showed these are not missed webhooks — the original webhook fired
correctly against the original org; some later admin process re-linked
the customer's stripe_customer_id pointer without transferring state.

The four certification gates (get_certification_module,
start_certification_module, test_out_modules, start_certification_exam)
now call ensureMembership() before denying. ensureMembership delegates
to attemptStripeReconciliation which:

- Reads org row; skips if already entitled or no stripe_customer_id
- Pulls customer + active subs from Stripe
- pickMembershipSub filters to membership lookup_keys
- UPDATEs subscription_* columns with WHERE subscription_status IS NULL
  guard so concurrent webhook writes always win
- Returns {healed, reason} for caller logging

The user clicking the paywall is the trigger; they never see the drift.
Within this handler turn, in-memory memberContext is updated so the rest
of the handler proceeds with member-status semantics.

Deliberate scope: does NOT write user_agreement_acceptances, audit log,
or org_activities rows. The webhook handler (handle-subscription-created)
is the canonical place for those side effects, keyed off
pending_agreement_user_id from checkbox-click time. Paywall click is
action-signal but not fresh consent.

Verified end-to-end against the sandbox lina_class fixture: drift
detected, heal succeeds, row populated with subscription_id + amount +
lookup_key. Re-run on healed row returns already_entitled (idempotent).

Adds .stripe-key to .gitignore (live Stripe key file).

Tests: 11-case unit suite covering happy path, all skip reasons
(no_stripe_customer, customer_deleted, no_membership_sub, sub_not_entitled),
multi-sub correct picking, concurrent-webhook race, transient Stripe error,
trialing-as-entitled.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant