async-bulkhead-llm 3.7.0 → 3.8.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.
Files changed (56) hide show
  1. package/README.md +145 -3
  2. package/dist/cjs/adaptive.cjs +128 -0
  3. package/dist/cjs/adaptive.cjs.map +1 -0
  4. package/dist/cjs/bulkhead.cjs +838 -0
  5. package/dist/cjs/bulkhead.cjs.map +1 -0
  6. package/dist/cjs/dedup.cjs +111 -0
  7. package/dist/cjs/dedup.cjs.map +1 -0
  8. package/dist/cjs/errors.cjs +16 -0
  9. package/dist/cjs/errors.cjs.map +1 -0
  10. package/dist/cjs/estimators.cjs +205 -0
  11. package/dist/cjs/estimators.cjs.map +1 -0
  12. package/dist/cjs/index.cjs +27 -1123
  13. package/dist/cjs/index.cjs.map +1 -1
  14. package/dist/cjs/profiles.cjs +16 -0
  15. package/dist/cjs/profiles.cjs.map +1 -0
  16. package/dist/cjs/types.cjs +3 -0
  17. package/dist/cjs/types.cjs.map +1 -0
  18. package/dist/cjs/validation.cjs +39 -0
  19. package/dist/cjs/validation.cjs.map +1 -0
  20. package/dist/esm/adaptive.js +125 -0
  21. package/dist/esm/adaptive.js.map +1 -0
  22. package/dist/esm/bulkhead.js +835 -0
  23. package/dist/esm/bulkhead.js.map +1 -0
  24. package/dist/esm/dedup.js +106 -0
  25. package/dist/esm/dedup.js.map +1 -0
  26. package/dist/esm/errors.js +12 -0
  27. package/dist/esm/errors.js.map +1 -0
  28. package/dist/esm/estimators.js +200 -0
  29. package/dist/esm/estimators.js.map +1 -0
  30. package/dist/esm/index.js +19 -1117
  31. package/dist/esm/index.js.map +1 -1
  32. package/dist/esm/profiles.js +13 -0
  33. package/dist/esm/profiles.js.map +1 -0
  34. package/dist/esm/types.js +2 -0
  35. package/dist/esm/types.js.map +1 -0
  36. package/dist/esm/validation.js +32 -0
  37. package/dist/esm/validation.js.map +1 -0
  38. package/dist/types/adaptive.d.ts +109 -0
  39. package/dist/types/adaptive.d.ts.map +1 -0
  40. package/dist/types/bulkhead.d.ts +59 -0
  41. package/dist/types/bulkhead.d.ts.map +1 -0
  42. package/dist/types/dedup.d.ts +32 -0
  43. package/dist/types/dedup.d.ts.map +1 -0
  44. package/dist/types/errors.d.ts +9 -0
  45. package/dist/types/errors.d.ts.map +1 -0
  46. package/dist/types/estimators.d.ts +91 -0
  47. package/dist/types/estimators.d.ts.map +1 -0
  48. package/dist/types/index.d.ts +27 -660
  49. package/dist/types/index.d.ts.map +1 -1
  50. package/dist/types/profiles.d.ts +11 -0
  51. package/dist/types/profiles.d.ts.map +1 -0
  52. package/dist/types/types.d.ts +566 -0
  53. package/dist/types/types.d.ts.map +1 -0
  54. package/dist/types/validation.d.ts +12 -0
  55. package/dist/types/validation.d.ts.map +1 -0
  56. package/package.json +1 -1
