Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(budget): eng I6 settle reservations by id, release attempts that never billed

time-attack3098b419a540
diff --git a/src/core/ai/decide/index.ts b/src/core/ai/decide/index.ts
index 9231a45af3..0cfdcc3ff4 100644
--- a/src/core/ai/decide/index.ts
+++ b/src/core/ai/decide/index.ts
@@ -156,7 +156,7 @@ async function runTypesafe(req: DecideRequest, ctx: DecideContext, cfg: DecideCo
if (req.remote && spent.remote + estimate > cfg.dailyUsd * cfg.remoteShare) throw new DecideError('budget_exhausted', 'decide: remote share of the daily budget exhausted');
}
const tracker = getCurrentBudgetTracker();
- tracker?.reserve({ modelId: a.provider, estimatedInputTokens: estimatedTokens, maxOutputTokens: 0, kind: budgetKind, label: 'gateway.decide' });
+ const reservation = tracker?.reserve({ modelId: a.provider, estimatedInputTokens: estimatedTokens, maxOutputTokens: 0, kind: budgetKind, label: 'gateway.decide' });
const { signal, done } = deadlineSignal(a.deadlineAt, a.now, req.signal);
const transport = decideTransport();
@@ -213,7 +213,7 @@ async function runTypesafe(req: DecideRequest, ctx: DecideContext, cfg: DecideCo
throw asDecideError(err, signal, req.signal);
} finally {
done();
- recordOnTracker(tracker, { modelId: a.provider, inputTokens, outputTokens: 0, kind: budgetKind, label: 'gateway.decide' });
+ recordOnTracker(tracker, { modelId: a.provider, reservation, inputTokens, outputTokens: 0, kind: budgetKind, label: 'gateway.decide' });
}
if (models.size > 1) throw new DecideError('mixed_model', `decide: batches answered by ${models.size} different models`);
const modelResolved = [...models][0] ?? modelId;
diff --git a/src/core/ai/decide/rerank-adapter.ts b/src/core/ai/decide/rerank-adapter.ts
index fca9e611b2..125d88f9cd 100644
--- a/src/core/ai/decide/rerank-adapter.ts
+++ b/src/core/ai/decide/rerank-adapter.ts
@@ -61,7 +61,7 @@ export async function rerankViaDecide(input: RerankInput, deps: RerankViaDecideD
if (bodies.some((body) => Buffer.byteLength(body, 'utf8') > deps.maxPayloadBytes)) {
throw new RerankError('TypeSafe rerank: request exceeds payload byte cap', 'payload_too_large');
}
- deps.tracker?.reserve({
+ const reservation = deps.tracker?.reserve({
modelId: deps.model, estimatedInputTokens: plan.reduce((n, b) => n + b.estimatedInputTokens, 0),
maxOutputTokens: 0, kind: 'rerank', label: 'gateway.rerank',
});
@@ -124,7 +124,7 @@ export async function rerankViaDecide(input: RerankInput, deps: RerankViaDecideD
} finally {
clearTimeout(timer);
input.signal?.removeEventListener('abort', callerAbort);
- recordOnTracker(deps.tracker, { modelId: deps.model, inputTokens, outputTokens: 0, kind: 'rerank', label: 'gateway.rerank', failed });
+ recordOnTracker(deps.tracker, { modelId: deps.model, reservation, inputTokens, outputTokens: 0, kind: 'rerank', label: 'gateway.rerank', failed });
}
// Equal scores keep the incoming fused rank. No threshold drops evidence.
results.sort((a, b) => b.relevanceScore - a.relevanceScore || a.index - b.index);
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index 279db7360f..cf548a4113 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -34,7 +34,7 @@ import { z } from 'zod';
import { DEFAULT_CHARS_PER_TOKEN, DEFAULT_SAFETY_FACTOR, embedRequestMaxInputTokens, planEmbedRequests, rerankRequestMaxInputTokens, truncateEmbedInputs } from './embed-batch-plan.ts';
export { splitByTokenBudget, capBatchItems, NO_BATCH_CAP_SUB_BATCH_ITEMS } from './embed-batch-plan.ts';
-import { BudgetTracker, type BudgetKind } from '../budget/budget-tracker.ts';
+import { BudgetTracker, type BudgetKind, type BudgetReservation } from '../budget/budget-tracker.ts';
import { failedCallUsage, recordOnTracker } from './budget-record.ts';
import { chatWithFallback, normalizeChatFallbackChain } from './chat-fallback.ts';
import type {
@@ -1557,21 +1557,6 @@ export async function embed(texts: string[], opts?: EmbedOpts): Promise<Float32A
const { model, recipe, modelId } = await resolveEmbeddingProvider(resolveTarget);
const truncated = truncateEmbedInputs(texts);
- // Reserve up front for the worst-case batch token count. Embeddings have
- // no output rate, so maxOutputTokens=0. record() at the end uses the
- // actual total reported by the SDK across all sub-batches.
- if (tracker) {
- const charsPerToken = recipe.touchpoints?.embedding?.chars_per_token ?? DEFAULT_CHARS_PER_TOKEN;
- const totalChars = truncated.reduce((s, t) => s + t.length, 0);
- const estimatedInputTokens = Math.ceil(totalChars / Math.max(charsPerToken, 1));
- tracker.reserve({
- modelId: `${recipe.id}:${modelId}`,
- estimatedInputTokens,
- maxOutputTokens: 0,
- kind: 'embed',
- label: 'gateway.embed',
- });
- }
// Dim override (D10) — when caller passes `dimensions`, use it. Otherwise
// fall back to the global cfg default. dimsProviderOptions throws a
// clear AIConfigError when a Voyage flexible-dim model gets an
@@ -1594,6 +1579,20 @@ export async function embed(texts: string[], opts?: EmbedOpts): Promise<Float32A
const sent = sendableEmbeddingInputs(truncated);
const batches = sent.length ? planEmbedRequests(sent.map(i => truncated[i]!), recipe, effectiveSafetyFactor(recipe), envCap) : [];
+ // Reserve for the worst-case batch token count after every preflight that
+ // can throw (dims, batch planning), so a config error leaves no hold.
+ // Embeddings have no output rate, so maxOutputTokens=0. record() at the end
+ // uses the actual total reported by the SDK and settles this reservation.
+ const charsPerToken = recipe.touchpoints?.embedding?.chars_per_token ?? DEFAULT_CHARS_PER_TOKEN;
+ const totalChars = truncated.reduce((s, t) => s + t.length, 0);
+ const reservation = tracker?.reserve({
+ modelId: `${recipe.id}:${modelId}`,
+ estimatedInputTokens: Math.ceil(totalChars / Math.max(charsPerToken, 1)),
+ maxOutputTokens: 0,
+ kind: 'embed',
+ label: 'gateway.embed',
+ });
+
const allEmbeddings: Float32Array[] = [];
let _embedThrew = false;
// Provider-reported input tokens summed across sub-batches; null as soon as
@@ -1622,10 +1621,9 @@ export async function embed(texts: string[], opts?: EmbedOpts): Promise<Float32A
const measured = !_embedThrew && reportedTokens !== null && reportedTokens > 0
? reportedTokens
: null;
- const charsPerToken = recipe.touchpoints?.embedding?.chars_per_token ?? DEFAULT_CHARS_PER_TOKEN;
- const totalChars = truncated.reduce((s, t) => s + t.length, 0);
recordOnTracker(tracker, {
modelId: `${recipe.id}:${modelId}`,
+ reservation,
requestedModelId: resolveTarget,
inputTokens: measured ?? Math.ceil(totalChars / Math.max(charsPerToken, 1)),
outputTokens: 0,
@@ -3451,21 +3449,42 @@ export async function chat(opts: ChatOpts): Promise<ChatResult> {
}
const estimatedInputTokens = estimateChatInputTokens(opts);
const maxOutputTokens = opts.maxTokens ?? defaultMaxOutputTokens(modelStrEarly);
- const chatRecord = { requestedModelId: modelStrEarly, purpose: opts.purpose, label: 'gateway.chat' };
// TX5: reserve BEFORE the provider call. Throws BudgetExhausted on cost,
// runtime, or no_pricing (when cap is set). Pre-resolution model id is
// fine here — resolveChatProvider would map aliases the same way for the
- // cost lookup. record() below uses the real result.model.
- if (tracker) {
- tracker.reserve({
- modelId: modelStrEarly,
+ // cost lookup. record() uses the real result.model and settles this
+ // reservation by id; the finally frees it when the attempt never billed
+ // (provider resolution failed, an invocation policy refused it).
+ const reservation = tracker?.reserve({
+ modelId: modelStrEarly,
+ estimatedInputTokens,
+ maxOutputTokens,
+ kind: 'chat' as BudgetKind,
+ label: 'gateway.chat',
+ });
+ try {
+ return await chatAdmitted(opts, {
+ tracker,
+ modelStrEarly,
estimatedInputTokens,
maxOutputTokens,
- kind: 'chat' as BudgetKind,
- label: 'gateway.chat',
+ chatRecord: { requestedModelId: modelStrEarly, purpose: opts.purpose, label: 'gateway.chat', reservation },
});
+ } finally {
+ tracker?.release(reservation);
}
+}
+
+/** One admitted chat attempt: the provider call plus its budget record. */
+async function chatAdmitted(opts: ChatOpts, admitted: {
+ tracker: BudgetTracker | null;
+ modelStrEarly: string;
+ estimatedInputTokens: number;
+ maxOutputTokens: number;
+ chatRecord: { requestedModelId: string; purpose?: string; label: string; reservation?: BudgetReservation };
+}): Promise<ChatResult> {
+ const { tracker, modelStrEarly, estimatedInputTokens, maxOutputTokens, chatRecord } = admitted;
// Test seam: when a test transport is installed, route through it without
// touching provider resolution, AI SDK, or any network. See
@@ -3493,9 +3512,13 @@ export async function chat(opts: ChatOpts): Promise<ChatResult> {
threw = err;
throw err;
} finally {
- recordOnTracker(tracker, res
- ? { ...chatRecord, modelId: res.model ?? modelStrEarly, inputTokens: res.usage.input_tokens, outputTokens: res.usage.output_tokens }
- : { ...chatRecord, modelId: modelStrEarly, ...failedCallUsage(threw, { inputTokens: estimatedInputTokens, outputTokens: maxOutputTokens }) });
+ // A policy refusal never reached the provider: nothing to charge, and
+ // chat()'s finally releases the reservation.
+ if (res || threw) {
+ recordOnTracker(tracker, res
+ ? { ...chatRecord, modelId: res.model ?? modelStrEarly, inputTokens: res.usage.input_tokens, outputTokens: res.usage.output_tokens }
+ : { ...chatRecord, modelId: modelStrEarly, ...failedCallUsage(threw, { inputTokens: estimatedInputTokens, outputTokens: maxOutputTokens }) });
+ }
}
}
@@ -4283,19 +4306,19 @@ export async function rerank(input: RerankInput): Promise<RerankResult[]> {
// leaking one projection per search on a keyless brain under a cost cap.
// Reranker pricing resolves through the embedding pricing table (the default
// model is priced); an unpriced custom reranker still hits the warn-once
- // (no cap) / TX2 hard-fail (cap set) path. record() below settles it.
- if (tracker) {
- const totalChars = input.query.length + input.documents.reduce((s, d) => s + d.length, 0);
- tracker.reserve({
- modelId: modelStr,
- // Honor the recipe's tokenizer density (Voyage declares ~1 char/token on
- // dense payloads) so a cap cannot be under-reserved ~4× by CJK/JSON docs.
- estimatedInputTokens: Math.ceil(totalChars / (recipe.touchpoints.embedding?.chars_per_token ?? 4)),
- maxOutputTokens: 0,
- kind: 'rerank',
- label: 'gateway.rerank',
- });
- }
+ // (no cap) / TX2 hard-fail (cap set) path. record() below settles it by
+ // id; a policy refusal releases it in the finally.
+ const reservation = tracker?.reserve({
+ modelId: modelStr,
+ // Honor the recipe's tokenizer density (Voyage declares ~1 char/token on
+ // dense payloads) so a cap cannot be under-reserved ~4× by CJK/JSON docs.
+ estimatedInputTokens: Math.ceil(
+ (input.query.length + input.documents.reduce((s, d) => s + d.length, 0)) / (recipe.touchpoints.embedding?.chars_per_token ?? 4),
+ ),
+ maxOutputTokens: 0,
+ kind: 'rerank',
+ label: 'gateway.rerank',
+ });
// Timeout via AbortController; merges with caller-supplied signal.
const ctrl = new AbortController();
@@ -4313,6 +4336,7 @@ export async function rerank(input: RerankInput): Promise<RerankResult[]> {
const totalChars = input.query.length + input.documents.reduce((s, d) => s + d.length, 0);
recordOnTracker(tracker, {
modelId: modelStr,
+ reservation,
inputTokens: Math.ceil(totalChars / 4),
outputTokens: 0,
kind: 'rerank',
@@ -4381,6 +4405,7 @@ export async function rerank(input: RerankInput): Promise<RerankResult[]> {
throw new RerankError(`rerank: ${msg}`, 'network');
} finally {
clearTimeout(t);
+ tracker?.release(reservation);
}
}
diff --git a/src/core/budget/budget-tracker.ts b/src/core/budget/budget-tracker.ts
index 6d13164142..2756b4da37 100644
--- a/src/core/budget/budget-tracker.ts
+++ b/src/core/budget/budget-tracker.ts
@@ -67,8 +67,18 @@ export interface BudgetEstimate {
label?: string;
}
+/**
+ * Opaque handle for one admitted reservation. `reserve()` returns it when it
+ * holds a projection against the cap; the caller hands it back to `record()`
+ * (settles it with the real usage) or `release()` (frees it when the call
+ * never reached the provider). Settlement is by identity, never by model.
+ */
+export type BudgetReservation = string & { readonly __budgetReservation: unique symbol };
+
export interface BudgetActualUsage {
modelId: string;
+ /** The reservation this usage settles, as returned by `reserve()`. */
+ reservation?: BudgetReservation;
inputTokens: number;
outputTokens?: number;
/** For embeddings: dimension count, surfaces in audit only. */
@@ -255,8 +265,9 @@ export class BudgetTracker {
* (N-1)×per-call cost. Admission checks cumulative + outstanding instead.
*/
private outstandingUsd = 0;
- /** FIFO of unsettled projections keyed `${modelId}|${kind}` (gateway pairs reserve→record 1:1). */
- private readonly outstandingByKey = new Map<string, number[]>();
+ /** Unsettled projections by reservation id (eng I6: settle by identity, not FIFO-by-model). */
+ private readonly outstanding = new Map<BudgetReservation, number>();
+ private nextReservation = 0;
private callsRecorded = 0;
private readonly ledger = new ModelLedger();
private readonly startedAt: number;
@@ -310,8 +321,12 @@ export class BudgetTracker {
*
* When maxCostUsd is unset, missing pricing warns-once but does not throw
* (legacy behavior preserved for non-priced providers).
+ *
+ * Returns the reservation id when the projection is held against the cap
+ * (a cap is set and the model is priced); undefined when nothing is held.
+ * The caller settles it with `record({ reservation })` or `release()`.
*/
- reserve(estimate: BudgetEstimate): void {
+ reserve(estimate: BudgetEstimate): BudgetReservation | undefined {
this.assertRuntime(estimate.modelId);
const projected = reservationCostUsd(
@@ -380,7 +395,7 @@ export class BudgetTracker {
estimated_input_tokens: estimate.estimatedInputTokens,
max_output_tokens: estimate.maxOutputTokens,
});
- return;
+ return undefined;
}
if (this.opts.maxCostUsd !== undefined) {
@@ -405,12 +420,16 @@ export class BudgetTracker {
this.opts.maxCostUsd, estimate.modelId,
);
}
- // Admission passed — hold the projection until record() settles it so
- // parallel reserve() calls can't all admit against the same cumulative.
- const key = `${estimate.modelId}|${estimate.kind}`;
- const queue = this.outstandingByKey.get(key) ?? [];
- queue.push(projected);
- this.outstandingByKey.set(key, queue);
+ }
+ // Admission passed — hold the projection until record() or release()
+ // settles this id, so parallel reserve() calls can't all admit against the
+ // same cumulative, and a small call settling first can't free a large
+ // in-flight call's hold.
+ const reservation = this.opts.maxCostUsd !== undefined
+ ? `r${++this.nextReservation}` as BudgetReservation
+ : undefined;
+ if (reservation) {
+ this.outstanding.set(reservation, projected);
this.outstandingUsd += projected;
}
@@ -422,10 +441,30 @@ export class BudgetTracker {
kind: estimate.kind,
model: estimate.modelId,
sub_label: estimate.label,
+ reservation: reservation ?? null,
projected_cost_usd: projected,
cumulative_cost_usd: this.cumulativeUsd,
max_cost_usd: this.opts.maxCostUsd ?? null,
});
+ return reservation;
+ }
+
+ /**
+ * Free a reservation whose call never reached the provider (provider
+ * resolution failed, an invocation policy refused it, a preflight threw).
+ * A no-op for an id `record()` already settled, or for undefined, so a
+ * caller can release unconditionally in a `finally`.
+ */
+ release(reservation: BudgetReservation | undefined): void {
+ if (!reservation || !this.settleReservation(reservation)) return;
+ appendAuditLine(this.auditPath, {
+ schema_version: 1,
+ ts: new Date().toISOString(),
+ event: 'release',
+ label: this.opts.label,
+ reservation,
+ outstanding_usd: this.outstandingUsd,
+ });
}
/**
@@ -464,9 +503,12 @@ export class BudgetTracker {
});
if (cost === null) {
- // Unpriced model: record audit but skip cumulative math. Cap (if set)
+ // Unpriced model: record audit but skip cumulative math. A user cap
// already rejected this call at reserve(); a record() here means the
- // unpriced warn-once path let it through (cap unset).
+ // unpriced warn-once path let it through (cap unset or default/derived).
+ // A served model can be unpriced while the requested one held a
+ // projection (fallback hop): settle it anyway.
+ if (actual.reservation) this.settleReservation(actual.reservation);
appendAuditLine(this.auditPath, {
schema_version: 1,
ts: new Date().toISOString(),
@@ -482,7 +524,7 @@ export class BudgetTracker {
return;
}
- this.settleReservation(actual.modelId, kind);
+ if (actual.reservation) this.settleReservation(actual.reservation);
this.cumulativeUsd += cost;
appendAuditLine(this.auditPath, {
schema_version: 1,
@@ -491,6 +533,8 @@ export class BudgetTracker {
label: this.opts.label,
kind,
model: actual.modelId,
+ requested_model: actual.requestedModelId ?? null,
+ reservation: actual.reservation ?? null,
sub_label: actual.label,
input_tokens: actual.inputTokens,
output_tokens: actual.outputTokens ?? 0,
@@ -522,31 +566,19 @@ export class BudgetTracker {
}
/**
- * Release the oldest unsettled reservation for this call's model+kind.
- * Exact key first; on miss, the oldest same-kind entry — gateway.chat
- * reserves with the pre-resolution model string (alias/bare/slash form)
- * but records `${recipe.id}:${modelId}`, and a missed pop would leak
- * phantom outstanding budget for the tracker's lifetime. Records with no
- * reservation at all (expand/OCR spend sites) pop nothing.
+ * Drop one reservation's hold. Settlement is by id: the gateway reserves
+ * with the pre-resolution model string and records the served id, and two
+ * same-model calls of different sizes settle in any order, so a model key
+ * cannot say which hold a record belongs to. Records with no reservation
+ * (expand/OCR spend sites) settle nothing. Returns false for an id that was
+ * already settled.
*/
- private settleReservation(modelId: string, kind: BudgetKind): void {
- let key = `${modelId}|${kind}`;
- let queue = this.outstandingByKey.get(key);
- if (!queue || queue.length === 0) {
- const suffix = `|${kind}`;
- queue = undefined;
- for (const [k, q] of this.outstandingByKey) {
- if (k.endsWith(suffix) && q.length > 0) {
- key = k;
- queue = q;
- break;
- }
- }
- }
- if (!queue || queue.length === 0) return;
- const amount = queue.shift()!;
- if (queue.length === 0) this.outstandingByKey.delete(key);
+ private settleReservation(reservation: BudgetReservation): boolean {
+ const amount = this.outstanding.get(reservation);
+ if (amount === undefined) return false;
+ this.outstanding.delete(reservation);
this.outstandingUsd = Math.max(0, this.outstandingUsd - amount);
+ return true;
}
/** Internal helper: throw BudgetExhausted(reason:'runtime') when the wall-clock cap fires. */
diff --git a/src/core/embed-facts.ts b/src/core/embed-facts.ts
index bba934f42a..227d300b43 100644
--- a/src/core/embed-facts.ts
+++ b/src/core/embed-facts.ts
@@ -144,10 +144,10 @@ export async function embedStaleFacts(engine: BrainEngine, opts: EmbedFactsOpts,
if (await engine.getConfig('embedding_model') !== dbModel || await engine.getConfig('embedding_dimensions') !== dbDims) {
throw new Error('Embedding model changed during fact backfill; rerun the scoped preview');
}
- tracker.reserve({ modelId: call.model, kind: 'embed', estimatedInputTokens: inputCeiling, maxOutputTokens: 0 });
+ const reservation = tracker.reserve({ modelId: call.model, kind: 'embed', estimatedInputTokens: inputCeiling, maxOutputTokens: 0 });
return { settle: async usage => {
if (!usage) result.cost_estimated = true;
- tracker.record({ modelId: call.model, kind: 'embed', inputTokens: usage?.inputTokens ?? inputCeiling, outputTokens: 0 });
+ tracker.record({ modelId: call.model, reservation, kind: 'embed', inputTokens: usage?.inputTokens ?? inputCeiling, outputTokens: 0 });
} };
}, () => embed(batch.map(row => row.fact), {
abortSignal: signal, embeddingModel: model, dimensions: dims, inputType: 'document',
diff --git a/test/core/budget/budget-tracker.test.ts b/test/core/budget/budget-tracker.test.ts
index 3de97509a2..4a4842d828 100644
--- a/test/core/budget/budget-tracker.test.ts
+++ b/test/core/budget/budget-tracker.test.ts
@@ -551,22 +551,23 @@ describe('BudgetTracker outstanding reservations (#4365)', () => {
test('record() settles the reservation: reserve→record→reserve at the same margin succeeds', () => {
const t = new BudgetTracker({ maxCostUsd: 1.0, label: 'test', auditPath });
t.record({ modelId: 'claude-haiku-4-5-20251001', inputTokens: 900_000, outputTokens: 0, kind: 'chat' });
- t.reserve(estimate);
- // Actual usage far under the projection: cumulative $0.901.
- t.record({ modelId: 'claude-haiku-4-5-20251001', inputTokens: 1000, outputTokens: 0, kind: 'chat' });
+ const reservation = t.reserve(estimate);
+ // Actual usage far under the projection: cumulative $0.901. The record
+ // settles the reservation it names (eng I6: by id, not FIFO-by-model).
+ t.record({ modelId: 'claude-haiku-4-5-20251001', inputTokens: 1000, outputTokens: 0, kind: 'chat', reservation });
// Outstanding released — the same $0.06 projection fits again
// ($0.901 + $0.06 = $0.961 ≤ $1.00).
expect(() => t.reserve(estimate)).not.toThrow();
});
- test('record() under the post-resolution model id still settles (same-kind fallback)', () => {
+ test('record() under the post-resolution model id still settles (by reservation id)', () => {
// gateway.chat reserves with the pre-resolution string (alias/bare/slash
- // form) but records `${recipe.id}:${modelId}` — a missed pop would leak
- // phantom outstanding budget forever.
+ // form) but records `${recipe.id}:${modelId}` — a missed settle would leak
+ // phantom outstanding budget forever. The id makes the model string moot.
const t = new BudgetTracker({ maxCostUsd: 1.0, label: 'test', auditPath });
t.record({ modelId: 'claude-haiku-4-5-20251001', inputTokens: 900_000, outputTokens: 0, kind: 'chat' });
- t.reserve({ ...estimate, modelId: 'anthropic/claude-haiku-4-5-20251001' });
- t.record({ modelId: 'anthropic:claude-haiku-4-5-20251001', inputTokens: 1000, outputTokens: 0, kind: 'chat' });
+ const reservation = t.reserve({ ...estimate, modelId: 'anthropic/claude-haiku-4-5-20251001' });
+ t.record({ modelId: 'anthropic:claude-haiku-4-5-20251001', inputTokens: 1000, outputTokens: 0, kind: 'chat', reservation });
expect(() => t.reserve(estimate)).not.toThrow();
});
diff --git a/test/core/budget/reservation-identity.test.ts b/test/core/budget/reservation-identity.test.ts
new file mode 100644
index 0000000000..37770d0d32
--- /dev/null
+++ b/test/core/budget/reservation-identity.test.ts
@@ -0,0 +1,152 @@
+/**
+ * Eng I6: reservation identity. `reserve()` returns an opaque id and the call
+ * that made it settles it, by id, through `record()` or `release()`.
+ *
+ * Pre-fix, settlement popped the OLDEST outstanding projection for the
+ * recorded model (FIFO by model, falling back to any same-kind entry). Two
+ * concurrent same-model calls of different sizes therefore freed the large
+ * call's hold when the small one finished first, and a third large call was
+ * admitted past the cap while the first was still in flight. An attempt that
+ * never reached the provider (provider resolution failed, an invocation
+ * policy refused it) was never settled at all, leaking its hold for the
+ * tracker's lifetime, or (policy refusal on the test lane) was charged the
+ * pessimistic failure usage.
+ *
+ * Hermetic: tmp audit path; the gateway runs through __setChatTransportForTests.
+ */
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { BudgetExhausted, BudgetTracker, _resetBudgetTrackerWarningsForTest } from '../../../src/core/budget/budget-tracker.ts';
+import { chat, withBudgetTracker, __setChatTransportForTests, type ChatOpts, type ChatResult } from '../../../src/core/ai/gateway.ts';
+import { withAIInvocationGuard } from '../../../src/core/ai/invocation-guard.ts';
+
+const MODEL = 'anthropic:claude-haiku-4-5-20251001'; // $1 in / $5 out per 1M
+const LARGE = 100_000; // $0.50 of output ceiling
+const SMALL = 1_000; // $0.005
+
+let tmp: string;
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), 'gbrain-reservation-'));
+ _resetBudgetTrackerWarningsForTest();
+});
+afterEach(() => {
+ __setChatTransportForTests(null);
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+const tracker = (cap = 1) => new BudgetTracker({ label: 'test.reservation', auditPath: join(tmp, 'a.jsonl'), maxCostUsd: cap });
+const est = (maxOutputTokens: number, modelId = MODEL) => ({ modelId, kind: 'chat' as const, estimatedInputTokens: 0, maxOutputTokens });
+
+function result(model: string, output: number): ChatResult {
+ return {
+ text: 'ok',
+ blocks: [{ type: 'text', text: 'ok' }],
+ stopReason: 'end',
+ model,
+ providerId: 'anthropic',
+ usage: { input_tokens: 0, output_tokens: output, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ };
+}
+
+describe('BudgetTracker settles reservations by id', () => {
+ test('a small call settling first keeps the large in-flight hold; a third large call is refused', () => {
+ const t = tracker();
+ const large = t.reserve(est(LARGE));
+ const small = t.reserve(est(SMALL));
+ expect(large).toBeDefined();
+ expect(small).toBeDefined();
+ t.record({ modelId: MODEL, kind: 'chat', inputTokens: 0, outputTokens: 100, reservation: small });
+ expect(() => t.reserve(est(LARGE))).toThrow(BudgetExhausted);
+ t.record({ modelId: MODEL, kind: 'chat', inputTokens: 0, outputTokens: 100, reservation: large });
+ expect(() => t.reserve(est(LARGE))).not.toThrow();
+ });
+
+ test('an alias reservation is settled by the served id record', () => {
+ const t = tracker();
+ const r = t.reserve(est(LARGE * 1.8, 'claude-cli:haiku'));
+ expect(r).toBeDefined();
+ t.record({ modelId: 'claude-cli:claude-haiku-4-5-20251001', kind: 'chat', inputTokens: 0, outputTokens: 0, reservation: r });
+ expect(() => t.reserve(est(LARGE * 1.8))).not.toThrow();
+ });
+
+ test('release frees an unbilled hold once; a settled or undefined id is a no-op', () => {
+ const t = tracker();
+ const r = t.reserve(est(LARGE * 1.8));
+ t.release(r);
+ t.release(r);
+ t.release(undefined);
+ const r2 = t.reserve(est(LARGE * 1.8));
+ t.record({ modelId: MODEL, kind: 'chat', inputTokens: 0, outputTokens: 0, reservation: r2 });
+ t.release(r2);
+ expect(() => t.reserve(est(LARGE * 1.8))).not.toThrow();
+ });
+
+ test('a record without a reservation (expand/OCR sites) settles no one else\'s hold', () => {
+ const t = tracker();
+ t.reserve(est(LARGE));
+ t.record({ modelId: MODEL, kind: 'chat', inputTokens: 0, outputTokens: 0 });
+ expect(() => t.reserve(est(LARGE * 1.2))).toThrow(BudgetExhausted);
+ });
+
+ test('uncapped and unpriced reservations hold nothing and return no id', () => {
+ expect(new BudgetTracker({ label: 'x', auditPath: join(tmp, 'b.jsonl') }).reserve(est(LARGE))).toBeUndefined();
+ expect(new BudgetTracker({ label: 'x', auditPath: join(tmp, 'b.jsonl'), maxCostUsd: 1, capSource: 'default' })
+ .reserve(est(LARGE, 'mystery:unpriced'))).toBeUndefined();
+ });
+});
+
+describe('gateway.chat settles every admitted attempt', () => {
+ test('concurrent large + small same-model calls: small finishes first, a third large call is refused', async () => {
+ const t = tracker();
+ const gates: Record<string, () => void> = {};
+ __setChatTransportForTests(async (opts: ChatOpts) => {
+ const key = String(opts.maxTokens);
+ if (!gates[key]) await new Promise<void>((resolve) => { gates[key] = resolve; });
+ return result(MODEL, 100);
+ });
+ await withBudgetTracker(t, async () => {
+ const large = chat({ model: MODEL, maxTokens: LARGE, messages: [{ role: 'user', content: 'a' }] });
+ const small = chat({ model: MODEL, maxTokens: SMALL, messages: [{ role: 'user', content: 'b' }] });
+ while (!gates[String(LARGE)] || !gates[String(SMALL)]) await new Promise((r) => setTimeout(r, 1));
+ gates[String(SMALL)]!();
+ await small;
+ await expect(chat({ model: MODEL, maxTokens: LARGE, messages: [{ role: 'user', content: 'c' }] })).rejects.toBeInstanceOf(BudgetExhausted);
+ gates[String(LARGE)]!();
+ await large;
+ });
+ });
+
+ test('an invocation policy refusal is released, not charged', async () => {
+ const t = tracker();
+ __setChatTransportForTests(async () => result(MODEL, 100));
+ await withBudgetTracker(t, async () => {
+ await expect(withAIInvocationGuard(async () => { throw new Error('policy refused'); }, () =>
+ chat({ model: MODEL, maxTokens: LARGE * 1.8, messages: [{ role: 'user', content: 'a' }] }))).rejects.toThrow('policy refused');
+ });
+ expect(t.totalSpent).toBe(0);
+ expect(() => t.reserve(est(LARGE * 1.8))).not.toThrow();
+ });
+
+ test('a provider-resolution failure releases the hold', async () => {
+ const t = new BudgetTracker({
+ label: 'test.reservation', auditPath: join(tmp, 'a.jsonl'), maxCostUsd: 1,
+ pricingOverrides: { 'no-such-provider:model': { input: 0, output: 5 } },
+ });
+ await withBudgetTracker(t, async () => {
+ await expect(chat({ model: 'no-such-provider:model', maxTokens: LARGE * 1.8, messages: [{ role: 'user', content: 'a' }] })).rejects.toThrow();
+ });
+ expect(() => t.reserve(est(LARGE * 1.8))).not.toThrow();
+ });
+
+ test('an aborted provider call is charged its failure usage and settles its own hold', async () => {
+ const t = tracker();
+ __setChatTransportForTests(async () => { throw Object.assign(new Error('aborted'), { name: 'AbortError', usage: { input_tokens: 0, output_tokens: 10 } }); });
+ await withBudgetTracker(t, async () => {
+ await expect(chat({ model: MODEL, maxTokens: LARGE * 1.8, messages: [{ role: 'user', content: 'a' }] })).rejects.toThrow('aborted');
+ });
+ expect(t.totalSpent).toBeCloseTo(10 * 5 / 1_000_000, 12);
+ expect(() => t.reserve(est(LARGE * 1.8))).not.toThrow();
+ });
+});