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