Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(budget): make paid MCP spend atomic and fail closed (#3203)

caterpillarC1518513c65be00
diff --git a/src/core/minions/budget-meter.ts b/src/core/minions/budget-meter.ts
index d81840079b..cf0117ab6d 100644
--- a/src/core/minions/budget-meter.ts
+++ b/src/core/minions/budget-meter.ts
@@ -1,11 +1,11 @@
/**
- * v0.38 Slice 2 — budget meter for the subagent tool loop.
+ * Durable reserve-then-settle meter for paid OAuth/MCP operations.
*
- * Reserve-then-settle pattern (D3) prevents the "concurrent agents bust the
+ * Reserve-then-settle pattern (D3) prevents the "concurrent requests bust the
* cap" race that the pre-v82 best-effort post-call recording allowed. Two
- * agents from the same OAuth client both pre-flight pass at $2 of $5,
- * both spend $2, total spend = $4 of $5 → fine. But raise the per-agent
- * estimate to $3 and both agents see "$5 cap - $2 spent = $3 headroom, ok"
+ * calls from the same OAuth client both pre-flight pass at $2 of $5,
+ * both spend $2, total spend = $4 of $5 → fine. But raise the per-call
+ * estimate to $3 and both calls see "$5 cap - $2 spent = $3 headroom, ok"
* and both proceed, total spend = $8. That's the bug. The fix is atomic
* check-and-reserve under pg_advisory_xact_lock.
*
@@ -22,8 +22,8 @@ import type { BrainEngine } from '../engine.ts';
import { sqlQueryForEngine } from '../sql-query.ts';
import { BudgetExceededError } from '../spend-log.ts';
-/** Reservation TTL — 10 minutes. Long enough for any normal subagent call;
- * short enough that crashed workers don't strand capacity for long. */
+/** Reservation TTL — 10 minutes. Long enough for a normal provider call;
+ * short enough that crashed callers don't strand capacity for long. */
export const RESERVATION_TTL_MS = 10 * 60 * 1000;
/** Generate an int hash of client_id for pg_advisory_xact_lock. */
@@ -34,7 +34,7 @@ function clientLockKey(clientId: string): number {
h ^= clientId.charCodeAt(i);
h = Math.imul(h, 0x01000193);
}
- // pg_advisory_xact_lock(BIGINT) — keep within INT32 positive range.
+ // pg_advisory_xact_lock(BIGINT) — unsigned 32-bit value fits in BIGINT.
return h >>> 0;
}
@@ -63,72 +63,86 @@ export interface Reservation {
* 4. INSERT pending reservation row with TTL.
* 5. Return reservation id.
*
- * Lock auto-releases at transaction end (xact-scoped). The whole operation
- * is single round-trip (one transaction).
+ * Lock auto-releases at transaction end (xact-scoped). All statements commit
+ * or roll back as one transaction.
*/
export async function reserve(
engine: BrainEngine,
opts: ReserveOpts,
): Promise<Reservation> {
- const sql = sqlQueryForEngine(engine);
+ assertNonEmpty('clientId', opts.clientId);
+ assertFiniteNonNegative('estimatedCents', opts.estimatedCents);
+ assertFiniteNonNegative('capCents', opts.capCents);
+ assertNonEmpty('model', opts.model);
+ assertNonEmpty('provider', opts.provider);
+ if (opts.jobId !== undefined && (!Number.isSafeInteger(opts.jobId) || opts.jobId <= 0)) {
+ throw new TypeError('jobId must be a positive safe integer when provided');
+ }
+
const reservationId = randomUUIDv7();
const lockKey = clientLockKey(opts.clientId);
const expiresAt = new Date(Date.now() + RESERVATION_TTL_MS);
const todayStart = todayStartIso();
- // The Postgres path runs everything inside a transaction with
- // pg_advisory_xact_lock; PGLite is single-process so the lock isn't
- // strictly needed but we use the same query for shape consistency.
- // PGLite's pg_advisory_xact_lock is a no-op pre-v0.3.x, so the lock
- // call is wrapped in a defensive fallback.
+ await engine.transaction(async (tx) => {
+ const sql = sqlQueryForEngine(tx);
- // Step 1: sweep expired reservations for this client.
- await sql`
- UPDATE mcp_spend_reservations
- SET status = 'expired', actual_cents = 0
- WHERE client_id = ${opts.clientId}
- AND status = 'pending'
- AND expires_at < now()
- `;
+ // Postgres can run several MCP requests for one client concurrently.
+ // Hold a transaction-scoped lock across sweep + read + insert so two
+ // callers cannot both observe the same headroom. PGLite serializes its
+ // single connection and does not implement advisory locks.
+ if (tx.kind === 'postgres') {
+ await sql`SELECT pg_advisory_xact_lock(${BigInt(lockKey)})`;
+ }
- // Step 2 + 3: SUM committed + pending, refuse if over cap.
- const rows = await sql`
- SELECT
- COALESCE((
- SELECT SUM(spend_cents)::text
- FROM mcp_spend_log
- WHERE client_id = ${opts.clientId}
- AND created_at >= ${todayStart}
- ), '0') AS committed_text,
- COALESCE((
- SELECT SUM(estimated_cents)::text
- FROM mcp_spend_reservations
- WHERE client_id = ${opts.clientId}
- AND status = 'pending'
- AND created_at >= ${todayStart}
- ), '0') AS pending_text
- `;
- const committedCents = parseFloat(String(rows[0]?.committed_text ?? '0'));
- const pendingCents = parseFloat(String(rows[0]?.pending_text ?? '0'));
- const totalProjected = committedCents + pendingCents + opts.estimatedCents;
- if (totalProjected > opts.capCents) {
- throw new BudgetExceededError(
- `budget exceeded for client ${opts.clientId}: ` +
- `committed=${committedCents.toFixed(2)}¢, pending=${pendingCents.toFixed(2)}¢, ` +
- `estimated=${opts.estimatedCents.toFixed(2)}¢, cap=${opts.capCents.toFixed(2)}¢`,
- Math.round(committedCents + pendingCents),
- Math.round(opts.capCents),
- );
- }
+ // Step 1: sweep expired reservations for this client.
+ await sql`
+ UPDATE mcp_spend_reservations
+ SET status = 'expired', actual_cents = 0
+ WHERE client_id = ${opts.clientId}
+ AND status = 'pending'
+ AND expires_at < now()
+ `;
- // Step 4: INSERT reservation.
- await sql`
- INSERT INTO mcp_spend_reservations
- (reservation_id, client_id, job_id, estimated_cents, model, provider, status, expires_at)
- VALUES
- (${reservationId}, ${opts.clientId}, ${opts.jobId ?? null},
- ${opts.estimatedCents}, ${opts.model}, ${opts.provider}, 'pending', ${expiresAt})
- `;
+ // Step 2 + 3: SUM committed + pending, refuse if over cap.
+ const rows = await sql`
+ SELECT
+ COALESCE((
+ SELECT SUM(spend_cents)::text
+ FROM mcp_spend_log
+ WHERE client_id = ${opts.clientId}
+ AND created_at >= ${todayStart}
+ ), '0') AS committed_text,
+ COALESCE((
+ SELECT SUM(estimated_cents)::text
+ FROM mcp_spend_reservations
+ WHERE client_id = ${opts.clientId}
+ AND status = 'pending'
+ AND created_at >= ${todayStart}
+ ), '0') AS pending_text
+ `;
+ const committedCents = requiredFiniteTotal(rows[0]?.committed_text, 'committed spend');
+ const pendingCents = requiredFiniteTotal(rows[0]?.pending_text, 'pending spend');
+ const totalProjected = committedCents + pendingCents + opts.estimatedCents;
+ if (totalProjected > opts.capCents) {
+ throw new BudgetExceededError(
+ `budget exceeded for client ${opts.clientId}: ` +
+ `committed=${committedCents.toFixed(2)}¢, pending=${pendingCents.toFixed(2)}¢, ` +
+ `estimated=${opts.estimatedCents.toFixed(2)}¢, cap=${opts.capCents.toFixed(2)}¢`,
+ committedCents + pendingCents,
+ opts.capCents,
+ );
+ }
+
+ // Step 4: INSERT reservation before releasing the client lock.
+ await sql`
+ INSERT INTO mcp_spend_reservations
+ (reservation_id, client_id, job_id, estimated_cents, model, provider, status, expires_at)
+ VALUES
+ (${reservationId}, ${opts.clientId}, ${opts.jobId ?? null},
+ ${opts.estimatedCents}, ${opts.model}, ${opts.provider}, 'pending', ${expiresAt})
+ `;
+ });
return {
reservationId,
@@ -147,35 +161,51 @@ export async function settle(
reservationId: string,
actualCents: number,
operation: string = 'subagent_loop',
+ tokenName: string | null = null,
): Promise<void> {
- const sql = sqlQueryForEngine(engine);
- // Single UPDATE with WHERE status='pending' to ensure idempotent settles.
- const updated = await sql`
- UPDATE mcp_spend_reservations
- SET status = 'settled',
- actual_cents = ${actualCents},
- settled_at = now()
- WHERE reservation_id = ${reservationId}
- AND status = 'pending'
- RETURNING client_id, model, provider
- `;
- if (updated.length === 0) {
- // Already settled or expired; treat as no-op.
- return;
- }
- const row = updated[0];
- // Mirror into mcp_spend_log so getTodaySpendCents/reserve sees it.
- await sql`
- INSERT INTO mcp_spend_log
- (client_id, token_name, operation, spend_cents, provider, model)
- VALUES
- (${String(row.client_id)}, ${null}, ${operation}, ${actualCents},
- ${String(row.provider)}, ${String(row.model)})
- `;
+ assertNonEmpty('reservationId', reservationId);
+ assertFiniteNonNegative('actualCents', actualCents);
+ assertNonEmpty('operation', operation);
+
+ await engine.transaction(async (tx) => {
+ const sql = sqlQueryForEngine(tx);
+ // A late result may arrive after the TTL sweeper marked the hold expired.
+ // Settle that paid work too: truthfully recording a late overage is safer
+ // than dropping it. WHERE excludes 'settled', preserving idempotency. The
+ // log insert is in the same transaction, so accounting failure rolls the
+ // state transition back.
+ const updated = await sql`
+ UPDATE mcp_spend_reservations
+ SET status = 'settled',
+ actual_cents = ${actualCents},
+ settled_at = now()
+ WHERE reservation_id = ${reservationId}
+ AND status IN ('pending', 'expired')
+ RETURNING client_id, model, provider
+ `;
+ if (updated.length === 0) {
+ const existing = await sql`
+ SELECT status
+ FROM mcp_spend_reservations
+ WHERE reservation_id = ${reservationId}
+ `;
+ if (existing[0]?.status === 'settled') return;
+ throw new Error(`spend reservation not found: ${reservationId}`);
+ }
+ const row = updated[0];
+ // Mirror into mcp_spend_log so getTodaySpendCents/reserve sees it.
+ await sql`
+ INSERT INTO mcp_spend_log
+ (client_id, token_name, operation, spend_cents, provider, model)
+ VALUES
+ (${String(row.client_id)}, ${tokenName}, ${operation}, ${actualCents},
+ ${String(row.provider)}, ${String(row.model)})
+ `;
+ });
}
/**
- * Best-effort sweeper. Called by tests + the worker startup hook. Marks any
+ * Sweeper called by tests + the worker startup hook. Marks any
* pending reservation past its TTL as 'expired' with actual_cents=0.
*
* Returns the number of rows expired.
@@ -198,22 +228,23 @@ export async function getClientDailyCapCents(
engine: BrainEngine,
clientId: string,
): Promise<number | null> {
- try {
- const sql = sqlQueryForEngine(engine);
- const rows = await sql`
- SELECT budget_usd_per_day::text AS cap
- FROM oauth_clients
- WHERE client_id = ${clientId}
- `;
- if (rows.length === 0) return null;
- const raw = rows[0]?.cap;
- if (raw === null || raw === undefined) return null;
- const usd = parseFloat(String(raw));
- if (!isFinite(usd)) return null;
- return Math.round(usd * 100);
- } catch {
- return null;
+ assertNonEmpty('clientId', clientId);
+ const sql = sqlQueryForEngine(engine);
+ const rows = await sql`
+ SELECT budget_usd_per_day::text AS cap
+ FROM oauth_clients
+ WHERE client_id = ${clientId}
+ `;
+ if (rows.length === 0) return null;
+ const raw = rows[0]?.cap;
+ if (raw === null || raw === undefined) return null;
+ const usd = Number(raw);
+ if (!Number.isFinite(usd) || usd < 0) {
+ throw new Error(`invalid budget_usd_per_day for OAuth client ${clientId}`);
}
+ // oauth_clients stores NUMERIC(..., 2) USD, so its public cents view is
+ // integral. Round to avoid binary floating-point artifacts (e.g. 0.29).
+ return Math.round(usd * 100);
}
function todayStartIso(): string {
@@ -222,6 +253,26 @@ function todayStartIso(): string {
return d.toISOString();
}
+function assertNonEmpty(name: string, value: string): void {
+ if (typeof value !== 'string' || value.trim().length === 0) {
+ throw new TypeError(`${name} must be a non-empty string`);
+ }
+}
+
+function assertFiniteNonNegative(name: string, value: number): void {
+ if (!Number.isFinite(value) || value < 0) {
+ throw new TypeError(`${name} must be a finite non-negative number`);
+ }
+}
+
+function requiredFiniteTotal(value: unknown, label: string): number {
+ const total = Number(value ?? 0);
+ if (!Number.isFinite(total) || total < 0) {
+ throw new Error(`invalid ${label} returned by spend ledger`);
+ }
+ return total;
+}
+
/** Use the lockKey helper in case future callers want it (e.g. integration tests). */
export { clientLockKey };
diff --git a/src/core/operations.ts b/src/core/operations.ts
index 7433006858..d7464c1902 100644
--- a/src/core/operations.ts
+++ b/src/core/operations.ts
@@ -4532,14 +4532,10 @@ const search_by_image: Operation = {
throw new Error('search_by_image accepts only one of: image_path, image_url, image_data');
}
- // D23-#6 — pre-flight daily-budget check for remote OAuth clients.
- // Local CLI callers (ctx.remote=false) bypass the cap (clientId="").
+ // D23-#6 — remote OAuth clients are charged through the durable
+ // reserve-then-settle ledger below. Local CLI callers bypass the cap
+ // (clientId="") because they use their own provider credentials.
const clientId = (ctx.remote === true ? (ctx.auth?.clientId ?? '') : '');
- if (clientId) {
- const budgetUsd = await getDailyImageBudgetUsd(ctx.engine);
- const { checkBudget } = await import('./spend-log.ts');
- await checkBudget(ctx.engine, clientId, Math.round(budgetUsd * 100));
- }
// Resolve image bytes via the SSRF-defended loader. For remote callers,
// tighter byte cap.
@@ -4559,33 +4555,75 @@ const search_by_image: Operation = {
// one spread — `__all__` spans the brain only for trusted local callers.
const imageSourceScope = resolveRequestedScope(ctx, sourceIdParam);
- const { searchByImage } = await import('./search/by-image.ts');
- const results = await searchByImage(
- ctx.engine,
- { base64: loaded.base64, mime: loaded.contentType },
- {
- limit: (p.limit as number) || 20,
- offset: (p.offset as number) || 0,
- query: queryRefinement,
- ...imageSourceScope,
- },
- );
-
- // D23-#6 — record successful Voyage call. Best-effort; failures don't
- // block the response.
+ // Reserve immediately before entering the paid search routine. Validation,
+ // image loading, and scope resolution happen first so known no-charge
+ // failures do not strand reservations. An ambiguous provider failure is
+ // settled at this operation's fixed-price upper bound below; pessimistic
+ // accounting is safer than reopening daily headroom after the TTL.
+ let spendReservationId: string | null = null;
+ let estimatedSpendCents = 0;
if (clientId) {
- const { recordSpend, VOYAGE_MULTIMODAL_3_PER_IMAGE_CENTS } = await import('./spend-log.ts');
- // Approximate: 1 image embed + (query ? 1 text embed : 0). Both are
- // billed at the same per-call rate by Voyage.
+ const { VOYAGE_MULTIMODAL_3_PER_IMAGE_CENTS } = await import('./spend-log.ts');
+ const { reserve } = await import('./minions/budget-meter.ts');
const calls = 1 + (queryRefinement ? 1 : 0);
- void recordSpend(ctx.engine, {
+ estimatedSpendCents = VOYAGE_MULTIMODAL_3_PER_IMAGE_CENTS * calls;
+ const budgetUsd = await getDailyImageBudgetUsd(ctx.engine);
+ const reservation = await reserve(ctx.engine, {
clientId,
- tokenName: ctx.auth?.clientName ?? null,
- operation: 'search_by_image',
- spendCents: VOYAGE_MULTIMODAL_3_PER_IMAGE_CENTS * calls,
+ estimatedCents: estimatedSpendCents,
+ capCents: budgetUsd * 100,
provider: 'voyage',
model: 'voyage-multimodal-3',
});
+ spendReservationId = reservation.reservationId;
+ }
+
+ const { searchByImage } = await import('./search/by-image.ts');
+ let results: Awaited<ReturnType<typeof searchByImage>>;
+ try {
+ results = await searchByImage(
+ ctx.engine,
+ { base64: loaded.base64, mime: loaded.contentType },
+ {
+ limit: (p.limit as number) || 20,
+ offset: (p.offset as number) || 0,
+ query: queryRefinement,
+ ...imageSourceScope,
+ },
+ );
+ } catch (providerError) {
+ if (spendReservationId) {
+ const { settle } = await import('./minions/budget-meter.ts');
+ try {
+ await settle(
+ ctx.engine,
+ spendReservationId,
+ estimatedSpendCents,
+ 'search_by_image_error_pessimistic',
+ ctx.auth?.clientName ?? null,
+ );
+ } catch (accountingError) {
+ throw new AggregateError(
+ [providerError, accountingError],
+ 'search_by_image provider call failed and its spend reservation could not be settled',
+ );
+ }
+ }
+ throw providerError;
+ }
+
+ // Settlement and the spend-log mirror commit in one transaction. A
+ // database/accounting failure blocks the response and leaves the pending
+ // reservation holding headroom rather than returning an unmetered success.
+ if (spendReservationId) {
+ const { settle } = await import('./minions/budget-meter.ts');
+ await settle(
+ ctx.engine,
+ spendReservationId,
+ estimatedSpendCents,
+ 'search_by_image',
+ ctx.auth?.clientName ?? null,
+ );
}
return results;
diff --git a/src/core/spend-log.ts b/src/core/spend-log.ts
index 4d72e18772..fe59abc19a 100644
--- a/src/core/spend-log.ts
+++ b/src/core/spend-log.ts
@@ -1,9 +1,10 @@
/**
* v0.36 Phase 2 (D23-#6) — per-OAuth-client paid-API spend tracking.
*
- * Backs the daily-budget gate for `search_by_image`. Each successful Voyage
- * multimodal call records an entry; before any new call, `checkBudget`
- * sums today's spend and rejects when it exceeds the configured cap.
+ * Legacy spend-log readers/writers retained for existing accounting callers.
+ * Paid `search_by_image` requests use the atomic reserve/settle primitive in
+ * `minions/budget-meter.ts`; a read-then-call check cannot enforce a cap under
+ * concurrency.
*
* Config: `search.image_query.daily_budget_usd_per_client` (default $5).
*
@@ -60,6 +61,9 @@ export async function getTodaySpendCents(
/**
* Pre-flight budget gate.
*
+ * @deprecated Non-atomic under concurrent paid calls. New OAuth/MCP spend
+ * callers must use `reserve()` / `settle()` from `gbrain/budget/mcp`.
+ *
* Throws `BudgetExceededError` when the client has already spent at or above
* the configured daily cap. Returns silently when there's room.
*
diff --git a/test/e2e/mcp-budget-reservation-postgres.test.ts b/test/e2e/mcp-budget-reservation-postgres.test.ts
new file mode 100644
index 0000000000..fd8442ee8d
--- /dev/null
+++ b/test/e2e/mcp-budget-reservation-postgres.test.ts
@@ -0,0 +1,75 @@
+/**
+ * Real-Postgres proof for the OAuth/MCP spend reservation critical section.
+ *
+ * PGLite serializes one embedded connection and cannot prove the
+ * pg_advisory_xact_lock behavior. This test deliberately issues competing
+ * native reservation calls through a PostgresEngine pool and verifies that only
+ * cap-fitting reservations commit.
+ *
+ * Run:
+ * DATABASE_URL=postgresql://... bun test test/e2e/mcp-budget-reservation-postgres.test.ts
+ */
+
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUIDv7 } from 'bun';
+import { PostgresEngine } from 'gbrain';
+import { BudgetExceededError, reserve } from '../../src/core/minions/budget-meter.ts';
+
+const databaseUrl = process.env.DATABASE_URL;
+const describePostgres = databaseUrl ? describe : describe.skip;
+
+describePostgres('MCP spend reservation — Postgres concurrency', () => {
+ let engine: PostgresEngine;
+ let clientId = '';
+
+ beforeAll(async () => {
+ engine = new PostgresEngine();
+ await engine.connect({ database_url: databaseUrl!, poolSize: 16 });
+ await engine.initSchema();
+ });
+
+ afterEach(async () => {
+ if (!clientId) return;
+ await engine.executeRaw(
+ `DELETE FROM mcp_spend_reservations WHERE client_id = $1`,
+ [clientId],
+ );
+ await engine.executeRaw(
+ `DELETE FROM mcp_spend_log WHERE client_id = $1`,
+ [clientId],
+ );
+ });
+
+ afterAll(async () => {
+ await engine?.disconnect();
+ });
+
+ test('same-client competitors cannot reserve beyond the daily cap', async () => {
+ clientId = `mcp-budget-e2e-${randomUUIDv7()}`;
+ const attempts = await Promise.allSettled(
+ Array.from({ length: 20 }, () => reserve(engine, {
+ clientId,
+ estimatedCents: 10,
+ capCents: 100,
+ provider: 'test-provider',
+ model: 'test-provider:test-model',
+ })),
+ );
+
+ const fulfilled = attempts.filter(result => result.status === 'fulfilled');
+ const rejected = attempts.filter(result => result.status === 'rejected');
+ expect(fulfilled).toHaveLength(10);
+ expect(rejected).toHaveLength(10);
+ for (const result of rejected) {
+ expect((result as PromiseRejectedResult).reason).toBeInstanceOf(BudgetExceededError);
+ }
+
+ const rows = await engine.executeRaw<{ pending_cents: string }>(
+ `SELECT COALESCE(SUM(estimated_cents), 0)::text AS pending_cents
+ FROM mcp_spend_reservations
+ WHERE client_id = $1 AND status = 'pending'`,
+ [clientId],
+ );
+ expect(Number(rows[0]?.pending_cents)).toBe(100);
+ });
+});
diff --git a/test/minions/budget-meter.test.ts b/test/minions/budget-meter.test.ts
index 9fdc963a6d..121809f65a 100644
--- a/test/minions/budget-meter.test.ts
+++ b/test/minions/budget-meter.test.ts
@@ -103,6 +103,36 @@ describe('minions/budget-meter (v0.38 Slice 2 — D3 reserve-then-settle)', () =
}),
).rejects.toThrow(BudgetExceededError);
});
+
+ it('admits only cap-fitting reservations under concurrent pressure', async () => {
+ const attempts = await Promise.allSettled(
+ Array.from({ length: 10 }, () => reserve(engine, {
+ clientId: 'alice', estimatedCents: 20, capCents: 100,
+ model: 'm', provider: 'p',
+ })),
+ );
+ const fulfilled = attempts.filter(r => r.status === 'fulfilled');
+ const rejected = attempts.filter(r => r.status === 'rejected');
+ expect(fulfilled).toHaveLength(5);
+ expect(rejected).toHaveLength(5);
+ for (const result of rejected) {
+ expect((result as PromiseRejectedResult).reason).toBeInstanceOf(BudgetExceededError);
+ }
+
+ const rows = await engine.executeRaw<Record<string, unknown>>(
+ `SELECT COALESCE(SUM(estimated_cents), 0)::text AS total
+ FROM mcp_spend_reservations
+ WHERE client_id = 'alice' AND status = 'pending'`,
+ );
+ expect(Number(rows[0]?.total)).toBe(100);
+ });
+
+ it('rejects invalid numeric input before opening a transaction', async () => {
+ await expect(reserve(engine, {
+ clientId: 'alice', estimatedCents: Number.NaN, capCents: 100,
+ model: 'm', provider: 'p',
+ })).rejects.toThrow(TypeError);
+ });
});
describe('settle()', () => {
@@ -146,6 +176,84 @@ describe('minions/budget-meter (v0.38 Slice 2 — D3 reserve-then-settle)', () =
);
expect(Number(logCount[0]?.n)).toBe(1);
});
+
+ it('rolls reservation state back when the spend-log insert fails', async () => {
+ const r = await reserve(engine, {
+ clientId: 'alice', estimatedCents: 100, capCents: 500,
+ model: 'm', provider: 'p',
+ });
+
+ const failingEngine = Object.create(engine) as PGLiteEngine;
+ Object.defineProperty(failingEngine, 'transaction', {
+ value: <T>(fn: (tx: PGLiteEngine) => Promise<T>) => engine.transaction(async tx => {
+ const failingTx = Object.create(tx) as PGLiteEngine;
+ Object.defineProperty(failingTx, 'executeRaw', {
+ value: async (query: string, params?: unknown[]) => {
+ if (/INSERT\s+INTO\s+mcp_spend_log/i.test(query)) {
+ throw new Error('injected spend-log write failure');
+ }
+ return tx.executeRaw(query, params);
+ },
+ });
+ return fn(failingTx);
+ }),
+ });
+
+ await expect(settle(failingEngine, r.reservationId, 75))
+ .rejects.toThrow('injected spend-log write failure');
+ const rows = await engine.executeRaw<Record<string, unknown>>(
+ `SELECT status, actual_cents FROM mcp_spend_reservations WHERE reservation_id = $1`,
+ [r.reservationId],
+ );
+ expect(rows[0]?.status).toBe('pending');
+ expect(rows[0]?.actual_cents).toBeNull();
+ });
+
+ it('preserves OAuth token attribution in the committed spend row', async () => {
+ const r = await reserve(engine, {
+ clientId: 'alice', estimatedCents: 100, capCents: 500,
+ model: 'm', provider: 'p',
+ });
+ await settle(engine, r.reservationId, 50, 'search_by_image', 'client-token');
+ const rows = await engine.executeRaw<Record<string, unknown>>(
+ `SELECT token_name FROM mcp_spend_log WHERE client_id = 'alice'`,
+ );
+ expect(rows[0]?.token_name).toBe('client-token');
+ });
+
+ it('records a paid result that arrives after the reservation expired', async () => {
+ const r = await reserve(engine, {
+ clientId: 'alice', estimatedCents: 100, capCents: 500,
+ model: 'm', provider: 'p',
+ });
+ await engine.executeRaw(
+ `UPDATE mcp_spend_reservations
+ SET status = 'expired', actual_cents = 0
+ WHERE reservation_id = $1`,
+ [r.reservationId],
+ );
+
+ await settle(engine, r.reservationId, 75);
+ const rows = await engine.executeRaw<Record<string, unknown>>(
+ `SELECT status, actual_cents::text AS actual
+ FROM mcp_spend_reservations
+ WHERE reservation_id = $1`,
+ [r.reservationId],
+ );
+ expect(rows[0]?.status).toBe('settled');
+ expect(Number(rows[0]?.actual)).toBe(75);
+ const logs = await engine.executeRaw<Record<string, unknown>>(
+ `SELECT COALESCE(SUM(spend_cents), 0)::text AS total
+ FROM mcp_spend_log
+ WHERE client_id = 'alice'`,
+ );
+ expect(Number(logs[0]?.total)).toBe(75);
+ });
+
+ it('fails closed for an unknown reservation id', async () => {
+ await expect(settle(engine, '00000000-0000-0000-0000-000000000099', 1))
+ .rejects.toThrow('spend reservation not found');
+ });
});
describe('sweepExpiredReservations()', () => {
@@ -194,6 +302,14 @@ describe('minions/budget-meter (v0.38 Slice 2 — D3 reserve-then-settle)', () =
it('returns null for unknown client', async () => {
expect(await getClientDailyCapCents(engine, 'nobody')).toBe(null);
});
+ it('fails closed when the accounting read fails', async () => {
+ const unavailable = Object.create(engine) as PGLiteEngine;
+ Object.defineProperty(unavailable, 'executeRaw', {
+ value: async () => { throw new Error('accounting unavailable'); },
+ });
+ await expect(getClientDailyCapCents(unavailable, 'alice'))
+ .rejects.toThrow('accounting unavailable');
+ });
});
describe('committed spend feeds next reserve', () => {
diff --git a/test/search-by-image-op.test.ts b/test/search-by-image-op.test.ts
index b149e3cc28..21df0eecf8 100644
--- a/test/search-by-image-op.test.ts
+++ b/test/search-by-image-op.test.ts
@@ -6,7 +6,8 @@
// - Missing all three of image_path/url/data is rejected
// - Multiple of image_path/url/data is rejected
// - D23-#6 spend cap blocks at budget; allows under budget
-// - Spend log records on successful call
+// - Successful calls settle atomically into the spend log
+// - Ambiguous provider failures settle a pessimistic fixed-price charge
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
import { mkdtempSync, writeFileSync } from 'node:fs';
@@ -135,22 +136,54 @@ describe('search_by_image op — D23-#6 spend cap', () => {
{ image_data: PNG_BYTES.toString('base64') },
).catch((e: any) => e as Error);
expect(err).toBeInstanceOf(Error);
- expect((err as Error).message).toContain('Daily Voyage spend cap reached');
+ expect((err as Error).message).toContain('budget exceeded for client client_a');
});
test('allows remote call when under budget', async () => {
await engine.setConfig('search.image_query.daily_budget_usd_per_client', '5');
// No prior spend recorded.
const results = await op().handler(
- { engine, remote: true, auth: { token: 't', clientId: 'client_b', scopes: ['read'] } } as any,
+ { engine, remote: true, auth: { token: 't', clientId: 'client_b', clientName: 'image-token', scopes: ['read'] } } as any,
{ image_data: PNG_BYTES.toString('base64') },
);
expect(Array.isArray(results)).toBe(true);
- // Verify spend was recorded after the call.
- // (Allow a small tick for the async best-effort recordSpend.)
- await new Promise(r => setTimeout(r, 20));
+ // Settlement completes before the operation returns.
const spent = await getTodaySpendCents(engine, 'client_b');
expect(spent).toBeGreaterThan(0);
+ const rows = await engine.executeRaw<Record<string, unknown>>(
+ `SELECT r.status, l.token_name
+ FROM mcp_spend_reservations r
+ JOIN mcp_spend_log l ON l.client_id = r.client_id
+ WHERE r.client_id = 'client_b'`,
+ );
+ expect(rows).toHaveLength(1);
+ expect(rows[0]?.status).toBe('settled');
+ expect(rows[0]?.token_name).toBe('image-token');
+ });
+
+ test('settles pessimistic spend when provider outcome is ambiguous', async () => {
+ await engine.setConfig('search.image_query.daily_budget_usd_per_client', '5');
+ fetchHandler = async () => { throw new Error('provider connection lost'); };
+
+ const err = await op().handler(
+ { engine, remote: true, auth: { token: 't', clientId: 'client_c', scopes: ['read'] } } as any,
+ { image_data: PNG_BYTES.toString('base64') },
+ ).catch((e: any) => e as Error);
+ expect(err).toBeInstanceOf(Error);
+
+ const reservations = await engine.executeRaw<Record<string, unknown>>(
+ `SELECT status, estimated_cents::text AS estimated
+ FROM mcp_spend_reservations
+ WHERE client_id = 'client_c'`,
+ );
+ expect(reservations).toHaveLength(1);
+ expect(reservations[0]?.status).toBe('settled');
+ expect(Number(reservations[0]?.estimated)).toBeGreaterThan(0);
+ expect(await getTodaySpendCents(engine, 'client_c')).toBeGreaterThan(0);
+ const logs = await engine.executeRaw<Record<string, unknown>>(
+ `SELECT operation FROM mcp_spend_log WHERE client_id = 'client_c'`,
+ );
+ expect(logs[0]?.operation).toBe('search_by_image_error_pessimistic');
});
test('local CLI calls bypass budget gate (ctx.remote=false, no clientId)', async () => {