async-bulkhead-llm 1.0.3 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,10 +10,16 @@ Designed for services that need to enforce **cost ceilings, concurrency limits,
10
10
 
11
11
  - ✅ Hard **max in-flight** concurrency (`maxConcurrent`)
12
12
  - ✅ **Token-aware admission** — reserves against estimated input + max output tokens
13
+ - ✅ **Token refund** — reclaim unused budget capacity from actual usage post-completion
13
14
  - ✅ **Model-aware estimation** — per-model character ratios for known providers
15
+ - ✅ **Per-request model** — mixed-model routing through a single bulkhead
16
+ - ✅ **Multimodal content** — text blocks counted, non-text blocks ignored
14
17
  - ✅ **Fail-fast by default** — shed load early, never silently queue
15
18
  - ✅ **Opinionated profiles** — `'interactive'` and `'batch'` presets with escape hatch
16
19
  - ✅ **In-flight deduplication** — identical requests share one LLM call
20
+ - ✅ **Custom dedup key** — bring your own equivalence function
21
+ - ✅ **Event hooks** — `on('admit' | 'reject' | 'release' | 'dedup', fn)`
22
+ - ✅ **Graceful shutdown** — `close()` + `drain()`
17
23
  - ✅ Optional **AbortSignal** and **timeout** cancellation
18
24
  - ✅ `bulkhead.run(request, fn)` — acquire + release handled automatically
19
25
  - ✅ Zero dependencies beyond `async-bulkhead-ts`
@@ -21,6 +27,7 @@ Designed for services that need to enforce **cost ceilings, concurrency limits,
21
27
  - ✅ Node.js **20+**
22
28
 
23
29
  Non-goals (by design):
30
+
24
31
  - ❌ No retries
25
32
  - ❌ No provider SDK — bring your own client
26
33
  - ❌ No distributed coordination
@@ -28,6 +35,63 @@ Non-goals (by design):
28
35
 
29
36
  ---
30
37
 
38
+ ## Competitive Matrix (LLM Workloads)
39
+
40
+ | Capability / Library | async-bulkhead-llm | LangChain / LlamaIndex | OpenAI SDK (raw) | p-limit / Bottleneck | cockatiel / polly |
41
+ |---------------------|--------------------|------------------------|------------------|---------------------|-------------------|
42
+ | **Primary goal** | LLM admission control (cost + concurrency) | Orchestration / pipelines | API client | Concurrency / scheduling | Resilience patterns |
43
+ | **Fail-fast by default** | ✅ Yes | ❌ No | ❌ No | ❌ No | ⚠️ Depends |
44
+ | **Token-aware admission** | ✅ Yes (pre-admission budget) | ❌ No | ❌ No | ❌ No | ❌ No |
45
+ | **Token refund (post-call correction)** | ✅ Yes | ❌ No | ❌ No | ❌ No | ❌ No |
46
+ | **Cost ceiling enforcement** | ✅ Yes (`tokenBudget`) | ❌ No | ❌ No | ❌ No | ❌ No |
47
+ | **Concurrency limits** | ✅ Yes | ⚠️ Indirect | ❌ No | ✅ Yes | ⚠️ Indirect |
48
+ | **Bounded queue (optional)** | ✅ Yes | ⚠️ Internal | ❌ No | ✅ Yes | ⚠️ Indirect |
49
+ | **Fail-fast overload handling** | ✅ Core feature | ❌ No | ❌ No | ❌ No | ⚠️ Indirect |
50
+ | **In-flight deduplication** | ✅ Yes | ⚠️ Partial caching | ❌ No | ❌ No | ❌ No |
51
+ | **Custom dedup key** | ✅ Yes | ❌ No | ❌ No | ❌ No | ❌ No |
52
+ | **Model-aware estimation** | ✅ Yes | ❌ No | ❌ No | ❌ No | ❌ No |
53
+ | **Per-request model routing** | ✅ Yes | ✅ Yes | ✅ Yes | ❌ No | ❌ No |
54
+ | **Multimodal-aware estimation** | ✅ Yes (text-only counted) | ❌ No | ❌ No | ❌ No | ❌ No |
55
+ | **Abort / timeout (admission)** | ✅ Yes | ⚠️ Partial | ⚠️ SDK-level | ⚠️ Partial | ✅ Yes |
56
+ | **Event hooks (metrics/logging)** | ✅ Yes | ❌ No | ❌ No | ❌ No | ⚠️ Limited |
57
+ | **Graceful shutdown (drain/close)** | ✅ Yes | ❌ No | ❌ No | ❌ No | ❌ No |
58
+ | **Retries / fallback** | ❌ No | ⚠️ Yes | ❌ No | ❌ No | ✅ Yes |
59
+ | **LLM orchestration (chains/agents)** | ❌ No | ✅ Yes | ❌ No | ❌ No | ❌ No |
60
+
61
+ ---
62
+
63
+ ### Quick positioning
64
+
65
+ - **LangChain / LlamaIndex** → *what to run* (orchestration)
66
+ - **OpenAI SDK** → *how to call the provider*
67
+ - **p-limit / Bottleneck** → *how many tasks run*
68
+ - **cockatiel / polly** → *what happens after failure*
69
+ - **async-bulkhead-llm** → **whether a request should run at all**
70
+
71
+ ---
72
+
73
+ ### Rule of thumb
74
+
75
+ > If you want to **build LLM pipelines**, use LangChain.
76
+ > If you want to **protect your system and budget under load**, use async-bulkhead-llm.
77
+
78
+ ---
79
+
80
+ ### Key differentiator
81
+
82
+ > **Most LLM tooling optimizes execution.
83
+ > async-bulkhead-llm optimizes survival under load.**
84
+
85
+ It enforces:
86
+
87
+ - **concurrency ceilings**
88
+ - **token budget ceilings**
89
+ - **fail-fast admission**
90
+
91
+ before a request ever reaches your provider.
92
+
93
+ ---
94
+
31
95
  ## Install
