Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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";
}
}
15 changes: 15 additions & 0 deletions lib/credits/reservations/CreditReservationRejected.ts
Original file line number Diff line number Diff line change
@@ -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;
}
}
99 changes: 99 additions & 0 deletions lib/credits/reservations/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# 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. 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).

## 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.
16 changes: 16 additions & 0 deletions lib/credits/reservations/toCreditReservationRejection.ts
Original file line number Diff line number Diff line change
@@ -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);
}
17 changes: 17 additions & 0 deletions lib/credits/reservations/validateCreditReservation.ts
Original file line number Diff line number Diff line change
@@ -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<typeof creditReservationSchema>;

/** Validate a trusted server hold request without changing its operation identity. */
export function validateCreditReservation(input: CreditReservationInput): CreditReservationInput {
return creditReservationSchema.parse(input);
}
12 changes: 12 additions & 0 deletions lib/credits/reservations/validateCreditReservationRelease.ts
Original file line number Diff line number Diff line change
@@ -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<typeof schema>;

/** Validate a trusted server release request; it names the hold, never an amount. */
export function validateCreditReservationRelease(
input: CreditReservationReleaseInput,
): CreditReservationReleaseInput {
return schema.parse(input);
}
Original file line number Diff line number Diff line change
@@ -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,
});
});
108 changes: 108 additions & 0 deletions lib/supabase/credit_reservations/__tests__/reserveCreditsOnce.test.ts
Original file line number Diff line number Diff line change
@@ -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,
});
});
Loading
Loading