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