async-bulkhead-llm 3.8.0 → 3.10.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
@@ -9,6 +9,7 @@ Designed for services that need to enforce **cost ceilings, concurrency limits,
9
9
  ## Features
10
10
 
11
11
  - ✅ Hard **max in-flight** concurrency (`maxConcurrent`)
12
+ - ✅ **Atomic versioned limit updates** — apply concurrency, queue, token budget, and priority reserve as one revisioned snapshot
12
13
  - ✅ **Token-aware admission** — reserves against estimated input + max output tokens
13
14
  - ✅ **Token refund** — reclaim unused budget capacity from actual usage post-completion
14
15
  - ✅ **Model-aware estimation** — per-model character ratios for known providers
@@ -17,6 +18,7 @@ Designed for services that need to enforce **cost ceilings, concurrency limits,
17
18
  - ✅ **Full-request estimation** — `system` prompts counted natively; `extraInputTokens` carries caller-computed costs (tool schemas, provider-priced media)
18
19
  - ✅ **Per-call reservation override** — gateways with their own estimate can bypass the estimator via `reservation` on `acquire()`/`run()`/`wouldAdmit()`
19
20
  - ✅ **Fail-fast by default** — shed load early, never silently queue
21
+ - ✅ **Observe/shadow mode** — measure capacity-policy impact while still executing selected would-be-rejected calls
20
22
  - ✅ **Opinionated profiles** — `'interactive'` and `'batch'` presets with escape hatch
21
23
  - ✅ **In-flight deduplication** — identical requests share one LLM call; hashed keys, whole-request equality
22
24
  - ✅ **Custom dedup key + per-tenant scope** — bring your own equivalence function; `dedupScope` isolates tenants
@@ -26,7 +28,7 @@ Designed for services that need to enforce **cost ceilings, concurrency limits,
26
28
  - ✅ **Advisory capacity snapshots** — `wouldAdmit(request, { detail: true })` returns the same capacity numbers rejections carry
27
29
  - ✅ **Stable admission IDs** — correlate gateway requests, traces, usage, and release
28
30
  - ✅ **Ordered usage events** — sequence-numbered hold changes for external coordinators
29
- - ✅ **Event hooks** — `on('admit' | 'reject' | 'usage' | 'release' | 'dedup', fn)`
31
+ - ✅ **Event hooks** — admitted and bypassed lifecycles have separate telemetry events
30
32
  - ✅ **Graceful shutdown** — `close()` + `drain()`, with an optional bounded wait: `drain({ timeoutMs })`
31
33
  - ✅ Optional **AbortSignal** and **timeout** cancellation
32
34
  - ✅ `bulkhead.run(request, fn)` — acquire + release handled automatically
@@ -55,6 +57,7 @@ Non-goals (by design):
55
57
  | **Concurrency limits** | ✅ Yes | ⚠️ Indirect | ❌ No | ✅ Yes | ⚠️ Indirect |
56
58
  | **Bounded queue (optional)** | ✅ Yes | ⚠️ Internal | ❌ No | ✅ Yes | ⚠️ Indirect |
57
59
  | **Fail-fast overload handling** | ✅ Core feature | ❌ No | ❌ No | ❌ No | ⚠️ Indirect |
60
+ | **Observe/shadow rollout mode** | ✅ Yes | ❌ No | ❌ No | ❌ No | ❌ No |
58
61
  | **In-flight deduplication** | ✅ Yes | ⚠️ Partial caching | ❌ No | ❌ No | ❌ No |
59
62
  | **Custom dedup key** | ✅ Yes | ❌ No | ❌ No | ❌ No | ❌ No |
60
63
  | **Model-aware estimation** | ✅ Yes | ❌ No | ❌ No | ❌ No | ❌ No |
