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.
@@ -25,6 +25,29 @@ function resolvePreset(profile) {
25
25
  return profiles_js_1.PROFILES[profile];
26
26
  return profile;
27
27
  }
28
+ function validateAdmissionClassId(value, label) {
29
+ if (typeof value !== "string" || value.trim() === "") {
30
+ throw new Error(`${label} must be a non-empty string`);
31
+ }
32
+ return value;
33
+ }
34
+ function readAdmissionClassLimits(value, label, tokenBudgetEnabled) {
35
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
36
+ throw new Error(`${label} must be an object`);
37
+ }
38
+ const source = value;
39
+ const maxConcurrent = source.maxConcurrent;
40
+ const maxInFlightTokens = source.maxInFlightTokens;
41
+ (0, validation_js_1.assertOptionalNonNegativeInteger)(maxConcurrent, `${label}.maxConcurrent`);
42
+ (0, validation_js_1.assertOptionalNonNegativeInteger)(maxInFlightTokens, `${label}.maxInFlightTokens`);
43
+ if (!tokenBudgetEnabled && maxInFlightTokens !== undefined) {
44
+ throw new Error(`${label}.maxInFlightTokens requires tokenBudget to be configured`);
45
+ }
46
+ return Object.freeze({
47
+ ...(maxConcurrent !== undefined && { maxConcurrent }),
48
+ ...(maxInFlightTokens !== undefined && { maxInFlightTokens }),
49
+ });
50
+ }
28
51
  // ────────────────────────────────────────────
29
52
  // createLLMBulkhead
30
53
  // ────────────────────────────────────────────
@@ -53,6 +76,44 @@ function createLLMBulkhead(opts) {
53
76
  throw new Error("tokenBudget.highPriorityReserve must be <= tokenBudget.budget");
54
77
  }
55
78
  }
79
+ // ---- Bounded admission-class configuration ----
80
+ const admissionClassOptions = opts.admissionClasses;
81
+ let defaultAdmissionClass;
82
+ const admissionClassStates = new Map();
83
+ if (admissionClassOptions !== undefined) {
84
+ defaultAdmissionClass = validateAdmissionClassId(admissionClassOptions.defaultClass, "admissionClasses.defaultClass");
85
+ const classes = admissionClassOptions.classes;
86
+ if (typeof classes !== "object" || classes === null || Array.isArray(classes)) {
87
+ throw new Error("admissionClasses.classes must be an object");
88
+ }
89
+ const entries = Object.entries(classes);
90
+ if (entries.length === 0) {
91
+ throw new Error("admissionClasses.classes must contain at least one class");
92
+ }
93
+ for (const [id, rawLimits] of entries) {
94
+ validateAdmissionClassId(id, "admissionClasses class id");
95
+ const limits = readAdmissionClassLimits(rawLimits, `admissionClasses.classes[${JSON.stringify(id)}]`, opts.tokenBudget !== undefined);
96
+ admissionClassStates.set(id, {
97
+ id,
98
+ maxConcurrent: limits.maxConcurrent,
99
+ maxInFlightTokens: limits.maxInFlightTokens,
100
+ inFlight: 0,
101
+ inFlightTokens: 0,
102
+ admitted: 0,
103
+ released: 0,
104
+ rejected: 0,
105
+ rejectedByReason: {},
106
+ totalReserved: 0,
107
+ totalConsumed: 0,
108
+ totalRefunded: 0,
109
+ totalOverrun: 0,
110
+ });
111
+ }
112
+ if (!admissionClassStates.has(defaultAdmissionClass)) {
113
+ throw new Error(`admissionClasses.defaultClass ${JSON.stringify(defaultAdmissionClass)} ` +
114
+ `must name a configured class`);
115
+ }
116
+ }
56
117
  // ---- Internal reconfigurable concurrency bulkhead ----
