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