async-bulkhead-llm 3.9.0 → 3.11.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,8 @@ 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
13
+ - ✅ **Admission-linearized revisions** — every admitted or bypassed lifecycle retains the exact limit revision that made the decision
12
14
  - ✅ **Token-aware admission** — reserves against estimated input + max output tokens
13
15
  - ✅ **Token refund** — reclaim unused budget capacity from actual usage post-completion
14
16
  - ✅ **Model-aware estimation** — per-model character ratios for known providers
@@ -132,6 +134,106 @@ const result = await bulkhead.run(request, async () => {
132
134
 
133
135
  ---
134
136
 
137
+ ## What's New in v3.11 — Admission-linearized limit revisions
138
+
139
+ v3.11 makes every capacity decision traceable to the exact immutable limit
140
+ revision that produced it. The revision is captured at the admission or
141
+ rejection decision itself, so a concurrent reconfiguration cannot relabel work
142
+ that was evaluated under an earlier snapshot.
143
+
144
+ ### Highlights
145
+
146
+ - **Exact admission provenance:** successful `acquire()` results, `LLMToken`,
147
+ and `LLMRunContext` expose `limitRevision`.
148
+ - **Lifecycle consistency:** `admit`, `usage`, `release`, `bypass`,
149
+ `bypassUsage`, and `bypassRelease` events retain that same revision for the
150
+ full lifetime of the execution.
151
+ - **Revisioned rejection snapshots:** `LLMRejectDetail.limitRevision` records
152
+ the snapshot used for a capacity rejection, while every `reject` event also
153
+ includes a top-level `limitRevision`.
154
+ - **Race-safe reporting:** gateways no longer need to call `limits()` after
155
+ admission, which could observe a newer revision than the one that actually
156
+ authorized the request.
157
+ - **Additive API change:** existing call sites continue to work. Tests or
158
+ consumers that assert exact event or detail object shapes must include the
159
+ new `limitRevision` field.
160
+
161
+ ```ts
162
+ const acquired = await bulkhead.acquire(request);
163
+
164
+ if (acquired.ok) {
165
+ console.log(acquired.admissionId);
166
+ console.log(acquired.limitRevision);
167
+ console.log(acquired.token.limitRevision); // same immutable revision
168
+ acquired.token.release();
169
+ }
170
+
171
+ await bulkhead.run(request, async (_signal, ctx) => {
172
+ auditLog({
173
+ admissionId: ctx?.admissionId,
174
+ limitRevision: ctx?.limitRevision,
175
+ });
176
+
177
+ return callYourLLMProvider(request);
178
+ });
179
+
180
+ bulkhead.on('reject', ({ reason, limitRevision, detail }) => {
181
+ auditLog({ reason, limitRevision, capacity: detail });
182
+ });
183
+ ```
184
+
185
+ The revision identifies the library limit snapshot, not an external control
186
+ plane grant by itself. A gateway can associate that revision with its own
187
+ immutable grant metadata to provide end-to-end admission provenance.
188
+
189
+ ---
190
+
191
+ ## What's New in v3.10 — Atomic, versioned admission limits
192
+
193
+ v3.10 makes `async-bulkhead-llm` safer to operate from gateways and distributed
194
+ control-plane agents. All mutable admission limits can now be replaced in one
195
+ validated, revisioned snapshot instead of being updated independently.
196
+
197
+ ### Highlights
198
+
199
+ - **Atomic updates:** `maxConcurrent`, `maxQueue`, token budget, and
200
+ high-priority reserve change together or not at all.
201
+ - **Stale-update protection:** every snapshot carries a strictly increasing
202
+ `revision`; equal or older revisions are rejected without mutating state.
203
+ - **Shrink by attrition:** lowering limits never cancels in-flight work or
204
+ already accepted queue waiters. New work is admitted only as capacity returns.
205
+ - **Immediate scale-up:** raising concurrency starts eligible queued work as soon
206
+ as the new snapshot is applied.
207
+ - **Runtime kill switch:** setting `maxConcurrent` to `0` stops new admissions
208
+ while existing work drains normally.
209
+ - **Observable state:** `limits()`, `stats().limits`, and the `reconfigure` event
210
+ expose the active revision and previous/current snapshots.
211
+
212
+ ```ts
213
+ const result = bulkhead.applyLimits({
214
+ revision: 42,
215
+ maxConcurrent: 12,
216
+ maxQueue: 0,
217
+ tokenBudget: {
218
+ budget: 120_000,
219
+ highPriorityReserve: 20_000,
220
+ },
221
+ });
222
+
223
+ if (!result.applied) {
224
+ // Equal and lower revisions are ignored without mutation.
225
+ console.log(result.reason); // "stale_revision"
226
+ }
227
+ ```
228
+
229
+ Use `initialRevision` when restoring persisted control-plane state. A configured
230
+ token budget must remain configured in every later snapshot; estimator and
231
+ output-cap policy remain construction-time settings. `setBudget()` is still
232
+ supported for local use, but distributed integrations should use
233
+ `applyLimits()` exclusively so a single authority owns the revision sequence.
234
+
235
+ ---
236
+
135
237
  ## What's New in v3.9 — First-class observe mode
136
238
 
137
239
  v3.9 adds an explicit rollout mode for measuring admission policy before fully
@@ -586,7 +688,7 @@ const off = bulkhead.on('release', ({ reservedTokens, refundedTokens, usage }) =
586
688
  off(); // unsubscribe
587
689
  ```
588
690
 
589
- Events: `'admit'`, `'reject'`, `'usage'`, `'release'`, `'dedup'`.
691
+ Events: `'admit'`, `'reject'`, `'usage'`, `'release'`, `'reconfigure'`, `'dedup'`.
590
692
 
591
693
  ### Graceful Shutdown
592
694
 
@@ -707,28 +809,74 @@ adaptive.corrections(); // per-model calibration snapshot
707
809
  adaptive.reset(); // clear calibration
708
810
  ```
709
811
 
710
- ### Runtime Budget Adjustment
812
+ ### Atomic Runtime Reconfiguration
711
813
 
712
- `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.
814
+ `applyLimits(snapshot)` is the preferred runtime control surface for gateways
815
+ and distributed control-plane agents. The snapshot is complete rather than
816
+ partial, so concurrency, queue, budget, and reserve values cannot drift across
817
+ separate setter calls.
713
818
 
714
819
  ```ts
715
820
  const bulkhead = createLLMBulkhead({
716
- model: 'claude-sonnet-4',
821
+ model: 'claude-sonnet-4',
717
822
  maxConcurrent: 10,
718
- tokenBudget: { budget: 200_000 },
823
+ maxQueue: 0,
824
+ initialRevision: 100,
825
+ tokenBudget: {
826
+ budget: 200_000,
827
+ highPriorityReserve: 25_000,
828
+ },
829
+ });
830
+
831
+ const update = bulkhead.applyLimits({
832
+ revision: 101,
833
+ maxConcurrent: 6,
834
+ maxQueue: 20,
835
+ tokenBudget: {
836
+ budget: 90_000,
837
+ highPriorityReserve: 15_000,
838
+ },
719
839
  });
840
+ ```
841
+
842
+ Semantics:
843
+
844
+ * **Strictly increasing revision.** Equal or lower revisions return a stale
845
+ result and do not mutate any limit.
846
+ * **Full validation before mutation.** Invalid higher-revision snapshots throw
847
+ while the previous revision remains active.
848
+ * **Shrink by attrition.** In-flight work and accepted queue waiters are never
849
+ revoked. New admissions obey the lower ceilings immediately.
850
+ * **Immediate expansion.** Raising `maxConcurrent` pumps accepted waiters in
851
+ the same synchronous update, after the complete LLM-layer snapshot is active.
852
+ * **Zero-concurrency kill switch.** `maxConcurrent: 0` rejects new callers with
853
+ `"concurrency_limit"` instead of queueing them.
854
+ * **Budget reserve may exceed a shrunken budget.** The normal-priority ceiling
855
+ is clamped to 0 while high-priority traffic is checked against the full
856
+ budget, preserving the existing degraded-priority behavior.
857
+ * **Budget feature shape is fixed at construction.** A bulkhead created with
858
+ `tokenBudget` requires `tokenBudget` in every update. A bulkhead created
859
+ without it must omit that field; estimator policy is not hot-swapped.
860
+ * **Admission provenance is immutable.** `acquire()` results, tokens,
861
+ `LLMRunContext`, usage reports, and lifecycle events retain the revision
862
+ captured when the slot and token reservation were successfully acquired.
863
+ A later `applyLimits()` call cannot relabel already admitted work.
864
+
865
+ ```ts
866
+ const current = bulkhead.limits();
867
+ // { revision, maxConcurrent, maxQueue, tokenBudget? }
720
868
 
721
- bulkhead.setBudget(300_000); // raise the ceiling
722
- bulkhead.setBudget(50_000); // shrink the ceiling
869
+ bulkhead.on('reconfigure', ({ previous, current }) => {
870
+ publishAppliedRevision(previous.revision, current.revision);
871
+ });
723
872
  ```
724
873
 
725
- Semantics, pinned deliberately:
874
+ #### Compatibility: `setBudget(tokens)`
726
875
 
727
- * **Raising takes effect immediately.** The very next `acquire()`/`run()`/`wouldAdmit()` call sees the new headroom — there is no caching to invalidate.
728
- * **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.
729
- * **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.
730
- * **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).
731
- * **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.
876
+ `setBudget(tokens)` remains available for existing callers. It now applies a
877
+ complete budget-only update at `currentRevision + 1`. Do not mix it with an
878
+ external revision authority; distributed integrations should use
879
+ `applyLimits()` exclusively.
732
880
 
733
881
 
734
882
  ---
@@ -909,6 +1057,12 @@ try {
909
1057
  ```ts
910
1058
  const s = bulkhead.stats();
911
1059
 
1060
+ s.limits.revision
1061
+ s.limits.maxConcurrent
1062
+ s.limits.maxQueue
1063
+ s.limits.tokenBudget?.budget
1064
+ s.limits.tokenBudget?.highPriorityReserve
1065
+
912
1066
  s.bulkhead.inFlight
913
1067
  s.bulkhead.pending
914
1068
  s.bulkhead.maxConcurrent
@@ -940,6 +1094,7 @@ s.deduplication?.hits
940
1094
 
941
1095
  ```ts
942
1096
  type LLMStats = {
1097
+ limits: LLMAdmissionLimits;
943
1098
  bulkhead: Stats;
944
1099
  llm: {
945
1100
  admitted: number;
@@ -989,13 +1144,14 @@ off();
989
1144
 
990
1145
  | Event | Payload |
991
1146
  |-----------|---------|
992
- | `admit` | `{ request, admissionId, priority, reservedTokens }` |
993
- | `reject` | `{ request, reason, detail? }` |
994
- | `usage` | `{ request, admissionId, priority, sequence, reservedTokens, previousHeldTokens, heldTokens, deltaTokens, usage, outputCap, outputRemaining, overReservation }` |
995
- | `release` | `{ request, admissionId, priority, reservedTokens, heldTokens, refundedTokens, usageSequence, usage? }` |
996
- | `bypass` | `{ request, admissionId, priority, reason, detail?, reservation, raced }` |
997
- | `bypassUsage` | `{ request, admissionId, priority, reason, sequence, reservation, usage, outputCap, outputRemaining, overReservation }` |
998
- | `bypassRelease` | `{ request, admissionId, priority, reason, reservation, usageSequence, usage? }` |
1147
+ | `admit` | `{ request, admissionId, limitRevision, priority, reservedTokens }` |
1148
+ | `reject` | `{ request, reason, limitRevision, detail? }` |
1149
+ | `usage` | `{ request, admissionId, limitRevision, priority, sequence, reservedTokens, previousHeldTokens, heldTokens, deltaTokens, usage, outputCap, outputRemaining, overReservation }` |
1150
+ | `release` | `{ request, admissionId, limitRevision, priority, reservedTokens, heldTokens, refundedTokens, usageSequence, usage? }` |
1151
+ | `bypass` | `{ request, admissionId, limitRevision, priority, reason, detail?, reservation, raced }` |
1152
+ | `bypassUsage` | `{ request, admissionId, limitRevision, priority, reason, sequence, reservation, usage, outputCap, outputRemaining, overReservation }` |
1153
+ | `bypassRelease` | `{ request, admissionId, limitRevision, priority, reason, reservation, usageSequence, usage? }` |
1154
+ | `reconfigure` | `{ previous, current }` |
999
1155
  | `dedup` | `{ request }` |
1000
1156
 
1001
1157
  Listeners are synchronous and fire-and-forget. Exceptions are silently caught.
@@ -1023,6 +1179,7 @@ await bulkhead.drain(); // wait for in-flight work to finish
1023
1179
  type LLMBulkheadOptions = {
1024
1180
  model: string;
1025
1181
  maxConcurrent: number;
1182
+ initialRevision?: number; // non-negative safe integer; default 0
1026
1183
  maxQueue?: number;
1027
1184
  timeoutMs?: number; // integer >= 0
1028
1185
  profile?: 'interactive' | 'batch' | LLMBulkheadPreset;
@@ -1065,7 +1222,9 @@ run<T>(
1065
1222
  ): Promise<T>
1066
1223
  ```
1067
1224
 
1068
- `ctx.admissionId` is the stable execution identifier. In observe-mode
1225
+ `ctx.admissionId` is the stable execution identifier and
1226
+ `ctx.limitRevision` is the immutable revision associated with the admission
1227
+ or bypass decision. In observe-mode
1069
1228
  bypasses it uses a `shadow-` prefix. `ctx.reservation` is the exact evaluated
1070
1229
  reservation (or `null` when token budgeting is disabled),
1071
1230
  `ctx.admission` distinguishes `"admitted"` from `"bypassed"`, and
@@ -1104,13 +1263,15 @@ type LLMAcquireResult =
1104
1263
  | {
1105
1264
  ok: true;
1106
1265
  admissionId: string;
1266
+ limitRevision: number;
1107
1267
  reservation: LLMReservationEstimate | null;
1108
1268
  token: LLMToken;
1109
1269
  }
1110
- | { ok: false; reason: LLMRejectReason };
1270
+ | { ok: false; reason: LLMRejectReason; detail?: LLMRejectDetail };
1111
1271
 
1112
1272
  type LLMToken = {
1113
1273
  readonly admissionId: string;
1274
+ readonly limitRevision: number;
1114
1275
  readonly reservation: LLMReservationEstimate | null;
1115
1276
  reportUsage(usage: TokenUsage): UsageReport;
1116
1277
  release(usage?: TokenUsage): void;
@@ -1119,15 +1280,43 @@ type LLMToken = {
1119
1280
 
1120
1281
  ### `bulkhead.stats()`
1121
1282
 
1283
+ ### `bulkhead.limits()`
1284
+
1285
+ ```ts
1286
+ limits(): LLMAdmissionLimits
1287
+ ```
1288
+
1289
+ Returns a frozen copy of the currently applied complete snapshot.
1290
+
1291
+ ### `bulkhead.applyLimits(snapshot)`
1292
+
1293
+ ```ts
1294
+ applyLimits(snapshot: LLMAdmissionLimits): LLMApplyLimitsResult
1295
+
1296
+ type LLMAdmissionLimits = {
1297
+ readonly revision: number;
1298
+ readonly maxConcurrent: number; // runtime 0 = fail-fast kill switch
1299
+ readonly maxQueue: number;
1300
+ readonly tokenBudget?: {
1301
+ readonly budget: number;
1302
+ readonly highPriorityReserve: number;
1303
+ };
1304
+ };
1305
+ ```
1306
+
1307
+ Applies only strictly higher revisions. See
1308
+ [Atomic Runtime Reconfiguration](#atomic-runtime-reconfiguration).
1309
+
1122
1310
  ### `bulkhead.setBudget(tokens)`
1123
1311
 
1124
1312
  ```ts
1125
1313
  setBudget(tokens: number): void
1126
1314
  ```
1127
1315
 
1128
- Mutates the token budget ceiling at runtime. Throws if `tokenBudget` was not
1129
- configured at construction. Throws if `tokens` is not a non-negative integer.
1130
- See [Runtime Budget Adjustment](#runtime-budget-adjustment) for full semantics.
1316
+ Applies a complete budget-only update and advances the local revision by one.
1317
+ Throws if `tokenBudget` was not configured at construction or if `tokens` is
1318
+ not a non-negative integer. Externally managed callers should use
1319
+ `applyLimits()` instead.
1131
1320
 
1132
1321
  ### `bulkhead.close()`
1133
1322
 
@@ -1173,6 +1362,7 @@ type TokenEstimator = (request: LLMRequest) => TokenEstimate;
1173
1362
  type TokenUsage = { input: number; output: number };
1174
1363
  type UsageReport = {
1175
1364
  admissionId: string;
1365
+ limitRevision: number;
1176
1366
  sequence: number;
1177
1367
  reserved: number;
1178
1368
  held: number;
@@ -1196,6 +1386,23 @@ type LLMRejectReason =
1196
1386
 
1197
1387
  ## Migration
1198
1388
 
1389
+ ### v3.10 → v3.11
1390
+
1391
+ No admission call-site changes are required. Successful acquire results,
1392
+ admission tokens, run contexts, usage reports, lifecycle events, and rejection
1393
+ capacity details gain `limitRevision`. Code that uses exact deep equality on
1394
+ these objects must add the field. Gateways should read the captured revision
1395
+ from the result, token, context, event, or rejection detail instead of calling
1396
+ `limits()` after the decision.
1397
+
1398
+ ### v3.9 → v3.10
1399
+
1400
+ Existing admission calls require no changes. `stats()` gains a `limits` block,
1401
+ `LLMEventType` gains `"reconfigure"`, and `setBudget()` now advances the local
1402
+ revision. Code that exhaustively enumerates event types should add the new
1403
+ case. Control-plane integrations should move from `setBudget()` to complete
1404
+ `applyLimits()` snapshots.
1405
+
1199
1406
  ### v3.5 → v3.6
1200
1407
 
1201
1408
  No call-site changes are required. `admit` and `release` event payloads gained