From 5bffe464c249424a71a140df6e18dd4ca32d3302 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 15 Aug 2026 17:41:12 +0000 Subject: [PATCH 1/5] Add snapshot reconciliation with domain CAS and always-write freshness MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phase 3: observe the (eventAt, eventId) watermark, fetch provider truth afterward, and apply it through a decider that re-checks that domain token against fresh state. An intervening write drops the snapshot. A token match always writes — even when no field changed — so snapshotAt advances and a delayed intermediate webhook cannot land after a no-op sweep. Co-authored-by: Fly Over Coder --- AGENTS.md | 8 +- README.md | 16 +- docs/PROJECT_PLAN.md | 15 +- packages/billing-core/README.md | 35 +- packages/billing-core/package.json | 2 +- packages/billing-core/src/index.test.ts | 425 ++++++++++++++++++++++++ packages/billing-core/src/index.ts | 299 ++++++++++++++++- 7 files changed, 769 insertions(+), 31 deletions(-) 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..c5f7f11 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,13 @@ 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)`, +fetches provider truth afterward, and re-checks that token against fresh +state. An intervening write drops the snapshot. A token match always writes +— even when no field changed — so `snapshotAt` advances and a delayed +intermediate webhook cannot land after a no-op sweep. 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..1c7b79b 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,13 @@ import { isGrantingStatus, LIFECYCLE_RANK, lifecycleRank, + observeWatermark, reservationIsLive, sticky, + watermarksMatch, type LedgerEvent, type LedgerRecord, + type LedgerSnapshot, } from "./index.js"; declare module "vitest" { @@ -93,6 +98,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 = {}, @@ -1609,3 +1632,405 @@ 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, + observeWatermark(current), + snapshot(), + SNAPSHOT_BOUND, + ); + expect(decision).toMatchObject({ + action: "write", + value: { + eventId: "evt_seed", + eventAt: SECOND, + snapshotAt: SNAPSHOT_BOUND, + status: "active", + plan: "pro", + }, + }); + }); + + it("repairs field drift without touching watermark identity", () => { + const current = record("acct", { plan: "stale", snapshotAt: EARLIER }); + const decision = decideLedgerSnapshot( + current, + observeWatermark(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" }, + 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" }, + 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, + observeWatermark(current), + snapshot(), + SECOND, + ); + expect(decision).toMatchObject({ + action: "write", + value: { snapshotAt: SNAPSHOT_BOUND, eventId: "evt_seed" }, + }); + }); + + 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, + observeWatermark(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("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); + 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("fetches provider truth only after observing the watermark", async () => { + const clock = controllableClock(SECOND); + const base = freshStore(); + const order: string[] = []; + const ledger = createBillingLedger({ + store: { + collection(definition) { + 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); + }, + }; + }, + }, + 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..6bf7c8f 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. * @@ -160,6 +164,38 @@ 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; +} + +/** + * 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 +229,31 @@ export interface ReleaseResult { readonly released: boolean; } +export type SnapshotIgnoreReason = + "missing" | "unavailable" | "intervening-write"; + +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 +262,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 { @@ -474,13 +543,61 @@ 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; +} + +/** Reads the domain CAS token from a ledger row. */ +export function observeWatermark( + record: Pick, +): WatermarkToken { + return { eventAt: record.eventAt, eventId: record.eventId }; +} + +export function watermarksMatch( + current: Pick, + observed: WatermarkToken, +): boolean { + return ( + current.eventAt === observed.eventAt && current.eventId === observed.eventId + ); +} + function assertEvent( event: LedgerEvent, ): LedgerEvent { @@ -514,6 +631,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 { @@ -829,6 +975,70 @@ 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), + 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 WatermarkToken} first, then fetch provider + * truth, then call this against freshly read state. A token mismatch means + * an intervening write landed; drop the snapshot. A match ALWAYS writes — + * even when no field changed — so `snapshotAt` advances and a delayed + * intermediate webhook cannot land after a no-op sweep. `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: WatermarkToken, + snapshot: LedgerSnapshot, + snapshotAt: IsoTimestamp, + invariants?: LedgerInvariants, +): SnapshotDecision { + if (current === null) { + return { action: "keep", reason: "missing" }; + } + if (!watermarksMatch(current, observed)) { + return { action: "keep", reason: "intervening-write" }; + } + return { + action: "write", + value: projectSnapshotRecord(current, snapshot, snapshotAt, invariants), + }; +} + type EncodedLedgerRecord = Record< keyof LedgerFields | keyof THost, StoredValue @@ -948,6 +1158,65 @@ 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" }; + } + const token = observeWatermark(observed); + 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); + const snapshotAt = assertClockNow(clock); + const result = await rows.update(billingLedgerKey(accountId), (current) => + decideLedgerSnapshot(current, token, snapshot, snapshotAt, invariants), + ); + 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: result.value === null ? "missing" : "intervening-write", + }; + } + return { async get(accountId) { return rows.get(billingLedgerKey(accountId)); @@ -979,7 +1248,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 +1327,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 }; + }, }; } From 0d72216551a617a881033e2bee105fc34c26dd26 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 15 Aug 2026 17:41:53 +0000 Subject: [PATCH 2/5] Fix Phase 3 test types for snapshot result narrowing Narrow the reconcile union before reading written records, and type the observe-then-fetch store wrapper so tsc accepts the update decider. Co-authored-by: Fly Over Coder --- packages/billing-core/src/index.test.ts | 36 ++++++++++++++----------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/packages/billing-core/src/index.test.ts b/packages/billing-core/src/index.test.ts index 1c7b79b..f4aa35b 100644 --- a/packages/billing-core/src/index.test.ts +++ b/packages/billing-core/src/index.test.ts @@ -1775,6 +1775,9 @@ function snapshotReconciliation(name: string, freshStore: () => Store): void { 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); @@ -1873,23 +1876,24 @@ function snapshotReconciliation(name: string, freshStore: () => Store): void { const clock = controllableClock(SECOND); const base = freshStore(); const order: string[] = []; - const ledger = createBillingLedger({ - store: { - collection(definition) { - 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 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")); From 07fb5c4e5b4dab61a6b041a1875794de0395583d Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 15 Aug 2026 17:48:37 +0000 Subject: [PATCH 3/5] Harden snapshot CAS: pre-fetch bound, superseded drop, eventless skip Sample snapshotAt from the injected clock before fetchSnapshot so a cancel that lands during the fetch is not gated by a later bound. Re-check the observed snapshotAt so a slower stale fetch cannot clobber a newer reconciliation on the same event token. Refuse eventless and (null, null) rows so a reservation-only account is not given invented provider state or a freshness bound that would drop the founding webhook. Co-authored-by: Fly Over Coder --- packages/billing-core/README.md | 15 ++- packages/billing-core/src/index.test.ts | 163 +++++++++++++++++++++++- packages/billing-core/src/index.ts | 89 +++++++++++-- 3 files changed, 241 insertions(+), 26 deletions(-) diff --git a/packages/billing-core/README.md b/packages/billing-core/README.md index c5f7f11..870ebaf 100644 --- a/packages/billing-core/README.md +++ b/packages/billing-core/README.md @@ -76,12 +76,15 @@ 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. -Snapshot reconciliation observes the domain CAS token `(eventAt, eventId)`, -fetches provider truth afterward, and re-checks that token against fresh -state. An intervening write drops the snapshot. A token match always writes -— even when no field changed — so `snapshotAt` advances and a delayed -intermediate webhook cannot land after a no-op sweep. The watermark identity -is never touched. +Snapshot reconciliation observes the domain CAS token `(eventAt, eventId)` +and the current `snapshotAt`, samples the freshness bound from the injected +clock, then fetches provider truth. The decider re-checks both the watermark +and the observed `snapshotAt` 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 — so `snapshotAt` advances and a +delayed intermediate webhook cannot land after a no-op sweep. 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 diff --git a/packages/billing-core/src/index.test.ts b/packages/billing-core/src/index.test.ts index f4aa35b..9b2bf7c 100644 --- a/packages/billing-core/src/index.test.ts +++ b/packages/billing-core/src/index.test.ts @@ -35,6 +35,7 @@ import { isGrantingStatus, LIFECYCLE_RANK, lifecycleRank, + observeSnapshot, observeWatermark, reservationIsLive, sticky, @@ -1638,7 +1639,7 @@ describe("snapshot decider", () => { const current = record("acct", { snapshotAt: null }); const decision = decideLedgerSnapshot( current, - observeWatermark(current), + observeSnapshot(current), snapshot(), SNAPSHOT_BOUND, ); @@ -1658,7 +1659,7 @@ describe("snapshot decider", () => { const current = record("acct", { plan: "stale", snapshotAt: EARLIER }); const decision = decideLedgerSnapshot( current, - observeWatermark(current), + observeSnapshot(current), snapshot({ plan: "pro", status: "past_due" }), SNAPSHOT_BOUND, ); @@ -1679,7 +1680,7 @@ describe("snapshot decider", () => { expect( decideLedgerSnapshot( record("acct", { eventId: "evt_newer", eventAt: LATER }), - { eventAt: SECOND, eventId: "evt_seed" }, + { eventAt: SECOND, eventId: "evt_seed", snapshotAt: null }, snapshot({ plan: "should-not-land" }), SNAPSHOT_BOUND, ), @@ -1690,7 +1691,7 @@ describe("snapshot decider", () => { expect( decideLedgerSnapshot( null, - { eventAt: SECOND, eventId: "evt_seed" }, + { eventAt: SECOND, eventId: "evt_seed", snapshotAt: null }, snapshot(), SNAPSHOT_BOUND, ), @@ -1701,7 +1702,7 @@ describe("snapshot decider", () => { const current = record("acct", { snapshotAt: SNAPSHOT_BOUND }); const decision = decideLedgerSnapshot( current, - observeWatermark(current), + observeSnapshot(current), snapshot(), SECOND, ); @@ -1720,7 +1721,7 @@ describe("snapshot decider", () => { }; const decision = decideLedgerSnapshot( current, - observeWatermark(current), + observeSnapshot(current), snapshot({ fields: { foundingMember: false, @@ -1742,6 +1743,40 @@ describe("snapshot decider", () => { }); }); + 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 }, + 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({ @@ -1872,6 +1907,122 @@ function snapshotReconciliation(name: string, freshStore: () => Store): void { 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 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(); diff --git a/packages/billing-core/src/index.ts b/packages/billing-core/src/index.ts index 6bf7c8f..48e6b0d 100644 --- a/packages/billing-core/src/index.ts +++ b/packages/billing-core/src/index.ts @@ -173,6 +173,18 @@ export interface WatermarkToken { readonly eventId: string | null; } +/** + * What a sweep observed before fetching provider truth: the watermark + * identity plus the snapshot freshness bound already on the row. + * + * Another reconciliation that lands first changes `snapshotAt` without + * touching the watermark. Re-checking this bound is what drops the + * slower, stale fetch. + */ +export interface SnapshotObservation extends WatermarkToken { + readonly snapshotAt: IsoTimestamp | null; +} + /** * Provider truth used to repair field drift. It does not carry a watermark; * applying it must not change `eventAt` or `eventId`. @@ -230,7 +242,7 @@ export interface ReleaseResult { } export type SnapshotIgnoreReason = - "missing" | "unavailable" | "intervening-write"; + "missing" | "unavailable" | "eventless" | "intervening-write" | "superseded"; export type SnapshotDecision = | { readonly action: "write"; readonly value: LedgerRecord } @@ -589,6 +601,17 @@ export function observeWatermark( return { eventAt: record.eventAt, eventId: record.eventId }; } +/** Reads the watermark and the snapshot freshness bound already on the row. */ +export function observeSnapshot( + record: Pick, +): SnapshotObservation { + return { + eventAt: record.eventAt, + eventId: record.eventId, + snapshotAt: record.snapshotAt, + }; +} + export function watermarksMatch( current: Pick, observed: WatermarkToken, @@ -598,6 +621,12 @@ export function watermarksMatch( ); } +export function hasEventWatermark( + record: Pick, +): boolean { + return record.eventAt !== null && record.eventId !== null; +} + function assertEvent( event: LedgerEvent, ): LedgerEvent { @@ -1010,19 +1039,25 @@ function projectSnapshotRecord( /** * Decides whether a provider snapshot may repair the current ledger row. * - * The host must observe {@link WatermarkToken} first, then fetch provider - * truth, then call this against freshly read state. A token mismatch means - * an intervening write landed; drop the snapshot. A match ALWAYS writes — - * even when no field changed — so `snapshotAt` advances and a delayed - * intermediate webhook cannot land after a no-op sweep. `eventAt` and - * `eventId` are copied from current state and never replaced. + * 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 `snapshotAt` 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 — so `snapshotAt` + * advances and a delayed intermediate webhook cannot land after a no-op + * sweep. `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: WatermarkToken, + observed: SnapshotObservation, snapshot: LedgerSnapshot, snapshotAt: IsoTimestamp, invariants?: LedgerInvariants, @@ -1030,9 +1065,15 @@ export function decideLedgerSnapshot( 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) { + return { action: "keep", reason: "superseded" }; + } return { action: "write", value: projectSnapshotRecord(current, snapshot, snapshotAt, invariants), @@ -1175,7 +1216,16 @@ export function createBillingLedger( }); return { written: false, record: null, reason: "missing" }; } - const token = observeWatermark(observed); + 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", { @@ -1186,10 +1236,21 @@ export function createBillingLedger( return { written: false, record: observed, reason: "unavailable" }; } const snapshot = assertSnapshot(fetched); - const snapshotAt = assertClockNow(clock); - const result = await rows.update(billingLedgerKey(accountId), (current) => - decideLedgerSnapshot(current, token, snapshot, snapshotAt, invariants), - ); + 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", @@ -1213,7 +1274,7 @@ export function createBillingLedger( return { written: false, record: result.value, - reason: result.value === null ? "missing" : "intervening-write", + reason: ignore ?? "intervening-write", }; } From d2fb78809c27b521f9e4a13dc5155ea86ab6420c Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 15 Aug 2026 17:55:27 +0000 Subject: [PATCH 4/5] Strictly advance snapshotAt on every successful snapshot write laterTimestamp left the bound unchanged when two reconciles sampled the same instant, so the superseded CAS still matched and a slower fetch could clobber fresher fields. Every snapshot write now persists a strictly later snapshotAt (incoming if newer, otherwise current + 1ms). Pinned by overlapping same-bound sweep tests. Co-authored-by: Fly Over Coder --- packages/billing-core/src/index.test.ts | 84 ++++++++++++++++++++++++- packages/billing-core/src/index.ts | 41 +++++++----- 2 files changed, 107 insertions(+), 18 deletions(-) diff --git a/packages/billing-core/src/index.test.ts b/packages/billing-core/src/index.test.ts index 9b2bf7c..84944ac 100644 --- a/packages/billing-core/src/index.test.ts +++ b/packages/billing-core/src/index.test.ts @@ -1708,10 +1708,38 @@ describe("snapshot decider", () => { ); expect(decision).toMatchObject({ action: "write", - value: { snapshotAt: SNAPSHOT_BOUND, eventId: "evt_seed" }, + value: { + snapshotAt: "2026-08-15T16:05:00.001Z", + eventId: "evt_seed", + }, }); }); + it("strictly advances snapshotAt 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: "2026-08-15T16:00:00.001Z", 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"), @@ -1945,6 +1973,60 @@ function snapshotReconciliation(name: string, freshStore: () => Store): void { }); }); + 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("2026-08-15T16:00:00.001Z"); + 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: "2026-08-15T16:00:00.001Z", + }); + }); + it("overlapping sweep does not clobber a newer snapshot", async () => { const clock = controllableClock(SECOND); const store = freshStore(); diff --git a/packages/billing-core/src/index.ts b/packages/billing-core/src/index.ts index 48e6b0d..ea030a9 100644 --- a/packages/billing-core/src/index.ts +++ b/packages/billing-core/src/index.ts @@ -576,22 +576,28 @@ function assertSweepLimit(limit: number): number { return limit; } -function laterTimestamp( - left: IsoTimestamp | null, - right: IsoTimestamp, +/** + * Every successful snapshot write must persist a strictly later + * `snapshotAt` than the row already holds. Equality is not enough: two + * reconciles that observed the same bound would both pass the CAS check + * and the slower fetch could clobber fresher fields. + */ +function advancingSnapshotAt( + current: IsoTimestamp | null, + incoming: IsoTimestamp, ): IsoTimestamp { - if (left === null) { - return right; + if (current === null) { + return incoming; } - const leftMs = canonicalTimestampMilliseconds(left); - const rightMs = canonicalTimestampMilliseconds(right); - if (leftMs === null) { - return right; + const currentMs = canonicalTimestampMilliseconds(current); + const incomingMs = canonicalTimestampMilliseconds(incoming); + if (currentMs === null) { + return incoming; } - if (rightMs === null) { - return left; + if (incomingMs !== null && incomingMs > currentMs) { + return incoming; } - return leftMs >= rightMs ? left : right; + return addMilliseconds(current, 1); } /** Reads the domain CAS token from a ledger row. */ @@ -1025,7 +1031,7 @@ function projectSnapshotRecord( cancelAtPeriodEnd: snapshot.cancelAtPeriodEnd, eventAt: current.eventAt, eventId: current.eventId, - snapshotAt: laterTimestamp(current.snapshotAt, snapshotAt), + snapshotAt: advancingSnapshotAt(current.snapshotAt, snapshotAt), reservationId: granting ? null : (current.reservationId ?? null), reservationExpiresAt: granting ? null @@ -1047,10 +1053,11 @@ function projectSnapshotRecord( * 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 — so `snapshotAt` - * advances and a delayed intermediate webhook cannot land after a no-op - * sweep. `eventAt` and `eventId` are copied from current state and never - * replaced. + * A match ALWAYS writes — even when no field changed — and `snapshotAt` + * strictly advances so a same-bound overlapping sweep cannot clobber + * fresher fields. A delayed intermediate webhook cannot land after a + * no-op sweep. `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. From b0099774d3a26aedac845c7e265e1bf4936584e5 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 15 Aug 2026 18:02:44 +0000 Subject: [PATCH 5/5] Keep snapshotAt inside the watermark second; CAS via generation A 1ms snapshotAt bump from .999Z crossed into the next Unix second and raised effectiveWatermarkSecond, so same-second webhooks were dropped as stale instead of going through lifecycle rank. Snapshot writes now keep snapshotAt at max(current, sampled bound) and increment snapshotGeneration for the same-bound CAS. Pinned by a .999Z overlapping reconcile plus a same-second canceled webhook. Co-authored-by: Fly Over Coder --- packages/billing-core/README.md | 18 ++-- packages/billing-core/src/index.test.ts | 108 ++++++++++++++++++++++-- packages/billing-core/src/index.ts | 88 +++++++++++-------- 3 files changed, 164 insertions(+), 50 deletions(-) diff --git a/packages/billing-core/README.md b/packages/billing-core/README.md index 870ebaf..ed8af78 100644 --- a/packages/billing-core/README.md +++ b/packages/billing-core/README.md @@ -77,14 +77,16 @@ 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. Snapshot reconciliation observes the domain CAS token `(eventAt, eventId)` -and the current `snapshotAt`, samples the freshness bound from the injected -clock, then fetches provider truth. The decider re-checks both the watermark -and the observed `snapshotAt` 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 — so `snapshotAt` advances and a -delayed intermediate webhook cannot land after a no-op sweep. The watermark -identity is never touched. +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 diff --git a/packages/billing-core/src/index.test.ts b/packages/billing-core/src/index.test.ts index 84944ac..9cad4fb 100644 --- a/packages/billing-core/src/index.test.ts +++ b/packages/billing-core/src/index.test.ts @@ -136,6 +136,7 @@ function record( eventAt: SECOND, eventId: "evt_seed", snapshotAt: null, + snapshotGeneration: 0, reservationId: null, reservationExpiresAt: null, reservationSeeded: false, @@ -797,6 +798,7 @@ describe("billing ledger codec", () => { eventAt: SECOND, eventId: "evt_seed", snapshotAt: null, + snapshotGeneration: 0, reservationId: null, reservationExpiresAt: null, reservationSeeded: false, @@ -1448,6 +1450,7 @@ describe("declared invariants", () => { eventAt: SECOND, eventId: "evt_seed", snapshotAt: null, + snapshotGeneration: 0, reservationId: null, reservationExpiresAt: null, reservationSeeded: false, @@ -1649,6 +1652,7 @@ describe("snapshot decider", () => { eventId: "evt_seed", eventAt: SECOND, snapshotAt: SNAPSHOT_BOUND, + snapshotGeneration: 1, status: "active", plan: "pro", }, @@ -1680,7 +1684,12 @@ describe("snapshot decider", () => { expect( decideLedgerSnapshot( record("acct", { eventId: "evt_newer", eventAt: LATER }), - { eventAt: SECOND, eventId: "evt_seed", snapshotAt: null }, + { + eventAt: SECOND, + eventId: "evt_seed", + snapshotAt: null, + snapshotGeneration: 0, + }, snapshot({ plan: "should-not-land" }), SNAPSHOT_BOUND, ), @@ -1691,7 +1700,12 @@ describe("snapshot decider", () => { expect( decideLedgerSnapshot( null, - { eventAt: SECOND, eventId: "evt_seed", snapshotAt: null }, + { + eventAt: SECOND, + eventId: "evt_seed", + snapshotAt: null, + snapshotGeneration: 0, + }, snapshot(), SNAPSHOT_BOUND, ), @@ -1709,13 +1723,14 @@ describe("snapshot decider", () => { expect(decision).toMatchObject({ action: "write", value: { - snapshotAt: "2026-08-15T16:05:00.001Z", + snapshotAt: SNAPSHOT_BOUND, + snapshotGeneration: 1, eventId: "evt_seed", }, }); }); - it("strictly advances snapshotAt on a same-bound write so the next CAS drops", () => { + 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, @@ -1725,7 +1740,11 @@ describe("snapshot decider", () => { ); expect(first).toMatchObject({ action: "write", - value: { snapshotAt: "2026-08-15T16:00:00.001Z", plan: "fresh" }, + value: { + snapshotAt: SECOND, + snapshotGeneration: 1, + plan: "fresh", + }, }); if (first.action !== "write") { return; @@ -1798,7 +1817,12 @@ describe("snapshot decider", () => { expect( decideLedgerSnapshot( record("acct", { snapshotAt: SNAPSHOT_BOUND, plan: "fresh" }), - { eventAt: SECOND, eventId: "evt_seed", snapshotAt: null }, + { + eventAt: SECOND, + eventId: "evt_seed", + snapshotAt: null, + snapshotGeneration: 0, + }, snapshot({ plan: "stale-fetch" }), SECOND, ), @@ -2013,7 +2037,8 @@ function snapshotReconciliation(name: string, freshStore: () => Store): void { if (!fast.written) { throw new Error("expected fast snapshot write"); } - expect(fast.record.snapshotAt).toBe("2026-08-15T16:00:00.001Z"); + expect(fast.record.snapshotAt).toBe(SECOND); + expect(fast.record.snapshotGeneration).toBe(2); releaseSlow(); expect(await slow).toMatchObject({ written: false, @@ -2023,7 +2048,74 @@ function snapshotReconciliation(name: string, freshStore: () => Store): void { plan: "fresh-truth", status: "canceled", eventId: "evt_seed", - snapshotAt: "2026-08-15T16:00:00.001Z", + 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, }); }); diff --git a/packages/billing-core/src/index.ts b/packages/billing-core/src/index.ts index ea030a9..dc7e5ee 100644 --- a/packages/billing-core/src/index.ts +++ b/packages/billing-core/src/index.ts @@ -138,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; @@ -175,14 +176,15 @@ export interface WatermarkToken { /** * What a sweep observed before fetching provider truth: the watermark - * identity plus the snapshot freshness bound already on the row. + * identity plus the snapshot freshness bound and write generation. * - * Another reconciliation that lands first changes `snapshotAt` without - * touching the watermark. Re-checking this bound is what drops the - * slower, stale fetch. + * 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; } /** @@ -310,6 +312,7 @@ const CORE_FIELD_NAMES = new Set([ "eventAt", "eventId", "snapshotAt", + "snapshotGeneration", "reservationId", "reservationExpiresAt", "reservationSeeded", @@ -576,28 +579,32 @@ function assertSweepLimit(limit: number): number { return limit; } -/** - * Every successful snapshot write must persist a strictly later - * `snapshotAt` than the row already holds. Equality is not enough: two - * reconciles that observed the same bound would both pass the CAS check - * and the slower fetch could clobber fresher fields. - */ -function advancingSnapshotAt( - current: IsoTimestamp | null, - incoming: IsoTimestamp, +function laterTimestamp( + left: IsoTimestamp | null, + right: IsoTimestamp, ): IsoTimestamp { - if (current === null) { - return incoming; + if (left === null) { + return right; } - const currentMs = canonicalTimestampMilliseconds(current); - const incomingMs = canonicalTimestampMilliseconds(incoming); - if (currentMs === null) { - return incoming; + const leftMs = canonicalTimestampMilliseconds(left); + const rightMs = canonicalTimestampMilliseconds(right); + if (leftMs === null) { + return right; } - if (incomingMs !== null && incomingMs > currentMs) { - return incoming; + if (rightMs === null) { + return left; } - return addMilliseconds(current, 1); + 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. */ @@ -607,14 +614,18 @@ export function observeWatermark( return { eventAt: record.eventAt, eventId: record.eventId }; } -/** Reads the watermark and the snapshot freshness bound already on the row. */ +/** Reads the watermark, freshness bound, and snapshot write generation. */ export function observeSnapshot( - record: Pick, + record: Pick< + LedgerFields, + "eventAt" | "eventId" | "snapshotAt" | "snapshotGeneration" + >, ): SnapshotObservation { return { eventAt: record.eventAt, eventId: record.eventId, snapshotAt: record.snapshotAt, + snapshotGeneration: storedSnapshotGeneration(record.snapshotGeneration), }; } @@ -732,6 +743,7 @@ function blankLedgerRecord( eventAt: null, eventId: null, snapshotAt: null, + snapshotGeneration: 0, reservationId: null, reservationExpiresAt: null, reservationSeeded: false, @@ -892,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 @@ -1031,7 +1044,8 @@ function projectSnapshotRecord( cancelAtPeriodEnd: snapshot.cancelAtPeriodEnd, eventAt: current.eventAt, eventId: current.eventId, - snapshotAt: advancingSnapshotAt(current.snapshotAt, snapshotAt), + snapshotAt: laterTimestamp(current.snapshotAt, snapshotAt), + snapshotGeneration: nextSnapshotGeneration(current.snapshotGeneration), reservationId: granting ? null : (current.reservationId ?? null), reservationExpiresAt: granting ? null @@ -1048,15 +1062,16 @@ function projectSnapshotRecord( * 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 `snapshotAt` 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. + * 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 `snapshotAt` - * strictly advances so a same-bound overlapping sweep cannot clobber - * fresher fields. A delayed intermediate webhook cannot land after a - * no-op sweep. `eventAt` and `eventId` are copied from current state and + * 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 @@ -1078,7 +1093,10 @@ export function decideLedgerSnapshot( if (!watermarksMatch(current, observed)) { return { action: "keep", reason: "intervening-write" }; } - if (current.snapshotAt !== observed.snapshotAt) { + if ( + current.snapshotAt !== observed.snapshotAt || + current.snapshotGeneration !== observed.snapshotGeneration + ) { return { action: "keep", reason: "superseded" }; } return { @@ -1110,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, @@ -1158,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,