diff --git a/AGENTS.md b/AGENTS.md index 65e761e..edb47e0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -99,11 +99,11 @@ protected signed annotated `vX.Y.Z` tag already on `origin/main`, followed by ## Where things stand -Phase 2: `@pegma/billing-core` (ledger collection, `(eventAt, eventId)` +Phase 3: `@pegma/billing-core` (ledger collection, `(eventAt, eventId)` watermark, effective-watermark guard, lifecycle-rank tie-break, declared -`sticky` / `firstWins` combinators, checkout reservation). Nothing is -published. Snapshot reconciliation is Phase 3; `@pegma/billing-stripe` is -Phase 4 — do not create those packages here yet. +`sticky` / `firstWins` combinators, checkout reservation, snapshot +reconciliation). Nothing is published. `@pegma/billing-stripe` is Phase 4 +— do not create that package here yet. Siblings: [spine](https://github.com/pegma-dev/spine), [storage-core](https://github.com/pegma-dev/storage-core), diff --git a/README.md b/README.md index 5e36569..808d665 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ hosts: the durable record of what a customer's subscription **is**, maintained correctly under out-of-order webhook delivery. > [!IMPORTANT] -> Pegma is in early `0.x` development. `@pegma/billing-core` Phase 2 is +> Pegma is in early `0.x` development. `@pegma/billing-core` Phase 3 is > in-tree and unpublished. No public API is stable. ## The part everyone gets wrong @@ -29,10 +29,10 @@ makes that impossible: - periodic **snapshot reconciliation** that repairs field drift without disturbing the dedup identity of the events themselves. -Phase 2 ships the watermark, the effective-watermark guard, +Phase 3 ships the watermark, the effective-watermark guard, lifecycle-rank arbitration, declared ledger invariants (`sticky`, -`firstWins`), and the checkout reservation. Snapshot reconciliation and -the Stripe adapter are later phases. The core knows lifecycle states, not +`firstWins`), the checkout reservation, and snapshot reconciliation. +The Stripe adapter is a later phase. The core knows lifecycle states, not Stripe's vocabulary. And the data boundary is absolute: the ledger stores provider identifiers and derived state — never a card number, a raw payload, or an amount. @@ -54,10 +54,10 @@ application. ## Packages -| Package | Role | Phase | -| ----------------------- | ------------------------------------------------ | ----- | -| `@pegma/billing-core` | Ledger, watermark, rank, invariants, reservation | 2 | -| `@pegma/billing-stripe` | Event and snapshot translation | later | +| Package | Role | Phase | +| ----------------------- | ------------------------------------------------------- | ----- | +| `@pegma/billing-core` | Ledger, watermark, rank, invariants, reservation, sweep | 3 | +| `@pegma/billing-stripe` | Event and snapshot translation | later | The Stripe adapter package is not created until Phase 4. diff --git a/docs/PROJECT_PLAN.md b/docs/PROJECT_PLAN.md index fca302a..953d196 100644 --- a/docs/PROJECT_PLAN.md +++ b/docs/PROJECT_PLAN.md @@ -2,7 +2,7 @@ ## Status -**Stage:** Phase 2 — combinators and reservation in-tree. Nothing is +**Stage:** Phase 3 — snapshot reconciliation in-tree. Nothing is published. (`0.1.0`, unpublished.) **Extraction source:** the RetireGolden account API's subscription ledger — @@ -166,12 +166,12 @@ Ledger collection, watermark, effective-watermark guard, lifecycle rank, equal-second tie-breaking. The reference implementation's race tests are the conformance bar; suite runs over memory and real Azurite. -### Phase 2 — invariant combinators and the reservation (this tree) +### Phase 2 — invariant combinators and the reservation `sticky` and `firstWins` as declared rules; the single-opportunity reservation with its read-winner-back semantics and TTL expiry. -### Phase 3 — snapshot reconciliation +### Phase 3 — snapshot reconciliation (this tree) The sweep, the domain CAS token, the always-write freshness rule — with the delayed-intermediate-webhook scenario pinned as a named test. @@ -191,11 +191,10 @@ acceptance bar. ## Timing -Phase 2 is implemented in-tree. Later phases remain gated: snapshot -reconciliation (Phase 3) and the Stripe adapter (Phase 4) wait until a -named consumer needs them. Phase 5 (first consumer cutover) stays gated -on that application's operational calendar — never swap code under a soak -or mid-migration. +Phase 3 is implemented in-tree. Later phases remain gated: the Stripe +adapter (Phase 4) waits until a named consumer needs it. Phase 5 (first +consumer cutover) stays gated on that application's operational calendar +— never swap code under a soak or mid-migration. ## Open questions diff --git a/packages/billing-core/README.md b/packages/billing-core/README.md index a78314f..ed8af78 100644 --- a/packages/billing-core/README.md +++ b/packages/billing-core/README.md @@ -2,8 +2,8 @@ Provider-agnostic subscription ledger for Pegma hosts: a per-account watermark, an effective-watermark guard, lifecycle-rank tie-breaking at -the equal second, declared write-path invariants, and a single-opportunity -checkout reservation. +the equal second, declared write-path invariants, a single-opportunity +checkout reservation, and snapshot reconciliation. > [!IMPORTANT] > Pegma is in early `0.x` development. This package's public API is unstable. @@ -47,12 +47,26 @@ const reserved = await ledger.reserve("acct_456"); if (reserved.reserved) { await ledger.release("acct_456", reserved.reservationId); } + +await ledger.reconcile("acct_123", async (observed) => ({ + status: observed.status, + providerCustomerId: observed.providerCustomerId, + providerSubscriptionId: observed.providerSubscriptionId, + providerPriceId: observed.providerPriceId, + plan: observed.plan, + periodStartAt: observed.periodStartAt, + periodEndAt: observed.periodEndAt, + trialStartAt: observed.trialStartAt, + trialEndAt: observed.trialEndAt, + cancelAtPeriodEnd: observed.cancelAtPeriodEnd, +})); ``` Hosts inject a `@pegma/storage-core` `Store` and, optionally, a Spine -`Clock` and `Logger`. Reservation TTL is taken from the injected clock — -never from `Date.now()`. This package never creates a network client and -never stores card data, raw payloads, line items, or amounts. +`Clock` and `Logger`. Reservation TTL and snapshot freshness (`snapshotAt`) +are taken from the injected clock — never from `Date.now()`. This package +never creates a network client and never stores card data, raw payloads, +line items, or amounts. Arrival order proves nothing. Every apply goes through the effective-watermark guard and lifecycle rank. Exact redelivery is an idempotent no-op. @@ -62,6 +76,18 @@ enforced inside the update decider, so they re-evaluate against fresh state on every conflict. A reservation id is minted inside the decider and read back from storage; the caller's id is whatever the stored record says. -Phase 2 is the arbitration core plus combinators and reservation. Snapshot -reconciliation and the Stripe adapter are later phases — do not import them +Snapshot reconciliation observes the domain CAS token `(eventAt, eventId)` +and the current `snapshotAt` / `snapshotGeneration`, samples the freshness +bound from the injected clock, then fetches provider truth. The decider +re-checks the watermark and the observed generation against fresh state. +An intervening event or a newer reconciliation drops the snapshot. A +reservation-only row is skipped so a founding webhook is not gated by an +invented bound. A token match always writes — even when no field changed — +and increments `snapshotGeneration` so overlapping same-bound sweeps cannot +clobber fresher fields. `snapshotAt` never jumps into a later Unix second +than the sampled bound, so same-second webhooks still get lifecycle-rank +arbitration. The watermark identity is never touched. + +Phase 3 is the arbitration core, combinators, reservation, and snapshot +reconciliation. The Stripe adapter is a later phase — do not import it from this package. diff --git a/packages/billing-core/package.json b/packages/billing-core/package.json index 0b364c7..85102d7 100644 --- a/packages/billing-core/package.json +++ b/packages/billing-core/package.json @@ -1,7 +1,7 @@ { "name": "@pegma/billing-core", "version": "0.1.0", - "description": "Provider-agnostic subscription ledger: event watermark, lifecycle-rank arbitration, declared invariants, and checkout reservation.", + "description": "Provider-agnostic subscription ledger: event watermark, lifecycle-rank arbitration, declared invariants, checkout reservation, and snapshot reconciliation.", "license": "MIT", "type": "module", "sideEffects": false, diff --git a/packages/billing-core/src/index.test.ts b/packages/billing-core/src/index.test.ts index c9b187a..9cad4fb 100644 --- a/packages/billing-core/src/index.test.ts +++ b/packages/billing-core/src/index.test.ts @@ -23,8 +23,10 @@ import { billingLedgerKey, createBillingLedger, decideLedgerApplication, + decideLedgerSnapshot, decideReservation, DEFAULT_RESERVATION_TTL_MS, + DEFAULT_SWEEP_LIMIT, effectiveWatermarkSecond, firstWins, hasReservationProvenance, @@ -33,10 +35,14 @@ import { isGrantingStatus, LIFECYCLE_RANK, lifecycleRank, + observeSnapshot, + observeWatermark, reservationIsLive, sticky, + watermarksMatch, type LedgerEvent, type LedgerRecord, + type LedgerSnapshot, } from "./index.js"; declare module "vitest" { @@ -93,6 +99,24 @@ function event( }; } +function snapshot( + overrides: Partial> = {}, +): LedgerSnapshot { + return { + status: "active", + providerCustomerId: "cus_123", + providerSubscriptionId: "sub_123", + providerPriceId: "price_pro", + plan: "pro", + periodStartAt: "2026-08-01T00:00:00.000Z", + periodEndAt: "2026-09-01T00:00:00.000Z", + trialStartAt: null, + trialEndAt: null, + cancelAtPeriodEnd: false, + ...overrides, + }; +} + function record( accountId: string, overrides: Partial = {}, @@ -112,6 +136,7 @@ function record( eventAt: SECOND, eventId: "evt_seed", snapshotAt: null, + snapshotGeneration: 0, reservationId: null, reservationExpiresAt: null, reservationSeeded: false, @@ -773,6 +798,7 @@ describe("billing ledger codec", () => { eventAt: SECOND, eventId: "evt_seed", snapshotAt: null, + snapshotGeneration: 0, reservationId: null, reservationExpiresAt: null, reservationSeeded: false, @@ -1424,6 +1450,7 @@ describe("declared invariants", () => { eventAt: SECOND, eventId: "evt_seed", snapshotAt: null, + snapshotGeneration: 0, reservationId: null, reservationExpiresAt: null, reservationSeeded: false, @@ -1609,3 +1636,730 @@ describe("checkout reservation decider", () => { expect(isGrantingStatus("canceled")).toBe(false); }); }); + +describe("snapshot decider", () => { + it("always writes on a token match even when no field changed", () => { + const current = record("acct", { snapshotAt: null }); + const decision = decideLedgerSnapshot( + current, + observeSnapshot(current), + snapshot(), + SNAPSHOT_BOUND, + ); + expect(decision).toMatchObject({ + action: "write", + value: { + eventId: "evt_seed", + eventAt: SECOND, + snapshotAt: SNAPSHOT_BOUND, + snapshotGeneration: 1, + status: "active", + plan: "pro", + }, + }); + }); + + it("repairs field drift without touching watermark identity", () => { + const current = record("acct", { plan: "stale", snapshotAt: EARLIER }); + const decision = decideLedgerSnapshot( + current, + observeSnapshot(current), + snapshot({ plan: "pro", status: "past_due" }), + SNAPSHOT_BOUND, + ); + expect(decision.action).toBe("write"); + if (decision.action !== "write") { + return; + } + expect(decision.value).toMatchObject({ + plan: "pro", + status: "past_due", + eventId: "evt_seed", + eventAt: SECOND, + snapshotAt: SNAPSHOT_BOUND, + }); + }); + + it("drops the snapshot when the observed token no longer matches", () => { + expect( + decideLedgerSnapshot( + record("acct", { eventId: "evt_newer", eventAt: LATER }), + { + eventAt: SECOND, + eventId: "evt_seed", + snapshotAt: null, + snapshotGeneration: 0, + }, + snapshot({ plan: "should-not-land" }), + SNAPSHOT_BOUND, + ), + ).toEqual({ action: "keep", reason: "intervening-write" }); + }); + + it("does not create a row when none was observed", () => { + expect( + decideLedgerSnapshot( + null, + { + eventAt: SECOND, + eventId: "evt_seed", + snapshotAt: null, + snapshotGeneration: 0, + }, + snapshot(), + SNAPSHOT_BOUND, + ), + ).toEqual({ action: "keep", reason: "missing" }); + }); + + it("does not regress snapshotAt when the incoming bound is older", () => { + const current = record("acct", { snapshotAt: SNAPSHOT_BOUND }); + const decision = decideLedgerSnapshot( + current, + observeSnapshot(current), + snapshot(), + SECOND, + ); + expect(decision).toMatchObject({ + action: "write", + value: { + snapshotAt: SNAPSHOT_BOUND, + snapshotGeneration: 1, + eventId: "evt_seed", + }, + }); + }); + + it("increments snapshotGeneration on a same-bound write so the next CAS drops", () => { + const current = record("acct", { snapshotAt: SECOND, plan: "fresh" }); + const first = decideLedgerSnapshot( + current, + observeSnapshot(current), + snapshot({ plan: "fresh" }), + SECOND, + ); + expect(first).toMatchObject({ + action: "write", + value: { + snapshotAt: SECOND, + snapshotGeneration: 1, + plan: "fresh", + }, + }); + if (first.action !== "write") { + return; + } + expect( + decideLedgerSnapshot( + first.value, + observeSnapshot(current), + snapshot({ plan: "stale-fetch" }), + SECOND, + ), + ).toEqual({ action: "keep", reason: "superseded" }); + }); + + it("re-evaluates sticky and firstWins against the freshly read row", () => { + const current = { + ...record("acct"), + foundingMember: true, + consentAt: EARLIER, + consentVersion: "first", + }; + const decision = decideLedgerSnapshot( + current, + observeSnapshot(current), + snapshot({ + fields: { + foundingMember: false, + consentAt: LATER, + consentVersion: "second", + }, + }), + SNAPSHOT_BOUND, + HOST_FIELDS, + ); + expect(decision).toMatchObject({ + action: "write", + value: { + foundingMember: true, + consentAt: EARLIER, + consentVersion: "first", + eventId: "evt_seed", + }, + }); + }); + + it("refuses a (null, null) token match on an eventless row", () => { + const reserved = decideReservation( + null, + "acct_blank", + SECOND, + "rsv_1", + LATER, + ); + expect(reserved.action).toBe("write"); + if (reserved.action !== "write") { + return; + } + expect(isEventlessLedgerRow(reserved.value)).toBe(true); + expect( + decideLedgerSnapshot( + reserved.value, + observeSnapshot(reserved.value), + snapshot({ status: "active", plan: "invented" }), + SNAPSHOT_BOUND, + ), + ).toEqual({ action: "keep", reason: "eventless" }); + }); + + it("drops a snapshot superseded by a newer snapshotAt on the same event token", () => { + expect( + decideLedgerSnapshot( + record("acct", { snapshotAt: SNAPSHOT_BOUND, plan: "fresh" }), + { + eventAt: SECOND, + eventId: "evt_seed", + snapshotAt: null, + snapshotGeneration: 0, + }, + snapshot({ plan: "stale-fetch" }), + SECOND, + ), + ).toEqual({ action: "keep", reason: "superseded" }); + }); + + it("treats (eventAt, eventId) as the token, not a storage version", () => { + const current = record("acct", { plan: "kept-identity" }); + expect(observeWatermark(current)).toEqual({ + eventAt: SECOND, + eventId: "evt_seed", + }); + expect( + watermarksMatch(current, { eventAt: SECOND, eventId: "evt_seed" }), + ).toBe(true); + expect( + watermarksMatch(current, { eventAt: SECOND, eventId: "evt_other" }), + ).toBe(false); + expect(DEFAULT_SWEEP_LIMIT).toBe(100); + }); +}); + +function snapshotReconciliation(name: string, freshStore: () => Store): void { + describe(name, () => { + it("delayed-intermediate-webhook-after-sweep", async () => { + const clock = controllableClock(EARLIER); + const store = freshStore(); + const ledger = createBillingLedger({ store, clock }); + await ledger.apply( + "acct_delayed_after_sweep", + event("evt_applied", { eventAt: EARLIER, status: "active" }), + ); + + clock.set(SNAPSHOT_BOUND); + const swept = await ledger.reconcile( + "acct_delayed_after_sweep", + async (observed) => snapshot({ plan: observed.plan }), + ); + expect(swept.written).toBe(true); + if (!swept.written) { + throw new Error("expected snapshot write"); + } + expect(swept.record.snapshotAt).toBe(SNAPSHOT_BOUND); + expect(swept.record.eventId).toBe("evt_applied"); + expect(swept.record.eventAt).toBe(EARLIER); + + const delayed = await ledger.apply( + "acct_delayed_after_sweep", + event("evt_delayed_intermediate", { + eventAt: SECOND, + status: "past_due", + plan: "should-not-land", + }), + ); + expect(delayed.applied).toBe(false); + expect(await ledger.get("acct_delayed_after_sweep")).toMatchObject({ + status: "active", + eventId: "evt_applied", + eventAt: EARLIER, + snapshotAt: SNAPSHOT_BOUND, + plan: "pro", + }); + }); + + it("intervening-write drops snapshot", async () => { + const clock = controllableClock(SECOND); + const store = freshStore(); + const ledger = createBillingLedger({ store, clock }); + await ledger.apply( + "acct_intervening", + event("evt_seed", { eventAt: EARLIER, plan: "original" }), + ); + + const result = await ledger.reconcile("acct_intervening", async () => { + await ledger.apply( + "acct_intervening", + event("evt_newer", { + eventAt: LATER, + status: "canceled", + plan: "from-event", + }), + ); + return snapshot({ plan: "from-stale-fetch", status: "active" }); + }); + expect(result).toMatchObject({ + written: false, + reason: "intervening-write", + }); + expect(await ledger.get("acct_intervening")).toMatchObject({ + status: "canceled", + eventId: "evt_newer", + eventAt: LATER, + plan: "from-event", + snapshotAt: null, + }); + }); + + it("no-op still advances snapshotAt", async () => { + const clock = controllableClock(SECOND); + const base = freshStore(); + const tracked = trackLedgerStorage(base); + const ledger = createBillingLedger({ store: tracked.store, clock }); + await ledger.apply("acct_noop_sweep", event("evt_seed")); + const before = await ledger.get("acct_noop_sweep"); + expect(before?.snapshotAt).toBeNull(); + const updatesAfterApply = tracked.calls.update; + + clock.set(SNAPSHOT_BOUND); + const result = await ledger.reconcile( + "acct_noop_sweep", + async (observed) => + snapshot({ + status: observed.status, + plan: observed.plan, + providerCustomerId: observed.providerCustomerId, + providerSubscriptionId: observed.providerSubscriptionId, + providerPriceId: observed.providerPriceId, + periodStartAt: observed.periodStartAt, + periodEndAt: observed.periodEndAt, + trialStartAt: observed.trialStartAt, + trialEndAt: observed.trialEndAt, + cancelAtPeriodEnd: observed.cancelAtPeriodEnd, + }), + ); + expect(result.written).toBe(true); + expect(tracked.calls.update).toBeGreaterThan(updatesAfterApply); + expect(result.record).toMatchObject({ + eventId: "evt_seed", + eventAt: SECOND, + snapshotAt: SNAPSHOT_BOUND, + status: "active", + plan: "pro", + }); + expect(await ledger.get("acct_noop_sweep")).toEqual(result.record); + }); + + it("samples snapshotAt before fetch so a later cancel webhook can still apply", async () => { + const clock = controllableClock(SECOND); + const store = freshStore(); + const ledger = createBillingLedger({ store, clock }); + await ledger.apply( + "acct_bound_before_fetch", + event("evt_applied", { eventAt: EARLIER, status: "active" }), + ); + + const swept = await ledger.reconcile( + "acct_bound_before_fetch", + async () => { + clock.set(SNAPSHOT_BOUND); + return snapshot({ status: "active" }); + }, + ); + expect(swept.written).toBe(true); + if (!swept.written) { + throw new Error("expected snapshot write"); + } + expect(swept.record.snapshotAt).toBe(SECOND); + + const canceled = await ledger.apply( + "acct_bound_before_fetch", + event("evt_canceled", { + eventAt: LATER, + status: "canceled", + }), + ); + expect(canceled.applied).toBe(true); + expect(canceled.record).toMatchObject({ + status: "canceled", + eventId: "evt_canceled", + eventAt: LATER, + snapshotAt: SECOND, + }); + }); + + it("overlapping same-bound sweeps do not clobber fresher fields", async () => { + const clock = controllableClock(SECOND); + const store = freshStore(); + const ledger = createBillingLedger({ store, clock }); + await ledger.apply( + "acct_same_bound", + event("evt_seed", { plan: "original" }), + ); + const seeded = await ledger.reconcile("acct_same_bound", async () => + snapshot({ plan: "original" }), + ); + expect(seeded.written).toBe(true); + if (!seeded.written) { + throw new Error("expected seed snapshot write"); + } + expect(seeded.record.snapshotAt).toBe(SECOND); + + let releaseSlow = () => {}; + const slowGate = new Promise((resolve) => { + releaseSlow = resolve; + }); + let slowStarted = () => {}; + const slowIsFetching = new Promise((resolve) => { + slowStarted = resolve; + }); + + const slow = ledger.reconcile("acct_same_bound", async () => { + slowStarted(); + await slowGate; + return snapshot({ plan: "stale-fetch", status: "active" }); + }); + await slowIsFetching; + + const fast = await ledger.reconcile("acct_same_bound", async () => + snapshot({ plan: "fresh-truth", status: "canceled" }), + ); + expect(fast.written).toBe(true); + if (!fast.written) { + throw new Error("expected fast snapshot write"); + } + expect(fast.record.snapshotAt).toBe(SECOND); + expect(fast.record.snapshotGeneration).toBe(2); + releaseSlow(); + expect(await slow).toMatchObject({ + written: false, + reason: "superseded", + }); + expect(await ledger.get("acct_same_bound")).toMatchObject({ + plan: "fresh-truth", + status: "canceled", + eventId: "evt_seed", + snapshotAt: SECOND, + snapshotGeneration: 2, + }); + }); + + it("overlapping .999Z reconcile does not stale a same-second webhook", async () => { + const endOfSecond = "2026-08-15T16:00:00.999Z"; + const clock = controllableClock(endOfSecond); + const store = freshStore(); + const ledger = createBillingLedger({ store, clock }); + await ledger.apply( + "acct_end_of_second", + event("evt_applied", { eventAt: SECOND, status: "active" }), + ); + const seeded = await ledger.reconcile("acct_end_of_second", async () => + snapshot({ status: "active" }), + ); + expect(seeded.written).toBe(true); + if (!seeded.written) { + throw new Error("expected seed snapshot write"); + } + expect(seeded.record.snapshotAt).toBe(endOfSecond); + expect(effectiveWatermarkSecond(seeded.record)).toBe(unixSecond(SECOND)); + + let releaseSlow = () => {}; + const slowGate = new Promise((resolve) => { + releaseSlow = resolve; + }); + let slowStarted = () => {}; + const slowIsFetching = new Promise((resolve) => { + slowStarted = resolve; + }); + + const slow = ledger.reconcile("acct_end_of_second", async () => { + slowStarted(); + await slowGate; + return snapshot({ plan: "stale-fetch", status: "active" }); + }); + await slowIsFetching; + + const fast = await ledger.reconcile("acct_end_of_second", async () => + snapshot({ plan: "fresh-truth", status: "active" }), + ); + expect(fast.written).toBe(true); + if (!fast.written) { + throw new Error("expected fast snapshot write"); + } + expect(fast.record.snapshotAt).toBe(endOfSecond); + expect(effectiveWatermarkSecond(fast.record)).toBe(unixSecond(SECOND)); + releaseSlow(); + expect(await slow).toMatchObject({ + written: false, + reason: "superseded", + }); + + const canceled = await ledger.apply( + "acct_end_of_second", + event("evt_canceled", { + eventAt: SAME_SECOND_LATER_MS, + status: "canceled", + }), + ); + expect(canceled.applied).toBe(true); + expect(canceled.record).toMatchObject({ + status: "canceled", + eventId: "evt_canceled", + eventAt: SAME_SECOND_LATER_MS, + snapshotAt: endOfSecond, + }); + }); + + it("overlapping sweep does not clobber a newer snapshot", async () => { + const clock = controllableClock(SECOND); + const store = freshStore(); + const ledger = createBillingLedger({ store, clock }); + await ledger.apply( + "acct_overlap", + event("evt_seed", { plan: "original" }), + ); + + let releaseSlow = () => {}; + const slowGate = new Promise((resolve) => { + releaseSlow = resolve; + }); + let slowStarted = () => {}; + const slowIsFetching = new Promise((resolve) => { + slowStarted = resolve; + }); + + const slow = ledger.reconcile("acct_overlap", async () => { + slowStarted(); + await slowGate; + return snapshot({ plan: "stale-fetch", status: "active" }); + }); + await slowIsFetching; + + clock.set(SNAPSHOT_BOUND); + const fast = await ledger.reconcile("acct_overlap", async () => + snapshot({ plan: "fresh-truth", status: "canceled" }), + ); + expect(fast.written).toBe(true); + releaseSlow(); + expect(await slow).toMatchObject({ + written: false, + reason: "superseded", + }); + expect(await ledger.get("acct_overlap")).toMatchObject({ + plan: "fresh-truth", + status: "canceled", + eventId: "evt_seed", + snapshotAt: SNAPSHOT_BOUND, + }); + }); + + it("does not snapshot a reservation-only row so a founding webhook can still apply", async () => { + const clock = controllableClock(SNAPSHOT_BOUND); + const store = freshStore(); + const ledger = createBillingLedger({ store, clock }); + const reserved = await ledger.reserve("acct_eventless_snap"); + expect(reserved.reserved).toBe(true); + + let fetched = 0; + const result = await ledger.reconcile("acct_eventless_snap", async () => { + fetched += 1; + return snapshot({ status: "active", plan: "invented" }); + }); + expect(result).toMatchObject({ + written: false, + reason: "eventless", + }); + expect(fetched).toBe(0); + const held = await ledger.get("acct_eventless_snap"); + expect(held && isEventlessLedgerRow(held)).toBe(true); + expect(held?.snapshotAt).toBeNull(); + expect(held?.plan).toBeNull(); + + const founding = await ledger.apply( + "acct_eventless_snap", + event("evt_founding", { eventAt: EARLIER, status: "active" }), + ); + expect(founding.applied).toBe(true); + expect(founding.record).toMatchObject({ + eventId: "evt_founding", + eventAt: EARLIER, + status: "active", + snapshotAt: null, + }); + }); + + it("fetches provider truth only after observing the watermark", async () => { + const clock = controllableClock(SECOND); + const base = freshStore(); + const order: string[] = []; + const tracked: Store = { + collection(definition: CollectionDefinition): CollectionStore { + const delegate = base.collection(definition); + return { + ...delegate, + async get(key) { + order.push("observe"); + return delegate.get(key); + }, + async update(key, decide, updateOptions) { + order.push("update"); + return delegate.update(key, decide, updateOptions); + }, + }; + }, + }; + const ledger = createBillingLedger({ + store: tracked, + clock, + }); + await ledger.apply("acct_observe_first", event("evt_seed")); + order.length = 0; + await ledger.reconcile("acct_observe_first", async (observed) => { + order.push("fetch"); + expect(observed.eventId).toBe("evt_seed"); + expect(observed.eventAt).toBe(SECOND); + return snapshot(); + }); + expect(order).toEqual(["observe", "fetch", "update"]); + }); + + it("sweep pages accounts and writes each observed row", async () => { + const clock = controllableClock(SNAPSHOT_BOUND); + const store = freshStore(); + const ledger = createBillingLedger({ store, clock }); + await ledger.apply("acct_sweep_a", event("evt_a", { plan: "a" })); + await ledger.apply("acct_sweep_b", event("evt_b", { plan: "b" })); + + const first = await ledger.sweep( + async (observed) => snapshot({ plan: observed.plan }), + { + limit: 1, + }, + ); + expect(first.results).toHaveLength(1); + expect(first.results[0]?.written).toBe(true); + expect(first.nextCursor).not.toBeNull(); + + const second = await ledger.sweep( + async (observed) => snapshot({ plan: observed.plan }), + first.nextCursor === null + ? { limit: 1 } + : { limit: 1, cursor: first.nextCursor }, + ); + expect(second.results).toHaveLength(1); + expect(second.results[0]?.written).toBe(true); + expect(second.nextCursor).toBeNull(); + + expect(await ledger.get("acct_sweep_a")).toMatchObject({ + snapshotAt: SNAPSHOT_BOUND, + eventId: "evt_a", + plan: "a", + }); + expect(await ledger.get("acct_sweep_b")).toMatchObject({ + snapshotAt: SNAPSHOT_BOUND, + eventId: "evt_b", + plan: "b", + }); + }); + + it("skips a missing account and a null provider fetch without writing", async () => { + const clock = controllableClock(SNAPSHOT_BOUND); + const base = freshStore(); + const tracked = trackLedgerStorage(base); + const ledger = createBillingLedger({ store: tracked.store, clock }); + await ledger.apply("acct_present", event("evt_seed")); + const updatesAfterApply = tracked.calls.update; + + expect( + await ledger.reconcile("acct_missing", async () => snapshot()), + ).toEqual({ + written: false, + record: null, + reason: "missing", + }); + expect( + await ledger.reconcile("acct_present", async () => null), + ).toMatchObject({ + written: false, + reason: "unavailable", + record: { eventId: "evt_seed", snapshotAt: null }, + }); + expect(tracked.calls.update).toBe(updatesAfterApply); + }); + + it("logs snapshot outcomes without payload or amount fields", async () => { + const entries: Array<{ + level: string; + message: string; + fields?: Readonly>; + }> = []; + const logger: Logger = { + log(level, message, fields) { + entries.push({ + level, + message, + ...(fields === undefined ? {} : { fields }), + }); + }, + }; + const clock = controllableClock(SNAPSHOT_BOUND); + const ledger = createBillingLedger({ + store: freshStore(), + clock, + logger, + }); + await ledger.apply("acct_snap_log", event("evt_seed")); + entries.length = 0; + await ledger.reconcile("acct_snap_log", async () => snapshot()); + await ledger.reconcile("acct_snap_missing", async () => snapshot()); + + expect(entries).toEqual([ + { + level: "info", + message: "Billing ledger snapshot written", + fields: { + accountId: "acct_snap_log", + eventId: "evt_seed", + written: true, + }, + }, + { + level: "info", + message: "Billing ledger snapshot ignored", + fields: { + accountId: "acct_snap_missing", + written: false, + }, + }, + ]); + expect(JSON.stringify(entries)).not.toContain("payload"); + expect(JSON.stringify(entries)).not.toContain("amount"); + }); + }); +} + +snapshotReconciliation("snapshot reconciliation / memory", createMemoryStore); +snapshotReconciliation( + "snapshot reconciliation / Azure Tables", + freshAzureStore, +); + +describe("snapshot reconciliation clock discipline", () => { + it("requires an injected clock and never uses Date.now for snapshotAt", async () => { + const ledger = createBillingLedger({ store: createMemoryStore() }); + await expect( + ledger.reconcile("acct_no_clock", async () => snapshot()), + ).rejects.toThrow(/Clock/); + await expect(ledger.sweep(async () => snapshot())).rejects.toThrow(/Clock/); + expect(DEFAULT_SWEEP_LIMIT).toBe(100); + }); +}); diff --git a/packages/billing-core/src/index.ts b/packages/billing-core/src/index.ts index 7230684..dc7e5ee 100644 --- a/packages/billing-core/src/index.ts +++ b/packages/billing-core/src/index.ts @@ -6,6 +6,7 @@ import { } from "@pegma/spine"; import { defineCollection, + MAX_SCAN_PAGE_SIZE, type CollectionDefinition, type EntityKey, type Store, @@ -23,6 +24,9 @@ const LEDGER_ROW_ID = "subscription"; export const DEFAULT_RESERVATION_TTL_MS = 30 * 60 * 1000; const MAX_RESERVATION_TTL_MS = 24 * 60 * 60 * 1000; +/** Default page size for a snapshot-reconciliation sweep. */ +export const DEFAULT_SWEEP_LIMIT = 100; + /** * Provider-agnostic subscription lifecycle. * @@ -134,6 +138,7 @@ export interface LedgerFields { readonly eventAt: IsoTimestamp | null; readonly eventId: string | null; readonly snapshotAt: IsoTimestamp | null; + readonly snapshotGeneration: number; readonly reservationId: string | null; readonly reservationExpiresAt: IsoTimestamp | null; readonly reservationSeeded: boolean; @@ -160,6 +165,51 @@ export type LedgerEvent = { readonly fields?: Partial; }; +/** + * Domain CAS token for snapshot reconciliation: the `(eventAt, eventId)` + * pair observed before the provider fetch. Not a storage version. + */ +export interface WatermarkToken { + readonly eventAt: IsoTimestamp | null; + readonly eventId: string | null; +} + +/** + * What a sweep observed before fetching provider truth: the watermark + * identity plus the snapshot freshness bound and write generation. + * + * Another reconciliation that lands first increments `snapshotGeneration` + * without touching the watermark second. Re-checking that generation is + * what drops the slower, stale fetch. + */ +export interface SnapshotObservation extends WatermarkToken { + readonly snapshotAt: IsoTimestamp | null; + readonly snapshotGeneration: number; +} + +/** + * Provider truth used to repair field drift. It does not carry a watermark; + * applying it must not change `eventAt` or `eventId`. + */ +export type LedgerSnapshot = { + readonly status: LifecycleStatus; + readonly providerCustomerId: string | null; + readonly providerSubscriptionId: string | null; + readonly providerPriceId: string | null; + readonly plan: string | null; + readonly periodStartAt: IsoTimestamp | null; + readonly periodEndAt: IsoTimestamp | null; + readonly trialStartAt: IsoTimestamp | null; + readonly trialEndAt: IsoTimestamp | null; + readonly cancelAtPeriodEnd: boolean; + readonly offerRedeemed?: boolean; + readonly fields?: Partial; +}; + +export type FetchLedgerSnapshot = ( + observed: LedgerRecord, +) => Promise | null>; + export type IgnoreReason = "redelivery" | "stale" | "equal-rank"; export type ApplicationDecision = @@ -193,6 +243,31 @@ export interface ReleaseResult { readonly released: boolean; } +export type SnapshotIgnoreReason = + "missing" | "unavailable" | "eventless" | "intervening-write" | "superseded"; + +export type SnapshotDecision = + | { readonly action: "write"; readonly value: LedgerRecord } + | { readonly action: "keep"; readonly reason: SnapshotIgnoreReason }; + +export type ReconcileResult = + | { readonly written: true; readonly record: LedgerRecord } + | { + readonly written: false; + readonly record: LedgerRecord | null; + readonly reason: SnapshotIgnoreReason; + }; + +export interface SweepOptions { + readonly limit?: number; + readonly cursor?: string; +} + +export interface SweepResult { + readonly results: readonly ReconcileResult[]; + readonly nextCursor: string | null; +} + export interface BillingLedger { get(accountId: string): Promise | null>; apply( @@ -201,6 +276,14 @@ export interface BillingLedger { ): Promise>; reserve(accountId: string, options?: ReserveOptions): Promise; release(accountId: string, reservationId: string): Promise; + reconcile( + accountId: string, + fetchSnapshot: FetchLedgerSnapshot, + ): Promise>; + sweep( + fetchSnapshot: FetchLedgerSnapshot, + options?: SweepOptions, + ): Promise>; } export interface BillingLedgerOptions { @@ -229,6 +312,7 @@ const CORE_FIELD_NAMES = new Set([ "eventAt", "eventId", "snapshotAt", + "snapshotGeneration", "reservationId", "reservationExpiresAt", "reservationSeeded", @@ -474,13 +558,92 @@ function defaultNewId(): string { return cryptoApi.randomUUID(); } -function requireClock(clock: Clock | undefined): Clock { +function requireClock(clock: Clock | undefined, purpose: string): Clock { if (clock === undefined) { - throw new TypeError("Billing reservation requires an injected Clock."); + throw new TypeError(`${purpose} requires an injected Clock.`); } return clock; } +function assertSweepLimit(limit: number): number { + if ( + typeof limit !== "number" || + !Number.isInteger(limit) || + limit < 1 || + limit > MAX_SCAN_PAGE_SIZE + ) { + throw new TypeError( + `Unsupported sweep page size: expected an integer from 1 through ${MAX_SCAN_PAGE_SIZE}.`, + ); + } + return limit; +} + +function laterTimestamp( + left: IsoTimestamp | null, + right: IsoTimestamp, +): IsoTimestamp { + if (left === null) { + return right; + } + const leftMs = canonicalTimestampMilliseconds(left); + const rightMs = canonicalTimestampMilliseconds(right); + if (leftMs === null) { + return right; + } + if (rightMs === null) { + return left; + } + return leftMs >= rightMs ? left : right; +} + +function nextSnapshotGeneration(current: number): number { + return Number.isFinite(current) && current >= 0 ? Math.floor(current) + 1 : 1; +} + +function storedSnapshotGeneration(value: unknown): number { + return typeof value === "number" && Number.isFinite(value) && value >= 0 + ? Math.floor(value) + : 0; +} + +/** Reads the domain CAS token from a ledger row. */ +export function observeWatermark( + record: Pick, +): WatermarkToken { + return { eventAt: record.eventAt, eventId: record.eventId }; +} + +/** Reads the watermark, freshness bound, and snapshot write generation. */ +export function observeSnapshot( + record: Pick< + LedgerFields, + "eventAt" | "eventId" | "snapshotAt" | "snapshotGeneration" + >, +): SnapshotObservation { + return { + eventAt: record.eventAt, + eventId: record.eventId, + snapshotAt: record.snapshotAt, + snapshotGeneration: storedSnapshotGeneration(record.snapshotGeneration), + }; +} + +export function watermarksMatch( + current: Pick, + observed: WatermarkToken, +): boolean { + return ( + current.eventAt === observed.eventAt && current.eventId === observed.eventId + ); +} + +export function hasEventWatermark( + record: Pick, +): boolean { + return record.eventAt !== null && record.eventId !== null; +} + function assertEvent( event: LedgerEvent, ): LedgerEvent { @@ -514,6 +677,35 @@ function assertEvent( }; } +function assertSnapshot( + snapshot: LedgerSnapshot, +): LedgerSnapshot { + const fields = snapshot.fields; + return { + status: assertLifecycleStatus(snapshot.status), + providerCustomerId: assertNullableString( + snapshot.providerCustomerId, + "provider customer id", + ), + providerSubscriptionId: assertNullableString( + snapshot.providerSubscriptionId, + "provider subscription id", + ), + providerPriceId: assertNullableString( + snapshot.providerPriceId, + "provider price id", + ), + plan: assertNullableString(snapshot.plan, "plan"), + periodStartAt: optionalTimestamp(snapshot.periodStartAt, "period start"), + periodEndAt: optionalTimestamp(snapshot.periodEndAt, "period end"), + trialStartAt: optionalTimestamp(snapshot.trialStartAt, "trial start"), + trialEndAt: optionalTimestamp(snapshot.trialEndAt, "trial end"), + cancelAtPeriodEnd: snapshot.cancelAtPeriodEnd === true, + ...(snapshot.offerRedeemed === true ? { offerRedeemed: true } : {}), + ...(fields === undefined ? {} : { fields }), + }; +} + function blankHostFields( invariants: TFields | undefined, ): HostFromInvariants { @@ -551,6 +743,7 @@ function blankLedgerRecord( eventAt: null, eventId: null, snapshotAt: null, + snapshotGeneration: 0, reservationId: null, reservationExpiresAt: null, reservationSeeded: false, @@ -711,6 +904,7 @@ function projectAppliedRecord( eventAt: event.eventAt, eventId: event.eventId, snapshotAt: current?.snapshotAt ?? null, + snapshotGeneration: storedSnapshotGeneration(current?.snapshotGeneration), reservationId: granting ? null : (current?.reservationId ?? null), reservationExpiresAt: granting ? null @@ -829,6 +1023,88 @@ export function decideReservation( }; } +function projectSnapshotRecord( + current: LedgerRecord, + snapshot: LedgerSnapshot, + snapshotAt: IsoTimestamp, + invariants: LedgerInvariants | undefined, +): LedgerRecord { + const granting = isGrantingStatus(snapshot.status); + return { + accountId: current.accountId, + providerCustomerId: snapshot.providerCustomerId, + providerSubscriptionId: snapshot.providerSubscriptionId, + providerPriceId: snapshot.providerPriceId, + status: snapshot.status, + plan: snapshot.plan, + periodStartAt: snapshot.periodStartAt, + periodEndAt: snapshot.periodEndAt, + trialStartAt: snapshot.trialStartAt, + trialEndAt: snapshot.trialEndAt, + cancelAtPeriodEnd: snapshot.cancelAtPeriodEnd, + eventAt: current.eventAt, + eventId: current.eventId, + snapshotAt: laterTimestamp(current.snapshotAt, snapshotAt), + snapshotGeneration: nextSnapshotGeneration(current.snapshotGeneration), + reservationId: granting ? null : (current.reservationId ?? null), + reservationExpiresAt: granting + ? null + : (current.reservationExpiresAt ?? null), + reservationSeeded: current.reservationSeeded === true, + offerRedeemed: offerIsRedeemed(current, snapshot), + ...applyLedgerInvariants(current, snapshot.fields, invariants), + } as LedgerRecord; +} + +/** + * Decides whether a provider snapshot may repair the current ledger row. + * + * The host must observe {@link SnapshotObservation} first, sample the + * freshness bound, then fetch provider truth, then call this against + * freshly read state. A watermark mismatch means an intervening event + * landed; a `snapshotGeneration` mismatch means another reconciliation + * already wrote. Either drops the snapshot. A reservation-only / + * eventless row has no event identity to repair — refuse a `(null, null)` + * match so a founding webhook is not gated by an invented bound. + * + * A match ALWAYS writes — even when no field changed — and increments + * `snapshotGeneration` so a same-bound overlapping sweep cannot clobber + * fresher fields. `snapshotAt` never jumps into a later Unix second than + * the sampled bound, so same-second webhooks still get lifecycle-rank + * arbitration. `eventAt` and `eventId` are copied from current state and + * never replaced. + * + * Host-declared `sticky` / `firstWins` fields are enforced on the write + * against the freshly read row. + */ +export function decideLedgerSnapshot( + current: LedgerRecord | null, + observed: SnapshotObservation, + snapshot: LedgerSnapshot, + snapshotAt: IsoTimestamp, + invariants?: LedgerInvariants, +): SnapshotDecision { + if (current === null) { + return { action: "keep", reason: "missing" }; + } + if (isEventlessLedgerRow(current) || !hasEventWatermark(current)) { + return { action: "keep", reason: "eventless" }; + } + if (!watermarksMatch(current, observed)) { + return { action: "keep", reason: "intervening-write" }; + } + if ( + current.snapshotAt !== observed.snapshotAt || + current.snapshotGeneration !== observed.snapshotGeneration + ) { + return { action: "keep", reason: "superseded" }; + } + return { + action: "write", + value: projectSnapshotRecord(current, snapshot, snapshotAt, invariants), + }; +} + type EncodedLedgerRecord = Record< keyof LedgerFields | keyof THost, StoredValue @@ -852,6 +1128,7 @@ function encodeLedgerCore( eventAt: value.eventAt, eventId: value.eventId, snapshotAt: value.snapshotAt, + snapshotGeneration: storedSnapshotGeneration(value.snapshotGeneration), reservationId: value.reservationId, reservationExpiresAt: value.reservationExpiresAt, reservationSeeded: value.reservationSeeded, @@ -900,6 +1177,7 @@ function decodeLedgerRecord( eventAt: storedTimestamp(record["eventAt"]), eventId: toNullableString(record["eventId"]), snapshotAt: storedTimestamp(record["snapshotAt"]), + snapshotGeneration: storedSnapshotGeneration(record["snapshotGeneration"]), reservationId: toNullableString(record["reservationId"]), reservationExpiresAt: storedTimestamp(record["reservationExpiresAt"]), reservationSeeded: record["reservationSeeded"] === true, @@ -948,6 +1226,85 @@ export function createBillingLedger( const definition = billingLedgerCollection(options.fields); const rows = options.store.collection(definition); + async function reconcileAccount( + accountId: string, + fetchSnapshot: FetchLedgerSnapshot, + ): Promise> { + assertSafeAccountId(accountId); + const clock = requireClock( + options.clock, + "Billing snapshot reconciliation", + ); + const observed = await rows.get(billingLedgerKey(accountId)); + if (observed === null) { + logger.log("info", "Billing ledger snapshot ignored", { + accountId, + written: false, + }); + return { written: false, record: null, reason: "missing" }; + } + if (isEventlessLedgerRow(observed) || !hasEventWatermark(observed)) { + logger.log("info", "Billing ledger snapshot ignored", { + accountId, + eventId: observed.eventId, + written: false, + }); + return { written: false, record: observed, reason: "eventless" }; + } + const token = observeSnapshot(observed); + const snapshotAt = assertClockNow(clock); + const fetched = await fetchSnapshot(observed); + if (fetched === null) { + logger.log("info", "Billing ledger snapshot ignored", { + accountId, + eventId: token.eventId, + written: false, + }); + return { written: false, record: observed, reason: "unavailable" }; + } + const snapshot = assertSnapshot(fetched); + let ignore: SnapshotIgnoreReason | undefined; + const result = await rows.update(billingLedgerKey(accountId), (current) => { + const decision = decideLedgerSnapshot( + current, + token, + snapshot, + snapshotAt, + invariants, + ); + if (decision.action === "keep") { + ignore = decision.reason; + return { action: "keep" as const }; + } + return decision; + }); + const written = result.written; + logger.log( + "info", + written + ? "Billing ledger snapshot written" + : "Billing ledger snapshot ignored", + { + accountId, + eventId: token.eventId, + written, + }, + ); + if (written) { + if (result.value === null) { + throw new Error( + "Billing ledger snapshot write did not persist a record.", + ); + } + return { written: true, record: result.value }; + } + return { + written: false, + record: result.value, + reason: ignore ?? "intervening-write", + }; + } + return { async get(accountId) { return rows.get(billingLedgerKey(accountId)); @@ -979,7 +1336,7 @@ export function createBillingLedger( async reserve(accountId, reserveOptions) { assertSafeAccountId(accountId); - const clock = requireClock(options.clock); + const clock = requireClock(options.clock, "Billing reservation"); const ttlMs = assertTtlMs(reserveOptions?.ttlMs ?? defaultTtlMs); let refusal: ReserveRefusal | undefined; const result = await rows.update( @@ -1058,5 +1415,29 @@ export function createBillingLedger( }); return { released }; }, + + async reconcile(accountId, fetchSnapshot) { + return reconcileAccount(accountId, fetchSnapshot); + }, + + async sweep(fetchSnapshot, sweepOptions) { + requireClock(options.clock, "Billing snapshot reconciliation"); + const limit = assertSweepLimit( + sweepOptions?.limit ?? DEFAULT_SWEEP_LIMIT, + ); + const page = await rows.scan({ + limit, + ...(sweepOptions?.cursor === undefined + ? {} + : { cursor: sweepOptions.cursor }), + }); + const results: ReconcileResult[] = []; + for (const scanned of page.records) { + results.push( + await reconcileAccount(scanned.key.partition, fetchSnapshot), + ); + } + return { results, nextCursor: page.nextCursor }; + }, }; }