57
118
  const bulkhead = (0, reconfigurable_bulkhead_js_1.createReconfigurableBulkhead)({
58
119
  maxConcurrent: opts.maxConcurrent,
@@ -122,6 +183,48 @@ function createLLMBulkhead(opts) {
122
183
  llmRejectedByReason[reason] =
123
184
  (llmRejectedByReason[reason] ?? 0) + 1;
124
185
  }
186
+ function resolveAdmissionClass(requested) {
187
+ if (defaultAdmissionClass === undefined) {
188
+ if (requested !== undefined) {
189
+ throw new Error("admissionClass requires admissionClasses to be configured");
190
+ }
191
+ return undefined;
192
+ }
193
+ const id = requested === undefined
194
+ ? defaultAdmissionClass
195
+ : validateAdmissionClassId(requested, "admissionClass");
196
+ const state = admissionClassStates.get(id);
197
+ if (state === undefined) {
198
+ throw new Error(`unknown admissionClass ${JSON.stringify(id)}`);
199
+ }
200
+ return state;
201
+ }
202
+ function noteAdmissionClassReject(admissionClass, reason) {
203
+ if (admissionClass === undefined)
204
+ return;
205
+ admissionClass.rejected++;
206
+ admissionClass.rejectedByReason[reason] =
207
+ (admissionClass.rejectedByReason[reason] ?? 0) + 1;
208
+ }
209
+ function admissionClassLimitsSnapshot() {
210
+ if (defaultAdmissionClass === undefined)
211
+ return undefined;
212
+ const entries = [];
213
+ for (const [id, state] of admissionClassStates) {
214
+ entries.push([
215
+ id,
216
+ Object.freeze({
217
+ ...(state.maxConcurrent !== undefined && {
218
+ maxConcurrent: state.maxConcurrent,
219
+ }),
220
+ ...(state.maxInFlightTokens !== undefined && {
221
+ maxInFlightTokens: state.maxInFlightTokens,
222
+ }),
223
+ }),
224
+ ]);
225
+ }
226
+ return Object.freeze(Object.fromEntries(entries));
227
+ }
125
228
  // ---- Internal helpers ----
126
229
  function createDeferred() {
127
230
  let resolve;
@@ -220,10 +323,16 @@ function createLLMBulkhead(opts) {
220
323
  }
221
324
  return resolved;
222
325
  }
223
- function resolveAdmission(request, ao) {
326
+ function resolveAdmission(request, ao, resolvedAdmissionClass = resolveAdmissionClass(ao.admissionClass)) {
224
327
  const priority = resolvePriority(ao.priority);
328
+ const admissionClass = resolvedAdmissionClass;
225
329
  const parts = resolveReservation(request, ao.reservation);
226
- return { priority, parts, reserved: parts?.reserved ?? 0 };
330
+ return {
331
+ priority,
332
+ admissionClass,
333
+ parts,
334
+ reserved: parts?.reserved ?? 0,
335
+ };
227
336
  }
228
337
  /**
229
338
  * Budget ceiling applicable to a request at the given priority.
@@ -257,38 +366,75 @@ function createLLMBulkhead(opts) {
257
366
  ? currentBudget
258
367
  : Math.max(0, currentBudget - currentHighPriorityReserve);
259
368
  }
369
+ function checkAdmissionCapacity(reserved, priority, admissionClass) {
370
+ if (budget && inFlightTokens + reserved > effectiveBudget(priority)) {
371
+ return { reason: "budget_limit", constraint: "global" };
372
+ }
373
+ if (admissionClass?.maxInFlightTokens !== undefined &&
374
+ admissionClass.inFlightTokens + reserved >
375
+ admissionClass.maxInFlightTokens) {
376
+ return { reason: "budget_limit", constraint: "admission_class" };
377
+ }
378
+ if (admissionClass?.maxConcurrent !== undefined &&
379
+ admissionClass.inFlight >= admissionClass.maxConcurrent) {
380
+ return { reason: "concurrency_limit", constraint: "admission_class" };
381
+ }
382
+ return undefined;
383
+ }
260
384
  /**
261
- * Attempt token budget admission synchronously for a precomputed
262
- * reservation. Returns false if the priority-adjusted ceiling is
263
- * exceeded.
385
+ * Atomically reserve every non-queue capacity layer after the global
386
+ * concurrency slot is held. No counters are changed unless all checks pass.
264
387
  */
265
- function tryReserveTokens(reserved, priority) {
266
- if (!budget)
267
- return true;
268
- if (inFlightTokens + reserved > effectiveBudget(priority))
269
- return false;
270
- inFlightTokens += reserved;
271
- totalReserved += reserved;
272
- return true;
388
+ function tryReserveCapacity(reserved, priority, admissionClass) {
389
+ const failure = checkAdmissionCapacity(reserved, priority, admissionClass);
390
+ if (failure !== undefined)
391
+ return failure;
392
+ if (budget) {
393
+ inFlightTokens += reserved;
394
+ totalReserved += reserved;
395
+ }
396
+ if (admissionClass !== undefined) {
397
+ admissionClass.inFlight++;
398
+ admissionClass.admitted++;
399
+ if (budget) {
400
+ admissionClass.inFlightTokens += reserved;
401
+ admissionClass.totalReserved += reserved;
402
+ }
403
+ }
404
+ return undefined;
273
405
  }
274
- function releaseTokens(held, usage) {
406
+ function releaseCapacity(held, usage, admissionClass) {
275
407
  let refunded = 0;
276
408
  if (usage && held > 0) {
277
409
  const actual = usage.input + usage.output;
278
410
  totalConsumed += actual;
411
+ if (admissionClass !== undefined) {
412
+ admissionClass.totalConsumed += actual;
413
+ }
279
414
  if (actual < held) {
280
415
  refunded = held - actual;
281
416
  totalRefunded += refunded;
417
+ if (admissionClass !== undefined) {
418
+ admissionClass.totalRefunded += refunded;
419
+ }
282
420
  }
283
421
  }
284
422
  inFlightTokens = Math.max(0, inFlightTokens - held);
423
+ if (admissionClass !== undefined) {
424
+ admissionClass.inFlightTokens = Math.max(0, admissionClass.inFlightTokens - held);
425
+ admissionClass.inFlight = Math.max(0, admissionClass.inFlight - 1);
426
+ admissionClass.released++;
427
+ }
285
428
  return refunded;
286
429
  }
287
430
  /** Capacity snapshot for rejection results, events, and errors. */
288
- function buildRejectDetail(requested, priority) {
431
+ function buildRejectDetail(requested, priority, admissionClass, constraint) {
289
432
  const base = bulkhead.stats();
290
433
  const detail = {
291
434
  limitRevision: currentRevision,
435
+ ...(admissionClass !== undefined && constraint !== undefined
436
+ ? { constraint }
437
+ : {}),
292
438
  inFlight: base.inFlight,
293
439
  pending: base.pending,
294
440
  maxConcurrent: base.maxConcurrent,
@@ -304,13 +450,36 @@ function createLLMBulkhead(opts) {
304
450
  requested,
305
451
  };
306
452
  }
453
+ if (admissionClass !== undefined) {
454
+ detail.admissionClass = {
455
+ id: admissionClass.id,
456
+ inFlight: admissionClass.inFlight,
457
+ maxConcurrent: admissionClass.maxConcurrent ?? null,
458
+ availableConcurrent: admissionClass.maxConcurrent === undefined
459
+ ? null
460
+ : Math.max(0, admissionClass.maxConcurrent - admissionClass.inFlight),
461
+ ...(budget
462
+ ? {
463
+ tokenBudget: {
464
+ inFlightTokens: admissionClass.inFlightTokens,
465
+ maxInFlightTokens: admissionClass.maxInFlightTokens ?? null,
466
+ available: admissionClass.maxInFlightTokens === undefined
467
+ ? null
468
+ : Math.max(0, admissionClass.maxInFlightTokens -
469
+ admissionClass.inFlightTokens),
470
+ requested,
471
+ },
472
+ }
473
+ : {}),
474
+ };
475
+ }
307
476
  return detail;
308
477
  }
309
478
  function wouldAdmitResolved(admission, includeDetail) {
310
- const { priority, reserved } = admission;
311
- const withDetail = (result) => {
479
+ const { priority, admissionClass, reserved } = admission;
480
+ const withDetail = (result, constraint) => {
312
481
  if (includeDetail) {
313
- result.detail = buildRejectDetail(reserved, priority);
482
+ result.detail = buildRejectDetail(reserved, priority, admissionClass, constraint);
314
483
  }
315
484
  return result;
316
485
  };
@@ -318,14 +487,15 @@ function createLLMBulkhead(opts) {
318
487
  if (base.closed) {
319
488
  return withDetail({ admit: false, reason: "shutdown" });
320
489
  }
321
- if (budget && inFlightTokens + reserved > effectiveBudget(priority)) {
322
- return withDetail({ admit: false, reason: "budget_limit" });
490
+ const capacityFailure = checkAdmissionCapacity(reserved, priority, admissionClass);
491
+ if (capacityFailure !== undefined) {
492
+ return withDetail({ admit: false, reason: capacityFailure.reason }, capacityFailure.constraint);
323
493
  }
324
494
  if (base.inFlight < base.maxConcurrent) {
325
495
  return withDetail({ admit: true });
326
496
  }
327
497
  if (base.maxConcurrent === 0) {
328
- return withDetail({ admit: false, reason: "concurrency_limit" });
498
+ return withDetail({ admit: false, reason: "concurrency_limit" }, "global");
329
499
  }
330
500
  if (base.pending < base.maxQueue) {
331
501
  return withDetail({ admit: true });
@@ -333,11 +503,12 @@ function createLLMBulkhead(opts) {
333
503
  return withDetail({
334
504
  admit: false,
335
505
  reason: base.maxQueue > 0 ? "queue_limit" : "concurrency_limit",
336
- });
506
+ }, "global");
337
507
  }
338
508
  /** Return a detached snapshot of the currently applied limits. */
339
509
  function limits() {
340
510
  const base = bulkhead.stats();
511
+ const classLimits = admissionClassLimitsSnapshot();
341
512
  const snapshot = {
342
513
  revision: currentRevision,
343
514
  maxConcurrent: base.maxConcurrent,
@@ -350,12 +521,18 @@ function createLLMBulkhead(opts) {
350
521
  },
351
522
  }
352
523
  : {}),
524
+ ...(classLimits !== undefined
525
+ ? { admissionClasses: classLimits }
526
+ : {}),
353
527
  };
354
528
  return Object.freeze({
355
529
  ...snapshot,
356
530
  ...(snapshot.tokenBudget
357
531
  ? { tokenBudget: Object.freeze({ ...snapshot.tokenBudget }) }
358
532
  : {}),
533
+ ...(snapshot.admissionClasses
534
+ ? { admissionClasses: snapshot.admissionClasses }
535
+ : {}),
359
536
  });
360
537
  }
361
538
  /**
@@ -375,6 +552,7 @@ function createLLMBulkhead(opts) {
375
552
  const maxConcurrent = next.maxConcurrent;
376
553
  const maxQueue = next.maxQueue;
377
554
  const nextTokenBudget = next.tokenBudget;
555
+ const nextAdmissionClasses = next.admissionClasses;
378
556
  if (!Number.isSafeInteger(revision) || revision < 0) {
379
557
  throw new Error("limits.revision must be a non-negative safe integer");
380
558
  }
@@ -401,6 +579,31 @@ function createLLMBulkhead(opts) {
401
579
  else if (nextTokenBudget !== undefined) {
402
580
  throw new Error("limits.tokenBudget must be omitted because tokenBudget was not configured at construction");
403
581
  }
582
+ let preparedAdmissionClassLimits;
583
+ if (defaultAdmissionClass !== undefined) {
584
+ if (nextAdmissionClasses === undefined) {
585
+ throw new Error("limits.admissionClasses is required because admissionClasses was configured at construction");
586
+ }
587
+ if (typeof nextAdmissionClasses !== "object" ||
588
+ nextAdmissionClasses === null ||
589
+ Array.isArray(nextAdmissionClasses)) {
590
+ throw new Error("limits.admissionClasses must be an object");
591
+ }
592
+ const suppliedKeys = Object.keys(nextAdmissionClasses);
593
+ if (suppliedKeys.length !== admissionClassStates.size) {
594
+ throw new Error("limits.admissionClasses must contain exactly the construction-time class keys");
595
+ }
596
+ preparedAdmissionClassLimits = new Map();
597
+ for (const id of admissionClassStates.keys()) {
598
+ if (!Object.prototype.hasOwnProperty.call(nextAdmissionClasses, id)) {
599
+ throw new Error("limits.admissionClasses must contain exactly the construction-time class keys");
600
+ }
601
+ preparedAdmissionClassLimits.set(id, readAdmissionClassLimits(nextAdmissionClasses[id], `limits.admissionClasses[${JSON.stringify(id)}]`, budget !== undefined));
602
+ }
603
+ }
604
+ else if (nextAdmissionClasses !== undefined) {
605
+ throw new Error("limits.admissionClasses must be omitted because admissionClasses was not configured at construction");
606
+ }
404
607
  const previous = limits();
405
608
  // Install every LLM-layer value before pumping the concurrency queue.
406
609
  // Promise continuations from admitted waiters run only after this
@@ -410,6 +613,13 @@ function createLLMBulkhead(opts) {
410
613
  currentBudget = nextBudget;
411
614
  currentHighPriorityReserve = nextHighPriorityReserve;
412
615
  }
616
+ if (preparedAdmissionClassLimits !== undefined) {
617
+ for (const [id, nextLimits] of preparedAdmissionClassLimits) {
618
+ const state = admissionClassStates.get(id);
619
+ state.maxConcurrent = nextLimits.maxConcurrent;
620
+ state.maxInFlightTokens = nextLimits.maxInFlightTokens;
621
+ }
622
+ }
413
623
  bulkhead.applyLimits({ maxConcurrent, maxQueue });
414
624
  const current = limits();
415
625
  emit("reconfigure", { previous, current });
@@ -439,6 +649,9 @@ function createLLMBulkhead(opts) {
439
649
  budget: tokens,
440
650
  highPriorityReserve: currentHighPriorityReserve,
441
651
  },
652
+ ...(current.admissionClasses !== undefined
653
+ ? { admissionClasses: current.admissionClasses }
654
+ : {}),
442
655
  });
443
656
  }
444
657
  function normalizeAcquireOptions(ao) {
@@ -452,9 +665,17 @@ function createLLMBulkhead(opts) {
452
665
  }
453
666
  return normalized;
454
667
  }
455
- function noteDedupWaitRejection(request, reason) {
668
+ function noteDedupWaitRejection(request, reason, admissionClass) {
456
669
  noteLLMReject(reason);
457
- emit("reject", { request, reason, limitRevision: currentRevision });
670
+ noteAdmissionClassReject(admissionClass, reason);
671
+ emit("reject", {
672
+ request,
673
+ reason,
674
+ limitRevision: currentRevision,
675
+ ...(admissionClass !== undefined
676
+ ? { admissionClass: admissionClass.id }
677
+ : {}),
678
+ });
458
679
  const error = new errors_js_1.LLMBulkheadRejectedError(reason);
459
680
  dedupWaitErrors.add(error);
460
681
  return error;
@@ -473,12 +694,12 @@ function createLLMBulkhead(opts) {
473
694
  *
474
695
  * The leader never passes through this function.
475
696
  */
476
- function deliverShared(value, request) {
697
+ function deliverShared(value, request, admissionClass) {
477
698
  if (dedup.shareResult) {
478
699
  return dedup.shareResult(value);
479
700
  }
480
701
  if ((0, dedup_js_1.isUnsafeToShare)(value)) {
481
- throw noteDedupWaitRejection(request, "unshareable_result");
702
+ throw noteDedupWaitRejection(request, "unshareable_result", admissionClass);
482
703
  }
483
704
  return value;
484
705
  }
@@ -494,17 +715,17 @@ function createLLMBulkhead(opts) {
494
715
  * leader succeeded, defeating deduplication exactly when calls are
495
716
  * long. `signal` continues to apply as before.
496
717
  */
497
- function waitForSharedDedup(shared, request, ao) {
718
+ function waitForSharedDedup(shared, request, ao, admissionClass) {
498
719
  const signal = ao.signal;
499
720
  const effectiveTimeoutMs = ao.timeoutMs;
500
721
  if (effectiveTimeoutMs !== undefined) {
501
722
  (0, validation_js_1.assertNonNegativeInteger)(effectiveTimeoutMs, "timeoutMs");
502
723
  }
503
724
  if (signal?.aborted) {
504
- return Promise.reject(noteDedupWaitRejection(request, "aborted"));
725
+ return Promise.reject(noteDedupWaitRejection(request, "aborted", admissionClass));
505
726
  }
506
727
  if (signal === undefined && effectiveTimeoutMs === undefined) {
507
- return shared.then((value) => deliverShared(value, request));
728
+ return shared.then((value) => deliverShared(value, request, admissionClass));
508
729
  }
509
730
  return new Promise((resolve, reject) => {
510
731
  let timeoutId;
@@ -525,7 +746,7 @@ function createLLMBulkhead(opts) {
525
746
  };
526
747
  const onAbort = () => {
527
748
  settle(() => {
528
- reject(noteDedupWaitRejection(request, "aborted"));
749
+ reject(noteDedupWaitRejection(request, "aborted", admissionClass));
529
750
  });
530
751
  };
531
752
  if (signal !== undefined) {
@@ -534,13 +755,13 @@ function createLLMBulkhead(opts) {
534
755
  if (effectiveTimeoutMs !== undefined) {
535
756
  timeoutId = setTimeout(() => {
536
757
  settle(() => {
537
- reject(noteDedupWaitRejection(request, "timeout"));
758
+ reject(noteDedupWaitRejection(request, "timeout", admissionClass));
538
759
  });
539
760
  }, effectiveTimeoutMs);
540
761
  }
541
762
  void shared.then((value) => settle(() => {
542
763
  try {
543
- resolve(deliverShared(value, request));
764
+ resolve(deliverShared(value, request, admissionClass));
544
765
  }
545
766
  catch (err) {
546
767
  reject(err);
@@ -553,7 +774,7 @@ function createLLMBulkhead(opts) {
553
774
  * reservation and optionally applies the refund, and so that
554
775
  * streaming callers can report cumulative usage mid-flight.
555
776
  */
556
- function wrapToken(base, parts, request, admissionId, limitRevision, priority) {
777
+ function wrapToken(base, parts, request, admissionId, limitRevision, priority, admissionClass) {
557
778
  let released = false;
558
779
  /** Tokens currently held against the budget for this request. */
559
780
  let held = parts?.reserved ?? 0;
@@ -571,6 +792,9 @@ function createLLMBulkhead(opts) {
571
792
  return {
572
793
  admissionId,
573
794
  limitRevision,
795
+ ...(admissionClass !== undefined
796
+ ? { admissionClass: admissionClass.id }
797
+ : {}),
574
798
  sequence: usageSequence,
575
799
  reserved: parts?.reserved ?? 0,
576
800
  held,
@@ -582,8 +806,16 @@ function createLLMBulkhead(opts) {
582
806
  overReservation: parts ? consumed > parts.reserved : false,
583
807
  };
584
808
  };
585
- const reportUsage = (usage) => {
809
+ const reportUsage = (usage, reconciliation) => {
586
810
  const valid = (0, validation_js_1.validateTokenUsage)(usage);
811
+ if (reconciliation !== undefined) {
812
+ (0, validation_js_1.assertNonNegativeInteger)(reconciliation.remainingOutputTokens, "progressive reconciliation remainingOutputTokens");
813
+ (0, validation_js_1.assertOptionalNonNegativeInteger)(reconciliation.safetyMarginTokens, "progressive reconciliation safetyMarginTokens");
814
+ if (parts !== null &&
815
+ reconciliation.remainingOutputTokens > parts.maxOutput) {
816
+ throw new RangeError("progressive reconciliation remainingOutputTokens must not exceed the reserved output cap");
817
+ }
818
+ }
587
819
  const previousReported = reported;
588
820
  // Clamp to monotonic non-decreasing per field — cumulative
589
821
  // stream usage never shrinks; a lower report is stale.
@@ -599,32 +831,51 @@ function createLLMBulkhead(opts) {
599
831
  const previousHeldTokens = held;
600
832
  // Accounting only applies pre-release with a budget configured.
601
833
  if (!released && parts && budget) {
602
- // Hold = known input + the larger of (output ceiling, actual output).
603
- // Keeps the full output reservation while refunding input
604
- // over-estimates immediately; expands on output overrun.
605
- const newHold = reported.input + Math.max(parts.maxOutput, reported.output);
834
+ // Legacy mode holds known input plus the full output reservation.
835
+ // Progressive mode is opt-in and may be used only after prefill is
836
+ // known complete: it holds the caller-declared future output plus an
837
+ // explicit safety margin. Output beyond the configured cap is added
838
+ // back as overrun protection.
839
+ const outputOverrun = Math.max(0, reported.output - parts.maxOutput);
840
+ const newHold = reconciliation === undefined
841
+ ? reported.input + Math.max(parts.maxOutput, reported.output)
842
+ : reconciliation.remainingOutputTokens +
843
+ (reconciliation.safetyMarginTokens ?? 0) +
844
+ outputOverrun;
606
845
  const delta = newHold - held;
607
846
  if (delta > 0) {
608
847
  inFlightTokens += delta;
609
848
  totalOverrun += delta;
849
+ if (admissionClass !== undefined) {
850
+ admissionClass.inFlightTokens += delta;
851
+ admissionClass.totalOverrun += delta;
852
+ }
610
853
  }
611
854
  else if (delta < 0) {
612
855
  const refund = -delta;
613
856
  inFlightTokens = Math.max(0, inFlightTokens - refund);
614
857
  totalRefunded += refund;
858
+ if (admissionClass !== undefined) {
859
+ admissionClass.inFlightTokens = Math.max(0, admissionClass.inFlightTokens - refund);
860
+ admissionClass.totalRefunded += refund;
861
+ }
615
862
  }
616
863
  held = newHold;
617
864
  }
618
- if (!released && usageChanged) {
865
+ const holdChanged = held !== previousHeldTokens;
866
+ if (!released && (usageChanged || holdChanged)) {
619
867
  usageSequence++;
620
868
  }
621
869
  const report = snapshot();
622
- if (!released && usageChanged) {
870
+ if (!released && (usageChanged || holdChanged)) {
623
871
  emit("usage", {
624
872
  request,
625
873
  admissionId,
626
874
  limitRevision,
627
875
  priority,
876
+ ...(admissionClass !== undefined
877
+ ? { admissionClass: admissionClass.id }
878
+ : {}),
628
879
  sequence: usageSequence,
629
880
  reservedTokens: parts?.reserved ?? 0,
630
881
  previousHeldTokens,
@@ -634,6 +885,13 @@ function createLLMBulkhead(opts) {
634
885
  outputCap: report.outputCap,
635
886
  outputRemaining: report.outputRemaining,
636
887
  overReservation: report.overReservation,
888
+ ...(reconciliation === undefined
889
+ ? {}
890
+ : {
891
+ progressive: true,
892
+ remainingOutputTokens: reconciliation.remainingOutputTokens,
893
+ safetyMarginTokens: reconciliation.safetyMarginTokens ?? 0,
894
+ }),
637
895
  });
638
896
  }
639
897
  return report;
@@ -641,6 +899,9 @@ function createLLMBulkhead(opts) {
641
899
  return {
642
900
  admissionId,
643
901
  limitRevision,
902
+ ...(admissionClass !== undefined
903
+ ? { admissionClass: admissionClass.id }
904
+ : {}),
644
905
  reservation,
645
906
  reportUsage,
646
907
  release(usage) {
@@ -672,13 +933,16 @@ function createLLMBulkhead(opts) {
672
933
  // stale pre-release hold).
673
934
  const heldAtRelease = held;
674
935
  held = 0;
675
- const refunded = releaseTokens(heldAtRelease, validUsage);
936
+ const refunded = releaseCapacity(heldAtRelease, validUsage, admissionClass);
676
937
  noteLLMRelease();
677
938
  emit("release", {
678
939
  request,
679
940
  admissionId,
680
941
  limitRevision,
681
942
  priority,
943
+ ...(admissionClass !== undefined
944
+ ? { admissionClass: admissionClass.id }
945
+ : {}),
682
946
  reservedTokens: parts?.reserved ?? 0,
683
947
  heldTokens: heldAtRelease,
684
948
  refundedTokens: refunded,
@@ -693,31 +957,43 @@ function createLLMBulkhead(opts) {
693
957
  }
694
958
  // ---- Internal acquire ----
695
959
  async function _acquire(request, ao, resolved = resolveAdmission(request, ao)) {
696
- const { priority, parts, reserved } = resolved;
697
- const rejectWith = (reason) => {
698
- const detail = buildRejectDetail(reserved, priority);
960
+ const { priority, admissionClass, parts, reserved } = resolved;
961
+ const rejectWith = (reason, constraint) => {
962
+ const detail = buildRejectDetail(reserved, priority, admissionClass, constraint);
699
963
  noteLLMReject(reason);
964
+ noteAdmissionClassReject(admissionClass, reason);
700
965
  emit("reject", {
701
966
  request,
702
967
  reason,
703
968
  limitRevision: detail.limitRevision,
704
969
  detail,
970
+ ...(admissionClass !== undefined
971
+ ? { admissionClass: admissionClass.id }
972
+ : {}),
705
973
  });
706
974
  return { ok: false, reason, detail };
707
975
  };
708
- // Token budget: pre-check before entering the queue.
709
- if (budget && inFlightTokens + reserved > effectiveBudget(priority)) {
710
- return rejectWith("budget_limit");
976
+ // Every class ceiling is fail-fast and checked before entering the global
977
+ // queue. A second atomic check runs after the global slot is acquired.
978
+ const precheck = checkAdmissionCapacity(reserved, priority, admissionClass);
979
+ if (precheck !== undefined) {
980
+ return rejectWith(precheck.reason, precheck.constraint);
711
981
  }
712
982
  const mergedOptions = normalizeAcquireOptions(ao);
713
983
  const r = await bulkhead.acquire(mergedOptions);
714
984
  if (!r.ok) {
715
- return rejectWith(r.reason);
985
+ const constraint = r.reason === "concurrency_limit" ||
986
+ r.reason === "queue_limit" ||
987
+ r.reason === "timeout"
988
+ ? "global"
989
+ : undefined;
990
+ return rejectWith(r.reason, constraint);
716
991
  }
717
- // Post-admission: reserve the precomputed amount now.
718
- if (!tryReserveTokens(reserved, priority)) {
992
+ // Post-admission: atomically reserve global token and class capacity.
993
+ const postcheck = tryReserveCapacity(reserved, priority, admissionClass);
994
+ if (postcheck !== undefined) {
719
995
  r.token.release();
720
- return rejectWith("budget_limit");
996
+ return rejectWith(postcheck.reason, postcheck.constraint);
721
997
  }
722
998
  // Capture the revision at the admission linearization point: both the
723
999
  // concurrency slot and token reservation are held, and no listener or
@@ -725,19 +1001,25 @@ function createLLMBulkhead(opts) {
725
1001
  // provenance of this admitted work.
726
1002
  const limitRevision = currentRevision;
727
1003
  const admissionId = (0, node_crypto_1.randomUUID)();
728
- const token = wrapToken(r.token, parts, request, admissionId, limitRevision, priority);
1004
+ const token = wrapToken(r.token, parts, request, admissionId, limitRevision, priority, admissionClass);
729
1005
  noteLLMAdmit();
730
1006
  emit("admit", {
731
1007
  request,
732
1008
  admissionId,
733
1009
  limitRevision,
734
1010
  priority,
1011
+ ...(admissionClass !== undefined
1012
+ ? { admissionClass: admissionClass.id }
1013
+ : {}),
735
1014
  reservedTokens: reserved,
736
1015
  });
737
1016
  return {
738
1017
  ok: true,
739
1018
  admissionId,
740
1019
  limitRevision,
1020
+ ...(admissionClass !== undefined
1021
+ ? { admissionClass: admissionClass.id }
1022
+ : {}),
741
1023
  reservation: token.reservation,
742
1024
  token,
743
1025
  };
@@ -791,13 +1073,17 @@ function createLLMBulkhead(opts) {
791
1073
  ? "shutdown"
792
1074
  : undefined;
793
1075
  if (hardReason !== undefined) {
794
- const hardDetail = buildRejectDetail(admission.reserved, admission.priority);
1076
+ const hardDetail = buildRejectDetail(admission.reserved, admission.priority, admission.admissionClass);
795
1077
  noteLLMReject(hardReason);
1078
+ noteAdmissionClassReject(admission.admissionClass, hardReason);
796
1079
  emit("reject", {
797
1080
  request,
798
1081
  reason: hardReason,
799
1082
  limitRevision: hardDetail.limitRevision,
800
1083
  detail: hardDetail,
1084
+ ...(admission.admissionClass !== undefined
1085
+ ? { admissionClass: admission.admissionClass.id }
1086
+ : {}),
801
1087
  });
802
1088
  throw new errors_js_1.LLMBulkheadRejectedError(hardReason, hardDetail);
803
1089
  }
@@ -818,6 +1104,9 @@ function createLLMBulkhead(opts) {
818
1104
  admissionId,
819
1105
  limitRevision,
820
1106
  priority: admission.priority,
1107
+ ...(admission.admissionClass !== undefined
1108
+ ? { admissionClass: admission.admissionClass.id }
1109
+ : {}),
821
1110
  reason,
822
1111
  ...(detail !== undefined && { detail }),
823
1112
  reservation,
@@ -829,6 +1118,9 @@ function createLLMBulkhead(opts) {
829
1118
  return {
830
1119
  admissionId,
831
1120
  limitRevision,
1121
+ ...(admission.admissionClass !== undefined
1122
+ ? { admissionClass: admission.admissionClass.id }
1123
+ : {}),
832
1124
  sequence: usageSequence,
833
1125
  reserved: admission.reserved,
834
1126
  held: 0,
@@ -840,8 +1132,16 @@ function createLLMBulkhead(opts) {
840
1132
  overReservation: admission.parts !== null && consumed > admission.parts.reserved,
841
1133
  };
842
1134
  };
843
- const reportUsage = (usage) => {
1135
+ const reportUsage = (usage, reconciliation) => {
844
1136
  const valid = (0, validation_js_1.validateTokenUsage)(usage);
1137
+ if (reconciliation !== undefined) {
1138
+ (0, validation_js_1.assertNonNegativeInteger)(reconciliation.remainingOutputTokens, "progressive reconciliation remainingOutputTokens");
1139
+ (0, validation_js_1.assertOptionalNonNegativeInteger)(reconciliation.safetyMarginTokens, "progressive reconciliation safetyMarginTokens");
1140
+ if (admission.parts !== null &&
1141
+ reconciliation.remainingOutputTokens > admission.parts.maxOutput) {
1142
+ throw new RangeError("progressive reconciliation remainingOutputTokens must not exceed the reserved output cap");
1143
+ }
1144
+ }
845
1145
  const previous = reported;
846
1146
  reported = previous
847
1147
  ? {
@@ -860,6 +1160,9 @@ function createLLMBulkhead(opts) {
860
1160
  admissionId,
861
1161
  limitRevision,
862
1162
  priority: admission.priority,
1163
+ ...(admission.admissionClass !== undefined
1164
+ ? { admissionClass: admission.admissionClass.id }
1165
+ : {}),
863
1166
  reason,
864
1167
  sequence: usageSequence,
865
1168
  reservation,
@@ -867,6 +1170,13 @@ function createLLMBulkhead(opts) {
867
1170
  outputCap: current.outputCap,
868
1171
  outputRemaining: current.outputRemaining,
869
1172
  overReservation: current.overReservation,
1173
+ ...(reconciliation === undefined
1174
+ ? {}
1175
+ : {
1176
+ progressive: true,
1177
+ remainingOutputTokens: reconciliation.remainingOutputTokens,
1178
+ safetyMarginTokens: reconciliation.safetyMarginTokens ?? 0,
1179
+ }),
870
1180
  });
871
1181
  }
872
1182
  return snapshot();
@@ -874,6 +1184,9 @@ function createLLMBulkhead(opts) {
874
1184
  const context = {
875
1185
  admissionId,
876
1186
  limitRevision,
1187
+ ...(admission.admissionClass !== undefined
1188
+ ? { admissionClass: admission.admissionClass.id }
1189
+ : {}),
877
1190
  reservation,
878
1191
  admission: "bypassed",
879
1192
  bypassReason: reason,
@@ -894,6 +1207,9 @@ function createLLMBulkhead(opts) {
894
1207
  admissionId,
895
1208
  limitRevision,
896
1209
  priority: admission.priority,
1210
+ ...(admission.admissionClass !== undefined
1211
+ ? { admissionClass: admission.admissionClass.id }
1212
+ : {}),
897
1213
  reason,
898
1214
  reservation,
899
1215
  usageSequence,
@@ -941,6 +1257,11 @@ function createLLMBulkhead(opts) {
941
1257
  const { getUsage, mode: requestedMode, shadowReasons: requestedShadowReasons, dedupScope, dedup: perCallDedup, ...acquireOpts } = ao;
942
1258
  const mode = resolveAdmissionMode(requestedMode);
943
1259
  const shadowReasons = resolveShadowReasons(requestedShadowReasons);
1260
+ // Resolve before the dedup fast path so unknown class IDs cannot join an
1261
+ // existing call without validation. The resolved class also partitions
1262
+ // deduplication, preventing one policy class from inheriting another
1263
+ // class's admission decision or queue position.
1264
+ const selectedAdmissionClass = resolveAdmissionClass(acquireOpts.admissionClass);
944
1265
  // ---- Deduplication ----
945
1266
  let dedupKey = "";
946
1267
  if (dedup.enabled && perCallDedup !== false) {
@@ -953,7 +1274,10 @@ function createLLMBulkhead(opts) {
953
1274
  }
954
1275
  // "" opts out; only real keys are scoped + hashed.
955
1276
  if (rawKey !== "") {
956
- dedupKey = (0, dedup_js_1.hashDedupKey)(dedupScope ?? "", rawKey);
1277
+ const effectiveScope = selectedAdmissionClass === undefined
1278
+ ? dedupScope ?? ""
1279
+ : JSON.stringify([dedupScope ?? "", selectedAdmissionClass.id]);
1280
+ dedupKey = (0, dedup_js_1.hashDedupKey)(effectiveScope, rawKey);
957
1281
  }
958
1282
  }
959
1283
  let deferred;
@@ -962,9 +1286,14 @@ function createLLMBulkhead(opts) {
962
1286
  const existing = dedupMap.get(dedupKey);
963
1287
  if (existing) {
964
1288
  dedupHits++;
965
- emit("dedup", { request });
1289
+ emit("dedup", {
1290
+ request,
1291
+ ...(selectedAdmissionClass !== undefined
1292
+ ? { admissionClass: selectedAdmissionClass.id }
1293
+ : {}),
1294
+ });
966
1295
  try {
967
- return await waitForSharedDedup(existing, request, acquireOpts);
1296
+ return await waitForSharedDedup(existing, request, acquireOpts, selectedAdmissionClass);
968
1297
  }
969
1298
  catch (error) {
970
1299
  if (mode === "observe" &&
@@ -974,7 +1303,7 @@ function createLLMBulkhead(opts) {
974
1303
  return runBypassed(request, fn, {
975
1304
  ...(ao.signal !== undefined && { signal: ao.signal }),
976
1305
  ...(getUsage !== undefined && { getUsage }),
977
- }, resolveAdmission(request, acquireOpts), error.reason, error.detail, error.detail?.limitRevision ?? currentRevision, false);
1306
+ }, resolveAdmission(request, acquireOpts, selectedAdmissionClass), error.reason, error.detail, error.detail?.limitRevision ?? currentRevision, false);
978
1307
  }
979
1308
  throw error;
980
1309
  }
@@ -1005,7 +1334,7 @@ function createLLMBulkhead(opts) {
1005
1334
  let resolved;
1006
1335
  let advisory;
1007
1336
  if (mode === "observe") {
1008
- resolved = resolveAdmission(request, acquireOpts);
1337
+ resolved = resolveAdmission(request, acquireOpts, selectedAdmissionClass);
1009
1338
  advisory = wouldAdmitResolved(resolved, true);
1010
1339
  if (!advisory.admit &&
1011
1340
  advisory.reason !== undefined &&
@@ -1016,22 +1345,27 @@ function createLLMBulkhead(opts) {
1016
1345
  }, resolved, advisory.reason, advisory.detail, advisory.detail?.limitRevision ?? currentRevision, false));
1017
1346
  }
1018
1347
  }
1019
- const r = await _acquire(request, acquireOpts, resolved);
1348
+ const r = await _acquire(request, acquireOpts, resolved ??
1349
+ resolveAdmission(request, acquireOpts, selectedAdmissionClass));
1020
1350
  if (!r.ok) {
1021
1351
  if (mode === "observe" && shouldBypass(r.reason, shadowReasons)) {
1022
1352
  return publish(runBypassed(request, fn, {
1023
1353
  ...(ao.signal !== undefined && { signal: ao.signal }),
1024
1354
  ...(getUsage !== undefined && { getUsage }),
1025
- }, resolved ?? resolveAdmission(request, acquireOpts), r.reason, r.detail, r.detail?.limitRevision ?? currentRevision, advisory?.admit === true));
1355
+ }, resolved ??
1356
+ resolveAdmission(request, acquireOpts, selectedAdmissionClass), r.reason, r.detail, r.detail?.limitRevision ?? currentRevision, advisory?.admit === true));
1026
1357
  }
1027
1358
  throw new errors_js_1.LLMBulkheadRejectedError(r.reason, r.detail);
1028
1359
  }
1029
1360
  const ctx = {
1030
1361
  admissionId: r.admissionId,
1031
1362
  limitRevision: r.limitRevision,
1363
+ ...(r.admissionClass !== undefined
1364
+ ? { admissionClass: r.admissionClass }
1365
+ : {}),
1032
1366
  reservation: r.reservation,
1033
1367
  admission: "admitted",
1034
- reportUsage: (usage) => r.token.reportUsage(usage),
1368
+ reportUsage: (usage, reconciliation) => r.token.reportUsage(usage, reconciliation),
1035
1369
  };
1036
1370
  const work = (async () => {
1037
1371
  let result;
@@ -1108,6 +1442,34 @@ function createLLMBulkhead(opts) {
1108
1442
  hits: dedupHits,
1109
1443
  };
1110
1444
  }
1445
+ if (defaultAdmissionClass !== undefined) {
1446
+ result.admissionClasses = {
1447
+ defaultClass: defaultAdmissionClass,
1448
+ classes: Object.fromEntries(Array.from(admissionClassStates, ([id, state]) => [
1449
+ id,
1450
+ {
1451
+ limits: {
1452
+ ...(state.maxConcurrent !== undefined && {
1453
+ maxConcurrent: state.maxConcurrent,
1454
+ }),
1455
+ ...(state.maxInFlightTokens !== undefined && {
1456
+ maxInFlightTokens: state.maxInFlightTokens,
1457
+ }),
1458
+ },
1459
+ inFlight: state.inFlight,
1460
+ inFlightTokens: state.inFlightTokens,
1461
+ admitted: state.admitted,
1462
+ released: state.released,
1463
+ rejected: state.rejected,
1464
+ rejectedByReason: { ...state.rejectedByReason },
1465
+ totalReserved: state.totalReserved,
1466
+ totalConsumed: state.totalConsumed,
1467
+ totalRefunded: state.totalRefunded,
1468
+ totalOverrun: state.totalOverrun,
1469
+ },
1470
+ ])),
1471
+ };
1472
+ }
1111
1473
  return result;
1112
1474
  }
1113
1475
  /**