async-bulkhead-llm 3.1.1 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +76 -5
- package/dist/cjs/index.cjs +305 -58
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/esm/index.js +304 -57
- package/dist/esm/index.js.map +1 -1
- package/dist/types/index.d.ts +115 -5
- package/dist/types/index.d.ts.map +1 -1
- package/package.json +10 -4
package/README.md
CHANGED
|
@@ -122,6 +122,71 @@ const result = await bulkhead.run(request, async () => {
|
|
|
122
122
|
|
|
123
123
|
---
|
|
124
124
|
|
|
125
|
+
## What's New in v3.2 — Gateway readiness
|
|
126
|
+
|
|
127
|
+
v3.2 adds the admission-control primitives an AI gateway needs, all additive:
|
|
128
|
+
|
|
129
|
+
### Streaming budget enforcement (`reportUsage`)
|
|
130
|
+
|
|
131
|
+
Report *cumulative* usage as stream events arrive. Input over-estimates are
|
|
132
|
+
refunded to the budget immediately; output overruns expand the hold (blocking
|
|
133
|
+
new admissions until the runaway stream releases). The returned snapshot lets
|
|
134
|
+
a gateway decide to abort a stream:
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
await bulkhead.run(request, async (signal, ctx) => {
|
|
138
|
+
for await (const event of providerStream(request, signal)) {
|
|
139
|
+
const snap = ctx!.reportUsage({
|
|
140
|
+
input: event.usage.input_tokens,
|
|
141
|
+
output: event.usage.output_tokens, // cumulative
|
|
142
|
+
});
|
|
143
|
+
if (snap.outputRemaining === 0) {
|
|
144
|
+
// stream has consumed its entire output reservation — abort policy here
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return final;
|
|
148
|
+
});
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
If `release()` is called without usage, the last reported usage drives the
|
|
152
|
+
final refund. Reports are clamped monotonically non-decreasing per field.
|
|
153
|
+
|
|
154
|
+
### Priority admission (`highPriorityReserve`)
|
|
155
|
+
|
|
156
|
+
Reserve budget headroom that only `priority: "high"` requests may use, so
|
|
157
|
+
interactive traffic keeps admitting when batch traffic saturates the pool:
|
|
158
|
+
|
|
159
|
+
```ts
|
|
160
|
+
const bulkhead = createLLMBulkhead({
|
|
161
|
+
model: "claude-sonnet-4",
|
|
162
|
+
maxConcurrent: 50,
|
|
163
|
+
tokenBudget: { budget: 200_000, highPriorityReserve: 40_000 },
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
await bulkhead.run(request, callLLM, { priority: "high" });
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
### Rejection detail
|
|
170
|
+
|
|
171
|
+
Failed acquisitions, `reject` events, and `LLMBulkheadRejectedError` now carry
|
|
172
|
+
a capacity snapshot (`detail`) — slots, queue, and priority-adjusted budget
|
|
173
|
+
numbers — so gateways can emit informative 429/503 responses. No fabricated
|
|
174
|
+
`Retry-After` is provided: a fail-fast bulkhead has no honest ETA.
|
|
175
|
+
|
|
176
|
+
### `wouldAdmit(request, { priority })`
|
|
177
|
+
|
|
178
|
+
Advisory dry-run for routing decisions ("try another model pool"). It reserves
|
|
179
|
+
nothing and is inherently racy — never treat `true` as a guarantee.
|
|
180
|
+
|
|
181
|
+
### Scope note
|
|
182
|
+
|
|
183
|
+
This library remains single-process by design. Distributed budget
|
|
184
|
+
coordination across gateway replicas requires shared state and an async
|
|
185
|
+
admission path; it is out of scope here. For multi-replica deployments,
|
|
186
|
+
partition the budget per replica or coordinate above this layer.
|
|
187
|
+
|
|
188
|
+
---
|
|
189
|
+
|
|
125
190
|
## What's New in v3
|
|
126
191
|
|
|
127
192
|
### Stats are now namespaced
|
|
@@ -380,6 +445,12 @@ deduplication: {
|
|
|
380
445
|
|
|
381
446
|
Return `""` from `keyFn` to opt a specific request out.
|
|
382
447
|
|
|
448
|
+
When a request joins an existing in-flight call through deduplication, the
|
|
449
|
+
underlying LLM call is shared and is not cancelled by later callers. Each
|
|
450
|
+
deduped caller still gets its own `AbortSignal` and `timeoutMs` wait: aborting
|
|
451
|
+
or timing out that caller rejects only that caller's `run()` promise while the
|
|
452
|
+
shared work continues for the original caller and any other waiters.
|
|
453
|
+
|
|
383
454
|
---
|
|
384
455
|
|
|
385
456
|
## Cancellation
|
|
@@ -544,12 +615,12 @@ type LLMBulkheadOptions = {
|
|
|
544
615
|
model: string;
|
|
545
616
|
maxConcurrent: number;
|
|
546
617
|
maxQueue?: number;
|
|
547
|
-
timeoutMs?: number;
|
|
618
|
+
timeoutMs?: number; // integer >= 0
|
|
548
619
|
profile?: 'interactive' | 'batch' | LLMBulkheadPreset;
|
|
549
620
|
tokenBudget?: {
|
|
550
|
-
budget: number;
|
|
621
|
+
budget: number; // positive integer
|
|
551
622
|
estimator?: TokenEstimator;
|
|
552
|
-
outputCap?: number;
|
|
623
|
+
outputCap?: number; // integer >= 0
|
|
553
624
|
};
|
|
554
625
|
deduplication?: boolean | DeduplicationOptions;
|
|
555
626
|
};
|
|
@@ -567,7 +638,7 @@ run<T>(
|
|
|
567
638
|
fn: (signal?: AbortSignal) => Promise<T>,
|
|
568
639
|
options?: {
|
|
569
640
|
signal?: AbortSignal;
|
|
570
|
-
timeoutMs?: number;
|
|
641
|
+
timeoutMs?: number; // integer >= 0
|
|
571
642
|
getUsage?: (result: T) => TokenUsage | undefined;
|
|
572
643
|
},
|
|
573
644
|
): Promise<T>
|
|
@@ -578,7 +649,7 @@ run<T>(
|
|
|
578
649
|
```ts
|
|
579
650
|
acquire(
|
|
580
651
|
request: LLMRequest,
|
|
581
|
-
options?: { signal?: AbortSignal; timeoutMs?: number },
|
|
652
|
+
options?: { signal?: AbortSignal; timeoutMs?: number /* integer >= 0 */ },
|
|
582
653
|
): Promise<LLMAcquireResult>
|
|
583
654
|
|
|
584
655
|
type LLMAcquireResult =
|
package/dist/cjs/index.cjs
CHANGED
|
@@ -9,10 +9,12 @@ const async_bulkhead_ts_1 = require("async-bulkhead-ts");
|
|
|
9
9
|
class LLMBulkheadRejectedError extends Error {
|
|
10
10
|
reason;
|
|
11
11
|
code = "LLM_BULKHEAD_REJECTED";
|
|
12
|
-
|
|
12
|
+
detail;
|
|
13
|
+
constructor(reason, detail) {
|
|
13
14
|
super(`LLM bulkhead rejected: ${reason}`);
|
|
14
15
|
this.reason = reason;
|
|
15
16
|
this.name = "LLMBulkheadRejectedError";
|
|
17
|
+
this.detail = detail;
|
|
16
18
|
}
|
|
17
19
|
}
|
|
18
20
|
exports.LLMBulkheadRejectedError = LLMBulkheadRejectedError;
|
|
@@ -29,6 +31,37 @@ exports.PROFILES = {
|
|
|
29
31
|
// ────────────────────────────────────────────
|
|
30
32
|
const DEFAULT_OUTPUT_CAP = 2_048;
|
|
31
33
|
const NAIVE_CHAR_RATIO = 4.0;
|
|
34
|
+
function isNonNegativeInteger(value) {
|
|
35
|
+
return Number.isFinite(value) && Number.isInteger(value) && value >= 0;
|
|
36
|
+
}
|
|
37
|
+
function assertNonNegativeInteger(value, name) {
|
|
38
|
+
if (!isNonNegativeInteger(value)) {
|
|
39
|
+
throw new Error(`${name} must be an integer >= 0`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
function assertPositiveInteger(value, name) {
|
|
43
|
+
if (!Number.isFinite(value) || !Number.isInteger(value) || value <= 0) {
|
|
44
|
+
throw new Error(`${name} must be a positive integer`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
function assertOptionalNonNegativeInteger(value, name) {
|
|
48
|
+
if (value !== undefined)
|
|
49
|
+
assertNonNegativeInteger(value, name);
|
|
50
|
+
}
|
|
51
|
+
function validateTokenEstimate(estimate) {
|
|
52
|
+
assertNonNegativeInteger(estimate.input, "token estimator input");
|
|
53
|
+
assertNonNegativeInteger(estimate.maxOutput, "token estimator maxOutput");
|
|
54
|
+
const needed = estimate.input + estimate.maxOutput;
|
|
55
|
+
assertNonNegativeInteger(needed, "token reservation");
|
|
56
|
+
return needed;
|
|
57
|
+
}
|
|
58
|
+
function validateTokenUsage(usage) {
|
|
59
|
+
assertNonNegativeInteger(usage.input, "token usage input");
|
|
60
|
+
assertNonNegativeInteger(usage.output, "token usage output");
|
|
61
|
+
const actual = usage.input + usage.output;
|
|
62
|
+
assertNonNegativeInteger(actual, "token usage total");
|
|
63
|
+
return usage;
|
|
64
|
+
}
|
|
32
65
|
/**
|
|
33
66
|
* Extract total character count from message content.
|
|
34
67
|
* Handles both plain strings and multimodal content block arrays.
|
|
@@ -48,6 +81,8 @@ function extractTextLength(content) {
|
|
|
48
81
|
return len;
|
|
49
82
|
}
|
|
50
83
|
function resolveMaxOutput(request, fallback) {
|
|
84
|
+
assertNonNegativeInteger(fallback, "outputCap");
|
|
85
|
+
assertOptionalNonNegativeInteger(request.max_tokens, "request.max_tokens");
|
|
51
86
|
return request.max_tokens ?? fallback;
|
|
52
87
|
}
|
|
53
88
|
/**
|
|
@@ -118,6 +153,7 @@ function createModelAwareTokenEstimator(overridesOrOpts, maybeOpts) {
|
|
|
118
153
|
? overridesOrOpts
|
|
119
154
|
: (maybeOpts ?? {});
|
|
120
155
|
const outputCap = opts.outputCap ?? DEFAULT_OUTPUT_CAP;
|
|
156
|
+
assertNonNegativeInteger(outputCap, "outputCap");
|
|
121
157
|
function lookupRatio(model) {
|
|
122
158
|
// Exact overrides checked first (case-sensitive, then lowercased).
|
|
123
159
|
if (overrides) {
|
|
@@ -191,16 +227,25 @@ function defaultDedupKey(request) {
|
|
|
191
227
|
// ────────────────────────────────────────────
|
|
192
228
|
function createLLMBulkhead(opts) {
|
|
193
229
|
// ---- Validate ----
|
|
194
|
-
if (
|
|
230
|
+
if (typeof opts.model !== "string" || opts.model.trim() === "") {
|
|
195
231
|
throw new Error("model must be a non-empty string");
|
|
196
232
|
}
|
|
197
|
-
|
|
198
|
-
throw new Error("maxConcurrent must be a positive integer");
|
|
199
|
-
}
|
|
233
|
+
assertPositiveInteger(opts.maxConcurrent, "maxConcurrent");
|
|
200
234
|
// ---- Resolve profile defaults ----
|
|
201
235
|
const preset = resolvePreset(opts.profile);
|
|
202
236
|
const maxQueue = opts.maxQueue ?? preset.maxQueue ?? 0;
|
|
203
237
|
const timeoutMs = opts.timeoutMs ?? preset.timeoutMs;
|
|
238
|
+
assertNonNegativeInteger(maxQueue, "maxQueue");
|
|
239
|
+
assertOptionalNonNegativeInteger(timeoutMs, "timeoutMs");
|
|
240
|
+
if (opts.tokenBudget) {
|
|
241
|
+
assertPositiveInteger(opts.tokenBudget.budget, "tokenBudget.budget");
|
|
242
|
+
assertOptionalNonNegativeInteger(opts.tokenBudget.outputCap, "tokenBudget.outputCap");
|
|
243
|
+
assertOptionalNonNegativeInteger(opts.tokenBudget.highPriorityReserve, "tokenBudget.highPriorityReserve");
|
|
244
|
+
if (opts.tokenBudget.highPriorityReserve !== undefined &&
|
|
245
|
+
opts.tokenBudget.highPriorityReserve > opts.tokenBudget.budget) {
|
|
246
|
+
throw new Error("tokenBudget.highPriorityReserve must be <= tokenBudget.budget");
|
|
247
|
+
}
|
|
248
|
+
}
|
|
204
249
|
// ---- Internal bulkhead from async-bulkhead-ts ----
|
|
205
250
|
const bulkhead = (0, async_bulkhead_ts_1.createBulkhead)({
|
|
206
251
|
maxConcurrent: opts.maxConcurrent,
|
|
@@ -213,10 +258,12 @@ function createLLMBulkhead(opts) {
|
|
|
213
258
|
defaultModel: opts.model,
|
|
214
259
|
outputCap: budget?.outputCap,
|
|
215
260
|
});
|
|
261
|
+
const highPriorityReserve = budget?.highPriorityReserve ?? 0;
|
|
216
262
|
let inFlightTokens = 0;
|
|
217
263
|
let totalReserved = 0;
|
|
218
264
|
let totalConsumed = 0;
|
|
219
265
|
let totalRefunded = 0;
|
|
266
|
+
let totalOverrun = 0;
|
|
220
267
|
let llmAdmitted = 0;
|
|
221
268
|
let llmReleased = 0;
|
|
222
269
|
let llmRejected = 0;
|
|
@@ -263,98 +310,263 @@ function createLLMBulkhead(opts) {
|
|
|
263
310
|
});
|
|
264
311
|
return { promise, resolve, reject };
|
|
265
312
|
}
|
|
313
|
+
function estimateParts(request) {
|
|
314
|
+
if (!budget)
|
|
315
|
+
return null;
|
|
316
|
+
const estimate = estimator(request);
|
|
317
|
+
const reserved = validateTokenEstimate(estimate);
|
|
318
|
+
return { input: estimate.input, maxOut: estimate.maxOutput, reserved };
|
|
319
|
+
}
|
|
320
|
+
function resolvePriority(priority) {
|
|
321
|
+
if (priority === undefined)
|
|
322
|
+
return "normal";
|
|
323
|
+
if (priority !== "high" && priority !== "normal") {
|
|
324
|
+
throw new Error(`priority must be "high" or "normal"`);
|
|
325
|
+
}
|
|
326
|
+
return priority;
|
|
327
|
+
}
|
|
328
|
+
/** Budget ceiling applicable to a request at the given priority. */
|
|
329
|
+
function effectiveBudget(priority) {
|
|
330
|
+
if (!budget)
|
|
331
|
+
return Infinity;
|
|
332
|
+
return priority === "high"
|
|
333
|
+
? budget.budget
|
|
334
|
+
: budget.budget - highPriorityReserve;
|
|
335
|
+
}
|
|
266
336
|
/**
|
|
267
|
-
* Attempt token budget admission synchronously
|
|
268
|
-
* Returns
|
|
269
|
-
*
|
|
337
|
+
* Attempt token budget admission synchronously for a precomputed
|
|
338
|
+
* reservation. Returns false if the priority-adjusted ceiling is
|
|
339
|
+
* exceeded.
|
|
270
340
|
*/
|
|
271
|
-
function tryReserveTokens(
|
|
341
|
+
function tryReserveTokens(reserved, priority) {
|
|
272
342
|
if (!budget)
|
|
273
|
-
return
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
totalReserved += needed;
|
|
280
|
-
return needed;
|
|
343
|
+
return true;
|
|
344
|
+
if (inFlightTokens + reserved > effectiveBudget(priority))
|
|
345
|
+
return false;
|
|
346
|
+
inFlightTokens += reserved;
|
|
347
|
+
totalReserved += reserved;
|
|
348
|
+
return true;
|
|
281
349
|
}
|
|
282
|
-
function releaseTokens(
|
|
350
|
+
function releaseTokens(held, usage) {
|
|
283
351
|
let refunded = 0;
|
|
284
|
-
if (usage &&
|
|
352
|
+
if (usage && held > 0) {
|
|
285
353
|
const actual = usage.input + usage.output;
|
|
286
354
|
totalConsumed += actual;
|
|
287
|
-
if (actual <
|
|
288
|
-
refunded =
|
|
355
|
+
if (actual < held) {
|
|
356
|
+
refunded = held - actual;
|
|
289
357
|
totalRefunded += refunded;
|
|
290
358
|
}
|
|
291
359
|
}
|
|
292
|
-
inFlightTokens = Math.max(0, inFlightTokens -
|
|
360
|
+
inFlightTokens = Math.max(0, inFlightTokens - held);
|
|
293
361
|
return refunded;
|
|
294
362
|
}
|
|
363
|
+
/** Capacity snapshot for rejection results, events, and errors. */
|
|
364
|
+
function buildRejectDetail(requested, priority) {
|
|
365
|
+
const base = bulkhead.stats();
|
|
366
|
+
const detail = {
|
|
367
|
+
inFlight: base.inFlight,
|
|
368
|
+
pending: base.pending,
|
|
369
|
+
maxConcurrent: base.maxConcurrent,
|
|
370
|
+
maxQueue: base.maxQueue,
|
|
371
|
+
};
|
|
372
|
+
if (budget) {
|
|
373
|
+
const eff = effectiveBudget(priority);
|
|
374
|
+
detail.tokenBudget = {
|
|
375
|
+
budget: budget.budget,
|
|
376
|
+
inFlightTokens,
|
|
377
|
+
effectiveBudget: eff,
|
|
378
|
+
available: Math.max(0, eff - inFlightTokens),
|
|
379
|
+
requested,
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
return detail;
|
|
383
|
+
}
|
|
384
|
+
function normalizeAcquireOptions(ao) {
|
|
385
|
+
const normalized = {};
|
|
386
|
+
if (ao.signal !== undefined)
|
|
387
|
+
normalized.signal = ao.signal;
|
|
388
|
+
const effectiveTimeoutMs = ao.timeoutMs ?? timeoutMs;
|
|
389
|
+
if (effectiveTimeoutMs !== undefined) {
|
|
390
|
+
assertNonNegativeInteger(effectiveTimeoutMs, "timeoutMs");
|
|
391
|
+
normalized.timeoutMs = effectiveTimeoutMs;
|
|
392
|
+
}
|
|
393
|
+
return normalized;
|
|
394
|
+
}
|
|
395
|
+
function noteDedupWaitRejection(request, reason) {
|
|
396
|
+
noteLLMReject(reason);
|
|
397
|
+
emit("reject", { request, reason });
|
|
398
|
+
return new LLMBulkheadRejectedError(reason);
|
|
399
|
+
}
|
|
400
|
+
function waitForSharedDedup(shared, request, ao) {
|
|
401
|
+
const normalized = normalizeAcquireOptions(ao);
|
|
402
|
+
const signal = normalized.signal;
|
|
403
|
+
const effectiveTimeoutMs = normalized.timeoutMs;
|
|
404
|
+
if (signal?.aborted) {
|
|
405
|
+
return Promise.reject(noteDedupWaitRejection(request, "aborted"));
|
|
406
|
+
}
|
|
407
|
+
if (signal === undefined && effectiveTimeoutMs === undefined) {
|
|
408
|
+
return shared;
|
|
409
|
+
}
|
|
410
|
+
return new Promise((resolve, reject) => {
|
|
411
|
+
let timeoutId;
|
|
412
|
+
let settled = false;
|
|
413
|
+
const cleanup = () => {
|
|
414
|
+
if (timeoutId !== undefined)
|
|
415
|
+
clearTimeout(timeoutId);
|
|
416
|
+
if (signal !== undefined) {
|
|
417
|
+
signal.removeEventListener("abort", onAbort);
|
|
418
|
+
}
|
|
419
|
+
};
|
|
420
|
+
const settle = (fn) => {
|
|
421
|
+
if (settled)
|
|
422
|
+
return;
|
|
423
|
+
settled = true;
|
|
424
|
+
cleanup();
|
|
425
|
+
fn();
|
|
426
|
+
};
|
|
427
|
+
const onAbort = () => {
|
|
428
|
+
settle(() => {
|
|
429
|
+
reject(noteDedupWaitRejection(request, "aborted"));
|
|
430
|
+
});
|
|
431
|
+
};
|
|
432
|
+
if (signal !== undefined) {
|
|
433
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
434
|
+
}
|
|
435
|
+
if (effectiveTimeoutMs !== undefined) {
|
|
436
|
+
timeoutId = setTimeout(() => {
|
|
437
|
+
settle(() => {
|
|
438
|
+
reject(noteDedupWaitRejection(request, "timeout"));
|
|
439
|
+
});
|
|
440
|
+
}, effectiveTimeoutMs);
|
|
441
|
+
}
|
|
442
|
+
void shared.then((value) => settle(() => resolve(value)), (err) => settle(() => reject(err)));
|
|
443
|
+
});
|
|
444
|
+
}
|
|
295
445
|
/**
|
|
296
446
|
* Wraps a base Token so that release() also returns the token
|
|
297
|
-
* reservation and optionally applies the refund
|
|
447
|
+
* reservation and optionally applies the refund, and so that
|
|
448
|
+
* streaming callers can report cumulative usage mid-flight.
|
|
298
449
|
*/
|
|
299
|
-
function wrapToken(base,
|
|
450
|
+
function wrapToken(base, parts, request) {
|
|
300
451
|
let released = false;
|
|
452
|
+
/** Tokens currently held against the budget for this request. */
|
|
453
|
+
let held = parts?.reserved ?? 0;
|
|
454
|
+
/** Last reported cumulative usage (monotonically clamped). */
|
|
455
|
+
let reported;
|
|
456
|
+
const snapshot = () => {
|
|
457
|
+
const consumed = reported
|
|
458
|
+
? reported.input + reported.output
|
|
459
|
+
: 0;
|
|
460
|
+
const outputCap = parts ? parts.maxOut : null;
|
|
461
|
+
return {
|
|
462
|
+
reserved: parts?.reserved ?? 0,
|
|
463
|
+
held,
|
|
464
|
+
consumed,
|
|
465
|
+
outputCap,
|
|
466
|
+
outputRemaining: outputCap === null
|
|
467
|
+
? null
|
|
468
|
+
: Math.max(0, outputCap - (reported?.output ?? 0)),
|
|
469
|
+
overReservation: parts ? consumed > parts.reserved : false,
|
|
470
|
+
};
|
|
471
|
+
};
|
|
472
|
+
const reportUsage = (usage) => {
|
|
473
|
+
const valid = validateTokenUsage(usage);
|
|
474
|
+
// Clamp to monotonic non-decreasing per field — cumulative
|
|
475
|
+
// stream usage never shrinks; a lower report is stale.
|
|
476
|
+
reported = reported
|
|
477
|
+
? {
|
|
478
|
+
input: Math.max(reported.input, valid.input),
|
|
479
|
+
output: Math.max(reported.output, valid.output),
|
|
480
|
+
}
|
|
481
|
+
: valid;
|
|
482
|
+
// Accounting only applies pre-release with a budget configured.
|
|
483
|
+
if (!released && parts && budget) {
|
|
484
|
+
// Hold = known input + the larger of (output ceiling, actual output).
|
|
485
|
+
// Keeps the full output reservation while refunding input
|
|
486
|
+
// over-estimates immediately; expands on output overrun.
|
|
487
|
+
const newHold = reported.input + Math.max(parts.maxOut, reported.output);
|
|
488
|
+
const delta = newHold - held;
|
|
489
|
+
if (delta > 0) {
|
|
490
|
+
inFlightTokens += delta;
|
|
491
|
+
totalOverrun += delta;
|
|
492
|
+
}
|
|
493
|
+
else if (delta < 0) {
|
|
494
|
+
const refund = -delta;
|
|
495
|
+
inFlightTokens = Math.max(0, inFlightTokens - refund);
|
|
496
|
+
totalRefunded += refund;
|
|
497
|
+
}
|
|
498
|
+
held = newHold;
|
|
499
|
+
}
|
|
500
|
+
return snapshot();
|
|
501
|
+
};
|
|
301
502
|
return {
|
|
503
|
+
reportUsage,
|
|
302
504
|
release(usage) {
|
|
303
505
|
if (released)
|
|
304
506
|
return;
|
|
305
507
|
released = true;
|
|
508
|
+
let validUsage;
|
|
509
|
+
let usageError;
|
|
510
|
+
if (usage !== undefined) {
|
|
511
|
+
try {
|
|
512
|
+
validUsage = validateTokenUsage(usage);
|
|
513
|
+
}
|
|
514
|
+
catch (err) {
|
|
515
|
+
usageError = err;
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
// Fall back to the last mid-flight report when no (valid)
|
|
519
|
+
// explicit usage is provided at release.
|
|
520
|
+
if (validUsage === undefined && reported !== undefined) {
|
|
521
|
+
validUsage = reported;
|
|
522
|
+
}
|
|
306
523
|
try {
|
|
307
524
|
base.release();
|
|
308
525
|
}
|
|
309
526
|
finally {
|
|
310
|
-
const refunded = releaseTokens(
|
|
527
|
+
const refunded = releaseTokens(held, validUsage);
|
|
311
528
|
noteLLMRelease();
|
|
312
529
|
emit("release", {
|
|
313
530
|
request,
|
|
314
|
-
reservedTokens: reserved,
|
|
531
|
+
reservedTokens: parts?.reserved ?? 0,
|
|
315
532
|
refundedTokens: refunded,
|
|
316
|
-
...(
|
|
533
|
+
...(validUsage !== undefined && { usage: validUsage }),
|
|
317
534
|
});
|
|
318
535
|
}
|
|
536
|
+
if (usageError !== undefined)
|
|
537
|
+
throw usageError;
|
|
319
538
|
},
|
|
320
539
|
};
|
|
321
540
|
}
|
|
322
541
|
// ---- Internal acquire ----
|
|
323
542
|
async function _acquire(request, ao) {
|
|
543
|
+
assertOptionalNonNegativeInteger(request.max_tokens, "request.max_tokens");
|
|
544
|
+
const priority = resolvePriority(ao.priority);
|
|
545
|
+
const parts = estimateParts(request);
|
|
546
|
+
const reserved = parts?.reserved ?? 0;
|
|
547
|
+
const rejectWith = (reason) => {
|
|
548
|
+
const detail = buildRejectDetail(reserved, priority);
|
|
549
|
+
noteLLMReject(reason);
|
|
550
|
+
emit("reject", { request, reason, detail });
|
|
551
|
+
return { ok: false, reason, detail };
|
|
552
|
+
};
|
|
324
553
|
// Token budget: pre-check before entering the queue.
|
|
325
|
-
if (budget) {
|
|
326
|
-
|
|
327
|
-
const needed = estimate.input + estimate.maxOutput;
|
|
328
|
-
if (inFlightTokens + needed > budget.budget) {
|
|
329
|
-
noteLLMReject("budget_limit");
|
|
330
|
-
emit("reject", { request, reason: "budget_limit" });
|
|
331
|
-
return { ok: false, reason: "budget_limit" };
|
|
332
|
-
}
|
|
554
|
+
if (budget && inFlightTokens + reserved > effectiveBudget(priority)) {
|
|
555
|
+
return rejectWith("budget_limit");
|
|
333
556
|
}
|
|
334
|
-
const mergedOptions =
|
|
335
|
-
if (ao.signal !== undefined)
|
|
336
|
-
mergedOptions.signal = ao.signal;
|
|
337
|
-
if (ao.timeoutMs !== undefined)
|
|
338
|
-
mergedOptions.timeoutMs = ao.timeoutMs;
|
|
339
|
-
else if (timeoutMs !== undefined)
|
|
340
|
-
mergedOptions.timeoutMs = timeoutMs;
|
|
557
|
+
const mergedOptions = normalizeAcquireOptions(ao);
|
|
341
558
|
const r = await bulkhead.acquire(mergedOptions);
|
|
342
559
|
if (!r.ok) {
|
|
343
|
-
|
|
344
|
-
emit("reject", { request, reason: r.reason });
|
|
345
|
-
return { ok: false, reason: r.reason };
|
|
560
|
+
return rejectWith(r.reason);
|
|
346
561
|
}
|
|
347
|
-
// Post-admission: reserve
|
|
348
|
-
|
|
349
|
-
if (reserved === null) {
|
|
562
|
+
// Post-admission: reserve the precomputed amount now.
|
|
563
|
+
if (!tryReserveTokens(reserved, priority)) {
|
|
350
564
|
r.token.release();
|
|
351
|
-
|
|
352
|
-
emit("reject", { request, reason: "budget_limit" });
|
|
353
|
-
return { ok: false, reason: "budget_limit" };
|
|
565
|
+
return rejectWith("budget_limit");
|
|
354
566
|
}
|
|
355
567
|
noteLLMAdmit();
|
|
356
568
|
emit("admit", { request, reservedTokens: reserved });
|
|
357
|
-
return { ok: true, token: wrapToken(r.token,
|
|
569
|
+
return { ok: true, token: wrapToken(r.token, parts, request) };
|
|
358
570
|
}
|
|
359
571
|
// ---- Public API ----
|
|
360
572
|
/**
|
|
@@ -366,6 +578,34 @@ function createLLMBulkhead(opts) {
|
|
|
366
578
|
async function acquire(request, ao = {}) {
|
|
367
579
|
return _acquire(request, ao);
|
|
368
580
|
}
|
|
581
|
+
/**
|
|
582
|
+
* Advisory dry-run: would a request of this shape be admitted right
|
|
583
|
+
* now at the given priority?
|
|
584
|
+
*
|
|
585
|
+
* This is a snapshot for routing decisions (e.g. pick a different
|
|
586
|
+
* model pool). It does NOT reserve anything — the answer can change
|
|
587
|
+
* before a subsequent `acquire()`/`run()` lands. Never treat `true`
|
|
588
|
+
* as a guarantee.
|
|
589
|
+
*/
|
|
590
|
+
function wouldAdmit(request, opts = {}) {
|
|
591
|
+
const priority = resolvePriority(opts.priority);
|
|
592
|
+
const base = bulkhead.stats();
|
|
593
|
+
if (base.closed)
|
|
594
|
+
return { admit: false, reason: "shutdown" };
|
|
595
|
+
const parts = estimateParts(request);
|
|
596
|
+
const reserved = parts?.reserved ?? 0;
|
|
597
|
+
if (budget && inFlightTokens + reserved > effectiveBudget(priority)) {
|
|
598
|
+
return { admit: false, reason: "budget_limit" };
|
|
599
|
+
}
|
|
600
|
+
if (base.inFlight < base.maxConcurrent)
|
|
601
|
+
return { admit: true };
|
|
602
|
+
if (base.pending < base.maxQueue)
|
|
603
|
+
return { admit: true };
|
|
604
|
+
return {
|
|
605
|
+
admit: false,
|
|
606
|
+
reason: base.maxQueue > 0 ? "queue_limit" : "concurrency_limit",
|
|
607
|
+
};
|
|
608
|
+
}
|
|
369
609
|
/**
|
|
370
610
|
* Primary API. Acquire → call `fn` → release, automatically.
|
|
371
611
|
*
|
|
@@ -395,7 +635,7 @@ function createLLMBulkhead(opts) {
|
|
|
395
635
|
if (existing) {
|
|
396
636
|
dedupHits++;
|
|
397
637
|
emit("dedup", { request });
|
|
398
|
-
return existing;
|
|
638
|
+
return waitForSharedDedup(existing, request, acquireOpts);
|
|
399
639
|
}
|
|
400
640
|
deferred = createDeferred();
|
|
401
641
|
resultPromise = deferred.promise;
|
|
@@ -415,12 +655,15 @@ function createLLMBulkhead(opts) {
|
|
|
415
655
|
try {
|
|
416
656
|
const r = await _acquire(request, acquireOpts);
|
|
417
657
|
if (!r.ok) {
|
|
418
|
-
throw new LLMBulkheadRejectedError(r.reason);
|
|
658
|
+
throw new LLMBulkheadRejectedError(r.reason, r.detail);
|
|
419
659
|
}
|
|
660
|
+
const ctx = {
|
|
661
|
+
reportUsage: (usage) => r.token.reportUsage(usage),
|
|
662
|
+
};
|
|
420
663
|
const work = (async () => {
|
|
421
664
|
let result;
|
|
422
665
|
try {
|
|
423
|
-
result = await fn(ao.signal);
|
|
666
|
+
result = await fn(ao.signal, ctx);
|
|
424
667
|
}
|
|
425
668
|
catch (err) {
|
|
426
669
|
r.token.release(); // no usage on error
|
|
@@ -430,7 +673,9 @@ function createLLMBulkhead(opts) {
|
|
|
430
673
|
let usage;
|
|
431
674
|
if (getUsage) {
|
|
432
675
|
try {
|
|
433
|
-
|
|
676
|
+
const extracted = getUsage(result);
|
|
677
|
+
usage =
|
|
678
|
+
extracted === undefined ? undefined : validateTokenUsage(extracted);
|
|
434
679
|
}
|
|
435
680
|
catch {
|
|
436
681
|
// bad getUsage must not break release
|
|
@@ -473,6 +718,8 @@ function createLLMBulkhead(opts) {
|
|
|
473
718
|
totalReserved,
|
|
474
719
|
totalConsumed,
|
|
475
720
|
totalRefunded,
|
|
721
|
+
totalOverrun,
|
|
722
|
+
highPriorityReserve,
|
|
476
723
|
};
|
|
477
724
|
}
|
|
478
725
|
if (dedup.enabled) {
|
|
@@ -512,6 +759,6 @@ function createLLMBulkhead(opts) {
|
|
|
512
759
|
listeners[event].delete(listener);
|
|
513
760
|
};
|
|
514
761
|
}
|
|
515
|
-
return { acquire, run, stats, close, drain, on };
|
|
762
|
+
return { acquire, run, wouldAdmit, stats, close, drain, on };
|
|
516
763
|
}
|
|
517
|
-
//# sourceMappingURL=index.
|
|
764
|
+
//# sourceMappingURL=index.cjs.map
|