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/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 new file mode 100644 index 000000000..db79f0e3e --- /dev/null +++ b/lib/credits/reservations/README.md @@ -0,0 +1,101 @@ +# Credit reservations + +`reserveCreditsOnce`, `settleCreditReservation` and `releaseCreditReservation` in +`lib/supabase/credit_reservations` are opt-in adapters to the database +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 + +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. + +## 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 + 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. A duplicate receives a `reused` receipt with + the hold's current status: `held`, `settled` or `released`. Closed holds never + authorize new work. A reused `held` receipt still requires independently established + durable dispatch ownership or reconciliation before any paid provider call; + settlement charging once does not prevent duplicate provider work. The merged + Context accounting consumer conservatively reconciles every reused hold instead + of dispatching again. +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). + +## 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 + +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. + +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 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 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. + +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/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/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..6dc5416b6 --- /dev/null +++ b/lib/supabase/credit_reservations/__tests__/releaseCreditReservation.test.ts @@ -0,0 +1,89 @@ +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(); + }, +); + +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 new file mode 100644 index 000000000..f5cb2d40a --- /dev/null +++ b/lib/supabase/credit_reservations/__tests__/reserveCreditsOnce.test.ts @@ -0,0 +1,108 @@ +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(); +}); + +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 new file mode 100644 index 000000000..8ca57cfe7 --- /dev/null +++ b/lib/supabase/credit_reservations/__tests__/settleCreditReservation.test.ts @@ -0,0 +1,106 @@ +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(); +}); + +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 new file mode 100644 index 000000000..89d294513 --- /dev/null +++ b/lib/supabase/credit_reservations/releaseCreditReservation.ts @@ -0,0 +1,49 @@ +import { z } from "zod"; +import supabase from "../serverClient"; +import { + validateCreditReservationRelease, + 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({ + 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 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 new file mode 100644 index 000000000..28c406ec1 --- /dev/null +++ b/lib/supabase/credit_reservations/reserveCreditsOnce.ts @@ -0,0 +1,66 @@ +import { z } from "zod"; +import supabase from "../serverClient"; +import { + validateCreditReservation, + 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(); +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`. 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, +): 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 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 new file mode 100644 index 000000000..dc6810eb6 --- /dev/null +++ b/lib/supabase/credit_reservations/settleCreditReservation.ts @@ -0,0 +1,59 @@ +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 { 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(); +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`. 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( + 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 toCreditReservationRejection(error) ?? 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) { + if (cause instanceof CreditReservationRejected) throw cause; + throw new CreditChargeNeedsReconciliation(cause); + } +}