async-bulkhead-llm 3.8.0 → 3.10.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 +287 -21
- package/dist/cjs/bulkhead.cjs +378 -73
- package/dist/cjs/bulkhead.cjs.map +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/reconfigurable-bulkhead.cjs +261 -0
- package/dist/cjs/reconfigurable-bulkhead.cjs.map +1 -0
- package/dist/esm/bulkhead.js +378 -73
- package/dist/esm/bulkhead.js.map +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/reconfigurable-bulkhead.js +258 -0
- package/dist/esm/reconfigurable-bulkhead.js.map +1 -0
- package/dist/types/bulkhead.d.ts +5 -31
- package/dist/types/bulkhead.d.ts.map +1 -1
- package/dist/types/index.d.ts +1 -1
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/reconfigurable-bulkhead.d.ts +25 -0
- package/dist/types/reconfigurable-bulkhead.d.ts.map +1 -0
- package/dist/types/types.d.ts +147 -4
- package/dist/types/types.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/esm/bulkhead.js
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* `createLLMBulkhead`: admission (concurrency + token budget +
|
|
3
|
-
* priority), reservation and refund accounting, streaming usage
|
|
4
|
-
* reports, deduplication orchestration, events, stats, and shutdown.
|
|
5
|
-
*/
|
|
6
|
-
import { createBulkhead, } from "async-bulkhead-ts";
|
|
7
1
|
import { randomUUID } from "node:crypto";
|
|
8
2
|
import { LLMBulkheadRejectedError } from "./errors.js";
|
|
9
3
|
import { PROFILES } from "./profiles.js";
|
|
10
4
|
import { createModelAwareTokenEstimator } from "./estimators.js";
|
|
11
5
|
import { assertNonNegativeInteger, assertOptionalNonNegativeInteger, assertPositiveInteger, validateTokenEstimate, validateTokenUsage, } from "./validation.js";
|
|
12
6
|
import { hashDedupKey, isUnsafeToShare, resolveDedup } from "./dedup.js";
|
|
7
|
+
import { createReconfigurableBulkhead } from "./reconfigurable-bulkhead.js";
|
|
8
|
+
const DEFAULT_SHADOW_REASONS = [
|
|
9
|
+
"budget_limit",
|
|
10
|
+
"concurrency_limit",
|
|
11
|
+
"queue_limit",
|
|
12
|
+
"timeout",
|
|
13
|
+
];
|
|
14
|
+
const SHADOWABLE_REASONS = new Set(DEFAULT_SHADOW_REASONS);
|
|
13
15
|
// ────────────────────────────────────────────
|
|
14
16
|
// Option resolution
|
|
15
17
|
// ────────────────────────────────────────────
|
|
@@ -29,6 +31,10 @@ export function createLLMBulkhead(opts) {
|
|
|
29
31
|
throw new Error("model must be a non-empty string");
|
|
30
32
|
}
|
|
31
33
|
assertPositiveInteger(opts.maxConcurrent, "maxConcurrent");
|
|
34
|
+
const initialRevision = opts.initialRevision ?? 0;
|
|
35
|
+
if (!Number.isSafeInteger(initialRevision) || initialRevision < 0) {
|
|
36
|
+
throw new Error("initialRevision must be a non-negative safe integer");
|
|
37
|
+
}
|
|
32
38
|
// ---- Resolve profile defaults ----
|
|
33
39
|
const preset = resolvePreset(opts.profile);
|
|
34
40
|
const maxQueue = opts.maxQueue ?? preset.maxQueue ?? 0;
|
|
@@ -44,8 +50,8 @@ export function createLLMBulkhead(opts) {
|
|
|
44
50
|
throw new Error("tokenBudget.highPriorityReserve must be <= tokenBudget.budget");
|
|
45
51
|
}
|
|
46
52
|
}
|
|
47
|
-
// ---- Internal
|
|
48
|
-
const bulkhead =
|
|
53
|
+
// ---- Internal reconfigurable concurrency bulkhead ----
|
|
54
|
+
const bulkhead = createReconfigurableBulkhead({
|
|
49
55
|
maxConcurrent: opts.maxConcurrent,
|
|
50
56
|
maxQueue,
|
|
51
57
|
});
|
|
@@ -56,16 +62,10 @@ export function createLLMBulkhead(opts) {
|
|
|
56
62
|
defaultModel: opts.model,
|
|
57
63
|
outputCap: budget?.outputCap,
|
|
58
64
|
});
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
* Mutable budget ceiling, initialized from `tokenBudget.budget`.
|
|
62
|
-
* `undefined` when `tokenBudget` was never configured — `setBudget()`
|
|
63
|
-
* throws in that case rather than silently no-op'ing.
|
|
64
|
-
* Mutated only by `setBudget()`. All admission math reads this value
|
|
65
|
-
* (via `effectiveBudget()`), not the frozen `opts.tokenBudget.budget`,
|
|
66
|
-
* so budget changes take effect on the very next admission check.
|
|
67
|
-
*/
|
|
65
|
+
/** Current versioned admission-limit state. */
|
|
66
|
+
let currentRevision = initialRevision;
|
|
68
67
|
let currentBudget = budget?.budget;
|
|
68
|
+
let currentHighPriorityReserve = budget?.highPriorityReserve ?? 0;
|
|
69
69
|
let inFlightTokens = 0;
|
|
70
70
|
let totalReserved = 0;
|
|
71
71
|
let totalConsumed = 0;
|
|
@@ -75,9 +75,16 @@ export function createLLMBulkhead(opts) {
|
|
|
75
75
|
let llmReleased = 0;
|
|
76
76
|
let llmRejected = 0;
|
|
77
77
|
const llmRejectedByReason = {};
|
|
78
|
+
let observeBypassed = 0;
|
|
79
|
+
let observeRaceBypassed = 0;
|
|
80
|
+
const observeBypassedByReason = {};
|
|
81
|
+
let observeUsageReported = 0;
|
|
82
|
+
let observeTotalInputTokens = 0;
|
|
83
|
+
let observeTotalOutputTokens = 0;
|
|
78
84
|
// ---- Deduplication state ----
|
|
79
85
|
const dedup = resolveDedup(opts.deduplication);
|
|
80
86
|
const dedupMap = new Map();
|
|
87
|
+
const dedupWaitErrors = new WeakSet();
|
|
81
88
|
let dedupHits = 0;
|
|
82
89
|
// ---- Event emitter state ----
|
|
83
90
|
const listeners = {
|
|
@@ -85,6 +92,10 @@ export function createLLMBulkhead(opts) {
|
|
|
85
92
|
reject: new Set(),
|
|
86
93
|
release: new Set(),
|
|
87
94
|
usage: new Set(),
|
|
95
|
+
bypass: new Set(),
|
|
96
|
+
bypassUsage: new Set(),
|
|
97
|
+
bypassRelease: new Set(),
|
|
98
|
+
reconfigure: new Set(),
|
|
88
99
|
dedup: new Set(),
|
|
89
100
|
};
|
|
90
101
|
function emit(event, payload) {
|
|
@@ -185,6 +196,32 @@ export function createLLMBulkhead(opts) {
|
|
|
185
196
|
}
|
|
186
197
|
return priority;
|
|
187
198
|
}
|
|
199
|
+
function resolveAdmissionMode(mode) {
|
|
200
|
+
if (mode === undefined)
|
|
201
|
+
return "enforce";
|
|
202
|
+
if (mode !== "enforce" && mode !== "observe") {
|
|
203
|
+
throw new Error(`mode must be "enforce" or "observe"`);
|
|
204
|
+
}
|
|
205
|
+
return mode;
|
|
206
|
+
}
|
|
207
|
+
function resolveShadowReasons(reasons) {
|
|
208
|
+
if (reasons === undefined)
|
|
209
|
+
return SHADOWABLE_REASONS;
|
|
210
|
+
const resolved = new Set();
|
|
211
|
+
for (const reason of reasons) {
|
|
212
|
+
if (!SHADOWABLE_REASONS.has(reason)) {
|
|
213
|
+
throw new Error(`shadowReasons may contain only budget_limit, concurrency_limit, ` +
|
|
214
|
+
`queue_limit, or timeout`);
|
|
215
|
+
}
|
|
216
|
+
resolved.add(reason);
|
|
217
|
+
}
|
|
218
|
+
return resolved;
|
|
219
|
+
}
|
|
220
|
+
function resolveAdmission(request, ao) {
|
|
221
|
+
const priority = resolvePriority(ao.priority);
|
|
222
|
+
const parts = resolveReservation(request, ao.reservation);
|
|
223
|
+
return { priority, parts, reserved: parts?.reserved ?? 0 };
|
|
224
|
+
}
|
|
188
225
|
/**
|
|
189
226
|
* Budget ceiling applicable to a request at the given priority.
|
|
190
227
|
*
|
|
@@ -192,14 +229,15 @@ export function createLLMBulkhead(opts) {
|
|
|
192
229
|
* `tokenBudget` validation block above) — that check catches config
|
|
193
230
|
* typos once, at startup. It intentionally does *not* run again here.
|
|
194
231
|
*
|
|
195
|
-
* `setBudget()` can lower `currentBudget` below
|
|
232
|
+
* `applyLimits()` or `setBudget()` can lower `currentBudget` below
|
|
233
|
+
* `highPriorityReserve` at
|
|
196
234
|
* runtime (e.g. a lease-renewal ledger reporting a shrunk grant), and
|
|
197
235
|
* that is allowed, not re-validated. Rejecting a renewal-driven update
|
|
198
236
|
* would be wrong: the ledger's grant is reality — the bulkhead has no
|
|
199
237
|
* standing to refuse it. So `currentBudget` can legitimately end up
|
|
200
238
|
* smaller than `highPriorityReserve`.
|
|
201
239
|
*
|
|
202
|
-
* Consequence, deliberately embraced: `currentBudget! -
|
|
240
|
+
* Consequence, deliberately embraced: `currentBudget! - currentHighPriorityReserve`
|
|
203
241
|
* would go negative in that state, so it is clamped to `0` here. That
|
|
204
242
|
* means normal-priority admission is fully rejected (nothing fits under
|
|
205
243
|
* a `0` ceiling) while high-priority admission is still checked against
|
|
@@ -214,7 +252,7 @@ export function createLLMBulkhead(opts) {
|
|
|
214
252
|
return Infinity;
|
|
215
253
|
return priority === "high"
|
|
216
254
|
? currentBudget
|
|
217
|
-
: Math.max(0, currentBudget -
|
|
255
|
+
: Math.max(0, currentBudget - currentHighPriorityReserve);
|
|
218
256
|
}
|
|
219
257
|
/**
|
|
220
258
|
* Attempt token budget admission synchronously for a precomputed
|
|
@@ -264,32 +302,140 @@ export function createLLMBulkhead(opts) {
|
|
|
264
302
|
}
|
|
265
303
|
return detail;
|
|
266
304
|
}
|
|
305
|
+
function wouldAdmitResolved(admission, includeDetail) {
|
|
306
|
+
const { priority, reserved } = admission;
|
|
307
|
+
const withDetail = (result) => {
|
|
308
|
+
if (includeDetail) {
|
|
309
|
+
result.detail = buildRejectDetail(reserved, priority);
|
|
310
|
+
}
|
|
311
|
+
return result;
|
|
312
|
+
};
|
|
313
|
+
const base = bulkhead.stats();
|
|
314
|
+
if (base.closed) {
|
|
315
|
+
return withDetail({ admit: false, reason: "shutdown" });
|
|
316
|
+
}
|
|
317
|
+
if (budget && inFlightTokens + reserved > effectiveBudget(priority)) {
|
|
318
|
+
return withDetail({ admit: false, reason: "budget_limit" });
|
|
319
|
+
}
|
|
320
|
+
if (base.inFlight < base.maxConcurrent) {
|
|
321
|
+
return withDetail({ admit: true });
|
|
322
|
+
}
|
|
323
|
+
if (base.maxConcurrent === 0) {
|
|
324
|
+
return withDetail({ admit: false, reason: "concurrency_limit" });
|
|
325
|
+
}
|
|
326
|
+
if (base.pending < base.maxQueue) {
|
|
327
|
+
return withDetail({ admit: true });
|
|
328
|
+
}
|
|
329
|
+
return withDetail({
|
|
330
|
+
admit: false,
|
|
331
|
+
reason: base.maxQueue > 0 ? "queue_limit" : "concurrency_limit",
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
/** Return a detached snapshot of the currently applied limits. */
|
|
335
|
+
function limits() {
|
|
336
|
+
const base = bulkhead.stats();
|
|
337
|
+
const snapshot = {
|
|
338
|
+
revision: currentRevision,
|
|
339
|
+
maxConcurrent: base.maxConcurrent,
|
|
340
|
+
maxQueue: base.maxQueue,
|
|
341
|
+
...(budget
|
|
342
|
+
? {
|
|
343
|
+
tokenBudget: {
|
|
344
|
+
budget: currentBudget,
|
|
345
|
+
highPriorityReserve: currentHighPriorityReserve,
|
|
346
|
+
},
|
|
347
|
+
}
|
|
348
|
+
: {}),
|
|
349
|
+
};
|
|
350
|
+
return Object.freeze({
|
|
351
|
+
...snapshot,
|
|
352
|
+
...(snapshot.tokenBudget
|
|
353
|
+
? { tokenBudget: Object.freeze({ ...snapshot.tokenBudget }) }
|
|
354
|
+
: {}),
|
|
355
|
+
});
|
|
356
|
+
}
|
|
267
357
|
/**
|
|
268
|
-
*
|
|
358
|
+
* Atomically apply a complete, higher-revision admission-limit snapshot.
|
|
269
359
|
*
|
|
270
|
-
*
|
|
360
|
+
* All fields are validated before any state changes. Equal or lower
|
|
361
|
+
* revisions are rejected as stale without mutation. Lower concurrency,
|
|
362
|
+
* queue, or token ceilings use shrink-by-attrition: in-flight work and
|
|
363
|
+
* already accepted waiters are not cancelled. Raising concurrency pumps
|
|
364
|
+
* accepted waiters immediately after the complete snapshot is installed.
|
|
365
|
+
*/
|
|
366
|
+
function applyLimits(next) {
|
|
367
|
+
// Read each externally supplied property once. This prevents accessor
|
|
368
|
+
// objects from returning one value during validation and another during
|
|
369
|
+
// installation.
|
|
370
|
+
const revision = next.revision;
|
|
371
|
+
const maxConcurrent = next.maxConcurrent;
|
|
372
|
+
const maxQueue = next.maxQueue;
|
|
373
|
+
const nextTokenBudget = next.tokenBudget;
|
|
374
|
+
if (!Number.isSafeInteger(revision) || revision < 0) {
|
|
375
|
+
throw new Error("limits.revision must be a non-negative safe integer");
|
|
376
|
+
}
|
|
377
|
+
if (revision <= currentRevision) {
|
|
378
|
+
return {
|
|
379
|
+
applied: false,
|
|
380
|
+
reason: "stale_revision",
|
|
381
|
+
current: limits(),
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
assertNonNegativeInteger(maxConcurrent, "limits.maxConcurrent");
|
|
385
|
+
assertNonNegativeInteger(maxQueue, "limits.maxQueue");
|
|
386
|
+
let nextBudget;
|
|
387
|
+
let nextHighPriorityReserve;
|
|
388
|
+
if (budget) {
|
|
389
|
+
if (nextTokenBudget === undefined) {
|
|
390
|
+
throw new Error("limits.tokenBudget is required because tokenBudget was configured at construction");
|
|
391
|
+
}
|
|
392
|
+
nextBudget = nextTokenBudget.budget;
|
|
393
|
+
nextHighPriorityReserve = nextTokenBudget.highPriorityReserve;
|
|
394
|
+
assertNonNegativeInteger(nextBudget, "limits.tokenBudget.budget");
|
|
395
|
+
assertNonNegativeInteger(nextHighPriorityReserve, "limits.tokenBudget.highPriorityReserve");
|
|
396
|
+
}
|
|
397
|
+
else if (nextTokenBudget !== undefined) {
|
|
398
|
+
throw new Error("limits.tokenBudget must be omitted because tokenBudget was not configured at construction");
|
|
399
|
+
}
|
|
400
|
+
const previous = limits();
|
|
401
|
+
// Install every LLM-layer value before pumping the concurrency queue.
|
|
402
|
+
// Promise continuations from admitted waiters run only after this
|
|
403
|
+
// synchronous operation returns, so they observe one coherent revision.
|
|
404
|
+
currentRevision = revision;
|
|
405
|
+
if (budget) {
|
|
406
|
+
currentBudget = nextBudget;
|
|
407
|
+
currentHighPriorityReserve = nextHighPriorityReserve;
|
|
408
|
+
}
|
|
409
|
+
bulkhead.applyLimits({ maxConcurrent, maxQueue });
|
|
410
|
+
const current = limits();
|
|
411
|
+
emit("reconfigure", { previous, current });
|
|
412
|
+
return { applied: true, previous, current };
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* Backward-compatible budget-only setter.
|
|
271
416
|
*
|
|
272
|
-
*
|
|
273
|
-
*
|
|
274
|
-
*
|
|
275
|
-
* - **Lowering below `inFlightTokens` is legal — shrink by attrition.**
|
|
276
|
-
* No in-flight work is revoked or cancelled. New admissions reject
|
|
277
|
-
* with `"budget_limit"` until enough in-flight work releases to bring
|
|
278
|
-
* `inFlightTokens` back under the new ceiling. This mirrors the
|
|
279
|
-
* library's existing overrun tolerance (`inFlightTokens` can already
|
|
280
|
-
* exceed `budget` via `reportUsage()` overrun) — over-budget in-flight
|
|
281
|
-
* state is an established, intentional condition, not an invariant
|
|
282
|
-
* violation.
|
|
283
|
-
* - **Throws if `tokenBudget` was never configured.** An explicit error
|
|
284
|
-
* beats a silent no-op — there is no budget ceiling to adjust.
|
|
285
|
-
* - **Validation:** `tokens` must be a non-negative integer.
|
|
417
|
+
* This is implemented as a complete local reconfiguration at
|
|
418
|
+
* `currentRevision + 1`. Externally managed deployments should use
|
|
419
|
+
* `applyLimits()` exclusively so one authority owns the revision stream.
|
|
286
420
|
*/
|
|
287
421
|
function setBudget(tokens) {
|
|
288
422
|
if (!budget) {
|
|
289
423
|
throw new Error("setBudget requires tokenBudget to be configured at construction");
|
|
290
424
|
}
|
|
291
425
|
assertNonNegativeInteger(tokens, "tokens");
|
|
292
|
-
|
|
426
|
+
if (currentRevision >= Number.MAX_SAFE_INTEGER) {
|
|
427
|
+
throw new Error("cannot advance admission-limit revision beyond MAX_SAFE_INTEGER");
|
|
428
|
+
}
|
|
429
|
+
const current = limits();
|
|
430
|
+
applyLimits({
|
|
431
|
+
revision: currentRevision + 1,
|
|
432
|
+
maxConcurrent: current.maxConcurrent,
|
|
433
|
+
maxQueue: current.maxQueue,
|
|
434
|
+
tokenBudget: {
|
|
435
|
+
budget: tokens,
|
|
436
|
+
highPriorityReserve: currentHighPriorityReserve,
|
|
437
|
+
},
|
|
438
|
+
});
|
|
293
439
|
}
|
|
294
440
|
function normalizeAcquireOptions(ao) {
|
|
295
441
|
const normalized = {};
|
|
@@ -305,7 +451,9 @@ export function createLLMBulkhead(opts) {
|
|
|
305
451
|
function noteDedupWaitRejection(request, reason) {
|
|
306
452
|
noteLLMReject(reason);
|
|
307
453
|
emit("reject", { request, reason });
|
|
308
|
-
|
|
454
|
+
const error = new LLMBulkheadRejectedError(reason);
|
|
455
|
+
dedupWaitErrors.add(error);
|
|
456
|
+
return error;
|
|
309
457
|
}
|
|
310
458
|
/**
|
|
311
459
|
* Deliver a shared in-flight result to a deduplication follower.
|
|
@@ -536,10 +684,8 @@ export function createLLMBulkhead(opts) {
|
|
|
536
684
|
};
|
|
537
685
|
}
|
|
538
686
|
// ---- Internal acquire ----
|
|
539
|
-
async function _acquire(request, ao) {
|
|
540
|
-
const priority =
|
|
541
|
-
const parts = resolveReservation(request, ao.reservation);
|
|
542
|
-
const reserved = parts?.reserved ?? 0;
|
|
687
|
+
async function _acquire(request, ao, resolved = resolveAdmission(request, ao)) {
|
|
688
|
+
const { priority, parts, reserved } = resolved;
|
|
543
689
|
const rejectWith = (reason) => {
|
|
544
690
|
const detail = buildRejectDetail(reserved, priority);
|
|
545
691
|
noteLLMReject(reason);
|
|
@@ -607,32 +753,138 @@ export function createLLMBulkhead(opts) {
|
|
|
607
753
|
* request now throws even when the bulkhead is closed.
|
|
608
754
|
*/
|
|
609
755
|
function wouldAdmit(request, opts = {}) {
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
756
|
+
return wouldAdmitResolved(resolveAdmission(request, opts), opts.detail === true);
|
|
757
|
+
}
|
|
758
|
+
function shouldBypass(reason, configured) {
|
|
759
|
+
return (SHADOWABLE_REASONS.has(reason) &&
|
|
760
|
+
configured.has(reason));
|
|
761
|
+
}
|
|
762
|
+
async function runBypassed(request, fn, opts, admission, reason, detail, raced) {
|
|
763
|
+
const hardReason = opts.signal?.aborted
|
|
764
|
+
? "aborted"
|
|
765
|
+
: bulkhead.stats().closed
|
|
766
|
+
? "shutdown"
|
|
767
|
+
: undefined;
|
|
768
|
+
if (hardReason !== undefined) {
|
|
769
|
+
const hardDetail = buildRejectDetail(admission.reserved, admission.priority);
|
|
770
|
+
noteLLMReject(hardReason);
|
|
771
|
+
emit("reject", { request, reason: hardReason, detail: hardDetail });
|
|
772
|
+
throw new LLMBulkheadRejectedError(hardReason, hardDetail);
|
|
773
|
+
}
|
|
774
|
+
const admissionId = `shadow-${randomUUID()}`;
|
|
775
|
+
const reservation = admission.parts === null
|
|
776
|
+
? null
|
|
777
|
+
: Object.freeze({ ...admission.parts });
|
|
778
|
+
let reported;
|
|
779
|
+
let usageSequence = 0;
|
|
780
|
+
let settled = false;
|
|
781
|
+
observeBypassed++;
|
|
782
|
+
if (raced)
|
|
783
|
+
observeRaceBypassed++;
|
|
784
|
+
observeBypassedByReason[reason] =
|
|
785
|
+
(observeBypassedByReason[reason] ?? 0) + 1;
|
|
786
|
+
emit("bypass", {
|
|
787
|
+
request,
|
|
788
|
+
admissionId,
|
|
789
|
+
priority: admission.priority,
|
|
790
|
+
reason,
|
|
791
|
+
...(detail !== undefined && { detail }),
|
|
792
|
+
reservation,
|
|
793
|
+
raced,
|
|
794
|
+
});
|
|
795
|
+
const snapshot = () => {
|
|
796
|
+
const consumed = reported ? reported.input + reported.output : 0;
|
|
797
|
+
const outputCap = admission.parts?.maxOutput ?? null;
|
|
798
|
+
return {
|
|
799
|
+
admissionId,
|
|
800
|
+
sequence: usageSequence,
|
|
801
|
+
reserved: admission.reserved,
|
|
802
|
+
held: 0,
|
|
803
|
+
consumed,
|
|
804
|
+
outputCap,
|
|
805
|
+
outputRemaining: outputCap === null
|
|
806
|
+
? null
|
|
807
|
+
: Math.max(0, outputCap - (reported?.output ?? 0)),
|
|
808
|
+
overReservation: admission.parts !== null && consumed > admission.parts.reserved,
|
|
809
|
+
};
|
|
810
|
+
};
|
|
811
|
+
const reportUsage = (usage) => {
|
|
812
|
+
const valid = validateTokenUsage(usage);
|
|
813
|
+
const previous = reported;
|
|
814
|
+
reported = previous
|
|
815
|
+
? {
|
|
816
|
+
input: Math.max(previous.input, valid.input),
|
|
817
|
+
output: Math.max(previous.output, valid.output),
|
|
818
|
+
}
|
|
819
|
+
: valid;
|
|
820
|
+
const changed = previous === undefined ||
|
|
821
|
+
reported.input !== previous.input ||
|
|
822
|
+
reported.output !== previous.output;
|
|
823
|
+
if (!settled && changed) {
|
|
824
|
+
usageSequence++;
|
|
825
|
+
const current = snapshot();
|
|
826
|
+
emit("bypassUsage", {
|
|
827
|
+
request,
|
|
828
|
+
admissionId,
|
|
829
|
+
priority: admission.priority,
|
|
830
|
+
reason,
|
|
831
|
+
sequence: usageSequence,
|
|
832
|
+
reservation,
|
|
833
|
+
usage: { ...reported },
|
|
834
|
+
outputCap: current.outputCap,
|
|
835
|
+
outputRemaining: current.outputRemaining,
|
|
836
|
+
overReservation: current.overReservation,
|
|
837
|
+
});
|
|
616
838
|
}
|
|
617
|
-
return
|
|
839
|
+
return snapshot();
|
|
618
840
|
};
|
|
619
|
-
const
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
841
|
+
const context = {
|
|
842
|
+
admissionId,
|
|
843
|
+
reservation,
|
|
844
|
+
admission: "bypassed",
|
|
845
|
+
bypassReason: reason,
|
|
846
|
+
...(detail !== undefined && { bypassDetail: detail }),
|
|
847
|
+
reportUsage,
|
|
848
|
+
};
|
|
849
|
+
const finish = (usage) => {
|
|
850
|
+
if (settled)
|
|
851
|
+
return;
|
|
852
|
+
settled = true;
|
|
853
|
+
if (usage !== undefined) {
|
|
854
|
+
observeUsageReported++;
|
|
855
|
+
observeTotalInputTokens += usage.input;
|
|
856
|
+
observeTotalOutputTokens += usage.output;
|
|
857
|
+
}
|
|
858
|
+
emit("bypassRelease", {
|
|
859
|
+
request,
|
|
860
|
+
admissionId,
|
|
861
|
+
priority: admission.priority,
|
|
862
|
+
reason,
|
|
863
|
+
reservation,
|
|
864
|
+
usageSequence,
|
|
865
|
+
...(usage !== undefined && { usage }),
|
|
866
|
+
});
|
|
867
|
+
};
|
|
868
|
+
try {
|
|
869
|
+
const result = await fn(opts.signal, context);
|
|
870
|
+
let finalUsage;
|
|
871
|
+
if (opts.getUsage !== undefined) {
|
|
872
|
+
try {
|
|
873
|
+
const extracted = opts.getUsage(result);
|
|
874
|
+
finalUsage =
|
|
875
|
+
extracted === undefined ? undefined : validateTokenUsage(extracted);
|
|
876
|
+
}
|
|
877
|
+
catch {
|
|
878
|
+
// A bad extractor must not turn observed work into a failure.
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
finish(finalUsage ?? reported);
|
|
882
|
+
return result;
|
|
628
883
|
}
|
|
629
|
-
|
|
630
|
-
|
|
884
|
+
catch (error) {
|
|
885
|
+
finish(reported);
|
|
886
|
+
throw error;
|
|
631
887
|
}
|
|
632
|
-
return withDetail({
|
|
633
|
-
admit: false,
|
|
634
|
-
reason: base.maxQueue > 0 ? "queue_limit" : "concurrency_limit",
|
|
635
|
-
});
|
|
636
888
|
}
|
|
637
889
|
/**
|
|
638
890
|
* Primary API. Acquire → call `fn` → release, automatically.
|
|
@@ -651,7 +903,9 @@ export function createLLMBulkhead(opts) {
|
|
|
651
903
|
* timeout) does not apply to that wait.
|
|
652
904
|
*/
|
|
653
905
|
async function run(request, fn, ao = {}) {
|
|
654
|
-
const { getUsage, dedupScope, dedup: perCallDedup, ...acquireOpts } = ao;
|
|
906
|
+
const { getUsage, mode: requestedMode, shadowReasons: requestedShadowReasons, dedupScope, dedup: perCallDedup, ...acquireOpts } = ao;
|
|
907
|
+
const mode = resolveAdmissionMode(requestedMode);
|
|
908
|
+
const shadowReasons = resolveShadowReasons(requestedShadowReasons);
|
|
655
909
|
// ---- Deduplication ----
|
|
656
910
|
let dedupKey = "";
|
|
657
911
|
if (dedup.enabled && perCallDedup !== false) {
|
|
@@ -674,7 +928,21 @@ export function createLLMBulkhead(opts) {
|
|
|
674
928
|
if (existing) {
|
|
675
929
|
dedupHits++;
|
|
676
930
|
emit("dedup", { request });
|
|
677
|
-
|
|
931
|
+
try {
|
|
932
|
+
return await waitForSharedDedup(existing, request, acquireOpts);
|
|
933
|
+
}
|
|
934
|
+
catch (error) {
|
|
935
|
+
if (mode === "observe" &&
|
|
936
|
+
error instanceof LLMBulkheadRejectedError &&
|
|
937
|
+
dedupWaitErrors.has(error) &&
|
|
938
|
+
shouldBypass(error.reason, shadowReasons)) {
|
|
939
|
+
return runBypassed(request, fn, {
|
|
940
|
+
...(ao.signal !== undefined && { signal: ao.signal }),
|
|
941
|
+
...(getUsage !== undefined && { getUsage }),
|
|
942
|
+
}, resolveAdmission(request, acquireOpts), error.reason, error.detail, false);
|
|
943
|
+
}
|
|
944
|
+
throw error;
|
|
945
|
+
}
|
|
678
946
|
}
|
|
679
947
|
deferred = createDeferred();
|
|
680
948
|
resultPromise = deferred.promise;
|
|
@@ -691,14 +959,42 @@ export function createLLMBulkhead(opts) {
|
|
|
691
959
|
};
|
|
692
960
|
void deferred.promise.then(cleanup, cleanup);
|
|
693
961
|
}
|
|
962
|
+
const publish = (work) => {
|
|
963
|
+
if (deferred) {
|
|
964
|
+
void work.then((value) => deferred.resolve(value), (error) => deferred.reject(error));
|
|
965
|
+
return resultPromise;
|
|
966
|
+
}
|
|
967
|
+
return work;
|
|
968
|
+
};
|
|
694
969
|
try {
|
|
695
|
-
|
|
970
|
+
let resolved;
|
|
971
|
+
let advisory;
|
|
972
|
+
if (mode === "observe") {
|
|
973
|
+
resolved = resolveAdmission(request, acquireOpts);
|
|
974
|
+
advisory = wouldAdmitResolved(resolved, true);
|
|
975
|
+
if (!advisory.admit &&
|
|
976
|
+
advisory.reason !== undefined &&
|
|
977
|
+
shouldBypass(advisory.reason, shadowReasons)) {
|
|
978
|
+
return publish(runBypassed(request, fn, {
|
|
979
|
+
...(ao.signal !== undefined && { signal: ao.signal }),
|
|
980
|
+
...(getUsage !== undefined && { getUsage }),
|
|
981
|
+
}, resolved, advisory.reason, advisory.detail, false));
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
const r = await _acquire(request, acquireOpts, resolved);
|
|
696
985
|
if (!r.ok) {
|
|
986
|
+
if (mode === "observe" && shouldBypass(r.reason, shadowReasons)) {
|
|
987
|
+
return publish(runBypassed(request, fn, {
|
|
988
|
+
...(ao.signal !== undefined && { signal: ao.signal }),
|
|
989
|
+
...(getUsage !== undefined && { getUsage }),
|
|
990
|
+
}, resolved ?? resolveAdmission(request, acquireOpts), r.reason, r.detail, advisory?.admit === true));
|
|
991
|
+
}
|
|
697
992
|
throw new LLMBulkheadRejectedError(r.reason, r.detail);
|
|
698
993
|
}
|
|
699
994
|
const ctx = {
|
|
700
995
|
admissionId: r.admissionId,
|
|
701
996
|
reservation: r.reservation,
|
|
997
|
+
admission: "admitted",
|
|
702
998
|
reportUsage: (usage) => r.token.reportUsage(usage),
|
|
703
999
|
};
|
|
704
1000
|
const work = (async () => {
|
|
@@ -725,11 +1021,7 @@ export function createLLMBulkhead(opts) {
|
|
|
725
1021
|
r.token.release(usage);
|
|
726
1022
|
return result;
|
|
727
1023
|
})();
|
|
728
|
-
|
|
729
|
-
void work.then((v) => deferred.resolve(v), (e) => deferred.reject(e));
|
|
730
|
-
return resultPromise;
|
|
731
|
-
}
|
|
732
|
-
return work;
|
|
1024
|
+
return publish(work);
|
|
733
1025
|
}
|
|
734
1026
|
catch (err) {
|
|
735
1027
|
if (deferred) {
|
|
@@ -743,6 +1035,7 @@ export function createLLMBulkhead(opts) {
|
|
|
743
1035
|
function stats() {
|
|
744
1036
|
const base = bulkhead.stats();
|
|
745
1037
|
const result = {
|
|
1038
|
+
limits: limits(),
|
|
746
1039
|
bulkhead: base,
|
|
747
1040
|
llm: {
|
|
748
1041
|
admitted: llmAdmitted,
|
|
@@ -760,7 +1053,17 @@ export function createLLMBulkhead(opts) {
|
|
|
760
1053
|
totalConsumed,
|
|
761
1054
|
totalRefunded,
|
|
762
1055
|
totalOverrun,
|
|
763
|
-
highPriorityReserve,
|
|
1056
|
+
highPriorityReserve: currentHighPriorityReserve,
|
|
1057
|
+
};
|
|
1058
|
+
}
|
|
1059
|
+
if (observeBypassed > 0) {
|
|
1060
|
+
result.observe = {
|
|
1061
|
+
bypassed: observeBypassed,
|
|
1062
|
+
raceBypassed: observeRaceBypassed,
|
|
1063
|
+
bypassedByReason: { ...observeBypassedByReason },
|
|
1064
|
+
usageReported: observeUsageReported,
|
|
1065
|
+
totalInputTokens: observeTotalInputTokens,
|
|
1066
|
+
totalOutputTokens: observeTotalOutputTokens,
|
|
764
1067
|
};
|
|
765
1068
|
}
|
|
766
1069
|
if (dedup.enabled) {
|
|
@@ -826,6 +1129,8 @@ export function createLLMBulkhead(opts) {
|
|
|
826
1129
|
run,
|
|
827
1130
|
wouldAdmit,
|
|
828
1131
|
stats,
|
|
1132
|
+
limits,
|
|
1133
|
+
applyLimits,
|
|
829
1134
|
setBudget,
|
|
830
1135
|
close,
|
|
831
1136
|
drain,
|