32
96
 
33
97
  ```bash
@@ -51,8 +115,6 @@ const request = {
51
115
  max_tokens: 1024,
52
116
  };
53
117
 
54
- // Acquire + release handled automatically.
55
- // Throws LLMBulkheadRejectedError on rejection.
56
118
  const result = await bulkhead.run(request, async () => {
57
119
  return callYourLLMProvider(request);
58
120
  });
@@ -60,6 +122,134 @@ const result = await bulkhead.run(request, async () => {
60
122
 
61
123
  ---
62
124
 
125
+ ## What's New in v3
126
+
127
+ ### Stats are now namespaced
128
+
129
+ `bulkhead.stats()` now separates:
130
+
131
+ - underlying bulkhead stats → stats().bulkhead
132
+ - LLM-layer request stats → stats().llm
133
+
134
+ This avoids conflating base bulkhead slot lifecycle with higher-level LLM request outcomes
135
+ such as 'budget_limit'.
136
+
137
+ ---
138
+
139
+ ## What's New in v2
140
+
141
+ ### Token Refund
142
+
143
+ v1 reserved `input + maxOutput` tokens and held that full reservation until release. Most calls use far fewer output tokens than `max_tokens`. v2 reclaims the difference:
144
+
145
+ ```ts
146
+ // Via run() — extract usage from your provider's response
147
+ const result = await bulkhead.run(
148
+ request,
149
+ async () => callLLM(request),
150
+ {
151
+ getUsage: (response) => ({
152
+ input: response.usage.input_tokens,
153
+ output: response.usage.output_tokens,
154
+ }),
155
+ },
156
+ );
157
+
158
+ // Via acquire() — pass usage at release time
159
+ const r = await bulkhead.acquire(request);
160
+ if (r.ok) {
161
+ try {
162
+ const response = await callLLM(request);
163
+ return response;
164
+ } finally {
165
+ r.token.release({
166
+ input: response.usage.input_tokens,
167
+ output: response.usage.output_tokens,
168
+ });
169
+ }
170
+ }
171
+ ```
172
+
173
+ When usage is reported, the refund is `reserved - (actual input + actual output)`. Budget capacity is returned immediately. Without usage, behavior is identical to v1.
174
+
175
+ ### Multimodal Content
176
+
177
+ `content` may now be a plain string or an array of content blocks:
178
+
179
+ ```ts
180
+ const request = {
181
+ messages: [{
182
+ role: 'user',
183
+ content: [
184
+ { type: 'text', text: 'Describe this image...' },
185
+ { type: 'image', source: { type: 'base64', data: '...' } },
186
+ ],
187
+ }],
188
+ max_tokens: 1024,
189
+ };
190
+ ```
191
+
192
+ Built-in estimators extract text from text blocks and ignore non-text blocks. Token estimates for multimodal requests are a lower bound. Provide a custom `estimator` for accurate multimodal estimation.
193
+
194
+ ### Per-Request Model
195
+
196
+ Route multiple models through a single bulkhead with accurate per-model estimation:
197
+
198
+ ```ts
199
+ const bulkhead = createLLMBulkhead({
200
+ model: 'claude-sonnet-4', // default for estimation
201
+ maxConcurrent: 20,
202
+ tokenBudget: { budget: 500_000 },
203
+ });
204
+
205
+ // Estimator uses request.model when present
206
+ await bulkhead.run(
207
+ { model: 'claude-haiku-4-5', messages, max_tokens: 512 },
208
+ async () => callLLM(request),
209
+ );
210
+ ```
211
+
212
+ ### Custom Dedup Key
213
+
214
+ ```ts
215
+ const bulkhead = createLLMBulkhead({
216
+ model: 'claude-sonnet-4',
217
+ maxConcurrent: 10,
218
+ deduplication: {
219
+ keyFn: (request) => {
220
+ // Your own equivalence logic
221
+ return hash(request.messages);
222
+ },
223
+ },
224
+ });
225
+ ```
226
+
227
+ The default key now includes `messages`, `max_tokens`, and `model`. Return an empty string to opt a specific request out.
228
+
229
+ ### Event Hooks
230
+
231
+ ```ts
232
+ const off = bulkhead.on('release', ({ reservedTokens, refundedTokens, usage }) => {
233
+ metrics.histogram('llm.tokens.reserved', reservedTokens);
234
+ metrics.histogram('llm.tokens.refunded', refundedTokens);
235
+ });
236
+
237
+ // Later:
238
+ off(); // unsubscribe
239
+ ```
240
+
241
+ Events: `'admit'`, `'reject'`, `'release'`, `'dedup'`.
242
+
243
+ ### Graceful Shutdown
244
+
245
+ ```ts
246
+ // In your SIGTERM handler:
247
+ bulkhead.close(); // reject all pending; block future admission
248
+ await bulkhead.drain(); // wait for in-flight work to complete
249
+ ```
250
+
251
+ ---
252
+
63
253
  ## Profiles
64
254
 
65
255
  Two built-in presets cover the common cases. Explicit options always override preset defaults.
@@ -69,17 +259,17 @@ Two built-in presets cover the common cases. Explicit options always override pr
69
259
  const bulkhead = createLLMBulkhead({
70
260
  model: 'claude-sonnet-4',
71
261
  maxConcurrent: 10,
72
- profile: 'interactive', // maxQueue: 0
262
+ profile: 'interactive',
73
263
  });
74
264
 
75
265
  // Batch — bounded queue, 30s timeout
76
266
  const bulkhead = createLLMBulkhead({
77
267
  model: 'claude-sonnet-4',
78
268
  maxConcurrent: 4,
79
- profile: 'batch', // maxQueue: 20, timeoutMs: 30_000
269
+ profile: 'batch',
80
270
  });
81
271
 
82
- // Escape hatch — plain object, same shape as the options
272
+ // Escape hatch — plain object
83
273
  const bulkhead = createLLMBulkhead({
84
274
  model: 'claude-sonnet-4',
85
275
  maxConcurrent: 4,
@@ -87,39 +277,31 @@ const bulkhead = createLLMBulkhead({
87
277
  });
88
278
  ```
