State machines
Every lifecycle the API persists, its invariants, its legal transitions, and the reachable invalid states that were found and fixed.
Each lifecycle below is stored in Postgres and changed only by the named service. A transition not listed is illegal. "Guard" is the SQL predicate or lock that enforces it under retries and concurrency, so check the guard before you add a transition.
Subscription (subscriptions.status, users.is_premium)
Owner: apps/server/src/domains/billing/service.ts. Input: provider webhooks normalized by
@app/billing, plus billing:reconcile.
States: incomplete, trialing, active, past_due, unpaid, paused, canceled,
incomplete_expired. canceled covers both a scheduled cancellation (period end in the future) and
an ended subscription (period end in the past).
Invariants:
- One transaction claims
(provider, event_id)and applies the change; a failure rolls back both, so the provider retry is the recovery path. - A per-subscription advisory lock serializes events; an event older than
provider_modified_atchanges nothing. users.is_premiumequalsevaluateSubscriptionEntitlementof the row as of the last event. Access checks read the row, never the flag.- A scheduled cancellation (
cancelAtPeriodEndwhile active or trialing) is stored ascanceled. - An ended
canceledsubscription stores the earlier of its period end and its end time, and once that end has passed no latercanceledstate moves it forward, so no event or reconciliation restores access, unless the provider reports the subscription active or trialing with a period that starts at or after that end (a renewal on the same subscription).
| Event | From | To | Paid access after |
|---|---|---|---|
subscription.created | none | provider status | per entitlement |
subscription.active | none or any | active, or canceled if still scheduled | yes |
subscription.updated | any | provider status (scheduled → canceled) | per entitlement |
payment.failed | any | past_due / unpaid / paused | no |
subscription.canceled | any | canceled, period end kept | until period end |
subscription.uncanceled | canceled | provider status, canceled_at cleared | per entitlement |
subscription.revoked | any | canceled, period end clamped to end time | no |
reconcile --apply | drifted | remote state via subscription.updated | per entitlement |
Revocation sources: Polar subscription.revoked, Stripe customer.subscription.deleted, Dodo
subscription.cancelled and subscription.expired (Dodo represents a scheduled cancellation as an
active subscription with cancel_at_next_billing_date, so a cancelled status has ended).
Checkout intent (billing_checkout_intents)
open (consumed_at IS NULL, unexpired) → consumed. A partial unique index allows one open
intent per user; concurrent checkouts reuse it. Consumed by expiry (on the next checkout), by
subscription.created / .active, or by payment.failed.
Organization membership (organization_members.role)
Owner: apps/server/src/domains/organizations/service.ts.
Invariants: exactly one owner per organization (unique partial index for "at most", the transfer
transaction for "at least"); a personal organization has exactly its creator; an organization with
no members is deleted by trigger; users.active_organization_id falls back to the personal
organization when it points at a lost membership.
| Action | Transition | Guard |
|---|---|---|
| invite accept | none → admin / member | invitation claim (below) |
| change role | admin ↔ member | role <> 'owner' |
| remove / leave | admin / member → none | role <> 'owner' |
| transfer | owner → admin, target → owner | locks both member rows in user order; demotes only the caller's own owner row; zero rows promoted rolls back |
| delete team | all → none | owner permission; locks the team's member rows first; members return to personal organization |
| delete account | non-owner team rows → none | locks own member rows, then revokes owned-team invitations, then locks owned teams; refused while one has other active members |
Invitation (organization_invitations)
open → accepted | revoked; open past expires_at is expired (derived, never stored). A
unique partial index allows one open row per organization and email, and that index cannot see
expiry, so creating a new invitation first revokes an expired one. Acceptance claims the row with
accepted_at IS NULL AND revoked_at IS NULL AND expires_at > NOW() in the same transaction that
adds the member. Deleting an account revokes open invitations to the teams it owns.
Upload (uploads.status)
Owner: apps/server/src/domains/upload/service.ts.
| From | To | Trigger |
|---|---|---|
| none | pending | presign |
pending | validating | confirm claims the row (also reclaims a claim idle 10 minutes) |
validating | completed | object validated and published |
validating | failed | object missing, wrong size, type, or bytes, changed, or claim expired |
validating | pending | unexpected error (storage outage, lost org access); retry allowed |
Only one confirmation can complete: completion and failure both require status = 'validating'.
Account (users.status) and sessions
active → deleted only (the inactive and suspended values are unused). Deletion is refused
while billing can still renew or paid access remains, or while the account owns a shared team. It
removes sessions, accounts, and push devices in the same transaction, and a trigger refuses a
session insert for a non-active user.
Start edition (apps/start, D1)
Subscription statuses are trialing, active, past_due, canceled, expired; a revocation or
an ended cancellation is expired. One row per user, upserted only when the event's provider time
is not older. Invitations are deleted and replaced on re-invite, and expired ones are pruned by the
cron. Ownership transfer is one D1 batch that demotes the caller only when the target is a non-owner
member.
Findings, November 2026
Fixed, each with a regression test:
- Revocation kept paid access.
subscription.revokedran the scheduled-cancel path, so a mid-period revoke (Stripe immediate cancel, Polar revoke) kept access and blocked a new checkout until the old period ended. A revoke following a scheduled cancellation was skipped as a duplicate and leftis_premiumtrue. Dodocancelled/expiredhad the same effect. subscription.activeerased a scheduled cancellation, storingactivewithcanceled_atset.- Expired invitations blocked re-invites forever: the open-invitation index ignores expiry and the list hides expired rows, so the admin could neither resend nor revoke.
- Ownership transfer could leave a team with no owner when the target left or was removed concurrently, and a caller whose ownership had already moved could still transfer.
- Deleting an account left teams owned by a deleted user with no one able to manage them.
- A transient storage error during confirmation failed the upload permanently instead of releasing the claim for a retry.
- An ended subscription could regain access from a later
subscription.updatedor reconciliation that reported the original period end without an end time. - Accepting an invitation while the team owner deleted the account deadlocked (one side got a 500), and a transfer to an account being deleted left the team owned by a deleted user.
Known and accepted:
- Accepting an invitation while the team is being deleted can deadlock (a 500 for one side); this was already true before these changes.
- A confirmation that runs longer than 10 minutes can be reclaimed by a second request; the slower one then fails its completion and deletes its published copy. No request path runs that long.
- The open-invitation cap of 50 is checked before insert and can be exceeded by concurrent invites.
- Start edition account deletion checks for shared teams before its delete batch, so a member joining in between is removed with the team.