async-bulkhead-llm 3.12.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,9 +9,11 @@ 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
16
+ - ✅ **Progressive reconciliation** — release processed input and generated-output reservation during live streams
15
17
  - ✅ **Token refund** — reclaim unused budget capacity from actual usage post-completion
16
18
  - ✅ **Model-aware estimation** — per-model character ratios for known providers
17
19
  - ✅ **Per-request model** — mixed-model routing through a single bulkhead
@@ -134,6 +136,95 @@ const result = await bulkhead.run(request, async () => {
134
136
 
135
137
  ---
136
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
+
137
228
  ## What's New in v3.12 — Fail-closed startup
138
229
 
139
230
  v3.12 allows `maxConcurrent: 0` at construction time. A gateway managed by an
@@ -782,6 +873,60 @@ const bulkhead = createLLMBulkhead({
782
873
 
783
874
  ---
784
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
+
785
930
  ## Token Budget
786
931
 
787
932
  ```ts
@@ -879,6 +1024,13 @@ const bulkhead = createLLMBulkhead({
879
1024
  budget: 200_000,
880
1025
  highPriorityReserve: 25_000,
881
1026
  },
1027
+ admissionClasses: {
1028
+ defaultClass: 'standard',
1029
+ classes: {
1030
+ premium: { maxConcurrent: 7, maxInFlightTokens: 140_000 },
1031
+ standard: { maxConcurrent: 3, maxInFlightTokens: 60_000 },
1032
+ },
1033
+ },
882
1034
  });
883
1035
 
884
1036
  const update = bulkhead.applyLimits({
@@ -907,9 +1059,11 @@ Semantics:
907
1059
  * **Budget reserve may exceed a shrunken budget.** The normal-priority ceiling
908
1060
  is clamped to 0 while high-priority traffic is checked against the full
909
1061
  budget, preserving the existing degraded-priority behavior.
910
- * **Budget feature shape is fixed at construction.** A bulkhead created with
1062
+ * **Feature shapes are fixed at construction.** A bulkhead created with
911
1063
  `tokenBudget` requires `tokenBudget` in every update. A bulkhead created
912
- 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.
913
1067
  * **Admission provenance is immutable.** `acquire()` results, tokens,
914
1068
  `LLMRunContext`, usage reports, and lifecycle events retain the revision
915
1069
  captured when the slot and token reservation were successfully acquired.
@@ -917,7 +1071,7 @@ Semantics:
917
1071
 
918
1072
  ```ts
919
1073
  const current = bulkhead.limits();
920
- // { revision, maxConcurrent, maxQueue, tokenBudget? }
1074
+ // { revision, maxConcurrent, maxQueue, tokenBudget?, admissionClasses? }
921
1075
 
922
1076
  bulkhead.on('reconfigure', ({ previous, current }) => {
923
1077
  publishAppliedRevision(previous.revision, current.revision);
@@ -1115,6 +1269,7 @@ s.limits.maxConcurrent
1115
1269
  s.limits.maxQueue
1116
1270
  s.limits.tokenBudget?.budget
1117
1271
  s.limits.tokenBudget?.highPriorityReserve
1272
+ s.limits.admissionClasses?.premium?.maxConcurrent
1118
1273
 
1119
1274
  s.bulkhead.inFlight
1120
1275
  s.bulkhead.pending
@@ -1141,6 +1296,11 @@ s.tokenBudget?.totalReserved // v3.1: cumulative tokens reserved at admis
1141
1296
  s.tokenBudget?.totalConsumed // v3.1: cumulative actual tokens consumed (usage required)
1142
1297
  s.tokenBudget?.totalRefunded // v2: cumulative refunded tokens
1143
1298
 
1299
+ s.admissionClasses?.defaultClass
1300
+ s.admissionClasses?.classes.premium?.inFlight
1301
+ s.admissionClasses?.classes.premium?.inFlightTokens
1302
+ s.admissionClasses?.classes.premium?.rejectedByReason
1303
+
1144
1304
  s.deduplication?.active
1145
1305
  s.deduplication?.hits
1146
1306
  ```
@@ -1174,6 +1334,10 @@ type LLMStats = {
1174
1334
  totalInputTokens: number;
1175
1335
  totalOutputTokens: number;
1176
1336
  };
1337
+ admissionClasses?: {
1338
+ defaultClass: string;
1339
+ classes: Record<string, LLMAdmissionClassStats>;
1340
+ };
1177
1341
  deduplication?: {
1178
1342
  active: number;
1179
1343
  hits: number;
@@ -1197,13 +1361,13 @@ off();
1197
1361
 
1198
1362
  | Event | Payload |
1199
1363
  |-----------|---------|
1200
- | `admit` | `{ request, admissionId, limitRevision, priority, reservedTokens }` |
1201
- | `reject` | `{ request, reason, limitRevision, detail? }` |
1202
- | `usage` | `{ request, admissionId, limitRevision, priority, sequence, reservedTokens, previousHeldTokens, heldTokens, deltaTokens, usage, outputCap, outputRemaining, overReservation }` |
1203
- | `release` | `{ request, admissionId, limitRevision, priority, reservedTokens, heldTokens, refundedTokens, usageSequence, usage? }` |
1204
- | `bypass` | `{ request, admissionId, limitRevision, priority, reason, detail?, reservation, raced }` |
1205
- | `bypassUsage` | `{ request, admissionId, limitRevision, priority, reason, sequence, reservation, usage, outputCap, outputRemaining, overReservation }` |
1206
- | `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? }` |
1207
1371
  | `reconfigure` | `{ previous, current }` |
1208
1372
  | `dedup` | `{ request }` |
1209
1373
 
@@ -1242,6 +1406,13 @@ type LLMBulkheadOptions = {
1242
1406
  outputCap?: number; // integer >= 0
1243
1407
  highPriorityReserve?: number; // integer >= 0 and <= initial budget
1244
1408
  };
1409
+ admissionClasses?: {
1410
+ defaultClass: string;
1411
+ classes: Record<string, {
1412
+ maxConcurrent?: number;
1413
+ maxInFlightTokens?: number; // requires tokenBudget
1414
+ }>;
1415
+ };
1245
1416
  deduplication?: boolean | DeduplicationOptions;
1246
1417
  };
1247
1418
 
@@ -1261,6 +1432,7 @@ run<T>(
1261
1432
  signal?: AbortSignal;
1262
1433
  timeoutMs?: number; // integer >= 0
1263
1434
  priority?: 'normal' | 'high';
1435
+ admissionClass?: string; // fixed configured policy-class ID
1264
1436
  getUsage?: (result: T) => TokenUsage | undefined;
1265
1437
  mode?: 'enforce' | 'observe'; // default: 'enforce' (v3.9)
1266
1438
  shadowReasons?: readonly (
@@ -1277,7 +1449,8 @@ run<T>(
1277
1449
 
1278
1450
  `ctx.admissionId` is the stable execution identifier and
1279
1451
  `ctx.limitRevision` is the immutable revision associated with the admission
1280
- 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
1281
1454
  bypasses it uses a `shadow-` prefix. `ctx.reservation` is the exact evaluated
1282
1455
  reservation (or `null` when token budgeting is disabled),
1283
1456
  `ctx.admission` distinguishes `"admitted"` from `"bypassed"`, and
@@ -1309,6 +1482,7 @@ acquire(
1309
1482
  signal?: AbortSignal;
1310
1483
  timeoutMs?: number; // integer >= 0
1311
1484
  priority?: 'normal' | 'high';
1485
+ admissionClass?: string;
1312
1486
  },
1313
1487
  ): Promise<LLMAcquireResult>
1314
1488
 
@@ -1317,6 +1491,7 @@ type LLMAcquireResult =
1317
1491
  ok: true;
1318
1492
  admissionId: string;
1319
1493
  limitRevision: number;
1494
+ admissionClass?: string;
1320
1495
  reservation: LLMReservationEstimate | null;
1321
1496
  token: LLMToken;
1322
1497
  }
@@ -1325,8 +1500,15 @@ type LLMAcquireResult =
1325
1500
  type LLMToken = {
1326
1501
  readonly admissionId: string;
1327
1502
  readonly limitRevision: number;
1503
+ readonly admissionClass?: string;
1328
1504
  readonly reservation: LLMReservationEstimate | null;
1329
- reportUsage(usage: TokenUsage): UsageReport;
1505
+ reportUsage(
1506
+ usage: TokenUsage,
1507
+ reconciliation?: {
1508
+ remainingOutputTokens: number;
1509
+ safetyMarginTokens?: number;
1510
+ },
1511
+ ): UsageReport;
1330
1512
  release(usage?: TokenUsage): void;
1331
1513
  };
1332
1514
  ```
@@ -1354,6 +1536,10 @@ type LLMAdmissionLimits = {
1354
1536
  readonly budget: number;
1355
1537
  readonly highPriorityReserve: number;
1356
1538
  };
1539
+ readonly admissionClasses?: Readonly<Record<string, {
1540
+ readonly maxConcurrent?: number;
1541
+ readonly maxInFlightTokens?: number;
1542
+ }>>;
1357
1543
  };
1358
1544
  ```
1359
1545
 
@@ -1416,6 +1602,7 @@ type TokenUsage = { input: number; output: number };
1416
1602
  type UsageReport = {
1417
1603
  admissionId: string;
1418
1604
  limitRevision: number;
1605
+ admissionClass?: string;
1419
1606
  sequence: number;
1420
1607
  reserved: number;
1421
1608
  held: number;
@@ -1439,6 +1626,17 @@ type LLMRejectReason =
1439
1626
 
1440
1627
  ## Migration
1441
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
+
1442
1640
  ### v3.11.0 → v3.11.1
1443
1641
 
1444
1642
  No code changes are required. Update the dependency to v3.11.1 and regenerate