89
279
 
90
- If no profile is set, the default is fail-fast (`maxQueue: 0`).
91
-
92
280
  ---
93
281
 
94
282
  ## Token Budget
95
283
 
96
- Enforce a ceiling on total tokens in-flight simultaneously. Admission is always **fail-fast** when the ceiling is hit, regardless of profile or concurrency headroom.
97
-
98
284
  ```ts
99
285
  const bulkhead = createLLMBulkhead({
100
286
  model: 'claude-sonnet-4',
101
287
  maxConcurrent: 10,
102
288
  tokenBudget: {
103
- budget: 200_000, // max tokens in-flight at once
289
+ budget: 200_000,
104
290
  },
105
291
  });
106
292
  ```
107
293
 
108
- Token reservations are calculated pre-admission from `input + maxOutput`. Capacity is returned when each request completes.
294
+ Token reservations are calculated pre-admission from `input + maxOutput`. Capacity is returned when each request completes. When `TokenUsage` is provided at release, the refund reclaims unused capacity immediately.
109
295
 
110
- ### How estimation works
296
+ ### How Estimation Works
111
297
 
112
298
  The default estimator is `createModelAwareTokenEstimator` seeded with the bulkhead's `model`. It uses per-model character-to-token ratios for known model families, falling back to a flat `4.0` ratio for unknown models.
