async-bulkhead-llm 3.13.0 → 3.14.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,7 +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
12
+ - ✅ **Atomic versioned limit updates** — apply concurrency, queue, token budget, priority reserve, and admission-class ceilings as one revisioned snapshot
13
+ - ✅ **Bounded admission classes** — isolate policy classes with hard per-class concurrency and in-flight token ceilings
13
14
  - ✅ **Admission-linearized revisions** — every admitted or bypassed lifecycle retains the exact limit revision that made the decision
14
15
  - ✅ **Token-aware admission** — reserves against estimated input + max output tokens
15
16
  - ✅ **Progressive reconciliation** — release processed input and generated-output reservation during live streams
@@ -135,6 +136,95 @@ const result = await bulkhead.run(request, async () => {
135
136
 
136
137
  ---
137
138
 
139
+ ## What's New in v3.14 — Bounded admission classes
140
+
141
+ v3.14 adds a bounded hierarchical admission layer inside one bulkhead. A
142
+ trusted gateway can map tenant or application identity to a small, static set
143
+ of policy classes, then enforce hard concurrency and in-flight token ceilings
144
+ for each class while retaining the enclosing global limits.
145
+
146
+ ```ts
147
+ const bulkhead = createLLMBulkhead({
148
+ model: "gpt-4o",
149
+ maxConcurrent: 12,
150
+ tokenBudget: { budget: 24_000 },
151
+ admissionClasses: {
152
+ defaultClass: "standard",
153
+ classes: {
154
+ premium: { maxConcurrent: 8, maxInFlightTokens: 18_000 },
155
+ standard: { maxConcurrent: 4, maxInFlightTokens: 6_000 },
156
+ },
157
+ },
158
+ });
159
+
160
+ await bulkhead.run(request, callProvider, {
161
+ admissionClass: "premium",
162
+ dedupScope: trustedTenantId,
163
+ });
164
+ ```
165
+
166
+ The class table is fixed at construction. Unknown IDs throw instead of creating
167
+ unbounded state or metric cardinality. Class ceilings are fail-fast and are
168
+ checked together with global concurrency, priority-adjusted token budget, and
169
+ shutdown state. `applyLimits()` may update class numbers atomically, but every
170
+ snapshot must contain exactly the construction-time class keys.
171
+
172
+ When in-flight deduplication is enabled, the selected admission class is an
173
+ automatic deduplication partition. Identical requests in `premium` and
174
+ `standard` therefore execute independently rather than sharing the first
175
+ class's admission decision or queue position. `dedupScope` remains necessary
176
+ for tenant-level isolation inside a class.
177
+
178
+ Admission classes are intentionally policy buckets, not raw tenant IDs. The
179
+ library does not authenticate callers, assign identities, implement weighted
180
+ fairness, reserve borrowable floors, or coordinate capacity across processes.
181
+ Those responsibilities remain in the gateway and control plane. When
182
+ in-flight deduplication is enabled, `admissionClass` also does not replace
183
+ `dedupScope`; include trusted tenant identity in `dedupScope` when results must
184
+ not be shared across tenants.
185
+
186
+ Lifecycle results, run contexts, tokens, usage reports, capacity details, and
187
+ telemetry events now carry `admissionClass` when configured. Rejection detail
188
+ also identifies whether the binding constraint was `global` or
189
+ `admission_class`, and `stats().admissionClasses` exposes bounded per-class
190
+ accounting.
191
+
192
+ ---
193
+
194
+ ## What's New in v3.13 — Progressive reconciliation
195
+
196
+ Gateways that receive cumulative streaming usage may opt into shrinking the
197
+ active hold before request completion:
198
+
199
+ ```ts
200
+ const report = ctx!.reportUsage(
201
+ { input: actualInput, output: cumulativeOutput },
202
+ {
203
+ remainingOutputTokens: Math.max(0, maxOutput - cumulativeOutput),
204
+ safetyMarginTokens: 128,
205
+ },
206
+ );
207
+ ```
208
+
209
+ The progressive hold is:
210
+
211
+ ```text
212
+ remainingOutputTokens + safetyMarginTokens + output overrun
213
+ ```
214
+
215
+ This lets processed input and already-generated output stop occupying the
216
+ in-flight budget. The caller must use the option only after prefill is known to
217
+ be complete and must derive `remainingOutputTokens` from an authoritative
218
+ provider output cap. Omitting the second argument preserves the legacy behavior
219
+ of retaining the full output reservation until release. Final `release()`
220
+ settlement remains authoritative.
221
+
222
+ Progressive updates share the existing sequence-numbered `usage` event. Events
223
+ include `progressive`, `remainingOutputTokens`, and `safetyMarginTokens` when the
224
+ new mode is used.
225
+
226
+ ---
227
+
138
228
  ## What's New in v3.12 — Fail-closed startup
139
229
 
140
230
  v3.12 allows `maxConcurrent: 0` at construction time. A gateway managed by an
@@ -560,40 +650,6 @@ await distributedLedger.setHold({
560
650
 
561
651
  ---
562
652
 
563
- ## What's New in v3.13 — Progressive reconciliation
564
-
565
- Gateways that receive cumulative streaming usage may opt into shrinking the
566
- active hold before request completion:
567
-
568
- ```ts
569
- const report = ctx!.reportUsage(
570
- { input: actualInput, output: cumulativeOutput },
571
- {
572
- remainingOutputTokens: Math.max(0, maxOutput - cumulativeOutput),
573
- safetyMarginTokens: 128,
574
- },
575
- );
576
- ```
577
-
578
- The progressive hold is:
579
-
580
- ```text
581
- remainingOutputTokens + safetyMarginTokens + output overrun
582
- ```
583
-
584
- This lets processed input and already-generated output stop occupying the
585
- in-flight budget. The caller must use the option only after prefill is known to
586
- be complete and must derive `remainingOutputTokens` from an authoritative
587
- provider output cap. Omitting the second argument preserves the legacy behavior
588
- of retaining the full output reservation until release. Final `release()`
589
- settlement remains authoritative.
590
-
591
- Progressive updates share the existing sequence-numbered `usage` event. Events
592
- include `progressive`, `remainingOutputTokens`, and `safetyMarginTokens` when the
593
- new mode is used.
594
-
595
- ---
596
-
597
653
  ## What's New in v3.2 — Gateway readiness
598
654
 
599
655
  v3.2 adds the admission-control primitives an AI gateway needs, all additive:
@@ -817,6 +873,60 @@ const bulkhead = createLLMBulkhead({
817
873
 
818
874
  ---
819
875
 
876
+ ## Bounded Admission Classes
877
+
878
+ Admission classes add a second, bounded capacity layer beneath the global
879
+ bulkhead. They are useful when several trusted workload classes share one
880
+ provider/model pool but need hard limits on each class's share.
881
+
882
+ ```ts
883
+ const bulkhead = createLLMBulkhead({
884
+ model: 'gpt-4o',
885
+ maxConcurrent: 20,
886
+ tokenBudget: { budget: 50_000 },
887
+ admissionClasses: {
888
+ defaultClass: 'standard',
889
+ classes: {
890
+ latencySensitive: {
891
+ maxConcurrent: 12,
892
+ maxInFlightTokens: 32_000,
893
+ },
894
+ standard: {
895
+ maxConcurrent: 6,
896
+ maxInFlightTokens: 14_000,
897
+ },
898
+ background: {
899
+ maxConcurrent: 2,
900
+ maxInFlightTokens: 4_000,
901
+ },
902
+ },
903
+ },
904
+ });
905
+
906
+ await bulkhead.run(request, callProvider, {
907
+ admissionClass: 'latencySensitive',
908
+ });
909
+ ```
910
+
911
+ A request must fit both the global limits and its class limits. Omitting
912
+ `admissionClass` selects `defaultClass`. A class may omit either ceiling, in
913
+ which case that dimension is governed only by the global bulkhead. Zero is a
914
+ valid fail-closed class ceiling.
915
+
916
+ Class checks are deliberately fail-fast; `maxQueue` remains a global queue and
917
+ does not create per-class waiter queues. The fixed class keys keep runtime
918
+ state and observability cardinality bounded. Map authenticated tenants or
919
+ applications to these policy buckets before calling the library rather than
920
+ using arbitrary identity values as class IDs.
921
+
922
+ Identity verification, weights, minimum guarantees, lending, and distributed
923
+ coordination are outside this single-process library. They belong in the
924
+ calling gateway/control plane. Admission classes automatically partition
925
+ deduplication from one another, but a class may still group multiple tenants;
926
+ use `dedupScope` for tenant-level result isolation inside each class.
927
+
928
+ ---
929
+
820
930
  ## Token Budget
821
931
 
822
932
  ```ts
@@ -914,6 +1024,13 @@ const bulkhead = createLLMBulkhead({
914
1024
  budget: 200_000,
915
1025
  highPriorityReserve: 25_000,
916
1026
  },
1027
+ admissionClasses: {
1028
+ defaultClass: 'standard',
1029
+ classes: {
1030
+ premium: { maxConcurrent: 7, maxInFlightTokens: 140_000 },
1031
+ standard: { maxConcurrent: 3, maxInFlightTokens: 60_000 },
1032
+ },
1033
+ },
917
1034
  });
918
1035
 
919
1036
  const update = bulkhead.applyLimits({
@@ -942,9 +1059,11 @@ Semantics:
942
1059
  * **Budget reserve may exceed a shrunken budget.** The normal-priority ceiling
943
1060
  is clamped to 0 while high-priority traffic is checked against the full
944
1061
  budget, preserving the existing degraded-priority behavior.
945
- * **Budget feature shape is fixed at construction.** A bulkhead created with
1062
+ * **Feature shapes are fixed at construction.** A bulkhead created with
946
1063
  `tokenBudget` requires `tokenBudget` in every update. A bulkhead created
947
- without it must omit that field; estimator policy is not hot-swapped.
1064
+ without it must omit that field; estimator policy is not hot-swapped. The
1065
+ same rule applies to `admissionClasses`, whose complete fixed key set must be
1066
+ present in every update.
948
1067
  * **Admission provenance is immutable.** `acquire()` results, tokens,
949
1068
  `LLMRunContext`, usage reports, and lifecycle events retain the revision
950
1069
  captured when the slot and token reservation were successfully acquired.
@@ -952,7 +1071,7 @@ Semantics:
952
1071
 
953
1072
  ```ts
954
1073
  const current = bulkhead.limits();
955
- // { revision, maxConcurrent, maxQueue, tokenBudget? }
1074
+ // { revision, maxConcurrent, maxQueue, tokenBudget?, admissionClasses? }
956
1075
 
957
1076
  bulkhead.on('reconfigure', ({ previous, current }) => {
958
1077
  publishAppliedRevision(previous.revision, current.revision);
@@ -1150,6 +1269,7 @@ s.limits.maxConcurrent
1150
1269
  s.limits.maxQueue
1151
1270
  s.limits.tokenBudget?.budget
1152
1271
  s.limits.tokenBudget?.highPriorityReserve
1272
+ s.limits.admissionClasses?.premium?.maxConcurrent
1153
1273
 
1154
1274
  s.bulkhead.inFlight
1155
1275
  s.bulkhead.pending
@@ -1176,6 +1296,11 @@ s.tokenBudget?.totalReserved // v3.1: cumulative tokens reserved at admis
1176
1296
  s.tokenBudget?.totalConsumed // v3.1: cumulative actual tokens consumed (usage required)
1177
1297
  s.tokenBudget?.totalRefunded // v2: cumulative refunded tokens
1178
1298
 
1299
+ s.admissionClasses?.defaultClass
1300
+ s.admissionClasses?.classes.premium?.inFlight
1301
+ s.admissionClasses?.classes.premium?.inFlightTokens
1302
+ s.admissionClasses?.classes.premium?.rejectedByReason
1303
+
1179
1304
  s.deduplication?.active
1180
1305
  s.deduplication?.hits
1181
1306
  ```
@@ -1209,6 +1334,10 @@ type LLMStats = {
1209
1334
  totalInputTokens: number;
1210
1335
  totalOutputTokens: number;
1211
1336
  };
1337
+ admissionClasses?: {
1338
+ defaultClass: string;
1339
+ classes: Record<string, LLMAdmissionClassStats>;
1340
+ };
1212
1341
  deduplication?: {
1213
1342
  active: number;
1214
1343
  hits: number;
@@ -1232,13 +1361,13 @@ off();
1232
1361
 
1233
1362
  | Event | Payload |
1234
1363
  |-----------|---------|
1235
- | `admit` | `{ request, admissionId, limitRevision, priority, reservedTokens }` |
1236
- | `reject` | `{ request, reason, limitRevision, detail? }` |
1237
- | `usage` | `{ request, admissionId, limitRevision, priority, sequence, reservedTokens, previousHeldTokens, heldTokens, deltaTokens, usage, outputCap, outputRemaining, overReservation }` |
1238
- | `release` | `{ request, admissionId, limitRevision, priority, reservedTokens, heldTokens, refundedTokens, usageSequence, usage? }` |
1239
- | `bypass` | `{ request, admissionId, limitRevision, priority, reason, detail?, reservation, raced }` |
1240
- | `bypassUsage` | `{ request, admissionId, limitRevision, priority, reason, sequence, reservation, usage, outputCap, outputRemaining, overReservation }` |
1241
- | `bypassRelease` | `{ request, admissionId, limitRevision, priority, reason, reservation, usageSequence, usage? }` |
1364
+ | `admit` | `{ request, admissionId, limitRevision, priority, admissionClass?, reservedTokens }` |
1365
+ | `reject` | `{ request, reason, limitRevision, admissionClass?, detail? }` |
1366
+ | `usage` | `{ request, admissionId, limitRevision, priority, admissionClass?, sequence, reservedTokens, previousHeldTokens, heldTokens, deltaTokens, usage, outputCap, outputRemaining, overReservation }` |
1367
+ | `release` | `{ request, admissionId, limitRevision, priority, admissionClass?, reservedTokens, heldTokens, refundedTokens, usageSequence, usage? }` |
1368
+ | `bypass` | `{ request, admissionId, limitRevision, priority, admissionClass?, reason, detail?, reservation, raced }` |
1369
+ | `bypassUsage` | `{ request, admissionId, limitRevision, priority, admissionClass?, reason, sequence, reservation, usage, outputCap, outputRemaining, overReservation }` |
1370
+ | `bypassRelease` | `{ request, admissionId, limitRevision, priority, admissionClass?, reason, reservation, usageSequence, usage? }` |
1242
1371
  | `reconfigure` | `{ previous, current }` |
1243
1372
  | `dedup` | `{ request }` |
1244
1373
 
@@ -1277,6 +1406,13 @@ type LLMBulkheadOptions = {
1277
1406
  outputCap?: number; // integer >= 0
1278
1407
  highPriorityReserve?: number; // integer >= 0 and <= initial budget
1279
1408
  };
1409
+ admissionClasses?: {
1410
+ defaultClass: string;
1411
+ classes: Record<string, {
1412
+ maxConcurrent?: number;
1413
+ maxInFlightTokens?: number; // requires tokenBudget
1414
+ }>;
1415
+ };
1280
1416
  deduplication?: boolean | DeduplicationOptions;
1281
1417
  };
1282
1418
 
@@ -1296,6 +1432,7 @@ run<T>(
1296
1432
  signal?: AbortSignal;
1297
1433
  timeoutMs?: number; // integer >= 0
1298
1434
  priority?: 'normal' | 'high';
1435
+ admissionClass?: string; // fixed configured policy-class ID
1299
1436
  getUsage?: (result: T) => TokenUsage | undefined;
1300
1437
  mode?: 'enforce' | 'observe'; // default: 'enforce' (v3.9)
1301
1438
  shadowReasons?: readonly (
@@ -1312,7 +1449,8 @@ run<T>(
1312
1449
 
1313
1450
  `ctx.admissionId` is the stable execution identifier and
1314
1451
  `ctx.limitRevision` is the immutable revision associated with the admission
1315
- or bypass decision. In observe-mode
1452
+ or bypass decision, and `ctx.admissionClass` identifies the selected bounded
1453
+ policy class when configured. In observe-mode
1316
1454
  bypasses it uses a `shadow-` prefix. `ctx.reservation` is the exact evaluated
1317
1455
  reservation (or `null` when token budgeting is disabled),
1318
1456
  `ctx.admission` distinguishes `"admitted"` from `"bypassed"`, and
@@ -1344,6 +1482,7 @@ acquire(
1344
1482
  signal?: AbortSignal;
1345
1483
  timeoutMs?: number; // integer >= 0
1346
1484
  priority?: 'normal' | 'high';
1485
+ admissionClass?: string;
1347
1486
  },
1348
1487
  ): Promise<LLMAcquireResult>
1349
1488
 
@@ -1352,6 +1491,7 @@ type LLMAcquireResult =
1352
1491
  ok: true;
1353
1492
  admissionId: string;
1354
1493
  limitRevision: number;
1494
+ admissionClass?: string;
1355
1495
  reservation: LLMReservationEstimate | null;
1356
1496
  token: LLMToken;
1357
1497
  }
@@ -1360,6 +1500,7 @@ type LLMAcquireResult =
1360
1500
  type LLMToken = {
1361
1501
  readonly admissionId: string;
1362
1502
  readonly limitRevision: number;
1503
+ readonly admissionClass?: string;
1363
1504
  readonly reservation: LLMReservationEstimate | null;
1364
1505
  reportUsage(
1365
1506
  usage: TokenUsage,
@@ -1395,6 +1536,10 @@ type LLMAdmissionLimits = {
1395
1536
  readonly budget: number;
1396
1537
  readonly highPriorityReserve: number;
1397
1538
  };
1539
+ readonly admissionClasses?: Readonly<Record<string, {
1540
+ readonly maxConcurrent?: number;
1541
+ readonly maxInFlightTokens?: number;
1542
+ }>>;
1398
1543
  };
1399
1544
  ```
1400
1545
 
@@ -1457,6 +1602,7 @@ type TokenUsage = { input: number; output: number };
1457
1602
  type UsageReport = {
1458
1603
  admissionId: string;
1459
1604
  limitRevision: number;
1605
+ admissionClass?: string;
1460
1606
  sequence: number;
1461
1607
  reserved: number;
1462
1608
  held: number;
@@ -1480,6 +1626,17 @@ type LLMRejectReason =
1480
1626
 
1481
1627
  ## Migration
1482
1628
 
1629
+ ### v3.13 → v3.14
1630
+
1631
+ No existing call-site changes are required. `admissionClasses` is opt-in and
1632
+ all new lifecycle fields are optional when the feature is disabled. Code that
1633
+ exhaustively asserts event, stats, limit-snapshot, token, run-context, usage,
1634
+ or rejection-detail shapes should account for the additive class fields.
1635
+ Gateways should pass only trusted, bounded policy-class IDs. Admission class
1636
+ automatically partitions in-flight deduplication, while `dedupScope` remains
1637
+ required for tenant-level isolation inside a shared class.
1638
+
1639
+
1483
1640
  ### v3.11.0 → v3.11.1
1484
1641
 
1485
1642
  No code changes are required. Update the dependency to v3.11.1 and regenerate