@@ -0,0 +1,838 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
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
+ const node_crypto_1 = require("node:crypto");
11
+ const errors_js_1 = require("./errors.cjs");
12
+ const profiles_js_1 = require("./profiles.cjs");
13
+ const estimators_js_1 = require("./estimators.cjs");
14
+ const validation_js_1 = require("./validation.cjs");
15
+ const dedup_js_1 = require("./dedup.cjs");
16
+ // ────────────────────────────────────────────
17
+ // Option resolution
18
+ // ────────────────────────────────────────────
19
+ function resolvePreset(profile) {
20
+ if (!profile)
21
+ return {};
22
+ if (typeof profile === "string")
23
+ return profiles_js_1.PROFILES[profile];
24
+ return profile;
25
+ }
26
+ // ────────────────────────────────────────────
27
+ // createLLMBulkhead
28
+ // ────────────────────────────────────────────
29
+ function createLLMBulkhead(opts) {
30
+ // ---- Validate ----
31
+ if (typeof opts.model !== "string" || opts.model.trim() === "") {
32
+ throw new Error("model must be a non-empty string");
33
+ }
34
+ (0, validation_js_1.assertPositiveInteger)(opts.maxConcurrent, "maxConcurrent");
35
+ // ---- Resolve profile defaults ----
36
+ const preset = resolvePreset(opts.profile);
37
+ const maxQueue = opts.maxQueue ?? preset.maxQueue ?? 0;
38
+ const timeoutMs = opts.timeoutMs ?? preset.timeoutMs;
39
+ (0, validation_js_1.assertNonNegativeInteger)(maxQueue, "maxQueue");
40
+ (0, validation_js_1.assertOptionalNonNegativeInteger)(timeoutMs, "timeoutMs");
41
+ if (opts.tokenBudget) {
42
+ (0, validation_js_1.assertNonNegativeInteger)(opts.tokenBudget.budget, "tokenBudget.budget");
43
+ (0, validation_js_1.assertOptionalNonNegativeInteger)(opts.tokenBudget.outputCap, "tokenBudget.outputCap");
44
+ (0, validation_js_1.assertOptionalNonNegativeInteger)(opts.tokenBudget.highPriorityReserve, "tokenBudget.highPriorityReserve");
45
+ if (opts.tokenBudget.highPriorityReserve !== undefined &&
46
+ opts.tokenBudget.highPriorityReserve > opts.tokenBudget.budget) {
47
+ throw new Error("tokenBudget.highPriorityReserve must be <= tokenBudget.budget");
48
+ }
49
+ }
50
+ // ---- Internal bulkhead from async-bulkhead-ts ----
51
+ const bulkhead = (0, async_bulkhead_ts_1.createBulkhead)({
52
+ maxConcurrent: opts.maxConcurrent,
53
+ maxQueue,
54
+ });
55
+ // ---- Token budget state ----
56
+ const budget = opts.tokenBudget;
57
+ const estimator = budget?.estimator ??
58
+ (0, estimators_js_1.createModelAwareTokenEstimator)(undefined, {
59
+ defaultModel: opts.model,
60
+ outputCap: budget?.outputCap,
61
+ });
62
+ const highPriorityReserve = budget?.highPriorityReserve ?? 0;
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
+ */
71
+ let currentBudget = budget?.budget;
72
+ let inFlightTokens = 0;
73
+ let totalReserved = 0;
74
+ let totalConsumed = 0;
75
+ let totalRefunded = 0;
76
+ let totalOverrun = 0;
77
+ let llmAdmitted = 0;
78
+ let llmReleased = 0;
79
+ let llmRejected = 0;
80
+ const llmRejectedByReason = {};
81
+ // ---- Deduplication state ----
82
+ const dedup = (0, dedup_js_1.resolveDedup)(opts.deduplication);
83
+ const dedupMap = new Map();
84
+ let dedupHits = 0;
85
+ // ---- Event emitter state ----
86
+ const listeners = {
87
+ admit: new Set(),
88
+ reject: new Set(),
89
+ release: new Set(),
90
+ usage: new Set(),
91
+ dedup: new Set(),
92
+ };
93
+ function emit(event, payload) {
94
+ for (const fn of listeners[event]) {
95
+ try {
96
+ fn(payload);
97
+ }
98
+ catch {
99
+ // listeners must not throw into the bulkhead
100
+ }
101
+ }
102
+ }
103
+ function noteLLMAdmit() {
104
+ llmAdmitted++;
105
+ }
106
+ function noteLLMRelease() {
107
+ llmReleased++;
108
+ }
109
+ function noteLLMReject(reason) {
110
+ llmRejected++;
111
+ llmRejectedByReason[reason] =
112
+ (llmRejectedByReason[reason] ?? 0) + 1;
113
+ }
114
+ // ---- Internal helpers ----
115
+ function createDeferred() {
116
+ let resolve;
117
+ let reject;
118
+ const promise = new Promise((res, rej) => {
119
+ resolve = res;
120
+ reject = rej;
121
+ });
122
+ return { promise, resolve, reject };
123
+ }
124
+ function estimateParts(request) {
125
+ return resolveReservation(request, undefined);
126
+ }
127
+ /**
128
+ * Reservation used for admission: the caller's per-call `reservation`
129
+ * override verbatim when provided, otherwise the estimator's output.
130
+ * Both paths validate as non-negative integers. `null` when
131
+ * `tokenBudget` is disabled (no reservation participates then, and
132
+ * the override is deliberately ignored).
133
+ */
134
+ function resolveReservation(request, override) {
135
+ (0, validation_js_1.assertOptionalNonNegativeInteger)(request.max_tokens, "request.max_tokens");
136
+ if (!budget)
137
+ return null;
138
+ if (override !== undefined) {
139
+ const reserved = (0, validation_js_1.validateTokenEstimate)(override);
140
+ // v3.8: `reserved`, when present (e.g. an `estimate()` result passed
141
+ // back verbatim), is a consistency check — not an independent input.
142
+ if (override.reserved !== undefined) {
143
+ (0, validation_js_1.assertNonNegativeInteger)(override.reserved, "reservation.reserved");
144
+ if (override.reserved !== reserved) {
145
+ throw new Error(`reservation.reserved (${override.reserved}) must equal ` +
146
+ `reservation.input + reservation.maxOutput (${reserved})`);
147
+ }
148
+ }
149
+ return {
150
+ input: override.input,
151
+ maxOutput: override.maxOutput,
152
+ reserved,
153
+ };
154
+ }
155
+ const estimate = estimator(request);
156
+ const reserved = (0, validation_js_1.validateTokenEstimate)(estimate);
157
+ return {
158
+ input: estimate.input,
159
+ maxOutput: estimate.maxOutput,
160
+ reserved,
161
+ };
162
+ }
163
+ /**
164
+ * Preview the exact token reservation that admission will calculate.
165
+ *
166
+ * This calls the same estimator and validation path as `acquire()`,
167
+ * `run()`, and `wouldAdmit()`. It does not reserve capacity. Returns
168
+ * `null` when `tokenBudget` is disabled because admission does not hold
169
+ * tokens in that mode.
170
+ *
171
+ * Custom estimators should be deterministic: if either the request or
172
+ * estimator output changes between `estimate()` and admission, the later
173
+ * admission will correctly use the newly calculated value.
174
+ *
175
+ * A per-call `reservation` override passed to `acquire()` / `run()` /
176
+ * `wouldAdmit()` bypasses the estimator and is NOT reflected here —
177
+ * `estimate()` always previews the estimator path.
178
+ */
179
+ function estimate(request) {
180
+ const parts = estimateParts(request);
181
+ return parts === null ? null : { ...parts };
182
+ }
183
+ function resolvePriority(priority) {
184
+ if (priority === undefined)
185
+ return "normal";
186
+ if (priority !== "high" && priority !== "normal") {
187
+ throw new Error(`priority must be "high" or "normal"`);
188
+ }
189
+ return priority;
190
+ }
191
+ /**
192
+ * Budget ceiling applicable to a request at the given priority.
193
+ *
194
+ * Construction validates `0 <= highPriorityReserve <= budget` (see the
195
+ * `tokenBudget` validation block above) — that check catches config
196
+ * typos once, at startup. It intentionally does *not* run again here.
197
+ *
198
+ * `setBudget()` can lower `currentBudget` below `highPriorityReserve` at
199
+ * runtime (e.g. a lease-renewal ledger reporting a shrunk grant), and
200
+ * that is allowed, not re-validated. Rejecting a renewal-driven update
201
+ * would be wrong: the ledger's grant is reality — the bulkhead has no
202
+ * standing to refuse it. So `currentBudget` can legitimately end up
203
+ * smaller than `highPriorityReserve`.
204
+ *
205
+ * Consequence, deliberately embraced: `currentBudget! - highPriorityReserve`
206
+ * would go negative in that state, so it is clamped to `0` here. That
207
+ * means normal-priority admission is fully rejected (nothing fits under
208
+ * a `0` ceiling) while high-priority admission is still checked against
209
+ * the full (shrunk) `currentBudget` and can keep admitting whatever
210
+ * capacity remains. That is exactly the right degraded behavior — the
211
+ * entire purpose of `highPriorityReserve` is protecting interactive
212
+ * traffic when capacity is scarce, and capacity has never been scarcer
213
+ * than when the grant itself drops below the reserve.
214
+ */
215
+ function effectiveBudget(priority) {
216
+ if (!budget)
217
+ return Infinity;
218
+ return priority === "high"
219
+ ? currentBudget
220
+ : Math.max(0, currentBudget - highPriorityReserve);
221
+ }
222
+ /**
223
+ * Attempt token budget admission synchronously for a precomputed
224
+ * reservation. Returns false if the priority-adjusted ceiling is
225
+ * exceeded.
226
+ */
227
+ function tryReserveTokens(reserved, priority) {
228
+ if (!budget)
229
+ return true;
230
+ if (inFlightTokens + reserved > effectiveBudget(priority))
231
+ return false;
232
+ inFlightTokens += reserved;
233
+ totalReserved += reserved;
234
+ return true;
235
+ }
236
+ function releaseTokens(held, usage) {
237
+ let refunded = 0;
238
+ if (usage && held > 0) {
239
+ const actual = usage.input + usage.output;
240
+ totalConsumed += actual;
241
+ if (actual < held) {
242
+ refunded = held - actual;
243
+ totalRefunded += refunded;
244
+ }
245
+ }
246
+ inFlightTokens = Math.max(0, inFlightTokens - held);
247
+ return refunded;
248
+ }
249
+ /** Capacity snapshot for rejection results, events, and errors. */
250
+ function buildRejectDetail(requested, priority) {
251
+ const base = bulkhead.stats();
252
+ const detail = {
253
+ inFlight: base.inFlight,
254
+ pending: base.pending,
255
+ maxConcurrent: base.maxConcurrent,
256
+ maxQueue: base.maxQueue,
257
+ };
258
+ if (budget) {
259
+ const eff = effectiveBudget(priority);
260
+ detail.tokenBudget = {
261
+ budget: currentBudget,
262
+ inFlightTokens,
263
+ effectiveBudget: eff,
264
+ available: Math.max(0, eff - inFlightTokens),
265
+ requested,
266
+ };
267
+ }
268
+ return detail;
269
+ }
270
+ /**
271
+ * Update the token budget ceiling at runtime.
272
+ *
273
+ * Semantics (deliberate, not incidental):
274
+ *
275
+ * - **Raising takes effect immediately.** The very next admission check
276
+ * reads the new ceiling via `effectiveBudget()` — no caching to
277
+ * invalidate, no in-flight work touched.
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.
289
+ */
290
+ function setBudget(tokens) {
291
+ if (!budget) {
292
+ throw new Error("setBudget requires tokenBudget to be configured at construction");
293
+ }
294
+ (0, validation_js_1.assertNonNegativeInteger)(tokens, "tokens");
295
+ currentBudget = tokens;
296
+ }
297
+ function normalizeAcquireOptions(ao) {
298
+ const normalized = {};
299
+ if (ao.signal !== undefined)
300
+ normalized.signal = ao.signal;
301
+ const effectiveTimeoutMs = ao.timeoutMs ?? timeoutMs;
302
+ if (effectiveTimeoutMs !== undefined) {
303
+ (0, validation_js_1.assertNonNegativeInteger)(effectiveTimeoutMs, "timeoutMs");
304
+ normalized.timeoutMs = effectiveTimeoutMs;
305
+ }
306
+ return normalized;
307
+ }
308
+ function noteDedupWaitRejection(request, reason) {
309
+ noteLLMReject(reason);
310
+ emit("reject", { request, reason });
311
+ return new errors_js_1.LLMBulkheadRejectedError(reason);
312
+ }
313
+ /**
314
+ * Deliver a shared in-flight result to a deduplication follower.
315
+ *
316
+ * - With a `shareResult` hook: the hook decides what the follower
317
+ * receives (called for every follower, safe results included).
318
+ * Hook exceptions propagate to the follower as-is.
319
+ * - Without a hook: single-consumer values (streams, `Response`
320
+ * bodies, async iterables) are refused with
321
+ * `"unshareable_result"` instead of being handed out by
322
+ * reference — a locked stream downstream is a silent correctness
323
+ * bug; a typed rejection at the bulkhead is actionable.
324
+ *
325
+ * The leader never passes through this function.
326
+ */
327
+ function deliverShared(value, request) {
328
+ if (dedup.shareResult) {
329
+ return dedup.shareResult(value);
330
+ }
331
+ if ((0, dedup_js_1.isUnsafeToShare)(value)) {
332
+ throw noteDedupWaitRejection(request, "unshareable_result");
333
+ }
334
+ return value;
335
+ }
336
+ /**
337
+ * Wait on another caller's in-flight shared call.
338
+ *
339
+ * v3.4: only an *explicitly passed* per-call `timeoutMs` caps this
340
+ * wait. The bulkhead-level `timeoutMs` default is deliberately NOT
341
+ * applied here — it is documented as a *queue-wait* timeout, and a
342
+ * follower is not queued; it is waiting on a call that is already
343
+ * running. Applying the default (e.g. the `batch` profile's 30s) made
344
+ * every follower of a slow LLM call fail with `"timeout"` while the
345
+ * leader succeeded, defeating deduplication exactly when calls are
346
+ * long. `signal` continues to apply as before.
347
+ */
348
+ function waitForSharedDedup(shared, request, ao) {
349
+ const signal = ao.signal;
350
+ const effectiveTimeoutMs = ao.timeoutMs;
351
+ if (effectiveTimeoutMs !== undefined) {
352
+ (0, validation_js_1.assertNonNegativeInteger)(effectiveTimeoutMs, "timeoutMs");
353
+ }
354
+ if (signal?.aborted) {
355
+ return Promise.reject(noteDedupWaitRejection(request, "aborted"));
356
+ }
357
+ if (signal === undefined && effectiveTimeoutMs === undefined) {
358
+ return shared.then((value) => deliverShared(value, request));
359
+ }
360
+ return new Promise((resolve, reject) => {
361
+ let timeoutId;
362
+ let settled = false;
363
+ const cleanup = () => {
364
+ if (timeoutId !== undefined)
365
+ clearTimeout(timeoutId);
366
+ if (signal !== undefined) {
367
+ signal.removeEventListener("abort", onAbort);
368
+ }
369
+ };
370
+ const settle = (fn) => {
371
+ if (settled)
372
+ return;
373
+ settled = true;
374
+ cleanup();
375
+ fn();
376
+ };
377
+ const onAbort = () => {
378
+ settle(() => {
379
+ reject(noteDedupWaitRejection(request, "aborted"));
380
+ });
381
+ };
382
+ if (signal !== undefined) {
383
+ signal.addEventListener("abort", onAbort, { once: true });
384
+ }
385
+ if (effectiveTimeoutMs !== undefined) {
386
+ timeoutId = setTimeout(() => {
387
+ settle(() => {
388
+ reject(noteDedupWaitRejection(request, "timeout"));
389
+ });
390
+ }, effectiveTimeoutMs);
391
+ }
392
+ void shared.then((value) => settle(() => {
393
+ try {
394
+ resolve(deliverShared(value, request));
395
+ }
396
+ catch (err) {
397
+ reject(err);
398
+ }
399
+ }), (err) => settle(() => reject(err)));
400
+ });
401
+ }
402
+ /**
403
+ * Wraps a base Token so that release() also returns the token
404
+ * reservation and optionally applies the refund, and so that
405
+ * streaming callers can report cumulative usage mid-flight.
406
+ */
407
+ function wrapToken(base, parts, request, admissionId, priority) {
408
+ let released = false;
409
+ /** Tokens currently held against the budget for this request. */
410
+ let held = parts?.reserved ?? 0;
411
+ /** Last reported cumulative usage (monotonically clamped). */
412
+ let reported;
413
+ /** Monotonic sequence of effective pre-release usage updates. */
414
+ let usageSequence = 0;
415
+ /** Public copy: callers cannot mutate internal accounting parts. */
416
+ const reservation = parts === null ? null : Object.freeze({ ...parts });
417
+ const snapshot = () => {
418
+ const consumed = reported
419
+ ? reported.input + reported.output
420
+ : 0;
421
+ const outputCap = parts ? parts.maxOutput : null;
422
+ return {
423
+ admissionId,
424
+ sequence: usageSequence,
425
+ reserved: parts?.reserved ?? 0,
426
+ held,
427
+ consumed,
428
+ outputCap,
429
+ outputRemaining: outputCap === null
430
+ ? null
431
+ : Math.max(0, outputCap - (reported?.output ?? 0)),
432
+ overReservation: parts ? consumed > parts.reserved : false,
433
+ };
434
+ };
435
+ const reportUsage = (usage) => {
436
+ const valid = (0, validation_js_1.validateTokenUsage)(usage);
437
+ const previousReported = reported;
438
+ // Clamp to monotonic non-decreasing per field — cumulative
439
+ // stream usage never shrinks; a lower report is stale.
440
+ reported = previousReported
441
+ ? {
442
+ input: Math.max(previousReported.input, valid.input),
443
+ output: Math.max(previousReported.output, valid.output),
444
+ }
445
+ : valid;
446
+ const usageChanged = previousReported === undefined ||
447
+ reported.input !== previousReported.input ||
448
+ reported.output !== previousReported.output;
449
+ const previousHeldTokens = held;
450
+ // Accounting only applies pre-release with a budget configured.
451
+ if (!released && parts && budget) {
452
+ // Hold = known input + the larger of (output ceiling, actual output).
453
+ // Keeps the full output reservation while refunding input
454
+ // over-estimates immediately; expands on output overrun.
455
+ const newHold = reported.input + Math.max(parts.maxOutput, reported.output);
456
+ const delta = newHold - held;
457
+ if (delta > 0) {
458
+ inFlightTokens += delta;
459
+ totalOverrun += delta;
460
+ }
461
+ else if (delta < 0) {
462
+ const refund = -delta;
463
+ inFlightTokens = Math.max(0, inFlightTokens - refund);
464
+ totalRefunded += refund;
465
+ }
466
+ held = newHold;
467
+ }
468
+ if (!released && usageChanged) {
469
+ usageSequence++;
470
+ }
471
+ const report = snapshot();
472
+ if (!released && usageChanged) {
473
+ emit("usage", {
474
+ request,
475
+ admissionId,
476
+ priority,
477
+ sequence: usageSequence,
478
+ reservedTokens: parts?.reserved ?? 0,
479
+ previousHeldTokens,
480
+ heldTokens: held,
481
+ deltaTokens: held - previousHeldTokens,
482
+ usage: { ...reported },
483
+ outputCap: report.outputCap,
484
+ outputRemaining: report.outputRemaining,
485
+ overReservation: report.overReservation,
486
+ });
487
+ }
488
+ return report;
489
+ };
490
+ return {
491
+ admissionId,
492
+ reservation,
493
+ reportUsage,
494
+ release(usage) {
495
+ if (released)
496
+ return;
497
+ released = true;
498
+ let validUsage;
499
+ let usageError;
500
+ if (usage !== undefined) {
501
+ try {
502
+ validUsage = (0, validation_js_1.validateTokenUsage)(usage);
503
+ }
504
+ catch (err) {
505
+ usageError = err;
506
+ }
507
+ }
508
+ // Fall back to the last mid-flight report when no (valid)
509
+ // explicit usage is provided at release.
510
+ if (validUsage === undefined && reported !== undefined) {
511
+ validUsage = reported;
512
+ }
513
+ try {
514
+ base.release();
515
+ }
516
+ finally {
517
+ // Zero `held` before returning tokens: nothing is held against
518
+ // the budget after release, and post-release `reportUsage()`
519
+ // snapshots must reflect that (previously they reported the
520
+ // stale pre-release hold).
521
+ const heldAtRelease = held;
522
+ held = 0;
523
+ const refunded = releaseTokens(heldAtRelease, validUsage);
524
+ noteLLMRelease();
525
+ emit("release", {
526
+ request,
527
+ admissionId,
528
+ priority,
529
+ reservedTokens: parts?.reserved ?? 0,
530
+ heldTokens: heldAtRelease,
531
+ refundedTokens: refunded,
532
+ usageSequence,
533
+ ...(validUsage !== undefined && { usage: validUsage }),
534
+ });
535
+ }
536
+ if (usageError !== undefined)
537
+ throw usageError;
538
+ },
539
+ };
540
+ }
541
+ // ---- Internal acquire ----
542
+ async function _acquire(request, ao) {
543
+ const priority = resolvePriority(ao.priority);
544
+ const parts = resolveReservation(request, ao.reservation);
545
+ const reserved = parts?.reserved ?? 0;
546
+ const rejectWith = (reason) => {
547
+ const detail = buildRejectDetail(reserved, priority);
548
+ noteLLMReject(reason);
549
+ emit("reject", { request, reason, detail });
550
+ return { ok: false, reason, detail };
551
+ };
552
+ // Token budget: pre-check before entering the queue.
553
+ if (budget && inFlightTokens + reserved > effectiveBudget(priority)) {
554
+ return rejectWith("budget_limit");
555
+ }
556
+ const mergedOptions = normalizeAcquireOptions(ao);
557
+ const r = await bulkhead.acquire(mergedOptions);
558
+ if (!r.ok) {
559
+ return rejectWith(r.reason);
560
+ }
561
+ // Post-admission: reserve the precomputed amount now.
562
+ if (!tryReserveTokens(reserved, priority)) {
563
+ r.token.release();
564
+ return rejectWith("budget_limit");
565
+ }
566
+ const admissionId = (0, node_crypto_1.randomUUID)();
567
+ const token = wrapToken(r.token, parts, request, admissionId, priority);
568
+ noteLLMAdmit();
569
+ emit("admit", { request, admissionId, priority, reservedTokens: reserved });
570
+ return {
571
+ ok: true,
572
+ admissionId,
573
+ reservation: token.reservation,
574
+ token,
575
+ };
576
+ }
577
+ // ---- Public API ----
578
+ /**
579
+ * Acquire a slot manually.
580
+ *
581
+ * The returned token accepts optional `TokenUsage` at release time
582
+ * to trigger the refund mechanism. For most use cases, prefer `run()`.
583
+ */
584
+ async function acquire(request, ao = {}) {
585
+ return _acquire(request, ao);
586
+ }
587
+ /**
588
+ * Advisory dry-run: would a request of this shape be admitted right
589
+ * now at the given priority?
590
+ *
591
+ * This is a snapshot for routing decisions (e.g. pick a different
592
+ * model pool). It does NOT reserve anything — the answer can change
593
+ * before a subsequent `acquire()`/`run()` lands. Never treat `true`
594
+ * as a guarantee.
595
+ *
596
+ * Accepts the same per-call `reservation` override as `acquire()` /
597
+ * `run()` (v3.7); pass the identical value to both for a consistent
598
+ * preview.
599
+ *
600
+ * v3.8: pass `detail: true` to also receive the same capacity
601
+ * snapshot (`LLMRejectDetail`) that real rejections carry — including
602
+ * on an `admit: true` answer, where it describes the capacity the
603
+ * request would be admitted against. Routing layers choosing between
604
+ * pools usually want these numbers, not just the boolean. Omitted by
605
+ * default so the result shape (and its cost) is unchanged for
606
+ * existing callers.
607
+ *
608
+ * v3.8: the request (and any `reservation` override) is validated
609
+ * before the shutdown check, matching `acquire()` — an invalid
610
+ * request now throws even when the bulkhead is closed.
611
+ */
612
+ function wouldAdmit(request, opts = {}) {
613
+ const priority = resolvePriority(opts.priority);
614
+ const parts = resolveReservation(request, opts.reservation);
615
+ const reserved = parts?.reserved ?? 0;
616
+ const withDetail = (result) => {
617
+ if (opts.detail === true) {
618
+ result.detail = buildRejectDetail(reserved, priority);
619
+ }
620
+ return result;
621
+ };
622
+ const base = bulkhead.stats();
623
+ if (base.closed) {
624
+ return withDetail({ admit: false, reason: "shutdown" });
625
+ }
626
+ if (budget && inFlightTokens + reserved > effectiveBudget(priority)) {
627
+ return withDetail({ admit: false, reason: "budget_limit" });
628
+ }
629
+ if (base.inFlight < base.maxConcurrent) {
630
+ return withDetail({ admit: true });
631
+ }
632
+ if (base.pending < base.maxQueue) {
633
+ return withDetail({ admit: true });
634
+ }
635
+ return withDetail({
636
+ admit: false,
637
+ reason: base.maxQueue > 0 ? "queue_limit" : "concurrency_limit",
638
+ });
639
+ }
640
+ /**
641
+ * Primary API. Acquire → call `fn` → release, automatically.
642
+ *
643
+ * Throws `LLMBulkheadRejectedError` on rejection.
644
+ *
645
+ * When `getUsage` is provided in options, it is called with the result
646
+ * of `fn` to extract actual token usage. The refund mechanism then
647
+ * returns the difference between the reservation and actual consumption
648
+ * to the budget.
649
+ *
650
+ * Deduplication (when enabled) applies to `run()` only; `acquire()`
651
+ * never deduplicates. A caller that joins an existing in-flight call
652
+ * is capped only by its own `signal` and an *explicitly passed*
653
+ * per-call `timeoutMs` — the bulkhead-level `timeoutMs` (a queue-wait
654
+ * timeout) does not apply to that wait.
655
+ */
656
+ async function run(request, fn, ao = {}) {
657
+ const { getUsage, dedupScope, dedup: perCallDedup, ...acquireOpts } = ao;
658
+ // ---- Deduplication ----
659
+ let dedupKey = "";
660
+ if (dedup.enabled && perCallDedup !== false) {
661
+ let rawKey;
662
+ try {
663
+ rawKey = dedup.keyFn(request);
664
+ }
665
+ catch {
666
+ rawKey = "";
667
+ }
668
+ // "" opts out; only real keys are scoped + hashed.
669
+ if (rawKey !== "") {
670
+ dedupKey = (0, dedup_js_1.hashDedupKey)(dedupScope ?? "", rawKey);
671
+ }
672
+ }
673
+ let deferred;
674
+ let resultPromise;
675
+ if (dedup.enabled && dedupKey !== "") {
676
+ const existing = dedupMap.get(dedupKey);
677
+ if (existing) {
678
+ dedupHits++;
679
+ emit("dedup", { request });
680
+ return waitForSharedDedup(existing, request, acquireOpts);
681
+ }
682
+ deferred = createDeferred();
683
+ resultPromise = deferred.promise;
684
+ dedupMap.set(dedupKey, deferred.promise);
685
+ const cleanup = () => {
686
+ try {
687
+ const p = dedupMap.get(dedupKey);
688
+ if (p === deferred.promise)
689
+ dedupMap.delete(dedupKey);
690
+ }
691
+ catch {
692
+ // never throw from cleanup
693
+ }
694
+ };
695
+ void deferred.promise.then(cleanup, cleanup);
696
+ }
697
+ try {
698
+ const r = await _acquire(request, acquireOpts);
699
+ if (!r.ok) {
700
+ throw new errors_js_1.LLMBulkheadRejectedError(r.reason, r.detail);
701
+ }
702
+ const ctx = {
703
+ admissionId: r.admissionId,
704
+ reservation: r.reservation,
705
+ reportUsage: (usage) => r.token.reportUsage(usage),
706
+ };
707
+ const work = (async () => {
708
+ let result;
709
+ try {
710
+ result = await fn(ao.signal, ctx);
711
+ }
712
+ catch (err) {
713
+ r.token.release(); // no usage on error
714
+ throw err;
715
+ }
716
+ // Extract usage for refund.
717
+ let usage;
718
+ if (getUsage) {
719
+ try {
720
+ const extracted = getUsage(result);
721
+ usage =
722
+ extracted === undefined ? undefined : (0, validation_js_1.validateTokenUsage)(extracted);
723
+ }
724
+ catch {
725
+ // bad getUsage must not break release
726
+ }
727
+ }
728
+ r.token.release(usage);
729
+ return result;
730
+ })();
731
+ if (deferred) {
732
+ void work.then((v) => deferred.resolve(v), (e) => deferred.reject(e));
733
+ return resultPromise;
734
+ }
735
+ return work;
736
+ }
737
+ catch (err) {
738
+ if (deferred) {
739
+ deferred.reject(err);
740
+ return resultPromise;
741
+ }
742
+ throw err;
743
+ }
744
+ }
745
+ /** Runtime stats. Optional fields are present only when the feature is enabled. */
746
+ function stats() {
747
+ const base = bulkhead.stats();
748
+ const result = {
749
+ bulkhead: base,
750
+ llm: {
751
+ admitted: llmAdmitted,
752
+ released: llmReleased,
753
+ rejected: llmRejected,
754
+ rejectedByReason: { ...llmRejectedByReason },
755
+ },
756
+ };
757
+ if (budget) {
758
+ result.tokenBudget = {
759
+ budget: currentBudget,
760
+ inFlightTokens,
761
+ available: Math.max(0, currentBudget - inFlightTokens),
762
+ totalReserved,
763
+ totalConsumed,
764
+ totalRefunded,
765
+ totalOverrun,
766
+ highPriorityReserve,
767
+ };
768
+ }
769
+ if (dedup.enabled) {
770
+ result.deduplication = {
771
+ active: dedupMap.size,
772
+ hits: dedupHits,
773
+ };
774
+ }
775
+ return result;
776
+ }
777
+ /**
778
+ * Stop admission permanently. All pending waiters in the underlying
779
+ * bulkhead are rejected with `'shutdown'`. Future `acquire`/`run`
780
+ * calls reject immediately. In-flight work is not interrupted.
781
+ */
782
+ function close() {
783
+ bulkhead.close();
784
+ }
785
+ function drain(opts) {
786
+ const timeoutMs = opts?.timeoutMs;
787
+ if (timeoutMs === undefined) {
788
+ return bulkhead.drain();
789
+ }
790
+ (0, validation_js_1.assertNonNegativeInteger)(timeoutMs, "timeoutMs");
791
+ return new Promise((resolve) => {
792
+ let settled = false;
793
+ const timer = setTimeout(() => {
794
+ if (settled)
795
+ return;
796
+ settled = true;
797
+ const base = bulkhead.stats();
798
+ resolve({
799
+ drained: false,
800
+ inFlight: base.inFlight,
801
+ pending: base.pending,
802
+ });
803
+ }, timeoutMs);
804
+ void bulkhead.drain().then(() => {
805
+ if (settled)
806
+ return;
807
+ settled = true;
808
+ clearTimeout(timer);
809
+ resolve({ drained: true, inFlight: 0, pending: 0 });
810
+ });
811
+ });
812
+ }
813
+ /**
814
+ * Subscribe to a bulkhead lifecycle event.
815
+ * Returns an unsubscribe function.
816
+ *
817
+ * Listeners are called synchronously from the bulkhead's internal
818
+ * control flow. They must not throw — exceptions are silently caught.
819
+ */
820
+ function on(event, listener) {
821
+ listeners[event].add(listener);
822
+ return () => {
823
+ listeners[event].delete(listener);
824
+ };
825
+ }
826
+ return {
827
+ estimate,
828
+ acquire,
829
+ run,
830
+ wouldAdmit,
831
+ stats,
832
+ setBudget,
833
+ close,
834
+ drain,
835
+ on,
836
+ };
837
+ }
838
+ //# sourceMappingURL=bulkhead.cjs.map