113
299
 
114
- Known model families: `claude-3-5-haiku`, `claude-3-5-sonnet`, `claude-3-*`, `claude-sonnet-4`, `claude-opus-4`, `gpt-4o`, `gpt-4-turbo`, `gpt-4`, `gpt-3.5`, `o1`, `o3`, `gemini-1.5`, `gemini-2`.
115
-
116
- **Accuracy:** ±15% for known models on English prose. Underestimates for code and non-Latin scripts.
117
- **Suitable for:** load-shedding and cost ceilings.
118
- **Not suitable for:** cost accounting or billing.
300
+ v2 checks `request.model` first (when present), then falls back to the bulkhead-level `defaultModel`.
119
301
 
120
- ### Custom estimator
302
+ Known model families: `claude-3-5-haiku`, `claude-3-5-sonnet`, `claude-3-*`, `claude-sonnet-4`, `claude-opus-4`, `claude-haiku-4`, `claude-*-4-5`, `gpt-4o`, `gpt-4-turbo`, `gpt-4.1`, `gpt-4`, `gpt-3.5`, `o1`, `o3`, `o4-mini`, `gemini-1.5`, `gemini-2`, `gemini-2.5`.
121
303
 
122
- Bring your own for higher accuracy, or to support Azure deployment names and other non-standard model strings:
304
+ ### Custom Estimator
123
305
 
124
306
  ```ts
125
307
  import { Tiktoken } from 'tiktoken';
@@ -132,42 +314,47 @@ const bulkhead = createLLMBulkhead({
132
314
  tokenBudget: {
133
315
  budget: 200_000,
134
316
  estimator: (request) => ({
135
- input: enc.encode(request.messages.map(m => m.content).join('')).length,
317
+ input: enc.encode(request.messages.map(m =>
318
+ typeof m.content === 'string'
319
+ ? m.content
320
+ : m.content.filter(b => b.type === 'text').map(b => b.text).join('')
321
+ ).join('')).length,
136
322
  maxOutput: request.max_tokens ?? 2_048,
137
323
  }),
138
324
  },
139
325
  });
140
326
  ```
141
327
 
142
- ### Estimator utilities
143
-
144
- Both estimators are exported for use outside the bulkhead — in logging, pre-flight checks, or request routing:
328
+ ### Estimator Utilities
145
329
 
146
330
  ```ts
147
- import { naiveTokenEstimator, createModelAwareTokenEstimator } from 'async-bulkhead-llm';
331
+ import {
332
+ naiveTokenEstimator,
333
+ createModelAwareTokenEstimator,
334
+ extractTextLength,
335
+ } from 'async-bulkhead-llm';
148
336
 
149
- // Flat 4.0 ratio, zero configuration
337
+ // Flat 4.0 ratio, multimodal-safe
150
338
  const est1 = naiveTokenEstimator(request);
151
339
 
152
- // Per-model ratios, optional override map
340
+ // Per-model ratios
153
341
  const estimate = createModelAwareTokenEstimator(
154
- { 'my-azure-deployment': 3.7 }, // exact overrides
342
+ { 'my-azure-deployment': 3.7 },
155
343
  {
156
344
  defaultModel: 'claude-sonnet-4',
157
345
  outputCap: 2_048,
158
346
  onUnknownModel: (model) => console.warn(`Unknown model: ${model}`),
159
347
  },
160
348
  );
161
- ```
162
349
 
163
- `onUnknownModel` fires when neither an override nor a built-in prefix matches. Use it to log, alert, or throw in strict environments.
350
+ // Utility for multimodal content
351
+ const charCount = extractTextLength(message.content);
352
+ ```
164
353
 
165
354
  ---
166
355
 
167
356
  ## Deduplication
168
357
 
169
- When enabled, requests with identical message content that arrive while a matching call is already in-flight share that call — only one LLM request is made.
170
-
171
358
  ```ts
