From 7bc81d64f4148829897744e45388972de8b230f5 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Sat, 10 Oct 2026 16:44:37 -0400 Subject: [PATCH 1/3] Add opt-in credit reservation adapters for AI work Paid AI work needs a before-call hold and an exactly-once settlement on the existing wallet (app#2105 milestone 1, reused by Context accounting app#2123). The current preflight only reads the balance, so concurrent requests can each pass it. reserveCreditsOnce, settleCreditReservation and releaseCreditReservation wrap the new database functions. Inputs are validated before the wallet is touched; insufficient capacity is a definite receipt so a caller can return a machine-readable 402. Lost replies and invalid receipts raise reconciliation errors that keep the operation key; settlement reuses the charge receipt identity and its CreditChargeNeedsReconciliation. No caller, price, ceiling, auto-top-up or provider call is added. Co-Authored-By: Claude Opus 5.5 --- .../CreditReservationNeedsReconciliation.ts | 7 ++ lib/credits/reservations/README.md | 53 ++++++++++++ .../reservations/validateCreditReservation.ts | 17 ++++ .../validateCreditReservationRelease.ts | 12 +++ .../releaseCreditReservation.test.ts | 65 ++++++++++++++ .../__tests__/reserveCreditsOnce.test.ts | 84 +++++++++++++++++++ .../__tests__/settleCreditReservation.test.ts | 82 ++++++++++++++++++ .../releaseCreditReservation.ts | 46 ++++++++++ .../credit_reservations/reserveCreditsOnce.ts | 62 ++++++++++++++ .../settleCreditReservation.ts | 55 ++++++++++++ 10 files changed, 483 insertions(+) create mode 100644 lib/credits/reservations/CreditReservationNeedsReconciliation.ts create mode 100644 lib/credits/reservations/README.md create mode 100644 lib/credits/reservations/validateCreditReservation.ts create mode 100644 lib/credits/reservations/validateCreditReservationRelease.ts create mode 100644 lib/supabase/credit_reservations/__tests__/releaseCreditReservation.test.ts create mode 100644 lib/supabase/credit_reservations/__tests__/reserveCreditsOnce.test.ts create mode 100644 lib/supabase/credit_reservations/__tests__/settleCreditReservation.test.ts create mode 100644 lib/supabase/credit_reservations/releaseCreditReservation.ts create mode 100644 lib/supabase/credit_reservations/reserveCreditsOnce.ts create mode 100644 lib/supabase/credit_reservations/settleCreditReservation.ts diff --git a/lib/credits/reservations/CreditReservationNeedsReconciliation.ts b/lib/credits/reservations/CreditReservationNeedsReconciliation.ts new file mode 100644 index 000000000..97e6100d5 --- /dev/null +++ b/lib/credits/reservations/CreditReservationNeedsReconciliation.ts @@ -0,0 +1,7 @@ +/** The hold may or may not exist. Replay with the same key; never start paid work on it. */ +export class CreditReservationNeedsReconciliation extends Error { + constructor(cause?: unknown) { + super("Credit reservation needs reconciliation; retain the same operation key", { cause }); + this.name = "CreditReservationNeedsReconciliation"; + } +} diff --git a/lib/credits/reservations/README.md b/lib/credits/reservations/README.md new file mode 100644 index 000000000..73d5c64b8 --- /dev/null +++ b/lib/credits/reservations/README.md @@ -0,0 +1,53 @@ +# Credit reservations + +`reserveCreditsOnce`, `settleCreditReservation` and `releaseCreditReservation` in +`lib/supabase/credit_reservations` are opt-in adapters to the database +reservation functions (`20261010210500_credit_reservations.sql`). They are the +shared AI-accounting primitive for app#2105 milestone 1, reused by Context +accounting (app#2123). They have no production callers and enable no Sites or +Context spending. + +## Wallet invariant + +Confirmed balance is `credits_usage.remaining_credits`. Outstanding holds are the +owner's unsettled reservations. Spendable is confirmed balance minus outstanding holds. +A hold is a claim, not a temporary debit, so the monthly refill, top-ups and +auto-top-up never see it as consumption. + +## Flow + +1. The trusted server resolves and authorizes the billing owner and chooses one + stable operation key for the chargeable attempt. +2. `reserveCreditsOnce` holds the estimated maximum. `insufficient` is a definite + denial and holds nothing, so the caller can return a machine-readable 402. Paid work + starts only on a hold whose status is `held` (a `reused` receipt reports `held`, + `settled` or `released`). +3. After the work, `settleCreditReservation` charges the actual credits (at most the + hold) through the same owner/key receipt as `recordCreditChargeOnce`, then the + remainder stops being held. Use the existing pricing rules for the amount. +4. `releaseCreditReservation` closes a hold with no charge, for work known not to + have incurred one (for example, cancelled before dispatch). + +Every RPC failure, lost response or invalid receipt throws a reconciliation error +(`CreditReservationNeedsReconciliation` for holds and releases, +`CreditChargeNeedsReconciliation` for settlement, which may have committed). Keep the +same key and replay the same call to learn the state. The adapters never retry, mint a +fresh key, call providers or trigger auto-top-up. `settleCreditReservation` does not +call `maybeAutoTopUp`; a future caller must decide that explicitly. + +## Not covered yet + +- Legacy debit writers (`recordCreditDeduction`, `deductCredits`, the + `deduct_credits*` RPCs) do not consult holds, so spendable can go negative while a + hold is outstanding. Sites production assets, research, content and x402 still use + `deductCredits`. +- No hold expiry. Unknown provider exposure stays held until reconciled. +- No request/pilot ceilings, pricing version, provider-expense versus customer-debit + report, or approved failure/cancellation billing policy. +- Existing preflight (`checkCreditsAvailable`) still reads the confirmed balance, not + spendable credit. + +Apply and verify the database migration through the database release process before +connecting a caller. Generated client types will follow that release; each adapter +narrowly types its single RPC at the access-layer boundary. Mocked adapter tests do not +prove production charging or authorization. diff --git a/lib/credits/reservations/validateCreditReservation.ts b/lib/credits/reservations/validateCreditReservation.ts new file mode 100644 index 000000000..aefcb5e79 --- /dev/null +++ b/lib/credits/reservations/validateCreditReservation.ts @@ -0,0 +1,17 @@ +import { z } from "zod"; + +export const creditReservationSchema = z.strictObject({ + accountId: z.uuid(), + operationKey: z + .string() + .min(1) + .max(200) + .refine(value => value.trim().length > 0), + creditsToReserve: z.number().int().positive().max(Number.MAX_SAFE_INTEGER), +}); +export type CreditReservationInput = z.infer; + +/** Validate a trusted server hold request without changing its operation identity. */ +export function validateCreditReservation(input: CreditReservationInput): CreditReservationInput { + return creditReservationSchema.parse(input); +} diff --git a/lib/credits/reservations/validateCreditReservationRelease.ts b/lib/credits/reservations/validateCreditReservationRelease.ts new file mode 100644 index 000000000..8e8c01313 --- /dev/null +++ b/lib/credits/reservations/validateCreditReservationRelease.ts @@ -0,0 +1,12 @@ +import { z } from "zod"; +import { creditReservationSchema } from "./validateCreditReservation"; + +const schema = creditReservationSchema.pick({ accountId: true, operationKey: true }); +export type CreditReservationReleaseInput = z.infer; + +/** Validate a trusted server release request; it names the hold, never an amount. */ +export function validateCreditReservationRelease( + input: CreditReservationReleaseInput, +): CreditReservationReleaseInput { + return schema.parse(input); +} diff --git a/lib/supabase/credit_reservations/__tests__/releaseCreditReservation.test.ts b/lib/supabase/credit_reservations/__tests__/releaseCreditReservation.test.ts new file mode 100644 index 000000000..651d16e54 --- /dev/null +++ b/lib/supabase/credit_reservations/__tests__/releaseCreditReservation.test.ts @@ -0,0 +1,65 @@ +import { beforeEach, expect, it, vi } from "vitest"; +import supabase from "@/lib/supabase/serverClient"; +import { releaseCreditReservation } from "../releaseCreditReservation"; + +vi.mock("@/lib/supabase/serverClient", () => ({ default: { rpc: vi.fn() } })); +const input = { + accountId: "123e4567-e89b-42d3-a456-426614174000", + operationKey: "sites:generation-1:attempt-1", +}; +const receipt = { + state: "released", + reservationId: `hold-v1-${"b".repeat(64)}`, + creditsHeld: 300, + creditsReleased: 300, +}; +beforeEach(() => vi.clearAllMocks()); + +it.each(["released", "reused"])("returns a validated %s receipt", async state => { + vi.mocked(supabase.rpc).mockResolvedValue({ data: { ...receipt, state }, error: null } as never); + await expect(releaseCreditReservation(input)).resolves.toEqual({ ...receipt, state }); + expect(supabase.rpc).toHaveBeenCalledWith("release_credit_reservation", { + p_account_id: input.accountId, + p_operation_key: input.operationKey, + }); +}); + +it("keeps the same operation identity after a lost response without retrying internally", async () => { + const cause = new Error("Private storage detail"); + vi.mocked(supabase.rpc).mockRejectedValueOnce(cause); + await expect(releaseCreditReservation(input)).rejects.toMatchObject({ + name: "CreditReservationNeedsReconciliation", + cause, + }); + expect(supabase.rpc).toHaveBeenCalledOnce(); +}); + +it.each([ + null, + { ...receipt, creditsReleased: 299 }, + { ...receipt, state: "settled" }, + { ...receipt, reservationId: "hold-v1-short" }, + { ...receipt, extra: true }, +])("treats an invalid receipt as uncertain: %j", async data => { + vi.mocked(supabase.rpc).mockResolvedValue({ data, error: null } as never); + await expect(releaseCreditReservation(input)).rejects.toMatchObject({ + name: "CreditReservationNeedsReconciliation", + }); +}); + +it("retains a returned database error as an internal cause", async () => { + const error = { message: "Credit reservation was settled" }; + vi.mocked(supabase.rpc).mockResolvedValue({ data: null, error } as never); + await expect(releaseCreditReservation(input)).rejects.toMatchObject({ + name: "CreditReservationNeedsReconciliation", + cause: error, + }); +}); + +it.each([{ operationKey: "" }, { accountId: "invalid" }, { creditsToReserve: 300 }])( + "rejects invalid input before touching the wallet: %j", + async invalid => { + await expect(releaseCreditReservation({ ...input, ...invalid } as never)).rejects.toThrow(); + expect(supabase.rpc).not.toHaveBeenCalled(); + }, +); diff --git a/lib/supabase/credit_reservations/__tests__/reserveCreditsOnce.test.ts b/lib/supabase/credit_reservations/__tests__/reserveCreditsOnce.test.ts new file mode 100644 index 000000000..0639f620a --- /dev/null +++ b/lib/supabase/credit_reservations/__tests__/reserveCreditsOnce.test.ts @@ -0,0 +1,84 @@ +import { beforeEach, expect, it, vi } from "vitest"; +import supabase from "@/lib/supabase/serverClient"; +import { reserveCreditsOnce } from "../reserveCreditsOnce"; + +vi.mock("@/lib/supabase/serverClient", () => ({ default: { rpc: vi.fn() } })); +const input = { + accountId: "123e4567-e89b-42d3-a456-426614174000", + operationKey: "sites:generation-1:attempt-1", + creditsToReserve: 300, +}; +const reservationId = `hold-v1-${"b".repeat(64)}`; +const held = { state: "held", reservationId, creditsHeld: 300, spendableCredits: 700 }; +beforeEach(() => vi.clearAllMocks()); + +it.each([ + held, + { state: "reused", reservationId, status: "held", creditsHeld: 300 }, + { state: "reused", reservationId, status: "released", creditsHeld: 300 }, + { state: "insufficient", creditsRequested: 300, spendableCredits: -20 }, +])("returns a validated $state receipt", async receipt => { + vi.mocked(supabase.rpc).mockResolvedValue({ data: receipt, error: null } as never); + await expect(reserveCreditsOnce(input)).resolves.toEqual(receipt); + expect(supabase.rpc).toHaveBeenCalledWith("reserve_credits_once", { + p_account_id: input.accountId, + p_operation_key: input.operationKey, + p_credits: 300, + }); +}); + +it("keeps the same operation identity after a lost response without retrying internally", async () => { + const cause = new Error("Private storage detail"); + vi.mocked(supabase.rpc).mockRejectedValueOnce(cause); + await expect(reserveCreditsOnce(input)).rejects.toMatchObject({ + name: "CreditReservationNeedsReconciliation", + cause, + message: "Credit reservation needs reconciliation; retain the same operation key", + }); + expect(supabase.rpc).toHaveBeenCalledOnce(); + vi.mocked(supabase.rpc).mockResolvedValue({ + data: { state: "reused", reservationId, status: "held", creditsHeld: 300 }, + error: null, + } as never); + await expect(reserveCreditsOnce(input)).resolves.toMatchObject({ state: "reused" }); + expect(vi.mocked(supabase.rpc).mock.calls[0]).toEqual(vi.mocked(supabase.rpc).mock.calls[1]); +}); + +it.each([ + null, + { ...held, creditsHeld: 301 }, + { ...held, spendableCredits: -1 }, + { ...held, reservationId: "hold-v1-short" }, + { ...held, extra: true }, + { state: "insufficient", creditsRequested: 299, spendableCredits: 0 }, + { state: "reused", reservationId, status: "expired", creditsHeld: 300 }, + { state: "pending", reservationId, creditsHeld: 300 }, +])("treats an invalid receipt as uncertain: %j", async data => { + vi.mocked(supabase.rpc).mockResolvedValue({ data, error: null } as never); + await expect(reserveCreditsOnce(input)).rejects.toMatchObject({ + name: "CreditReservationNeedsReconciliation", + }); + expect(supabase.rpc).toHaveBeenCalledOnce(); +}); + +it("retains a returned database error as an internal cause", async () => { + const error = { message: "Credit reservation identity conflict" }; + vi.mocked(supabase.rpc).mockResolvedValue({ data: null, error } as never); + await expect(reserveCreditsOnce(input)).rejects.toMatchObject({ + name: "CreditReservationNeedsReconciliation", + cause: error, + }); +}); + +it.each([ + { operationKey: " " }, + { operationKey: "k".repeat(201) }, + { creditsToReserve: 0 }, + { creditsToReserve: 1.5 }, + { creditsToReserve: Number.MAX_SAFE_INTEGER + 1 }, + { accountId: "invalid" }, + { extra: true }, +])("rejects invalid input before touching the wallet: %j", async invalid => { + await expect(reserveCreditsOnce({ ...input, ...invalid } as never)).rejects.toThrow(); + expect(supabase.rpc).not.toHaveBeenCalled(); +}); diff --git a/lib/supabase/credit_reservations/__tests__/settleCreditReservation.test.ts b/lib/supabase/credit_reservations/__tests__/settleCreditReservation.test.ts new file mode 100644 index 000000000..611bc124e --- /dev/null +++ b/lib/supabase/credit_reservations/__tests__/settleCreditReservation.test.ts @@ -0,0 +1,82 @@ +import { beforeEach, expect, it, vi } from "vitest"; +import supabase from "@/lib/supabase/serverClient"; +import { settleCreditReservation } from "../settleCreditReservation"; + +vi.mock("@/lib/supabase/serverClient", () => ({ default: { rpc: vi.fn() } })); +const input = { + accountId: "123e4567-e89b-42d3-a456-426614174000", + operationKey: "sites:generation-1:attempt-1", + creditsToDeduct: 120, + event: { source: "api" as const, model_id: "fixture", output_tokens: 12 }, +}; +const receipt = { + state: "settled", + reservationId: `hold-v1-${"b".repeat(64)}`, + eventId: `charge-v1-${"a".repeat(64)}`, + creditsHeld: 300, + creditsCharged: 120, + creditsReleased: 180, +}; +beforeEach(() => vi.clearAllMocks()); + +it.each(["settled", "reused"])("returns a validated %s receipt", async state => { + vi.mocked(supabase.rpc).mockResolvedValue({ data: { ...receipt, state }, error: null } as never); + await expect(settleCreditReservation(input)).resolves.toEqual({ ...receipt, state }); + expect(supabase.rpc).toHaveBeenCalledWith("settle_credit_reservation", { + p_account_id: input.accountId, + p_operation_key: input.operationKey, + p_credits: 120, + p_event: input.event, + }); +}); + +it("treats a lost settlement reply as a possibly committed charge and never retries", async () => { + const cause = new Error("Private storage detail"); + vi.mocked(supabase.rpc).mockRejectedValueOnce(cause); + await expect(settleCreditReservation(input)).rejects.toMatchObject({ + name: "CreditChargeNeedsReconciliation", + cause, + }); + expect(supabase.rpc).toHaveBeenCalledOnce(); + vi.mocked(supabase.rpc).mockResolvedValue({ + data: { ...receipt, state: "reused" }, + error: null, + } as never); + await expect(settleCreditReservation(input)).resolves.toMatchObject({ state: "reused" }); + expect(vi.mocked(supabase.rpc).mock.calls[0]).toEqual(vi.mocked(supabase.rpc).mock.calls[1]); +}); + +it.each([ + null, + { ...receipt, creditsCharged: 121, creditsReleased: 179 }, + { ...receipt, creditsReleased: 0 }, + { ...receipt, eventId: "charge-v1-short" }, + { ...receipt, state: "released" }, + { ...receipt, extra: true }, +])("treats an invalid receipt as uncertain: %j", async data => { + vi.mocked(supabase.rpc).mockResolvedValue({ data, error: null } as never); + await expect(settleCreditReservation(input)).rejects.toMatchObject({ + name: "CreditChargeNeedsReconciliation", + }); + expect(supabase.rpc).toHaveBeenCalledOnce(); +}); + +it("retains a returned database error as an internal cause", async () => { + const error = { message: "Credit settlement exceeds reservation" }; + vi.mocked(supabase.rpc).mockResolvedValue({ data: null, error } as never); + await expect(settleCreditReservation(input)).rejects.toMatchObject({ + name: "CreditChargeNeedsReconciliation", + cause: error, + }); +}); + +it.each([ + { operationKey: " " }, + { creditsToDeduct: 0 }, + { event: { input_tokens: -1 } }, + { event: { extra: true } }, + { accountId: "invalid" }, +])("rejects invalid input before touching the wallet: %j", async invalid => { + await expect(settleCreditReservation({ ...input, ...invalid } as never)).rejects.toThrow(); + expect(supabase.rpc).not.toHaveBeenCalled(); +}); diff --git a/lib/supabase/credit_reservations/releaseCreditReservation.ts b/lib/supabase/credit_reservations/releaseCreditReservation.ts new file mode 100644 index 000000000..65111aefc --- /dev/null +++ b/lib/supabase/credit_reservations/releaseCreditReservation.ts @@ -0,0 +1,46 @@ +import { z } from "zod"; +import supabase from "../serverClient"; +import { + validateCreditReservationRelease, + type CreditReservationReleaseInput, +} from "@/lib/credits/reservations/validateCreditReservationRelease"; +import { CreditReservationNeedsReconciliation } from "@/lib/credits/reservations/CreditReservationNeedsReconciliation"; + +const credits = z.number().int().positive(); +const receiptSchema = z.strictObject({ + state: z.enum(["released", "reused"]), + reservationId: z.string().regex(/^hold-v1-[a-f0-9]{64}$/), + creditsHeld: credits, + creditsReleased: credits, +}); +export type CreditReleaseReceipt = z.infer; + +/** + * Release an unsettled hold without any charge, for work known not to have incurred + * one (for example, cancelled before dispatch). Uncertain provider work stays held until + * reconciled; release is never a timeout. No usage event or balance write happens here. + */ +export async function releaseCreditReservation( + input: CreditReservationReleaseInput, +): Promise { + const args = validateCreditReservationRelease(input); + // The additive RPC is narrowly typed here until generated types follow database release. + const rpc = supabase.rpc.bind(supabase) as unknown as ( + name: "release_credit_reservation", + params: { p_account_id: string; p_operation_key: string }, + ) => PromiseLike<{ data: unknown; error: unknown }>; + try { + const { data, error } = await rpc("release_credit_reservation", { + p_account_id: args.accountId, + p_operation_key: args.operationKey, + }); + if (error) throw error; + const receipt = receiptSchema.parse(data); + if (receipt.creditsReleased !== receipt.creditsHeld) { + throw new Error("Credit release receipt mismatch"); + } + return receipt; + } catch (cause) { + throw new CreditReservationNeedsReconciliation(cause); + } +} diff --git a/lib/supabase/credit_reservations/reserveCreditsOnce.ts b/lib/supabase/credit_reservations/reserveCreditsOnce.ts new file mode 100644 index 000000000..01ce2935b --- /dev/null +++ b/lib/supabase/credit_reservations/reserveCreditsOnce.ts @@ -0,0 +1,62 @@ +import { z } from "zod"; +import supabase from "../serverClient"; +import { + validateCreditReservation, + type CreditReservationInput, +} from "@/lib/credits/reservations/validateCreditReservation"; +import { CreditReservationNeedsReconciliation } from "@/lib/credits/reservations/CreditReservationNeedsReconciliation"; + +const reservationId = z.string().regex(/^hold-v1-[a-f0-9]{64}$/); +const credits = z.number().int().positive(); +const receiptSchema = z.discriminatedUnion("state", [ + z.strictObject({ + state: z.literal("held"), + reservationId, + creditsHeld: credits, + spendableCredits: z.number().int().min(0), + }), + z.strictObject({ + state: z.literal("reused"), + reservationId, + status: z.enum(["held", "settled", "released"]), + creditsHeld: credits, + }), + z.strictObject({ + state: z.literal("insufficient"), + creditsRequested: credits, + spendableCredits: z.number().int(), + }), +]); +export type CreditReservationReceipt = z.infer; + +/** + * Opt-in server-only hold on the existing wallet before paid AI work starts. The caller + * resolves/authorizes the billing owner and supplies one stable key per chargeable attempt. + * `insufficient` is a definite denial (nothing held); paid work may start only on a hold + * whose status is `held`. No debit, usage event, provider call or auto-top-up happens here. + */ +export async function reserveCreditsOnce( + input: CreditReservationInput, +): Promise { + const args = validateCreditReservation(input); + // The additive RPC is narrowly typed here until generated types follow database release. + const rpc = supabase.rpc.bind(supabase) as unknown as ( + name: "reserve_credits_once", + params: { p_account_id: string; p_operation_key: string; p_credits: number }, + ) => PromiseLike<{ data: unknown; error: unknown }>; + try { + const { data, error } = await rpc("reserve_credits_once", { + p_account_id: args.accountId, + p_operation_key: args.operationKey, + p_credits: args.creditsToReserve, + }); + if (error) throw error; + const receipt = receiptSchema.parse(data); + const amount = + receipt.state === "insufficient" ? receipt.creditsRequested : receipt.creditsHeld; + if (amount !== args.creditsToReserve) throw new Error("Credit reservation receipt mismatch"); + return receipt; + } catch (cause) { + throw new CreditReservationNeedsReconciliation(cause); + } +} diff --git a/lib/supabase/credit_reservations/settleCreditReservation.ts b/lib/supabase/credit_reservations/settleCreditReservation.ts new file mode 100644 index 000000000..34e095f4d --- /dev/null +++ b/lib/supabase/credit_reservations/settleCreditReservation.ts @@ -0,0 +1,55 @@ +import { z } from "zod"; +import supabase from "../serverClient"; +import { + validateCreditCharge, + type CreditChargeInput, +} from "@/lib/credits/charges/validateCreditCharge"; +import { CreditChargeNeedsReconciliation } from "@/lib/credits/charges/CreditChargeNeedsReconciliation"; +import type { Json } from "@/types/database.types"; + +const credits = z.number().int().positive(); +const receiptSchema = z.strictObject({ + state: z.enum(["settled", "reused"]), + reservationId: z.string().regex(/^hold-v1-[a-f0-9]{64}$/), + eventId: z.string().regex(/^charge-v1-[a-f0-9]{64}$/), + creditsHeld: credits, + creditsCharged: credits, + creditsReleased: z.number().int().min(0), +}); +export type CreditSettlementReceipt = z.infer; + +/** + * Charge the actual credits for a held reservation and release the remainder. The charge + * goes through the same owner/key receipt as `recordCreditChargeOnce`, so a retry after a + * lost reply returns `reused`. Any failure may have committed: keep the key and reconcile. + * Auto-top-up is not triggered here. + */ +export async function settleCreditReservation( + input: CreditChargeInput, +): Promise { + const args = validateCreditCharge(input); + // The additive RPC is narrowly typed here until generated types follow database release. + const rpc = supabase.rpc.bind(supabase) as unknown as ( + name: "settle_credit_reservation", + params: { p_account_id: string; p_operation_key: string; p_credits: number; p_event: Json }, + ) => PromiseLike<{ data: unknown; error: unknown }>; + try { + const { data, error } = await rpc("settle_credit_reservation", { + p_account_id: args.accountId, + p_operation_key: args.operationKey, + p_credits: args.creditsToDeduct, + p_event: args.event, + }); + if (error) throw error; + const receipt = receiptSchema.parse(data); + if ( + receipt.creditsCharged !== args.creditsToDeduct || + receipt.creditsHeld - receipt.creditsCharged !== receipt.creditsReleased + ) { + throw new Error("Credit settlement receipt mismatch"); + } + return receipt; + } catch (cause) { + throw new CreditChargeNeedsReconciliation(cause); + } +} From ace711d0b1f4fd8e87e56039a27c88493203cf49 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Sat, 10 Oct 2026 17:43:29 -0400 Subject: [PATCH 2/3] Report rolled-back reservation rejections as definite Review follow-up for the credit reservation adapters. A returned database error with SQLSTATE 22023 is raised inside the RPC transaction, which rolls back, so the call wrote nothing. The adapters now throw CreditReservationRejected with the fixed database reason in that case, so a future caller can return a definite 402/409 instead of replaying an identical call forever. Every other error, lost reply or invalid receipt still raises the reconciliation error. The README now says a held receipt is not an execution lease (duplicate deliveries must be deduplicated by the caller's attempt identity) and that connecting any caller requires database#101, api#1009 and database#88. Co-Authored-By: Claude Opus 5.5 --- .../reservations/CreditReservationRejected.ts | 15 ++++++ lib/credits/reservations/README.md | 50 +++++++++++++++---- .../toCreditReservationRejection.ts | 16 ++++++ .../releaseCreditReservation.test.ts | 24 +++++++++ .../__tests__/reserveCreditsOnce.test.ts | 24 +++++++++ .../__tests__/settleCreditReservation.test.ts | 24 +++++++++ .../releaseCreditReservation.ts | 5 +- .../credit_reservations/reserveCreditsOnce.ts | 8 ++- .../settleCreditReservation.ts | 8 ++- 9 files changed, 160 insertions(+), 14 deletions(-) create mode 100644 lib/credits/reservations/CreditReservationRejected.ts create mode 100644 lib/credits/reservations/toCreditReservationRejection.ts diff --git a/lib/credits/reservations/CreditReservationRejected.ts b/lib/credits/reservations/CreditReservationRejected.ts new file mode 100644 index 000000000..51b2bf77d --- /dev/null +++ b/lib/credits/reservations/CreditReservationRejected.ts @@ -0,0 +1,15 @@ +/** + * The database rejected this call and rolled it back, so it wrote nothing. Never start + * paid work on it, and do not replay it unchanged expecting a different answer. `reason` + * is the fixed database message (for example a released or settled hold, a settlement + * above the hold, an identity conflict, or an unavailable or ambiguous wallet). + */ +export class CreditReservationRejected extends Error { + readonly reason: string; + + constructor(reason: string, cause?: unknown) { + super("Credit reservation request was rejected; nothing was written", { cause }); + this.name = "CreditReservationRejected"; + this.reason = reason; + } +} diff --git a/lib/credits/reservations/README.md b/lib/credits/reservations/README.md index 73d5c64b8..3f5036816 100644 --- a/lib/credits/reservations/README.md +++ b/lib/credits/reservations/README.md @@ -20,20 +20,50 @@ auto-top-up never see it as consumption. stable operation key for the chargeable attempt. 2. `reserveCreditsOnce` holds the estimated maximum. `insufficient` is a definite denial and holds nothing, so the caller can return a machine-readable 402. Paid work - starts only on a hold whose status is `held` (a `reused` receipt reports `held`, - `settled` or `released`). + is permitted only on a hold whose status is `held` (a `reused` receipt reports + `held`, `settled` or `released`). + + A hold is not an execution lease. Every duplicate delivery of the same key receives + a `reused` receipt with status `held`, so each one may look entitled to start the + work. Settlement still charges once, but deduplicate provider dispatch with the + caller's own attempt identity (for example a durable workflow step) before calling + a paid provider. 3. After the work, `settleCreditReservation` charges the actual credits (at most the hold) through the same owner/key receipt as `recordCreditChargeOnce`, then the remainder stops being held. Use the existing pricing rules for the amount. 4. `releaseCreditReservation` closes a hold with no charge, for work known not to have incurred one (for example, cancelled before dispatch). -Every RPC failure, lost response or invalid receipt throws a reconciliation error -(`CreditReservationNeedsReconciliation` for holds and releases, -`CreditChargeNeedsReconciliation` for settlement, which may have committed). Keep the -same key and replay the same call to learn the state. The adapters never retry, mint a -fresh key, call providers or trigger auto-top-up. `settleCreditReservation` does not -call `maybeAutoTopUp`; a future caller must decide that explicitly. +## Errors + +- **Definite rejection:** `CreditReservationRejected`. The database raised SQLSTATE + `22023` inside the RPC transaction and rolled it back, so the call wrote nothing. + `reason` holds the fixed database message: a released or settled hold, a settlement + above the hold, an identity conflict, a missing reservation, or an unavailable or + ambiguous wallet. An unchanged replay fails the same way, so map it to a definite + error response (for example 402 for a missing wallet, 409 for a conflict) and never + start paid work on it. +- **Uncertain outcome:** any other RPC error, a thrown transport failure, a lost + response or an invalid receipt raises a reconciliation error + (`CreditReservationNeedsReconciliation` for holds and releases, + `CreditChargeNeedsReconciliation` for settlement, which may have committed). Keep + the same key and replay the same call to learn the state. + +The adapters never retry, mint a fresh key, call providers or trigger auto-top-up. +`settleCreditReservation` does not call `maybeAutoTopUp`; a future caller must decide +that explicitly. + +## Activation prerequisites + +Do not connect any caller until these land along with the reservation migration: + +- **database#101 and api#1009** (atomic refill and top-up writers). On `main`, + `incrementRemainingCredits` and `checkAndResetCredits` read the balance and later + write an absolute value, which erases a settlement that commits in between while its + `usage_events` row remains. The database tests for top-up and refill alongside holds + model atomic writers, not these paths. +- **database#88** (one wallet per account). Until then, accounts with duplicate wallet + rows get a definite rejection instead of a hold or charge. ## Not covered yet @@ -41,7 +71,9 @@ call `maybeAutoTopUp`; a future caller must decide that explicitly. `deduct_credits*` RPCs) do not consult holds, so spendable can go negative while a hold is outstanding. Sites production assets, research, content and x402 still use `deductCredits`. -- No hold expiry. Unknown provider exposure stays held until reconciled. +- No hold expiry and no API listing of open holds. Unknown provider exposure stays + held until reconciled; the service role can find open holds in + `credit_reservations` where `state = 'held'`. - No request/pilot ceilings, pricing version, provider-expense versus customer-debit report, or approved failure/cancellation billing policy. - Existing preflight (`checkCreditsAvailable`) still reads the confirmed balance, not diff --git a/lib/credits/reservations/toCreditReservationRejection.ts b/lib/credits/reservations/toCreditReservationRejection.ts new file mode 100644 index 000000000..c16c445d6 --- /dev/null +++ b/lib/credits/reservations/toCreditReservationRejection.ts @@ -0,0 +1,16 @@ +import { CreditReservationRejected } from "./CreditReservationRejected"; + +/** SQLSTATE the reservation and charge functions use for every rejection they raise. */ +const DEFINITE_REJECTION = "22023"; + +/** + * A returned database error with SQLSTATE 22023 was raised inside the RPC transaction, + * which rolled back, so that call definitely wrote nothing. Any other error, a thrown + * transport failure or an invalid receipt stays uncertain and needs reconciliation. + */ +export function toCreditReservationRejection(error: unknown): CreditReservationRejected | null { + if (typeof error !== "object" || error === null) return null; + const { code, message } = error as { code?: unknown; message?: unknown }; + if (code !== DEFINITE_REJECTION || typeof message !== "string") return null; + return new CreditReservationRejected(message, error); +} diff --git a/lib/supabase/credit_reservations/__tests__/releaseCreditReservation.test.ts b/lib/supabase/credit_reservations/__tests__/releaseCreditReservation.test.ts index 651d16e54..6dc5416b6 100644 --- a/lib/supabase/credit_reservations/__tests__/releaseCreditReservation.test.ts +++ b/lib/supabase/credit_reservations/__tests__/releaseCreditReservation.test.ts @@ -63,3 +63,27 @@ it.each([{ operationKey: "" }, { accountId: "invalid" }, { creditsToReserve: 300 expect(supabase.rpc).not.toHaveBeenCalled(); }, ); + +it("reports a rolled-back database rejection as definite, not uncertain", async () => { + const error = { code: "22023", message: "Credit reservation was settled" }; + vi.mocked(supabase.rpc).mockResolvedValue({ data: null, error } as never); + await expect(releaseCreditReservation(input)).rejects.toMatchObject({ + name: "CreditReservationRejected", + reason: "Credit reservation was settled", + cause: error, + message: "Credit reservation request was rejected; nothing was written", + }); + expect(supabase.rpc).toHaveBeenCalledOnce(); +}); + +it.each([ + { code: "08006", message: "connection failure" }, + { code: "22023" }, + { code: 22023, message: "numeric code" }, +])("keeps any other returned database error uncertain: %j", async error => { + vi.mocked(supabase.rpc).mockResolvedValue({ data: null, error } as never); + await expect(releaseCreditReservation(input)).rejects.toMatchObject({ + name: "CreditReservationNeedsReconciliation", + cause: error, + }); +}); diff --git a/lib/supabase/credit_reservations/__tests__/reserveCreditsOnce.test.ts b/lib/supabase/credit_reservations/__tests__/reserveCreditsOnce.test.ts index 0639f620a..f5cb2d40a 100644 --- a/lib/supabase/credit_reservations/__tests__/reserveCreditsOnce.test.ts +++ b/lib/supabase/credit_reservations/__tests__/reserveCreditsOnce.test.ts @@ -82,3 +82,27 @@ it.each([ await expect(reserveCreditsOnce({ ...input, ...invalid } as never)).rejects.toThrow(); expect(supabase.rpc).not.toHaveBeenCalled(); }); + +it("reports a rolled-back database rejection as definite, not uncertain", async () => { + const error = { code: "22023", message: "Credit wallet is unavailable or ambiguous" }; + vi.mocked(supabase.rpc).mockResolvedValue({ data: null, error } as never); + await expect(reserveCreditsOnce(input)).rejects.toMatchObject({ + name: "CreditReservationRejected", + reason: "Credit wallet is unavailable or ambiguous", + cause: error, + message: "Credit reservation request was rejected; nothing was written", + }); + expect(supabase.rpc).toHaveBeenCalledOnce(); +}); + +it.each([ + { code: "08006", message: "connection failure" }, + { code: "22023" }, + { code: 22023, message: "numeric code" }, +])("keeps any other returned database error uncertain: %j", async error => { + vi.mocked(supabase.rpc).mockResolvedValue({ data: null, error } as never); + await expect(reserveCreditsOnce(input)).rejects.toMatchObject({ + name: "CreditReservationNeedsReconciliation", + cause: error, + }); +}); diff --git a/lib/supabase/credit_reservations/__tests__/settleCreditReservation.test.ts b/lib/supabase/credit_reservations/__tests__/settleCreditReservation.test.ts index 611bc124e..8ca57cfe7 100644 --- a/lib/supabase/credit_reservations/__tests__/settleCreditReservation.test.ts +++ b/lib/supabase/credit_reservations/__tests__/settleCreditReservation.test.ts @@ -80,3 +80,27 @@ it.each([ await expect(settleCreditReservation({ ...input, ...invalid } as never)).rejects.toThrow(); expect(supabase.rpc).not.toHaveBeenCalled(); }); + +it("reports a rolled-back database rejection as definite, not uncertain", async () => { + const error = { code: "22023", message: "Credit reservation was released" }; + vi.mocked(supabase.rpc).mockResolvedValue({ data: null, error } as never); + await expect(settleCreditReservation(input)).rejects.toMatchObject({ + name: "CreditReservationRejected", + reason: "Credit reservation was released", + cause: error, + message: "Credit reservation request was rejected; nothing was written", + }); + expect(supabase.rpc).toHaveBeenCalledOnce(); +}); + +it.each([ + { code: "08006", message: "connection failure" }, + { code: "22023" }, + { code: 22023, message: "numeric code" }, +])("keeps any other returned database error uncertain: %j", async error => { + vi.mocked(supabase.rpc).mockResolvedValue({ data: null, error } as never); + await expect(settleCreditReservation(input)).rejects.toMatchObject({ + name: "CreditChargeNeedsReconciliation", + cause: error, + }); +}); diff --git a/lib/supabase/credit_reservations/releaseCreditReservation.ts b/lib/supabase/credit_reservations/releaseCreditReservation.ts index 65111aefc..89d294513 100644 --- a/lib/supabase/credit_reservations/releaseCreditReservation.ts +++ b/lib/supabase/credit_reservations/releaseCreditReservation.ts @@ -5,6 +5,8 @@ import { type CreditReservationReleaseInput, } from "@/lib/credits/reservations/validateCreditReservationRelease"; import { CreditReservationNeedsReconciliation } from "@/lib/credits/reservations/CreditReservationNeedsReconciliation"; +import { CreditReservationRejected } from "@/lib/credits/reservations/CreditReservationRejected"; +import { toCreditReservationRejection } from "@/lib/credits/reservations/toCreditReservationRejection"; const credits = z.number().int().positive(); const receiptSchema = z.strictObject({ @@ -34,13 +36,14 @@ export async function releaseCreditReservation( p_account_id: args.accountId, p_operation_key: args.operationKey, }); - if (error) throw error; + if (error) throw toCreditReservationRejection(error) ?? error; const receipt = receiptSchema.parse(data); if (receipt.creditsReleased !== receipt.creditsHeld) { throw new Error("Credit release receipt mismatch"); } return receipt; } catch (cause) { + if (cause instanceof CreditReservationRejected) throw cause; throw new CreditReservationNeedsReconciliation(cause); } } diff --git a/lib/supabase/credit_reservations/reserveCreditsOnce.ts b/lib/supabase/credit_reservations/reserveCreditsOnce.ts index 01ce2935b..28c406ec1 100644 --- a/lib/supabase/credit_reservations/reserveCreditsOnce.ts +++ b/lib/supabase/credit_reservations/reserveCreditsOnce.ts @@ -5,6 +5,8 @@ import { type CreditReservationInput, } from "@/lib/credits/reservations/validateCreditReservation"; import { CreditReservationNeedsReconciliation } from "@/lib/credits/reservations/CreditReservationNeedsReconciliation"; +import { CreditReservationRejected } from "@/lib/credits/reservations/CreditReservationRejected"; +import { toCreditReservationRejection } from "@/lib/credits/reservations/toCreditReservationRejection"; const reservationId = z.string().regex(/^hold-v1-[a-f0-9]{64}$/); const credits = z.number().int().positive(); @@ -33,7 +35,8 @@ export type CreditReservationReceipt = z.infer; * Opt-in server-only hold on the existing wallet before paid AI work starts. The caller * resolves/authorizes the billing owner and supplies one stable key per chargeable attempt. * `insufficient` is a definite denial (nothing held); paid work may start only on a hold - * whose status is `held`. No debit, usage event, provider call or auto-top-up happens here. + * whose status is `held`. A rolled-back database rejection throws `CreditReservationRejected`. + * No debit, usage event, provider call or auto-top-up happens here. */ export async function reserveCreditsOnce( input: CreditReservationInput, @@ -50,13 +53,14 @@ export async function reserveCreditsOnce( p_operation_key: args.operationKey, p_credits: args.creditsToReserve, }); - if (error) throw error; + if (error) throw toCreditReservationRejection(error) ?? error; const receipt = receiptSchema.parse(data); const amount = receipt.state === "insufficient" ? receipt.creditsRequested : receipt.creditsHeld; if (amount !== args.creditsToReserve) throw new Error("Credit reservation receipt mismatch"); return receipt; } catch (cause) { + if (cause instanceof CreditReservationRejected) throw cause; throw new CreditReservationNeedsReconciliation(cause); } } diff --git a/lib/supabase/credit_reservations/settleCreditReservation.ts b/lib/supabase/credit_reservations/settleCreditReservation.ts index 34e095f4d..dc6810eb6 100644 --- a/lib/supabase/credit_reservations/settleCreditReservation.ts +++ b/lib/supabase/credit_reservations/settleCreditReservation.ts @@ -5,6 +5,8 @@ import { type CreditChargeInput, } from "@/lib/credits/charges/validateCreditCharge"; import { CreditChargeNeedsReconciliation } from "@/lib/credits/charges/CreditChargeNeedsReconciliation"; +import { CreditReservationRejected } from "@/lib/credits/reservations/CreditReservationRejected"; +import { toCreditReservationRejection } from "@/lib/credits/reservations/toCreditReservationRejection"; import type { Json } from "@/types/database.types"; const credits = z.number().int().positive(); @@ -21,7 +23,8 @@ export type CreditSettlementReceipt = z.infer; /** * Charge the actual credits for a held reservation and release the remainder. The charge * goes through the same owner/key receipt as `recordCreditChargeOnce`, so a retry after a - * lost reply returns `reused`. Any failure may have committed: keep the key and reconcile. + * lost reply returns `reused`. A rolled-back database rejection throws + * `CreditReservationRejected`; any other failure may have committed: keep the key and reconcile. * Auto-top-up is not triggered here. */ export async function settleCreditReservation( @@ -40,7 +43,7 @@ export async function settleCreditReservation( p_credits: args.creditsToDeduct, p_event: args.event, }); - if (error) throw error; + if (error) throw toCreditReservationRejection(error) ?? error; const receipt = receiptSchema.parse(data); if ( receipt.creditsCharged !== args.creditsToDeduct || @@ -50,6 +53,7 @@ export async function settleCreditReservation( } return receipt; } catch (cause) { + if (cause instanceof CreditReservationRejected) throw cause; throw new CreditChargeNeedsReconciliation(cause); } } From cdbd8179f156e196ccc073a3ece58d45da5c34ed Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:14:20 -0500 Subject: [PATCH 3/3] Document reservation composition with released pack billing --- lib/credits/reservations/README.md | 48 +++++++++++++++++++----------- 1 file changed, 31 insertions(+), 17 deletions(-) diff --git a/lib/credits/reservations/README.md b/lib/credits/reservations/README.md index 3f5036816..fda9121f0 100644 --- a/lib/credits/reservations/README.md +++ b/lib/credits/reservations/README.md @@ -2,15 +2,18 @@ `reserveCreditsOnce`, `settleCreditReservation` and `releaseCreditReservation` in `lib/supabase/credit_reservations` are opt-in adapters to the database -reservation functions (`20261010210500_credit_reservations.sql`). They are the +reservation functions (`20261010210500_credit_reservations.sql`) and their additive +wallet composition guard (`20261117000000_compose_credit_reservations.sql`). They are the shared AI-accounting primitive for app#2105 milestone 1, reused by Context accounting (app#2123). They have no production callers and enable no Sites or Context spending. ## Wallet invariant -Confirmed balance is `credits_usage.remaining_credits`. Outstanding holds are the -owner's unsettled reservations. Spendable is confirmed balance minus outstanding holds. +The wallet balance is `credits_usage.remaining_credits`. Existing release-pack holds +have already been deducted from it. Shared outstanding holds are the owner's unsettled +`credit_reservations` rows, which have not been deducted. Spendable is this wallet +balance minus shared outstanding holds; do not subtract pack holds a second time. A hold is a claim, not a temporary debit, so the monthly refill, top-ups and auto-top-up never see it as consumption. @@ -55,27 +58,38 @@ that explicitly. ## Activation prerequisites -Do not connect any caller until these land along with the reservation migration: +The original API1026/Database115 candidates are retained dependencies of this +successor; do not merge the old migration alone as completed wallet composition. +Before connecting any caller, release and verify the reservation migration plus +`20261117000000_compose_credit_reservations.sql` through the owning database workflow. +The latter guards wallet writes against outstanding shared holds, including legacy +debits and pack approvals. Settlement excludes only its own hold within the same +transaction; charge failure restores it. Successful reserve versions the locked wallet +row so an older repeatable-read writer fails rather than missing a newly committed hold. -- **database#101 and api#1009** (atomic refill and top-up writers). On `main`, - `incrementRemainingCredits` and `checkAndResetCredits` read the balance and later - write an absolute value, which erases a settlement that commits in between while its - `usage_events` row remains. The database tests for top-up and refill alongside holds - model atomic writers, not these paths. -- **database#88** (one wallet per account). Until then, accounts with duplicate wallet - rows get a definite rejection instead of a hold or charge. +Current main already has atomic `incrementRemainingCredits`, `checkAndResetCredits` +and `deductCredits` callers. The released pack migration supplies atomic increment, +adjustment and a refill floor that counts unconsumed pack holds. Open historical +Database101/API1009 PR labels are not evidence those writers are still absent. +Preserve the pack-aware refill; do not replace it with the old candidate's plain floor. + +One wallet per billing owner remains a separate prerequisite (Database88). The +reservation functions reject zero/multiple wallet rows; this successor does not repair +existing rows or add that uniqueness constraint. Verify actual released grants and +schema before activation; source and disposable transactions are not hosted evidence. ## Not covered yet -- Legacy debit writers (`recordCreditDeduction`, `deductCredits`, the - `deduct_credits*` RPCs) do not consult holds, so spendable can go negative while a - hold is outstanding. Sites production assets, research, content and x402 still use - `deductCredits`. +- Legacy provider dispatch is not moved onto reservations. The wallet guard prevents + a final debit from consuming promised funds, but a legacy caller may already have + incurred provider expense before its debit fails. This is not pre-dispatch spending + authorization or proof of bounded provider exposure. No live caller is enabled. - No hold expiry and no API listing of open holds. Unknown provider exposure stays held until reconciled; the service role can find open holds in `credit_reservations` where `state = 'held'`. -- No request/pilot ceilings, pricing version, provider-expense versus customer-debit - report, or approved failure/cancellation billing policy. +- No request/pilot ceilings or approved failure/cancellation billing policy. The shared + primitive stores neither pricing version nor provider expense. Existing Packs + accounting labels do not supply those Context-specific controls. - Existing preflight (`checkCreditsAvailable`) still reads the confirmed balance, not spendable credit.