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