async-bulkhead-llm 3.14.0 → 3.15.1

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/CHANGELOG.md ADDED
@@ -0,0 +1,900 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format loosely follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/)
6
+ and adheres to [Semantic Versioning](https://semver.org/).
7
+
8
+ ---
9
+
10
+ ## [3.15.1] - 2026-08-06
11
+
12
+ ### Fixed
13
+
14
+ * **npm package documentation.** The publish manifest now explicitly includes
15
+ `README.md`, `LICENSE`, and `CHANGELOG.md` so the npm registry package page
16
+ and downloaded package consistently contain the release documentation.
17
+
18
+ ## [3.15.0] - 2026-08-06
19
+
20
+ ### Added
21
+
22
+ * **Protected admission-class floors.** Admission classes may reserve strict
23
+ local concurrency with `protectedConcurrent` and strict in-flight token
24
+ capacity with `protectedInFlightTokens`. The sum of configured floors must
25
+ fit inside the corresponding global limit, and a class floor may not exceed
26
+ its hard class ceiling.
27
+
28
+ * **Shared-capacity borrowing.** Capacity remaining after all protected floors
29
+ forms a shared pool. A class consumes its floor first and may then borrow from
30
+ the shared remainder, subject to its class ceilings, global limits, and the
31
+ priority-adjusted token budget.
32
+
33
+ * **Protection-aware rejection detail.** Requests rejected to preserve another
34
+ class's floor report `constraint: "admission_class_protection"` and include
35
+ shared concurrency/token capacity plus protected and borrowed class usage.
36
+
37
+ * **Borrowing telemetry.** `stats().admissionClasses.shared` exposes the shared
38
+ remainder. Per-class stats expose current protected and borrowed usage,
39
+ cumulative admissions using shared concurrency, and cumulative reservation
40
+ tokens placed in shared capacity.
41
+
42
+ ### Changed
43
+
44
+ * **Non-revoking floor reconfiguration.** Floor changes are installed atomically
45
+ with the existing versioned admission snapshot. Increasing a floor never
46
+ revokes active work; new borrowing pauses until normal completion restores
47
+ the protected capacity by attrition.
48
+
49
+ ### Compatibility
50
+
51
+ * This is an additive minor release. Omitting both protected-floor fields
52
+ preserves v3.14 admission behavior. Exact object-shape assertions must allow
53
+ the new stats, rejection-detail, limit, and capacity-constraint fields.
54
+ * Protected floors are strict reservations and are not automatically lent while
55
+ idle. Demand-aware cross-class lending remains a gateway/control-plane policy
56
+ implemented by applying a newer limit snapshot.
57
+
58
+ ## [3.14.0] - 2026-08-04
59
+
60
+ ### Added
61
+
62
+ * **Bounded admission classes.** `admissionClasses` configures a fixed table of
63
+ policy-class IDs with optional hard `maxConcurrent` and
64
+ `maxInFlightTokens` ceilings. Calls select a class with `admissionClass` or
65
+ fall back to `defaultClass`; unknown IDs throw instead of creating
66
+ unbounded runtime state.
67
+
68
+ * **Hierarchical capacity decisions.** Successful admission must fit both the
69
+ enclosing global limits and the selected class limits. Class ceilings are
70
+ fail-fast, use shrink-by-attrition under reconfiguration, and remain atomic
71
+ with global concurrency and token accounting.
72
+
73
+ * **Class-aware progressive accounting.** Reservations, progressive usage
74
+ refunds, output overruns, and final release settlement update global and
75
+ class token holds together.
76
+
77
+ * **Class-aware telemetry.** Successful results, tokens, run contexts, usage
78
+ reports, lifecycle events, capacity details, and observe-mode bypasses carry
79
+ `admissionClass` when configured. Capacity details identify the binding
80
+ `constraint` as `global` or `admission_class`, and
81
+ `stats().admissionClasses` reports bounded per-class counters.
82
+
83
+ * **Class-safe deduplication.** Admission class is an automatic deduplication
84
+ partition when classes are configured, preventing one class from inheriting
85
+ another class's admission decision or queue position. Class IDs are validated
86
+ before the dedup follower fast path, and dedup/rejection events retain class
87
+ attribution.
88
+
89
+ * **Atomic class-limit updates.** `LLMAdmissionLimits.admissionClasses` updates
90
+ every construction-time class in the same versioned snapshot as global
91
+ concurrency, queue, token budget, and priority reserve. Runtime updates may
92
+ change numeric ceilings but cannot add or remove class keys.
93
+
94
+ ### Compatibility
95
+
96
+ * This is an additive minor release. Existing behavior and object shapes remain
97
+ unchanged when `admissionClasses` is omitted.
98
+ * Admission classes are bounded policy buckets, not an authentication layer or
99
+ a replacement for tenant-scoped deduplication. Identity mapping, weighted
100
+ fairness, protected-floor lending, and distributed coordination remain the
101
+ responsibility of the gateway/control plane.
102
+
103
+ ## [3.13.0] - 2026-08-01
104
+
105
+ ### Added
106
+
107
+ * **Progressive reservation reconciliation.** `reportUsage()` accepts an
108
+ optional `remainingOutputTokens` plus `safetyMarginTokens` declaration.
109
+ Gateways can release processed input and already-generated output capacity
110
+ during a live stream while retaining explicit future-output headroom.
111
+ * Progressive updates retain cumulative-usage monotonicity, preserve output
112
+ overrun protection, emit sequence-numbered usage events, and remain no-op
113
+ accounting in observe-mode bypasses.
114
+
115
+ ## [3.12.0] - 2026-07-26
116
+
117
+ ### Added
118
+
119
+ * **Fail-closed construction.** `createLLMBulkhead()` now accepts
120
+ `maxConcurrent: 0`, allowing gateways to start with no admission capacity and
121
+ remain closed until an external control plane installs a higher-revision
122
+ snapshot. Runtime zero-capacity behavior is unchanged: new work is rejected
123
+ with `concurrency_limit`, while later expansion begins admitting immediately.
124
+
125
+ ## [3.11.1] - 2026-07-24
126
+
127
+ ### Security
128
+
129
+ * Refreshed the development dependency lockfile so the ESLint/minimatch toolchain
130
+ uses `brace-expansion` 5.0.8, resolving the reported high-severity audit
131
+ finding. This dependency is development-only; the runtime dependency graph is
132
+ unchanged.
133
+
134
+ ### Fixed
135
+
136
+ * Published the finalized v3.11 contents under a new immutable package version
137
+ after the v3.11.0 registry tarball produced an integrity mismatch. Consumers
138
+ should install v3.11.1 rather than retrying the conflicting v3.11.0 artifact.
139
+
140
+ * Updated the strict admit-capacity snapshot test to include the additive
141
+ `limitRevision: 0` field introduced in v3.11.
142
+
143
+ ## [3.11.0] - 2026-07-24
144
+
145
+ ### Added
146
+
147
+ * **Admission-linearized limit revisions.** Successful `acquire()` results,
148
+ `LLMToken`, `LLMRunContext`, `UsageReport`, and admitted/bypassed lifecycle
149
+ events now carry an immutable `limitRevision` captured after both the
150
+ concurrency slot and token reservation are held.
151
+
152
+ * **Revisioned rejection snapshots.** `LLMRejectDetail.limitRevision` and the
153
+ `reject` event identify the exact limit snapshot used for the capacity
154
+ decision, allowing gateways to report authoritative revisions without a
155
+ later `limits()` lookup.
156
+
157
+ ### Fixed
158
+
159
+ * A synchronous `admit` listener can apply a newer limit snapshot before the
160
+ `run()` callback starts. The callback, usage events, and release event now
161
+ retain the original admission revision instead of being relabeled with the
162
+ newer configuration.
163
+
164
+ ## [3.10.0] - 2026-07-23
165
+
166
+ ### Added
167
+
168
+ * **Atomic, versioned admission-limit reconfiguration.**
169
+ `bulkhead.applyLimits(snapshot)` replaces `maxConcurrent`, `maxQueue`,
170
+ `tokenBudget.budget`, and `tokenBudget.highPriorityReserve` as one complete
171
+ snapshot. Updates require a strictly increasing non-negative safe-integer
172
+ `revision`; equal or lower revisions return
173
+ `{ applied: false, reason: "stale_revision" }` without mutation.
174
+
175
+ * **Runtime concurrency and queue changes.** Lower ceilings use
176
+ shrink-by-attrition: in-flight work and already accepted waiters are not
177
+ cancelled. Raising concurrency pumps accepted waiters immediately. A
178
+ runtime `maxConcurrent: 0` acts as a fail-fast kill switch for new work.
179
+
180
+ * **Limit inspection and telemetry.** `bulkhead.limits()` and
181
+ `stats().limits` expose the currently applied frozen snapshot.
182
+ `initialRevision` seeds the constructor state, and the new `reconfigure`
183
+ event contains the previous and current snapshots.
184
+
185
+ ### Changed
186
+
187
+ * `setBudget(tokens)` remains backward compatible but now delegates to a
188
+ complete local reconfiguration and advances the revision by one. Distributed
189
+ control-plane integrations should use `applyLimits()` exclusively so one
190
+ authority owns the revision stream.
191
+
192
+ * The internal concurrency gate now supports dynamic `maxConcurrent` and
193
+ `maxQueue` while preserving the public stats and rejection semantics used by
194
+ the LLM bulkhead.
195
+
196
+ ## [3.9.0] - 2026-07-22
197
+
198
+ ### Added
199
+
200
+ * **First-class observe mode for `run()`.** Pass `{ mode: "observe" }` to
201
+ execute work without holding concurrency or token capacity when admission
202
+ would reject for `budget_limit`, `concurrency_limit`, `queue_limit`, or
203
+ `timeout`. The default remains `{ mode: "enforce" }`. `shadowReasons` can
204
+ narrow the bypassable capacity reasons; shutdown, caller cancellation, and
205
+ unsafe deduplication fan-out remain hard failures and cannot be shadowed.
206
+
207
+ * **Admitted-versus-bypassed run context.** `LLMRunContext.admission` is
208
+ `"admitted"` or `"bypassed"`. Bypassed executions receive a stable
209
+ `shadow-...` identifier, the exact evaluated reservation, and optional
210
+ `bypassReason` / `bypassDetail`. `reportUsage()` remains available and
211
+ returns normal `UsageReport` snapshots without altering capacity accounting.
212
+
213
+ * **Observe telemetry.** `stats().observe` reports bypass counts, race
214
+ bypasses, reasons, and final usage totals. New `bypass`, `bypassUsage`, and
215
+ `bypassRelease` events expose the same lifecycle without misrepresenting
216
+ bypassed work as admitted or released capacity.
217
+
218
+ ### Changed
219
+
220
+ * Observe mode performs an exact advisory check before authoritative admission.
221
+ Obvious capacity rejections bypass immediately; a later queue timeout or
222
+ post-slot budget race is also bypassed and counted as `raceBypassed`. The
223
+ same resolved reservation is reused across both checks.
224
+
225
+ ## [3.8.0] - 2026-07-21
226
+
227
+ ### Added
228
+
229
+ * **Bounded drain: `drain({ timeoutMs })`.** The no-argument form keeps its
230
+ `Promise<void>` contract unchanged. With a deadline, the promise always
231
+ *resolves* (never rejects) with an `LLMDrainResult` —
232
+ `{ drained: true, inFlight: 0, pending: 0 }` when everything completed in
233
+ time, or `{ drained: false, inFlight, pending }` with the outstanding
234
+ counts at the moment the deadline elapsed. The deadline never cancels or
235
+ interrupts in-flight work and leaves accounting untouched: work that
236
+ finishes later still releases normally. Intended for shutdown paths that
237
+ must log what they are abandoning and proceed, rather than parking
238
+ forever behind one stuck upstream stream. `timeoutMs` must be a
239
+ non-negative integer; `0` is an immediate "is it drained right now?"
240
+ snapshot.
241
+
242
+ * **`wouldAdmit(request, { detail: true })`.** Opt in to receive the same
243
+ `LLMRejectDetail` capacity snapshot that real rejections carry — on
244
+ every outcome, including `admit: true`, where it describes the capacity
245
+ the request would be admitted against (`requested` is the reservation
246
+ this request needs). Routing layers choosing between pools want the
247
+ numbers, not just the boolean. Omitted by default, so the result shape
248
+ and cost are unchanged for existing callers (results still deep-equal
249
+ `{ admit: true }` etc.).
250
+
251
+ * **`estimate()` results round-trip as the `reservation` override.** The
252
+ per-call override now accepts `LLMReservationOverride`
253
+ (`TokenEstimate & { reserved?: number }`), so the frozen object returned
254
+ by `bulkhead.estimate()` can be passed back verbatim — no need to strip
255
+ `reserved` first. When `reserved` is present it is validated as a
256
+ consistency check: it must equal `input + maxOutput`, otherwise
257
+ admission throws. This catches hand-built overrides whose cached
258
+ `reserved` drifted from edited parts. Plain `{ input, maxOutput }`
259
+ overrides (the 3.7 shape) are unchanged.
260
+
261
+ * **`createAdaptiveTokenEstimator()` — self-calibrating estimation.** A
262
+ wrapper around `createModelAwareTokenEstimator` that closes the feedback
263
+ loop between estimates and reality. Feed it actual usage from completed
264
+ calls via `observe(request, usage)` (typically wired to the bulkhead's
265
+ `release` event); it maintains a per-model EWMA of
266
+ `actual input / estimated input` and multiplies future *input*
267
+ estimates by that factor — clamped to
268
+ `[minCorrection, maxCorrection]` (default `[0.5, 2]`) and applied only
269
+ after `minSamples` observations (default 5). Output reservations are
270
+ never corrected: `max_tokens` / `outputCap` is a ceiling, not an
271
+ estimate. Observations always measure against the *uncorrected* base
272
+ estimate, so the loop does not compound through its own corrections.
273
+ Tracked models are bounded (`maxModels`, default 64, oldest-inserted
274
+ evicted); `corrections()` exposes the calibration state for stats
275
+ endpoints and `reset(model?)` clears it. Calibration is in-memory and
276
+ per-instance — share one instance per bulkhead.
277
+
278
+ ### Changed
279
+
280
+ * **`wouldAdmit()` validates before the shutdown check.** The request (and
281
+ any `reservation` override) is now validated *before* the closed fast
282
+ path, matching `acquire()`'s ordering — an invalid request (e.g. a
283
+ negative `max_tokens`) now throws even when the bulkhead is closed,
284
+ instead of returning `{ admit: false, reason: "shutdown" }`. Valid
285
+ requests against a closed bulkhead behave exactly as before.
286
+
287
+ ### Internal
288
+
289
+ * **Source split into focused modules.** The former single-file
290
+ `src/index.ts` (~2,400 lines) is now a barrel over `types.ts`,
291
+ `errors.ts`, `profiles.ts`, `validation.ts`, `estimators.ts`,
292
+ `adaptive.ts`, `dedup.ts`, and `bulkhead.ts`. No public API change:
293
+ the package entry point re-exports the identical surface (verified
294
+ against the pre-split build), and the `exports` map still exposes
295
+ only the entry point — deep imports of the internal modules remain
296
+ unsupported. `dist/` now contains one file per module for ESM, CJS
297
+ (`.cjs`, with local requires rewritten), and declarations.
298
+
299
+ ### Notes
300
+
301
+ * All changes are additive and backward compatible for valid inputs:
302
+ `drain()` without arguments, `wouldAdmit()` without `detail`, and
303
+ `{ input, maxOutput }` reservation overrides behave exactly as in
304
+ 3.7.0. The only observable difference is the validation-ordering change
305
+ above, which affects invalid requests on closed bulkheads only.
306
+
307
+ ---
308
+
309
+ ## [3.7.0] - 2026-07-20
310
+
311
+ ### Added
312
+
313
+ * **`LLMRequest.system`** — optional system prompt (string or content-block
314
+ array), counted by both built-in estimators exactly like message content.
315
+ Previously, callers had to fold the system prompt into a synthetic message
316
+ for it to participate in estimation, which also distorted events, logs,
317
+ and deduplication keys.
318
+
319
+ * **`LLMRequest.extraInputTokens`** — a first-class channel for input tokens
320
+ the character-based estimators cannot see (tool schemas kept outside
321
+ `messages`, provider-priced media, etc.). Built-in estimators add the
322
+ value verbatim; custom estimators may honor or ignore it. Must be a
323
+ non-negative integer. Because it is an ordinary request field, it
324
+ participates in the default deduplication key — requests differing only
325
+ here are never conflated. This replaces the pattern of smuggling
326
+ out-of-band token costs through wrapper estimators or hidden properties.
327
+
328
+ * **`opaqueBlockTokens` on `createModelAwareTokenEstimator`** — a
329
+ configurable input-token surcharge for opaque (non-text) content blocks:
330
+ either a flat number per block, or `{ default?, byType? }` keyed by
331
+ `block.type`. Applies to blocks in `messages[].content` and `system`
332
+ arrays; validated at estimator creation. Without it, opaque blocks
333
+ contribute 0 input tokens (unchanged default) — an image-heavy request
334
+ estimates as nearly free, which is the wrong direction for admission
335
+ control. Malformed text blocks (`type: "text"` without a string `text`)
336
+ are treated as opaque, erring toward over-reservation.
337
+
338
+ * **Per-call reservation override** — `reservation?: TokenEstimate` on
339
+ `acquire()` / `run()` options and on `wouldAdmit()` options. When
340
+ provided with `tokenBudget` configured, admission reserves
341
+ `input + maxOutput` from the override verbatim and skips the estimator
342
+ for that call. Intended for gateways that already compute a more accurate
343
+ estimate from the full provider request than any character-ratio
344
+ estimator could. Validated as non-negative integers; ignored when
345
+ `tokenBudget` is not configured; not reflected by `estimate()`, which
346
+ always previews the estimator path.
347
+
348
+ ### Notes
349
+
350
+ * All changes are additive and backward compatible: requests without the
351
+ new fields, and estimators without the new option, behave exactly as in
352
+ 3.6.0. Requests that do carry `system` / `extraInputTokens` produce
353
+ different default deduplication keys than hand-rolled 3.6.0 projections
354
+ of the same prompt — as intended, since those fields now distinguish
355
+ requests.
356
+
357
+ ### Added
358
+
359
+ * **Exact reservation preview via `bulkhead.estimate(request)`.** The new
360
+ method runs the same estimator and validation path used by
361
+ `acquire()`, `run()`, and `wouldAdmit()`, returning
362
+ `{ input, maxOutput, reserved }` without acquiring capacity. It returns
363
+ `null` when token-budget admission is disabled. This gives gateways and
364
+ external capacity coordinators one authoritative reservation calculation
365
+ instead of forcing them to duplicate estimator logic.
366
+
367
+ * **Stable admission IDs.** Every successful admission now receives a
368
+ process-unique UUID exposed on the successful `acquire()` result,
369
+ `LLMToken`, `LLMRunContext`, and the `admit` / `release` lifecycle events.
370
+ Admission events also expose the resolved priority, and release events now
371
+ include the pre-release held-token count plus the final usage-event
372
+ sequence. These fields let gateways correlate HTTP requests, traces,
373
+ distributed leases, usage updates, and release records without maintaining
374
+ fragile side maps.
375
+
376
+ * **Ordered `usage` lifecycle events.** Effective cumulative
377
+ `reportUsage()` updates now emit an event containing the admission ID,
378
+ priority, monotonically increasing per-admission sequence, previous/current
379
+ hold, hold delta, cumulative usage, output-cap state, and over-reservation
380
+ status. Duplicate or stale reports that do not increase either cumulative
381
+ usage field are suppressed. Sequence numbers allow external coordinators to
382
+ reject duplicate or out-of-order updates safely. The returned `UsageReport`
383
+ now also includes `admissionId` and the current `sequence`, so a gateway can
384
+ await an external absolute-hold update before forwarding more streamed data.
385
+
386
+ ### Changed
387
+
388
+ * `LLMEventMap["admit"]` and `LLMEventMap["release"]` include additional
389
+ correlation and accounting fields. Existing listener behavior is unchanged;
390
+ the additions are backward-compatible for consumers that read only the
391
+ previous fields.
392
+
393
+ * `request.max_tokens` validation is centralized in the shared reservation
394
+ path, so `estimate()`, `wouldAdmit()`, `acquire()`, and `run()` now validate
395
+ it consistently even when a custom estimator ignores that field.
396
+
397
+ ---
398
+
399
+ ## [3.5.0] - 2026-07-19
400
+
401
+ ### Fixed
402
+
403
+ * **Deduplication no longer silently hands followers a single-consumer
404
+ result.** Dedup shares the leader's resolved value with every follower
405
+ by reference. For plain JSON results that is correct, but for streaming
406
+ results — `ReadableStream`, Node `Readable`, async iterables, `Response`
407
+ bodies — the shared object can only be consumed once: whichever caller
408
+ read first won, and the rest received a locked or drained stream, with
409
+ no error at the bulkhead. Followers whose shared result is detected as
410
+ single-consumer now reject with
411
+ `LLMBulkheadRejectedError("unshareable_result")` (new reject reason,
412
+ counted in `stats().llm.rejectedByReason` and emitted via the `reject`
413
+ event, without capacity detail — like other dedup-wait rejections).
414
+ The **leader is never affected** and always receives the original
415
+ result. Detection is deliberately shallow: only the result value itself
416
+ is inspected, so a stream nested inside a wrapper object is still
417
+ shared by reference as before.
418
+
419
+ ### Added
420
+
421
+ * **`deduplication.shareResult` fan-out hook.** Called once per follower
422
+ with the leader's resolved result; its return value is what that
423
+ follower receives. This is the seam for making streaming dedup
424
+ *work* rather than merely fail loudly — e.g.
425
+ `shareResult: (r) => (r as Response).clone()` for `fetch` responses, or
426
+ a tee/replay of your provider stream. When provided, the hook runs for
427
+ every follower delivery (safe results included) and the
428
+ single-consumer detection is bypassed — the hook owns fan-out policy.
429
+ A throwing hook rejects that follower with the thrown error as-is;
430
+ leader and other followers are unaffected.
431
+
432
+ * **Per-call `dedup: false` on `run()` options.** Opts a single call out
433
+ of deduplication entirely — it neither joins an existing in-flight
434
+ call nor registers as joinable. Intended for streaming routes on a
435
+ bulkhead where dedup is otherwise useful, replacing the previous
436
+ workaround of encoding exemptions in a bulkhead-wide `keyFn`.
437
+ `dedup: true` cannot enable deduplication when it is disabled at the
438
+ bulkhead level and is treated as omitted.
439
+
440
+ ---
441
+
442
+ ## [3.4.1] - 2026-07-18
443
+
444
+ > **Note:** This release is identical in content to what was intended to be
445
+ > published as `3.4.0`. That version was published to npm and then
446
+ > unpublished, and npm's registry policy prevents re-publishing a version
447
+ > number once it has been unpublished. This release republishes the same
448
+ > changes as `3.4.1`.
449
+
450
+ ### Changed
451
+
452
+
453
+ * **Default deduplication key now covers the entire request.** The old key
454
+ serialized only `{messages, max_tokens, model}`, silently conflating
455
+ requests that differed in any other field — identical messages with
456
+ `temperature: 0` vs `temperature: 1` shared one call, and the second
457
+ caller received a response generated under the first caller's parameters.
458
+ The default key is now a key-order-stable serialization of the whole
459
+ request object, so any own enumerable property difference prevents
460
+ conflation. Tradeoff: volatile per-request fields (request IDs,
461
+ timestamps) now also defeat deduplication — supply a custom `keyFn` that
462
+ omits them if your requests carry such fields. Missing a dedup
463
+ opportunity is cheap; serving a wrong-parameters response is a
464
+ correctness bug, so the default errs entirely toward non-conflation.
465
+ Dedup **hit rates may drop** for callers whose requests carry extra
466
+ fields; admission behavior is otherwise unchanged.
467
+
468
+ * **Dedup keys are SHA-256 hashed before storage.** The in-flight map
469
+ previously held full serialized prompt text as its keys — unbounded
470
+ per-entry key memory, and prompt content resident for the lifetime of
471
+ the entry. Keys are now hashed (scope + `\0` + raw key), bounding key
472
+ size and keeping prompt text out of the map. `keyFn` semantics are
473
+ unchanged: it still returns a plain string, and `""` still opts out.
474
+
475
+ * **Bulkhead-level `timeoutMs` no longer applies to dedup followers.**
476
+ `timeoutMs` is documented as a *queue-wait* timeout, but it was also
477
+ being applied to a follower's wait on an already-running shared call.
478
+ Under the `batch` profile (30s default), any LLM call slower than the
479
+ timeout caused every follower to reject with `"timeout"` while the
480
+ leader succeeded — defeating deduplication exactly when calls are long.
481
+ Followers are now capped only by their own `signal` and an *explicitly
482
+ passed* per-call `timeoutMs`. Callers who relied on the bulkhead
483
+ default bounding follower waits should pass `timeoutMs` per call.
484
+
485
+ * **`reportUsage()` after `release()` now reports `held: 0`.** The token's
486
+ internal hold counter was not zeroed at release, so post-release
487
+ snapshots reported the stale pre-release hold while
488
+ `stats().tokenBudget.inFlightTokens` correctly showed the tokens
489
+ returned. Budget accounting was always correct; only the snapshot lied.
490
+ `reserved` continues to report the historical pre-admission reservation.
491
+
492
+ ### Added
493
+
494
+ * **`dedupScope` option on `run()`.** Requests deduplicate only within the
495
+ same scope; different scopes never share an in-flight call even with
496
+ identical keys. Intended for multi-tenant gateways: the default key has
497
+ no tenant dimension, so without a scope (or a tenant-aware `keyFn`),
498
+ two tenants sending byte-identical requests would share one response.
499
+ Default: `""` (single global scope — prior behavior).
500
+
501
+ * Documented explicitly: deduplication applies to `run()` only;
502
+ `acquire()` never deduplicates. (Existing behavior, previously
503
+ undocumented.)
504
+
505
+ ---
506
+
507
+ ## [3.3.1] - 2026-07-17
508
+
509
+ ### Changed
510
+
511
+
512
+ * **`effectiveBudget("normal")` now clamps to `0` instead of going negative.**
513
+ Construction validates `0 <= highPriorityReserve <= budget` (a startup check
514
+ that catches config typos), but `setBudget()` does not re-run that
515
+ validation — a runtime budget update (e.g. driven by a lease-renewal
516
+ ledger) is trusted as-is, since rejecting the ledger's grant would be
517
+ incorrect. This means `currentBudget` can legitimately drop below
518
+ `highPriorityReserve` after `setBudget()`. Previously, the normal-priority
519
+ ceiling (`currentBudget - highPriorityReserve`) could go negative in that
520
+ state, which was surfaced as a negative `effectiveBudget`/`available` in
521
+ `stats()` and rejection `detail`. It is now `Math.max(0, currentBudget -
522
+ highPriorityReserve)`.
523
+ * **Behavioral consequence (unchanged, now made explicit):** when the
524
+ budget grant drops below the reserve, normal-priority requests are
525
+ fully rejected with `"budget_limit"` while `priority: "high"` requests
526
+ are still checked against the full (shrunk) `currentBudget` and can
527
+ keep admitting whatever capacity remains. This is the intended degraded
528
+ behavior — `highPriorityReserve` exists specifically to protect
529
+ interactive traffic when capacity is scarce, and capacity is never
530
+ scarcer than when the grant itself falls below the reserve.
531
+ * Admission decisions were already correct in this scenario (a negative
532
+ ceiling already rejected every normal-priority request); this change
533
+ only corrects the *reported* numbers (`stats().tokenBudget`, rejection
534
+ `detail.tokenBudget`) from negative to `0`.
535
+ * Construction-time validation (`highPriorityReserve <= budget`) is
536
+ unchanged.
537
+
538
+ ---
539
+
540
+
541
+ ## [3.3.0] - 2026-07-17
542
+
543
+ ### Changed
544
+
545
+ * **`tokenBudget.budget: 0` is now accepted at construction.** Previously,
546
+ `createLLMBulkhead({ tokenBudget: { budget: 0 } })` threw because `budget`
547
+ was validated as a positive integer. A budget of `0` is a legitimate state
548
+ — e.g. a lease ledger reporting pool exhaustion for the current cycle — and
549
+ the bulkhead now represents it as "reject all budget-gated admissions"
550
+ rather than an invalid configuration. `budget` is now validated as a
551
+ non-negative integer, matching the existing validation already used by
552
+ `setBudget()`. Admission behavior is unaffected for any `budget > 0`; a
553
+ `budget: 0` bulkhead rejects every admission that needs `> 0` tokens with
554
+ `"budget_limit"`, and admits requests whose estimator produces a `0`-token
555
+ reservation, consistent with `effectiveBudget()`/`tryReserveTokens()`
556
+ semantics already in place for runtime-lowered budgets.
557
+
558
+ ### Added
559
+
560
+ * **`bulkhead.setBudget(tokens)`** — mutate the token budget ceiling at
561
+ runtime. All admission math (`acquire`/`run`, `wouldAdmit`, rejection
562
+
563
+ `detail`, `stats()`) reads the ceiling dynamically, so a call to
564
+ `setBudget()` propagates immediately with no other behavioral changes.
565
+ * **Raising takes effect immediately** — the very next admission check
566
+ sees the new headroom.
567
+ * **Lowering below `inFlightTokens` is legal — shrink by attrition.**
568
+ No in-flight work is revoked or cancelled. New admissions reject with
569
+ `"budget_limit"` until enough in-flight work releases to bring
570
+ `inFlightTokens` back under the new ceiling. This is consistent with
571
+ the library's existing overrun tolerance (`inFlightTokens` can already
572
+ exceed `budget` via `reportUsage()` overrun) and is pinned with a
573
+ dedicated test.
574
+ * **Throws if `tokenBudget` was never configured** at construction — an
575
+ explicit error beats a silent no-op.
576
+ * **Validates `tokens`** as a non-negative integer (`0` is valid and
577
+ fully closes admission).
578
+
579
+ ### Notes
580
+
581
+ * Purely additive: existing `tokenBudget.budget` behavior is unchanged for
582
+ bulkheads that never call `setBudget()`.
583
+
584
+ ---
585
+
586
+ ## [3.2.0] - 2026-07-14
587
+
588
+
589
+ Gateway-readiness release. All changes are additive (semver-minor).
590
+
591
+ ### Added
592
+
593
+ * **`LLMToken.reportUsage(usage)` / run-context `ctx.reportUsage(usage)`** —
594
+ mid-flight cumulative usage reporting for streaming workloads.
595
+ * Input over-estimates are refunded to the budget immediately (the full
596
+ output reservation is retained until release).
597
+ * Consumption beyond the hold `expands it (overrun), which can push
598
+ `inFlightTokens` above `budget` and correctly blocks new admissions
599
+ until the overrunning request releases.
600
+ * Reports are clamped monotonically non-decreasing per field.
601
+ * `release()` without explicit usage falls back to the last reported
602
+ usage for the final refund.
603
+ * Returns a `UsageReport` snapshot (`reserved`, `held`, `consumed`,
604
+ `outputCap`, `outputRemaining`, `overReservation`).
605
+ * **Priority admission** — `tokenBudget.highPriorityReserve` plus per-call
606
+ `priority: "high" | "normal"` on `acquire()`/`run()`. Normal-priority
607
+ admission is checked against `budget - highPriorityReserve`; high-priority
608
+ against the full budget.
609
+ * **Rejection detail** — failed `acquire()` results, `reject` events, and
610
+ `LLMBulkheadRejectedError` now carry an optional `detail: LLMRejectDetail`
611
+ capacity snapshot (slots, queue, priority-adjusted budget numbers).
612
+ * **`wouldAdmit(request, { priority })`** — advisory, non-reserving dry-run
613
+ for routing decisions. Documented as racy.
614
+ * **Stats** — `tokenBudget.totalOverrun` and `tokenBudget.highPriorityReserve`.
615
+ * New exported types: `UsageReport`, ``LLMRunContext`, `LLMPriority`,
616
+ `LLMRejectDetail`, `LLMAcquireOptions`.
617
+
618
+ ### Changed
619
+
620
+ * `run()` callbacks now receive an optional second argument
621
+ (`LLMRunContext`). Existing single-argument callbacks are unaffected.
622
+ * Release-event semantics when `reportUsage()` was used: `refundedTokens`
623
+ on the `release` event reflects the refund *at release* (against the
624
+ current hold); early refunds from `reportUsage()` are already included
625
+ in `stats().tokenBudget.totalRefunded` as they occur. When
626
+ `reportUsage()` is never called, behavior is byte-identical to 3.1.x.
627
+
628
+ ### Notes
629
+
630
+ * Single-process by design: distributed budget coordination across replicas
631
+ is explicitly out of scope (see README "Scope note").
632
+ * Backward compatible: the full 3.1.x test suite passes unmodified.
633
+
634
+ ---
635
+
636
+ ## [3.1.2] — 2026-05-11
637
+ `
638
+ ### Fixed
639
+
640
+ * **Hardened token accounting input validation.** `tokenBudget.budget`, `tokenBudget.outputCap`, `request.max_tokens`, estimator output, and reported `TokenUsage` are now validated as finite non-negative integer token counts, with `tokenBudget.budget` required to be positive. Invalid usage passed to `release()` still releases capacity before surfacing the validation error.
641
+ * **Avoided duplicate estimator calls during admission.** Token reservation is now estimated once per acquisition attempt, then rechecked against the current budget after the underlying bulkhead slot is acquired.
642
+ * **Deduped caller cancellation.** Callers that join an existing in-flight deduplicated request now honor their own `AbortSignal` and `timeoutMs` while leaving the shared provider call running for other waiters.
643
+ * **CJS source maps after rename.** The CommonJS rename script now rewrites `sourceMappingURL` trailers and source map `file` fields from `.js` to `.cjs`.
644
+ * **Coverage setup.** Added the missing V8 coverage provider and a `test:coverage` script so `vitest run --coverage` works from a clean install.
645
+ * **Release checks.** Added stricter release scripts for lint, deterministic test runs, coverage, package smoke checks, and `npm pack --dry-run`.
646
+ * **Reduced build noise.** The CommonJS rename script no longer writes routine diagnostics during build or pack.
647
+ * **Security policy.** Updated supported versions to the current `3.x` line and removed the placeholder security email.
648
+ * **Deduplication docs.** Fixed the public JSDoc for the default deduplication key to include `model`, matching the implementation and README.
649
+
650
+ ### Tests
651
+
652
+ * Added coverage for invalid token options, invalid request `max_tokens`, invalid estimator output, invalid usage reporting, one-estimation-per-acquire behavior, deduped abort/timeout behavior, and packaged ESM/CJS smoke checks.
653
+
654
+ ### Notes
655
+
656
+ * Patch release: this is a hardening and packaging maintenance release. It rejects invalid numeric inputs that previously produced undefined or unsafe accounting states, but does not intentionally change supported valid API usage.
657
+
658
+ ---
659
+
660
+ ## [3.1.1] — 2026-05-06
661
+
662
+ ### Fixed
663
+
664
+ * **`createModelAwareTokenEstimator({ defaultModel })` typing.** The estimator factory now accepts an options object as the first argument when it includes `defaultModel`, matching external call-site expectations and avoiding the previous TypeScript error where `defaultModel` was interpreted as a numeric ratio override.
665
+
666
+ ### Notes
667
+
668
+ * Backward-compatible patch release. Existing `createModelAwareTokenEstimator(overrides, opts)` calls continue to work.
669
+ * Single-argument ratio overrides remain supported.
670
+ * No runtime changes to token estimation, admission, release, refund, deduplication, event, or shutdown semantics.
671
+
672
+ ---
673
+
674
+ ## [3.1.0] — 2026-04-26
675
+
676
+ ### Added
677
+
678
+ * **`stats().tokenBudget.totalReserved`** — cumulative tokens reserved at admission across all successful admissions. Monotonically increasing. Useful as the numerator companion to `inFlightTokens`/`available` for rate and saturation analysis over time.
679
+ * **`stats().tokenBudget.totalConsumed`** — cumulative actual tokens consumed (`usage.input + usage.output`), summed across releases that reported `TokenUsage` via `token.release(usage)` or `run({ getUsage })`. Releases without usage contribute 0 — `totalConsumed` is meaningful only when `getUsage` is wired up consistently. Not clamped: over-consumption (actual > reserved) is reported as-is.
680
+ When `getUsage` is wired consistently and no over-consumption occurs, the invariant `totalReserved == totalConsumed + totalRefunded` holds after all in-flight requests settle.
681
+
682
+ ### Changed
683
+
684
+ * No changes to admission, release, refund, deduplication, event, or shutdown semantics.
685
+ * **Documentation:** expanded the `release` event JSDoc to document the per-request consumption math (`usage ? usage.input + usage.output : null`) and the `null` vs `0` distinction for unreported usage. Pure docstring change — no API or behavior change.
686
+
687
+ ### Notes
688
+
689
+ * Strict superset of the existing `totalRefunded` field — no breaking changes.
690
+ * Both new fields are present whenever `tokenBudget` is configured (alongside `totalRefunded`); both are absent when `tokenBudget` is omitted.
691
+ * These counters are designed for the library's existing scope: saturation tracking, throughput analysis, and refund-efficiency tuning (e.g., `totalRefunded / totalReserved` to surface overly generous `max_tokens` settings).
692
+ * For accurate cost accounting, the `release` event remains the right primitive — it preserves the input/output split from `TokenUsage`, which `totalConsumed` collapses into a single sum. Token estimation in this library is approximate and intentionally suited to load-shedding, not finance-grade reconciliation.
693
+
694
+ ---
695
+
696
+ ## [3.0.0] — 2026-04-15
697
+
698
+ ### Breaking Changes
699
+
700
+ * **`LLMStats` shape changed.** `bulkhead.stats()` no longer returns base `Stats` fields at the top level.
701
+ Base bulkhead stats now live under `stats().bulkhead`, and LLM-layer counters now live under
702
+ `stats().llm`.
703
+ * Code that previously accessed:
704
+ * `stats().inFlight`
705
+ * `stats().pending`
706
+ * `stats().maxConcurrent`
707
+ * `stats().maxQueue`
708
+ * `stats().closed`
709
+
710
+ must now read:
711
+ * `stats().bulkhead.inFlight`
712
+ * `stats().bulkhead.pending`
713
+ * `stats().bulkhead.maxConcurrent`
714
+ * `stats().bulkhead.maxQueue`
715
+ * `stats().bulkhead.closed`
716
+
717
+ ### Added
718
+
719
+ * `stats().llm` block with LLM-layer request counters:
720
+ * `admitted`
721
+ * `released`
722
+ * `rejected`
723
+ * `rejectedByReason`
724
+
725
+ ### Changed
726
+
727
+ * The `run()` callback signal type now derives from `AcquireOptions["signal"]`
728
+ instead of referring to the global `AbortSignal` type directly.
729
+ * Test utilities now avoid direct dependency on ambient `AbortController` globals.
730
+ * Bumped `async-bulkhead-ts` to `^0.4.1`.
731
+
732
+ ### Migration Guide
733
+
734
+ **From v2 → v3, update stats access only.**
735
+
736
+ Before:
737
+
738
+ ```ts
739
+ const s = bulkhead.stats();
740
+ s.inFlight;
741
+ s.pending;
742
+ ```
743
+
744
+ After:
745
+
746
+ ```ts
747
+ const s = bulkhead.stats();
748
+ s.bulkhead.inFlight;
749
+ s.bulkhead.pending;
750
+ ```
751
+
752
+ LLM-layer counters are now separate:
753
+
754
+ ```ts
755
+ const s = bulkhead.stats();
756
+ s.llm.admitted;
757
+ s.llm.rejected;
758
+ s.llm.rejectedByReason.budget_limit;
759
+ ```
760
+
761
+ ### Notes
762
+
763
+ * No change to admission semantics, token budget semantics, deduplication behavior,
764
+ or graceful shutdown behavior.
765
+ * This release separates underlying bulkhead telemetry from LLM-layer request telemetry.
766
+
767
+ ---
768
+
769
+ ## [2.0.0] — 2026-03-03
770
+
771
+ ### Breaking Changes
772
+
773
+ * **Multimodal content:** `LLMMessage.content` is now `string | ContentBlock[]`. Plain strings remain valid — no changes required for text-only callers. Code that assumed `content` is always a `string` (e.g. `m.content.length`) must be updated to use `extractTextLength()` or handle both shapes.
774
+ * **Deduplication key:** the default key now includes `max_tokens` and `model` in addition to message content. Requests with identical messages but different `max_tokens` are no longer treated as duplicates (they were in v1). This is a behavioral change with no API signature change.
775
+ * **`LLMToken` replaces `Token`:** the token returned by `acquire()` now accepts optional `TokenUsage` at release time: `token.release(usage?)`. Callers that call `release()` with no arguments are unaffected.
776
+ * **`LLMStats.tokenBudget` shape:** added `totalRefunded` field to the token budget stats block.
777
+
778
+ ### Added
779
+
780
+ * **Token refund mechanism.** When `TokenUsage` is passed to `token.release(usage)` or extracted via `getUsage` in `run()`, the bulkhead returns the difference between the pre-admission reservation and actual consumption to the budget immediately. This dramatically improves budget utilization — requests that use fewer output tokens than `max_tokens` no longer hold phantom capacity.
781
+ * **`run()` `getUsage` option.** `run(request, fn, { getUsage })` accepts a function that extracts `TokenUsage` from the result of `fn`. The refund is applied automatically on successful completion.
782
+ * **Per-request model override.** `LLMRequest.model` is now an optional field. When present, the model-aware estimator uses it for ratio lookup instead of the bulkhead-level `defaultModel`. Supports A/B testing, canary deployments, and mixed-model routing.
783
+ * **Multimodal content blocks.** `LLMMessage.content` accepts `ContentBlock[]` with typed `TextContentBlock` and `OpaqueContentBlock` variants. Built-in estimators extract text from text blocks and ignore non-text blocks. `extractTextLength()` is exported as a utility.
784
+ * **Custom deduplication key.** `deduplication` now accepts `DeduplicationOptions` with a `keyFn` property. The default key function includes `messages`, `max_tokens`, and `model`. Return an empty string from `keyFn` to opt a specific request out of deduplication.
785
+ * **Event system.** `bulkhead.on(event, listener)` subscribes to lifecycle events: `'admit'`, `'reject'`, `'release'`, `'dedup'`. Returns an unsubscribe function. Listeners are called synchronously; exceptions are silently caught.
786
+ * **Graceful shutdown.** `bulkhead.close()` stops admission permanently. `bulkhead.drain()` returns a promise that resolves when all in-flight work completes. Compose as `close()` → `drain()` for clean shutdown. Both are forwarded from `async-bulkhead-ts`.
787
+ * **Expanded model ratios.** Built-in ratio table now includes: `claude-haiku-4`, `claude-sonnet-4-5`, `claude-opus-4-5`, `claude-haiku-4-5`, `gpt-4.1`, `o4-mini`, `gemini-2.5`.
788
+ * **`LLMStats.tokenBudget.totalRefunded`** — cumulative tokens returned to the budget via the refund mechanism.
789
+
790
+ ### Changed
791
+
792
+ * `createModelAwareTokenEstimator` now checks `request.model` before `defaultModel` for ratio lookup.
793
+ * Default deduplication key includes `max_tokens` and `model` (see Breaking Changes).
794
+ * Prefix matching in the estimator now uses an iterative longest-match scan instead of `filter + sort`, avoiding an allocation per call.
795
+ * `LLMBulkhead` return type now includes `close`, `drain`, and `on` methods.
796
+
797
+ ### Removed
798
+
799
+ * Nothing removed. All v1 public types remain exported.
800
+
801
+ ### Migration Guide
802
+
803
+ **From v1 → v2, most callers need zero changes.** The common path — `createLLMBulkhead(opts)` → `bulkhead.run(request, fn)` — is fully backward-compatible for text-only requests.
804
+
805
+ Changes required only if you:
806
+
807
+ 1. **Access `content` directly on `LLMMessage`:** replace `m.content.length` with `extractTextLength(m.content)` or guard with `typeof m.content === 'string'`.
808
+ 2. **Rely on dedup treating different `max_tokens` as identical:** pass a custom `keyFn` that omits `max_tokens`: `deduplication: { keyFn: (r) => JSON.stringify(r.messages) }`.
809
+ 3. **Inspect `tokenBudget` stats structurally:** the new `totalRefunded` field is always present when `tokenBudget` is configured.
810
+
811
+ ### Design Notes
812
+
813
+ * Token refund is opt-in and zero-cost when not used. Calling `release()` with no argument behaves identically to v1.
814
+ * `getUsage` is intentionally separated from `fn` to avoid coupling the LLM call signature to the bulkhead. The caller extracts usage from whatever their provider returns.
815
+ * The event system is deliberately minimal — synchronous, fire-and-forget, no async listeners. It's designed for metrics counters and logging, not for control flow.
816
+ * `close()` and `drain()` are thin forwards to `async-bulkhead-ts`. The LLM layer adds no new shutdown semantics — it inherits the base library's guarantees.
817
+ * Multimodal estimation is intentionally conservative. Non-text blocks contribute zero to the estimate. Callers who need accurate multimodal estimation should provide a custom `estimator`.
818
+
819
+ ---
820
+
821
+ ## [1.0.3] — 2026-02-26
822
+
823
+ ### Changed
824
+
825
+ * Aligned package.json license field with the repository license (Apache-2.0)
826
+ * No runtime, API, or type changes
827
+
828
+ ### Notes
829
+
830
+ * Metadata-only correction
831
+ * Fully compatible with 1.0.0–1.0.2
832
+ * Safe upgrade
833
+
834
+ ---
835
+
836
+ ## [1.0.2] — 2026-02-26
837
+
838
+ ### Changed
839
+
840
+ * Corrected GitHub URLs in `package.json` (homepage, repository, bugs) to point to the canonical repository
841
+ * No runtime, API, or type changes
842
+
843
+ ### Notes
844
+
845
+ * Packaging outputs (ESM, CJS, types) unchanged
846
+ * Fully compatible with `1.0.0` and `1.0.1`
847
+ * Safe upgrade — metadata-only correction
848
+
849
+ ---
850
+
851
+ ## [1.0.1] — 2026-02-26
852
+
853
+ ### Changed
854
+
855
+ * Bumped `async-bulkhead-ts` to `^0.3.0`
856
+
857
+ ### Notes
858
+
859
+ * No API changes
860
+ * No functional behavior changes in `async-bulkhead-llm`
861
+
862
+ ---
863
+
864
+ ## [1.0.0] — 2026-02-24
865
+
866
+ ### Added
867
+
868
+ * Initial release of **async-bulkhead-llm**
869
+ * `createLLMBulkhead(options)` — fail-fast admission control for LLM workloads, wrapping `async-bulkhead-ts`
870
+ * `model` required at construction time — one bulkhead per model is the enforced deployment pattern
871
+ * `profile` option — `'interactive'` (fail-fast, default) and `'batch'` (bounded queue, 30s timeout) presets; escape hatch via plain `LLMBulkheadPreset` object; explicit options always override preset defaults
872
+ * Token-aware admission via `tokenBudget` — reserves `input + maxOutput` tokens pre-admission; fail-fast when the budget ceiling is hit, independent of concurrency headroom and profile
873
+ * `naiveTokenEstimator` — flat 4.0 character-per-token ratio; zero configuration; suitable for load-shedding
874
+ * `createModelAwareTokenEstimator` — per-model character ratios for known model families across Anthropic, OpenAI, and Google; longest-prefix match; exact caller overrides checked before prefix scan; `onUnknownModel` hook; falls back to 4.0 ratio for unknown models
875
+ * In-flight request deduplication via `deduplication: true` — identical requests (keyed on `JSON.stringify(messages)`) share one in-flight LLM call; dedup hits tracked in `stats()`
876
+ * `bulkhead.run(request, fn, options?)` — primary API; acquire + release handled automatically; throws `LLMBulkheadRejectedError` on rejection
877
+ * `bulkhead.acquire(request, options?)` — manual acquire / release for advanced control flow; returns typed result object
878
+ * `LLMBulkheadRejectedError` — typed error with `code: 'LLM_BULKHEAD_REJECTED'` and `reason: LLMRejectReason`
879
+ * `LLMRejectReason` — extends base `RejectReason` from `async-bulkhead-ts` with `'budget_limit'`
880
+ * `TokenUsage` type — exported as a forward-looking type for v2 refund support; not acted on in v1
881
+ * `bulkhead.stats()` — returns `LLMStats` extending the base `Stats` type with optional `tokenBudget` and `deduplication` blocks; optional blocks are absent when the feature is disabled
882
+ * `PROFILES` exported — named presets available for direct inspection and composition
883
+ * AbortSignal and `timeoutMs` cancellation — threaded through to `fn` via `run()`; waiting-only timeout semantics inherited from `async-bulkhead-ts`
884
+ * ESM and CommonJS builds
885
+ * Full TypeScript typings
886
+ * Vitest test suite covering estimation, admission, token budget, deduplication, cancellation, profile resolution, and a 4-second soak test validating all invariants under churn
887
+
888
+ ### Design Notes
889
+
890
+ * Fail-fast is the opinionated default — `maxQueue: 0` unless overridden via `profile` or explicit option
891
+ * Token budget admission is always fail-fast, independent of queue configuration — budget is a cost ceiling, not a scheduling constraint
892
+ * One bulkhead per model is enforced by design; `model` is a required constructor argument and does not appear on `LLMRequest`; multi-model routing is documented as a README recipe
893
+ * Token estimation is intentionally approximate — suitable for load-shedding, not cost accounting
894
+ * Refund mechanism (correcting reservations against actual post-call usage) is deferred to v2; `TokenUsage` type is exported now to allow call sites to be written correctly ahead of v2
895
+ * Multimodal content (images, structured blocks) is a known v1 limitation — `content` must be a plain string; estimators ignore non-string content; documented on `LLMRequest`
896
+ * Deduplication key is `JSON.stringify(messages)` in v1 — requests with identical messages but different `max_tokens` are treated as duplicates; key design improvements deferred to v2
897
+ * `tryAcquire()` from the base library is not exposed — synchronous non-blocking admission is not meaningful for LLM workloads where token budget requires the full request object
898
+ * Zero dependencies beyond `async-bulkhead-ts`
899
+
900
+ ---