172
359
  const bulkhead = createLLMBulkhead({
173
360
  model: 'claude-sonnet-4',
@@ -175,28 +362,28 @@ const bulkhead = createLLMBulkhead({
175
362
  deduplication: true,
176
363
  });
177
364
 
178
- // Both callers get the same result; only one LLM call is made.
179
365
  const [r1, r2] = await Promise.all([
180
366
  bulkhead.run(request, async () => callLLM(request)),
181
367
  bulkhead.run(request, async () => callLLM(request)), // deduped
182
368
  ]);
183
369
  ```
184
370
 
185
- **v1 key:** `JSON.stringify(request.messages)`. Requests with different `max_tokens` but identical messages are treated as duplicates. Key design is a known limitation in v1.
371
+ v2 default key: `JSON.stringify({ m: request.messages, t: request.max_tokens, o: request.model })`. Requests with different `max_tokens` or `model` are not conflated.
186
372
 
187
- Deduplication stats are tracked:
373
+ Custom key:
188
374
 
189
375
  ```ts
190
- bulkhead.stats().deduplication
191
- // { active: 2, hits: 5 }
376
+ deduplication: {
377
+ keyFn: (request) => myHash(request.messages),
378
+ }
192
379
  ```
193
380
 
381
+ Return `""` from `keyFn` to opt a specific request out.
382
+
194
383
  ---
195
384
 
196
385
  ## Cancellation
197
386
 
198
- Cancel waiting or in-flight requests with an `AbortSignal`:
199
-
200
387
  ```ts
201
388
  const ac = new AbortController();
202
389
 
@@ -206,51 +393,44 @@ await bulkhead.run(
206
393
  { signal: ac.signal },
207
394
  );
208
395
 
209
- // Somewhere else:
210
- ac.abort(); // cancels if still waiting; signals fn if already in-flight
396
+ ac.abort();
211
397
  ```
212
398
 
213
- The signal is passed through to your function. The bulkhead does not forcibly terminate in-flight work — your function is responsible for observing the signal.
214
-
215
- Bound waiting time independently with `timeoutMs`:
399
+ Bound waiting time:
216
400
 
217
401
  ```ts
218
402
  await bulkhead.run(request, async () => callLLM(request), { timeoutMs: 5_000 });
219
403
  ```
220
404
 
221
- `timeoutMs` applies to the waiting period only. It has no effect when `maxQueue` is 0.
222
-
223
405
  ---
224
406
 
225
407
  ## Manual Acquire / Release
226
408
 
227
- For cases where `run()` doesn't fit your control flow:
228
-
229
409
  ```ts
230
410
  const r = await bulkhead.acquire(request);
231
411
 
232
412
  if (!r.ok) {
233
- // r.reason: 'concurrency_limit' | 'queue_limit' | 'budget_limit' | 'timeout' | 'aborted'
413
+ // r.reason: 'concurrency_limit' | 'queue_limit' | 'budget_limit'
414
+ // | 'timeout' | 'aborted' | 'shutdown'
234
415
  return respond503(r.reason);
235
416
  }
236
417
 
237
418
  try {
238
- return await callLLM(request);
419
+ const response = await callLLM(request);
420
+ return response;
239
421
  } finally {
240
- r.token.release();
422
+ // v2: pass usage for refund
423
+ r.token.release({
424
+ input: response.usage.input_tokens,
425
+ output: response.usage.output_tokens,
426
+ });
241
427
  }
242
428
  ```
243
429
 
244
- You must call `token.release()` exactly once if acquisition succeeds.
245
-
246
- > **v1 note:** Token budget reservations are not correctable after admission when using `acquire()` directly — the refund mechanism (adjusting reservations based on actual usage) is deferred to v2. For accurate budget accounting, prefer `run()`.
247
-
248
430
  ---
249
431
 
250
432
  ## Handling Rejections
251
433
 
252
- `run()` throws `LLMBulkheadRejectedError` on rejection:
253
-
254
434
  ```ts
255
435
  import { LLMBulkheadRejectedError } from 'async-bulkhead-llm';
256
436
 
@@ -258,17 +438,14 @@ try {
258
438
  await bulkhead.run(request, async () => callLLM(request));
259
439
  } catch (err) {
260
440
  if (err instanceof LLMBulkheadRejectedError) {
261
- // err.code === 'LLM_BULKHEAD_REJECTED'
262
- // err.reason === 'concurrency_limit' | 'queue_limit' | 'budget_limit'
263
- // | 'timeout' | 'aborted'
441
+ // err.reason: 'concurrency_limit' | 'queue_limit' | 'budget_limit'
442
+ // | 'timeout' | 'aborted' | 'shutdown'
264
443
  return respond503(`Shed: ${err.reason}`);
265
444
  }
266
445
  throw err;
267
446
  }
268
447
  ```
269
448
 
270
- `acquire()` returns a result object instead of throwing — check `r.ok` before using the token.
271
-
272
449
  ---
273
450
 
274
451
  ## Stats
@@ -276,49 +453,82 @@ try {
276
453
  ```ts
277
454
  const s = bulkhead.stats();
278
455
 
279
- s.inFlight // requests currently executing
280
- s.pending // requests waiting in queue
281
- s.maxConcurrent // configured limit
282
- s.maxQueue // configured queue depth
456
+ s.bulkhead.inFlight
457
+ s.bulkhead.pending
458
+ s.bulkhead.maxConcurrent
459
+ s.bulkhead.maxQueue
460
+ s.bulkhead.closed // true after close()
461
+
462
+ s.llm.admitted
463
+ s.llm.released
464
+ s.llm.rejected
465
+ s.llm.rejectedByReason?.budget_limit // true after close()
466
+
467
+ s.tokenBudget?.budget
468
+ s.tokenBudget?.inFlightTokens
469
+ s.tokenBudget?.available
470
+ s.tokenBudget?.totalRefunded // v2: cumulative refunded tokens
283
471
 
284
- // Present only when tokenBudget is configured:
285
- s.tokenBudget?.budget // total ceiling
286
- s.tokenBudget?.inFlightTokens // currently reserved
287
- s.tokenBudget?.available // remaining headroom
472
+ s.deduplication?.active
473
+ s.deduplication?.hits
474
+ ```
288
475
 
289
- // Present only when deduplication is enabled:
290
- s.deduplication?.active // distinct in-flight keys
291
- s.deduplication?.hits // cumulative dedup hits
476
+ ```ts
477
+ type LLMStats = {
478
+ bulkhead: Stats;
479
+ llm: {
480
+ admitted: number;
481
+ released: number;
482
+ rejected: number;
483
+ rejectedByReason: Partial<Record<LLMRejectReason, number>>;
484
+ };
485
+ tokenBudget?: {
486
+ budget: number;
487
+ inFlightTokens: number;
488
+ available: number;
489
+ totalRefunded: number;
490
+ };
491
+ deduplication?: {
492
+ active: number;
493
+ hits: number;
494
+ };
495
+ };
292
496
  ```
293
497
 
294
498
  ---
295
499
 
296
- ## Multi-Model Routing
500
+ ## Event Hooks
297
501
 
298
- One bulkhead per model is the recommended pattern. Different models have different cost profiles, latency characteristics, and provider rate limits — a unified ceiling can't express those correctly.
502
+ ```ts
503
+ // Subscribe
504
+ const off = bulkhead.on('admit', ({ request, reservedTokens }) => {
505
+ console.log(`Admitted: ${reservedTokens} tokens reserved`);
506
+ });
299
507
 
300
- For fallback routing, A/B testing, or canary deployments, compose multiple bulkheads with a thin routing layer:
508
+ // Unsubscribe
509
+ off();
510
+ ```
301
511
 
302
- ```ts
303
- const bulkheads = {
304
- sonnet: createLLMBulkhead({ model: 'claude-sonnet-4', maxConcurrent: 10 }),
305
- haiku: createLLMBulkhead({ model: 'claude-haiku-3', maxConcurrent: 40 }),
306
- };
512
+ | Event | Payload |
513
+ |-----------|---------|
514
+ | `admit` | `{ request, reservedTokens }` |
515
+ | `reject` | `{ request, reason }` |
516
+ | `release` | `{ request, reservedTokens, refundedTokens, usage? }` |
517
+ | `dedup` | `{ request }` |
307
518
 
308
- async function callWithFallback(request, isPriority: boolean) {
309
- const bulkhead = isPriority ? bulkheads.sonnet : bulkheads.haiku;
310
- try {
311
- return await bulkhead.run(request, () => callLLM(request));
312
- } catch (err) {
313
- if (err instanceof LLMBulkheadRejectedError && !isPriority) {
314
- // Haiku is saturated — shed rather than escalate to Sonnet.
315
- throw err;
316
- }
317
- throw err;
318
- }
319
- }
519
+ Listeners are synchronous and fire-and-forget. Exceptions are silently caught.
520
+
521
+ ---
522
+
523
+ ## Graceful Shutdown
524
+
525
+ ```ts
526
+ bulkhead.close(); // stop admission, reject pending waiters
527
+ await bulkhead.drain(); // wait for in-flight work to finish
320
528
  ```
321
529
 
530
+ `close()` is synchronous, idempotent, and irreversible. `drain()` resolves when `inFlight` and `pending` both reach zero.
531
+
322
532
  ---
323
533
 
324
534
  ## API Reference
@@ -327,84 +537,79 @@ async function callWithFallback(request, isPriority: boolean) {
327
537
 
328
538
  ```ts
329
539
  type LLMBulkheadOptions = {
330
- model: string; // required; one bulkhead per model
331
- maxConcurrent: number; // required
332
- maxQueue?: number; // default: 0 (fail-fast)
333
- timeoutMs?: number; // waiting timeout; no effect if maxQueue is 0
334
- profile?: 'interactive' // maxQueue: 0 (default behaviour)
335
- | 'batch' // maxQueue: 20, timeoutMs: 30_000
336
- | LLMBulkheadPreset; // escape hatch: plain options object
540
+ model: string;
541
+ maxConcurrent: number;
542
+ maxQueue?: number;
543
+ timeoutMs?: number;
544
+ profile?: 'interactive' | 'batch' | LLMBulkheadPreset;
337
545
  tokenBudget?: {
338
546
  budget: number;
339
- estimator?: TokenEstimator; // default: createModelAwareTokenEstimator
340
- outputCap?: number; // default: 2048
547
+ estimator?: TokenEstimator;
548
+ outputCap?: number;
341
549
  };
342
- deduplication?: boolean; // default: false
550
+ deduplication?: boolean | DeduplicationOptions;
343
551
  };
344
- ```
345
552
 
346
- Explicit options always override profile defaults.
553
+ type DeduplicationOptions = {
554
+ keyFn?: (request: LLMRequest) => string;
555
+ };
556
+ ```
347
557
 
348
558
  ### `bulkhead.run(request, fn, options?)`
349
559
 
350
- Primary API. Acquires a slot, calls `fn`, releases on completion or error.
351
-
352
560
  ```ts
353
561
  run<T>(
354
562
  request: LLMRequest,
355
563
  fn: (signal?: AbortSignal) => Promise<T>,
356
- options?: { signal?: AbortSignal; timeoutMs?: number },
564
+ options?: {
565
+ signal?: AbortSignal;
566
+ timeoutMs?: number;
567
+ getUsage?: (result: T) => TokenUsage | undefined;
568
+ },
357
569
  ): Promise<T>
358
570
  ```
359
571
 
360
- Throws `LLMBulkheadRejectedError` on rejection.
361
-
362
572
  ### `bulkhead.acquire(request, options?)`
363
573
 
364
- Advanced. Returns a result object; you manage the token lifecycle.
365
-
366
574
  ```ts
367
575
  acquire(
368
576
  request: LLMRequest,
369
577
  options?: { signal?: AbortSignal; timeoutMs?: number },
370
- ): Promise<
371
- | { ok: true; token: { release(): void } }
372
- | { ok: false; reason: LLMRejectReason }
373
- >
374
- ```
578
+ ): Promise<LLMAcquireResult>
375
579
 
376
- ### `bulkhead.stats()`
580
+ type LLMAcquireResult =
581
+ | { ok: true; token: LLMToken }
582
+ | { ok: false; reason: LLMRejectReason };
377
583
 
378
- Returns current runtime state. See [Stats](#stats) above.
584
+ type LLMToken = { release(usage?: TokenUsage): void };
585
+ ```
379
586
 
380
- ### `naiveTokenEstimator(request)`
587
+ ### `bulkhead.stats()`
381
588
 
382
- Plain function. Flat `4.0` character-per-token ratio. No configuration.
589
+ ### `bulkhead.close()`
383
590
 
384
- ### `createModelAwareTokenEstimator(overrides?, options?)`
591
+ ### `bulkhead.drain()`
385
592
 
386
- Factory. Per-model ratios, longest-prefix match, exact overrides checked first.
593
+ ### `bulkhead.on(event, listener)`
387
594
 
388
595
  ```ts
389
- createModelAwareTokenEstimator(
390
- overrides?: Record<string, number>, // exact-match; caller values win
391
- options?: {
392
- defaultModel?: string;
393
- outputCap?: number;
394
- onUnknownModel?: (model: string) => void;
395
- },
396
- ): TokenEstimator
596
+ on<K extends keyof LLMEventMap>(
597
+ event: K,
598
+ listener: (payload: LLMEventMap[K]) => void,
599
+ ): () => void // returns unsubscribe
397
600
  ```
398
601
 
399
602
  ### Types
400
603
 
401
604
  ```ts
402
- type LLMRequest = { messages: LLMMessage[]; max_tokens?: number };
403
- type LLMMessage = { role: string; content: string };
605
+ type LLMRequest = { model?: string; messages: LLMMessage[]; max_tokens?: number };
606
+ type LLMMessage = { role: string; content: string | ContentBlock[] };
607
+ type ContentBlock = TextContentBlock | OpaqueContentBlock;
608
+ type TextContentBlock = { type: 'text'; text: string };
609
+ type OpaqueContentBlock = { type: string; [key: string]: unknown };
610
+
404
611
  type TokenEstimate = { input: number; maxOutput: number };
405
612
  type TokenEstimator = (request: LLMRequest) => TokenEstimate;
406
-
407
- // Forward-looking: not acted on in v1, useful for annotating provider responses.
408
613
  type TokenUsage = { input: number; output: number };
409
614
 
410
615
  type LLMRejectReason =
@@ -412,37 +617,61 @@ type LLMRejectReason =
412
617
  | 'queue_limit'
413
618
  | 'budget_limit'
414
619
  | 'timeout'
415
- | 'aborted';
620
+ | 'aborted'
621
+ | 'shutdown';
416
622
  ```
417
623
 
418
624
  ---
419
625
 
420
- ## Design Notes
626
+ ## Migration
421
627
 
422
- This library enforces backpressure at the boundary of your LLM calls. It does not replace higher-level concerns:
628
+ ### v2 → v3
423
629
 
424
- - **Retries** — compose a retry library around the bulkhead, not inside it
425
- - **Cost accounting** — use provider response metadata; estimation here is for gating only
426
- - **Distributed rate limiting** — use a shared token bucket; bulkheads are per-process
427
- - **Model selection** — route above the bulkhead layer; each bulkhead instance is model-specific
630
+ Update stats access from top-level fields to the `bulkhead` block:
631
+
632
+ ```ts
633
+ const s = bulkhead.stats();
634
+
635
+ // v2
636
+ s.inFlight;
637
+ s.pending;
638
+
639
+ // v3
640
+ s.bulkhead.inFlight;
641
+ s.bulkhead.pending;
642
+ ```
643
+
644
+ LLM-layer counters are now available separately:
645
+
646
+ ```ts
647
+ const s = bulkhead.stats();
648
+ s.llm.admitted;
649
+ s.llm.rejected;
650
+ s.llm.rejectedByReason?.budget_limit;
651
+ ```
428
652
 
429
- Token estimation is deliberately approximate. The estimator's job is to prevent gross over-admission — not to predict your invoice. An estimator that's wrong by 20% still prevents the most common cost explosion: a burst of large-context requests all admitted simultaneously.
653
+ ### v1 → v2
430
654
 
431
- The refund mechanism (correcting reservations based on actual usage after a call completes) is on the roadmap for v2. In v1, reservations are based on `input + maxOutput` and held until release.
655
+ See [CHANGELOG](./CHANGELOG.md) for the v2 migration guide.
432
656
 
433
657
  ---
434
658
 
435
- ## Multimodal
659
+ ## Design Notes
660
+
661
+ This library enforces backpressure at the boundary of your LLM calls. It does not replace higher-level concerns:
436
662
 
437
- `content` must be a plain string in v1. Multimodal content (images, documents, tool results as structured blocks) is not supported by the built-in estimators — non-string content is ignored, causing underestimation. Treat token budget results as a lower bound for multimodal requests.
663
+ - **Retries** — compose a retry library around the bulkhead, not inside it
664
+ - **Cost accounting** — use provider response metadata; estimation here is for gating only
665
+ - **Distributed rate limiting** — use a shared token bucket; bulkheads are per-process
666
+ - **Model selection** — route above the bulkhead layer; each bulkhead instance is model-specific
438
667
 
439
- Full multimodal support is planned for v2.
668
+ Token estimation is deliberately approximate. The refund mechanism improves budget utilization but does not make estimation exact — it corrects after the fact based on actual usage.
440
669
 
441
670
  ---
442
671
 
443
672
  ## Compatibility
444
673
 
445
- - Node.js: 20+ (24 LTS recommended)
674
+ - Node.js: 20+
446
675
  - Module formats: ESM and CommonJS
447
676
 
448
677
  ---