@@ -130,6 +133,150 @@ const result = await bulkhead.run(request, async () => {
130
133
 
131
134
  ---
132
135
 
136
+ ## What's New in v3.10 — Atomic, versioned admission limits
137
+
138
+ v3.10 makes `async-bulkhead-llm` safer to operate from gateways and distributed
139
+ control-plane agents. All mutable admission limits can now be replaced in one
140
+ validated, revisioned snapshot instead of being updated independently.
141
+
142
+ ### Highlights
143
+
144
+ - **Atomic updates:** `maxConcurrent`, `maxQueue`, token budget, and
145
+ high-priority reserve change together or not at all.
146
+ - **Stale-update protection:** every snapshot carries a strictly increasing
147
+ `revision`; equal or older revisions are rejected without mutating state.
148
+ - **Shrink by attrition:** lowering limits never cancels in-flight work or
149
+ already accepted queue waiters. New work is admitted only as capacity returns.
150
+ - **Immediate scale-up:** raising concurrency starts eligible queued work as soon
151
+ as the new snapshot is applied.
152
+ - **Runtime kill switch:** setting `maxConcurrent` to `0` stops new admissions
153
+ while existing work drains normally.
154
+ - **Observable state:** `limits()`, `stats().limits`, and the `reconfigure` event
155
+ expose the active revision and previous/current snapshots.
156
+
157
+ ```ts
158
+ const result = bulkhead.applyLimits({
159
+ revision: 42,
160
+ maxConcurrent: 12,
161
+ maxQueue: 0,
162
+ tokenBudget: {
163
+ budget: 120_000,
164
+ highPriorityReserve: 20_000,
165
+ },
166
+ });
167
+
168
+ if (!result.applied) {
169
+ // Equal and lower revisions are ignored without mutation.
170
+ console.log(result.reason); // "stale_revision"
171
+ }
172
+ ```
173
+
174
+ Use `initialRevision` when restoring persisted control-plane state. A configured
175
+ token budget must remain configured in every later snapshot; estimator and
176
+ output-cap policy remain construction-time settings. `setBudget()` is still
177
+ supported for local use, but distributed integrations should use
178
+ `applyLimits()` exclusively so a single authority owns the revision sequence.
179
+
180
+ ---
181
+
182
+ ## What's New in v3.9 — First-class observe mode
183
+
184
+ v3.9 adds an explicit rollout mode for measuring admission policy before fully
185
+ enforcing it. `run()` still attempts normal admission first. When a configured
186
+ capacity-related rejection occurs, observe mode executes the callback without
187
+ holding a concurrency slot or token reservation and records the bypass on a
188
+ separate telemetry surface.
189
+
190
+ ```ts
191
+ const result = await bulkhead.run(
192
+ request,
193
+ async (signal, ctx) => {
194
+ logger.info({
195
+ admissionId: ctx?.admissionId,
196
+ admission: ctx?.admission, // "admitted" | "bypassed"
197
+ bypassReason: ctx?.bypassReason, // set only for bypassed work
198
+ bypassDetail: ctx?.bypassDetail, // capacity snapshot, when available
199
+ });
200
+
201
+ return callYourLLMProvider(request, {
202
+ signal,
203
+ onUsage: (usage) => ctx?.reportUsage(usage),
204
+ });
205
+ },
206
+ { mode: "observe" },
207
+ );
208
+ ```
209
+
210
+ By default, observe mode may bypass these capacity outcomes:
211
+
212
+ ```ts
213
+ "budget_limit" | "concurrency_limit" | "queue_limit" | "timeout"
214
+ ```
215
+
216
+ Shutdown, caller cancellation, and unsafe deduplication fan-out remain hard
217
+ failures. Observe mode is therefore not a global "ignore every rejection"
218
+ switch.
219
+
220
+ ### Restrict which outcomes may be bypassed
221
+
222
+ Use `shadowReasons` to roll out one policy at a time:
223
+
224
+ ```ts
225
+ await bulkhead.run(request, fn, {
226
+ mode: "observe",
227
+ shadowReasons: ["budget_limit"],
228
+ });
229
+ ```
230
+
231
+ An empty `shadowReasons` array keeps normal enforcement while still exposing
232
+ `ctx.admission === "admitted"` to callbacks.
233
+
234
+ ### Admitted and bypassed callback context
235
+
236
+ Normally admitted calls receive the same context with:
237
+
238
+ ```ts
239
+ ctx.admission === "admitted"
240
+ ctx.bypassReason === undefined
241
+ ```
242
+
243
+ Bypassed calls receive a `shadow-`-prefixed `admissionId`, the exact evaluated
244
+ reservation, the bypass reason, and the associated capacity detail. Their
245
+ `reportUsage()` snapshots always report `held: 0`, because observed work does
246
+ not consume bulkhead accounting capacity.
247
+
248
+ ### Separate observe telemetry
249
+
250
+ Bypassed work does not increment normal `admit`/`release` counters. It is
251
+ reported through:
252
+
253
+ ```ts
254
+ bulkhead.on("bypass", listener);
255
+ bulkhead.on("bypassUsage", listener);
256
+ bulkhead.on("bypassRelease", listener);
257
+
258
+ const observe = bulkhead.stats().observe;
259
+ // {
260
+ // bypassed,
261
+ // raceBypassed,
262
+ // bypassedByReason,
263
+ // usageReported,
264
+ // totalInputTokens,
265
+ // totalOutputTokens,
266
+ // }
267
+ ```
268
+
269
+ `raceBypassed` counts calls whose advisory check passed but whose authoritative
270
+ acquisition later rejected—for example, a queued request that timed out while
271
+ capacity changed. This makes preview-to-admission races visible instead of
272
+ silently merging them into ordinary bypasses.
273
+
274
+ > Observe mode intentionally allows work to proceed without capacity
275
+ > protection. Use it for policy calibration, migration, and audit periods—not
276
+ > as the steady-state overload posture of a saturated service.
277
+
278
+ ---
279
+
133
280
  ## What's New in v3.8 — Feedback and shutdown ergonomics
134
281
 
135
282
  ### Bounded drain
@@ -486,7 +633,7 @@ const off = bulkhead.on('release', ({ reservedTokens, refundedTokens, usage }) =
486
633
  off(); // unsubscribe
487
634
  ```
488
635
 
489
- Events: `'admit'`, `'reject'`, `'usage'`, `'release'`, `'dedup'`.
636
+ Events: `'admit'`, `'reject'`, `'usage'`, `'release'`, `'reconfigure'`, `'dedup'`.
490
637
 
491
638
  ### Graceful Shutdown
492
639
 
@@ -607,28 +754,70 @@ adaptive.corrections(); // per-model calibration snapshot
607
754
  adaptive.reset(); // clear calibration
608
755
  ```
609
756
 
610
- ### Runtime Budget Adjustment
757
+ ### Atomic Runtime Reconfiguration
611
758
 
612
- `setBudget(tokens)` mutates the token budget ceiling at runtime — useful for gateways that adjust cost limits based on external signals (billing tier changes, incident response, time-of-day throttling) without recreating the bulkhead.
759
+ `applyLimits(snapshot)` is the preferred runtime control surface for gateways
760
+ and distributed control-plane agents. The snapshot is complete rather than
761
+ partial, so concurrency, queue, budget, and reserve values cannot drift across
762
+ separate setter calls.
613
763
 
614
764
  ```ts
615
765
  const bulkhead = createLLMBulkhead({
616
- model: 'claude-sonnet-4',
766
+ model: 'claude-sonnet-4',
617
767
  maxConcurrent: 10,
618
- tokenBudget: { budget: 200_000 },
768
+ maxQueue: 0,
769
+ initialRevision: 100,
770
+ tokenBudget: {
771
+ budget: 200_000,
772
+ highPriorityReserve: 25_000,
773
+ },
619
774
  });
620
775
 
621
- bulkhead.setBudget(300_000); // raise the ceiling
622
- bulkhead.setBudget(50_000); // shrink the ceiling
776
+ const update = bulkhead.applyLimits({
777
+ revision: 101,
778
+ maxConcurrent: 6,
779
+ maxQueue: 20,
780
+ tokenBudget: {
781
+ budget: 90_000,
782
+ highPriorityReserve: 15_000,
783
+ },
784
+ });
785
+ ```
786
+
787
+ Semantics:
788
+
789
+ * **Strictly increasing revision.** Equal or lower revisions return a stale
790
+ result and do not mutate any limit.
791
+ * **Full validation before mutation.** Invalid higher-revision snapshots throw
792
+ while the previous revision remains active.
793
+ * **Shrink by attrition.** In-flight work and accepted queue waiters are never
794
+ revoked. New admissions obey the lower ceilings immediately.
795
+ * **Immediate expansion.** Raising `maxConcurrent` pumps accepted waiters in
796
+ the same synchronous update, after the complete LLM-layer snapshot is active.
797
+ * **Zero-concurrency kill switch.** `maxConcurrent: 0` rejects new callers with
798
+ `"concurrency_limit"` instead of queueing them.
799
+ * **Budget reserve may exceed a shrunken budget.** The normal-priority ceiling
800
+ is clamped to 0 while high-priority traffic is checked against the full
801
+ budget, preserving the existing degraded-priority behavior.
802
+ * **Budget feature shape is fixed at construction.** A bulkhead created with
803
+ `tokenBudget` requires `tokenBudget` in every update. A bulkhead created
804
+ without it must omit that field; estimator policy is not hot-swapped.
805
+
806
+ ```ts
807
+ const current = bulkhead.limits();
808
+ // { revision, maxConcurrent, maxQueue, tokenBudget? }
809
+
810
+ bulkhead.on('reconfigure', ({ previous, current }) => {
811
+ publishAppliedRevision(previous.revision, current.revision);
812
+ });
623
813
  ```
624
814
 
625
- Semantics, pinned deliberately:
815
+ #### Compatibility: `setBudget(tokens)`
626
816
 
627
- * **Raising takes effect immediately.** The very next `acquire()`/`run()`/`wouldAdmit()` call sees the new headroom — there is no caching to invalidate.
628
- * **Lowering below `inFlightTokens` is legal — shrink by attrition.** No in-flight request is revoked or cancelled. New admissions reject with `"budget_limit"` until enough in-flight work releases to bring `stats().tokenBudget.inFlightTokens` back under the new ceiling. This is consistent with the library's existing overrun tolerance — `inFlightTokens` can already exceed `budget` via `reportUsage()` overrun, so an over-budget in-flight state is an established, intentional condition rather than an edge case.
629
- * **Throws if `tokenBudget` was never configured at construction.** There is no ceiling to adjust, so an explicit error is raised instead of silently no-op'ing.
630
- * **Validates `tokens` as a non-negative integer** (`0` is valid — it fully closes admission until either budget is raised or in-flight work drains and no further reservation exists).
631
- * **Not re-validated against `highPriorityReserve`.** Construction requires `highPriorityReserve <= budget` (catches config typos), but `setBudget()` trusts the caller — a renewal-driven ledger grant is reality, and the bulkhead has no standing to refuse it even if it drops below the configured reserve. If that happens, the normal-priority ceiling (`budget - highPriorityReserve`) is clamped to `0`: normal-priority traffic is fully rejected with `"budget_limit"` while `priority: "high"` requests are still checked against the full (shrunk) budget and can keep admitting. This is the intended degraded behavior — protecting interactive traffic when capacity is scarcest is exactly what `highPriorityReserve` is for.
817
+ `setBudget(tokens)` remains available for existing callers. It now applies a
818
+ complete budget-only update at `currentRevision + 1`. Do not mix it with an
819
+ external revision authority; distributed integrations should use
820
+ `applyLimits()` exclusively.
632
821
 
633
822
 
634
823
  ---
@@ -809,6 +998,12 @@ try {
809
998
  ```ts
810
999
  const s = bulkhead.stats();
811
1000
 
1001
+ s.limits.revision
1002
+ s.limits.maxConcurrent
1003
+ s.limits.maxQueue
1004
+ s.limits.tokenBudget?.budget
1005
+ s.limits.tokenBudget?.highPriorityReserve
1006
+
812
1007
  s.bulkhead.inFlight
813
1008
  s.bulkhead.pending
814
1009
  s.bulkhead.maxConcurrent
@@ -818,7 +1013,14 @@ s.bulkhead.closed // true after close()
818
1013
  s.llm.admitted
819
1014
  s.llm.released
820
1015
  s.llm.rejected
821
- s.llm.rejectedByReason?.budget_limit // true after close()
1016
+ s.llm.rejectedByReason?.budget_limit
1017
+
1018
+ s.observe?.bypassed // v3.9: callbacks run without capacity
1019
+ s.observe?.raceBypassed // advisory admit raced with rejection
1020
+ s.observe?.bypassedByReason
1021
+ s.observe?.usageReported
1022
+ s.observe?.totalInputTokens
1023
+ s.observe?.totalOutputTokens
822
1024
 
823
1025
  s.tokenBudget?.budget
824
1026
  s.tokenBudget?.inFlightTokens
@@ -833,6 +1035,7 @@ s.deduplication?.hits
833
1035
 
834
1036
  ```ts
835
1037
  type LLMStats = {
1038
+ limits: LLMAdmissionLimits;
836
1039
  bulkhead: Stats;
837
1040
  llm: {
838
1041
  admitted: number;
@@ -848,6 +1051,17 @@ type LLMStats = {
848
1051
  totalConsumed: number;
849
1052
  totalRefunded: number;
850
1053
  };
1054
+ observe?: {
1055
+ bypassed: number;
1056
+ raceBypassed: number;
1057
+ bypassedByReason: Partial<Record<
1058
+ 'budget_limit' | 'concurrency_limit' | 'queue_limit' | 'timeout',
1059
+ number
1060
+ >>;
1061
+ usageReported: number;
1062
+ totalInputTokens: number;
1063
+ totalOutputTokens: number;
1064
+ };
851
1065
  deduplication?: {
852
1066
  active: number;
853
1067
  hits: number;
@@ -875,6 +1089,10 @@ off();
875
1089
  | `reject` | `{ request, reason, detail? }` |
876
1090
  | `usage` | `{ request, admissionId, priority, sequence, reservedTokens, previousHeldTokens, heldTokens, deltaTokens, usage, outputCap, outputRemaining, overReservation }` |
877
1091
  | `release` | `{ request, admissionId, priority, reservedTokens, heldTokens, refundedTokens, usageSequence, usage? }` |
1092
+ | `bypass` | `{ request, admissionId, priority, reason, detail?, reservation, raced }` |
1093
+ | `bypassUsage` | `{ request, admissionId, priority, reason, sequence, reservation, usage, outputCap, outputRemaining, overReservation }` |
1094
+ | `bypassRelease` | `{ request, admissionId, priority, reason, reservation, usageSequence, usage? }` |
1095
+ | `reconfigure` | `{ previous, current }` |
878
1096
  | `dedup` | `{ request }` |
879
1097
 
880
1098
  Listeners are synchronous and fire-and-forget. Exceptions are silently caught.
@@ -902,6 +1120,7 @@ await bulkhead.drain(); // wait for in-flight work to finish
902
1120
  type LLMBulkheadOptions = {
903
1121
  model: string;
904
1122
  maxConcurrent: number;
1123
+ initialRevision?: number; // non-negative safe integer; default 0
905
1124
  maxQueue?: number;
906
1125
  timeoutMs?: number; // integer >= 0
907
1126
  profile?: 'interactive' | 'batch' | LLMBulkheadPreset;
@@ -931,15 +1150,26 @@ run<T>(
931
1150
  timeoutMs?: number; // integer >= 0
932
1151
  priority?: 'normal' | 'high';
933
1152
  getUsage?: (result: T) => TokenUsage | undefined;
1153
+ mode?: 'enforce' | 'observe'; // default: 'enforce' (v3.9)
1154
+ shadowReasons?: readonly (
1155
+ | 'budget_limit'
1156
+ | 'concurrency_limit'
1157
+ | 'queue_limit'
1158
+ | 'timeout'
1159
+ )[];
934
1160
  dedupScope?: string; // dedup isolation scope (e.g. tenant / API key)
935
1161
  dedup?: boolean; // false = opt this call out of dedup (v3.5)
936
1162
  },
937
1163
  ): Promise<T>
938
1164
  ```
939
1165
 
940
- `ctx.admissionId` is the stable admission identifier. `ctx.reservation` is
941
- the exact reservation used at admission (or `null` when token budgeting is
942
- disabled), and `ctx.reportUsage()` reports cumulative streaming usage.
1166
+ `ctx.admissionId` is the stable execution identifier. In observe-mode
1167
+ bypasses it uses a `shadow-` prefix. `ctx.reservation` is the exact evaluated
1168
+ reservation (or `null` when token budgeting is disabled),
1169
+ `ctx.admission` distinguishes `"admitted"` from `"bypassed"`, and
1170
+ `ctx.bypassReason` / `ctx.bypassDetail` describe a bypass.
1171
+ `ctx.reportUsage()` reports cumulative streaming usage; bypassed usage is
1172
+ recorded for telemetry but never changes bulkhead capacity accounting.
943
1173
 
944
1174
  ### `bulkhead.estimate(request)`
945
1175
 
@@ -987,15 +1217,43 @@ type LLMToken = {
987
1217
 
988
1218
  ### `bulkhead.stats()`
989
1219
 
1220
+ ### `bulkhead.limits()`
1221
+
1222
+ ```ts
1223
+ limits(): LLMAdmissionLimits
1224
+ ```
1225
+
1226
+ Returns a frozen copy of the currently applied complete snapshot.
1227
+
1228
+ ### `bulkhead.applyLimits(snapshot)`
1229
+
1230
+ ```ts
1231
+ applyLimits(snapshot: LLMAdmissionLimits): LLMApplyLimitsResult
1232
+
1233
+ type LLMAdmissionLimits = {
1234
+ readonly revision: number;
1235
+ readonly maxConcurrent: number; // runtime 0 = fail-fast kill switch
1236
+ readonly maxQueue: number;
1237
+ readonly tokenBudget?: {
1238
+ readonly budget: number;
1239
+ readonly highPriorityReserve: number;
1240
+ };
1241
+ };
1242
+ ```
1243
+
1244
+ Applies only strictly higher revisions. See
1245
+ [Atomic Runtime Reconfiguration](#atomic-runtime-reconfiguration).
1246
+
990
1247
  ### `bulkhead.setBudget(tokens)`
991
1248
 
992
1249
  ```ts
993
1250
  setBudget(tokens: number): void
994
1251
  ```
995
1252
 
996
- Mutates the token budget ceiling at runtime. Throws if `tokenBudget` was not
997
- configured at construction. Throws if `tokens` is not a non-negative integer.
998
- See [Runtime Budget Adjustment](#runtime-budget-adjustment) for full semantics.
1253
+ Applies a complete budget-only update and advances the local revision by one.
1254
+ Throws if `tokenBudget` was not configured at construction or if `tokens` is
1255
+ not a non-negative integer. Externally managed callers should use
1256
+ `applyLimits()` instead.
999
1257
 
1000
1258
  ### `bulkhead.close()`
1001
1259
 
@@ -1064,6 +1322,14 @@ type LLMRejectReason =
1064
1322
 
1065
1323
  ## Migration
1066
1324
 
1325
+ ### v3.9 → v3.10
1326
+
1327
+ Existing admission calls require no changes. `stats()` gains a `limits` block,
1328
+ `LLMEventType` gains `"reconfigure"`, and `setBudget()` now advances the local
1329
+ revision. Code that exhaustively enumerates event types should add the new
1330
+ case. Control-plane integrations should move from `setBudget()` to complete
1331
+ `applyLimits()` snapshots.
1332
+
1067
1333
  ### v3.5 → v3.6
1068
1334
 
1069
1335
  No call-site changes are required. `admit` and `release` event payloads gained