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.
@@ -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,
@@ -622,11 +846,19 @@ function createLLMBulkhead(opts) {
622
846
  if (delta > 0) {
623
847
  inFlightTokens += delta;
624
848
  totalOverrun += delta;
849
+ if (admissionClass !== undefined) {
850
+ admissionClass.inFlightTokens += delta;
851
+ admissionClass.totalOverrun += delta;
852
+ }
625
853
  }
626
854
  else if (delta < 0) {
627
855
  const refund = -delta;
628
856
  inFlightTokens = Math.max(0, inFlightTokens - refund);
629
857
  totalRefunded += refund;
858
+ if (admissionClass !== undefined) {
859
+ admissionClass.inFlightTokens = Math.max(0, admissionClass.inFlightTokens - refund);
860
+ admissionClass.totalRefunded += refund;
861
+ }
630
862
  }
631
863
  held = newHold;
632
864
  }
@@ -641,6 +873,9 @@ function createLLMBulkhead(opts) {
641
873
  admissionId,
642
874
  limitRevision,
643
875
  priority,
876
+ ...(admissionClass !== undefined
877
+ ? { admissionClass: admissionClass.id }
878
+ : {}),
644
879
  sequence: usageSequence,
645
880
  reservedTokens: parts?.reserved ?? 0,
646
881
  previousHeldTokens,
@@ -664,6 +899,9 @@ function createLLMBulkhead(opts) {
664
899
  return {
665
900
  admissionId,
666
901
  limitRevision,
902
+ ...(admissionClass !== undefined
903
+ ? { admissionClass: admissionClass.id }
904
+ : {}),
667
905
  reservation,
668
906
  reportUsage,
669
907
  release(usage) {
@@ -695,13 +933,16 @@ function createLLMBulkhead(opts) {
695
933
  // stale pre-release hold).
696
934
  const heldAtRelease = held;
697
935
  held = 0;
698
- const refunded = releaseTokens(heldAtRelease, validUsage);
936
+ const refunded = releaseCapacity(heldAtRelease, validUsage, admissionClass);
699
937
  noteLLMRelease();
700
938
  emit("release", {
701
939
  request,
702
940
  admissionId,
703
941
  limitRevision,
704
942
  priority,
943
+ ...(admissionClass !== undefined
944
+ ? { admissionClass: admissionClass.id }
945
+ : {}),
705
946
  reservedTokens: parts?.reserved ?? 0,
706
947
  heldTokens: heldAtRelease,
707
948
  refundedTokens: refunded,
@@ -716,31 +957,43 @@ function createLLMBulkhead(opts) {
716
957
  }
717
958
  // ---- Internal acquire ----
718
959
  async function _acquire(request, ao, resolved = resolveAdmission(request, ao)) {
719
- const { priority, parts, reserved } = resolved;
720
- const rejectWith = (reason) => {
721
- 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);
722
963
  noteLLMReject(reason);
964
+ noteAdmissionClassReject(admissionClass, reason);
723
965
  emit("reject", {
724
966
  request,
725
967
  reason,
726
968
  limitRevision: detail.limitRevision,
727
969
  detail,
970
+ ...(admissionClass !== undefined
971
+ ? { admissionClass: admissionClass.id }
972
+ : {}),
728
973
  });
729
974
  return { ok: false, reason, detail };
730
975
  };
731
- // Token budget: pre-check before entering the queue.
732
- if (budget && inFlightTokens + reserved > effectiveBudget(priority)) {
733
- 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);
734
981
  }
735
982
  const mergedOptions = normalizeAcquireOptions(ao);
736
983
  const r = await bulkhead.acquire(mergedOptions);
737
984
  if (!r.ok) {
738
- 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);
739
991
  }
740
- // Post-admission: reserve the precomputed amount now.
741
- 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) {
742
995
  r.token.release();
743
- return rejectWith("budget_limit");
996
+ return rejectWith(postcheck.reason, postcheck.constraint);
744
997
  }
745
998
  // Capture the revision at the admission linearization point: both the
746
999
  // concurrency slot and token reservation are held, and no listener or
@@ -748,19 +1001,25 @@ function createLLMBulkhead(opts) {
748
1001
  // provenance of this admitted work.
749
1002
  const limitRevision = currentRevision;
750
1003
  const admissionId = (0, node_crypto_1.randomUUID)();
751
- const token = wrapToken(r.token, parts, request, admissionId, limitRevision, priority);
1004
+ const token = wrapToken(r.token, parts, request, admissionId, limitRevision, priority, admissionClass);
752
1005
  noteLLMAdmit();
753
1006
  emit("admit", {
754
1007
  request,
755
1008
  admissionId,
756
1009
  limitRevision,
757
1010
  priority,
1011
+ ...(admissionClass !== undefined
1012
+ ? { admissionClass: admissionClass.id }
1013
+ : {}),
758
1014
  reservedTokens: reserved,
759
1015
  });
760
1016
  return {
761
1017
  ok: true,
762
1018
  admissionId,
763
1019
  limitRevision,
1020
+ ...(admissionClass !== undefined
1021
+ ? { admissionClass: admissionClass.id }
1022
+ : {}),
764
1023
  reservation: token.reservation,
765
1024
  token,
766
1025
  };
@@ -814,13 +1073,17 @@ function createLLMBulkhead(opts) {
814
1073
  ? "shutdown"
815
1074
  : undefined;
816
1075
  if (hardReason !== undefined) {
817
- const hardDetail = buildRejectDetail(admission.reserved, admission.priority);
1076
+ const hardDetail = buildRejectDetail(admission.reserved, admission.priority, admission.admissionClass);
818
1077
  noteLLMReject(hardReason);
1078
+ noteAdmissionClassReject(admission.admissionClass, hardReason);
819
1079
  emit("reject", {
820
1080
  request,
821
1081
  reason: hardReason,
822
1082
  limitRevision: hardDetail.limitRevision,
823
1083
  detail: hardDetail,
1084
+ ...(admission.admissionClass !== undefined
1085
+ ? { admissionClass: admission.admissionClass.id }
1086
+ : {}),
824
1087
  });
825
1088
  throw new errors_js_1.LLMBulkheadRejectedError(hardReason, hardDetail);
826
1089
  }
@@ -841,6 +1104,9 @@ function createLLMBulkhead(opts) {
841
1104
  admissionId,
842
1105
  limitRevision,
843
1106
  priority: admission.priority,
1107
+ ...(admission.admissionClass !== undefined
1108
+ ? { admissionClass: admission.admissionClass.id }
1109
+ : {}),
844
1110
  reason,
845
1111
  ...(detail !== undefined && { detail }),
846
1112
  reservation,
@@ -852,6 +1118,9 @@ function createLLMBulkhead(opts) {
852
1118
  return {
853
1119
  admissionId,
854
1120
  limitRevision,
1121
+ ...(admission.admissionClass !== undefined
1122
+ ? { admissionClass: admission.admissionClass.id }
1123
+ : {}),
855
1124
  sequence: usageSequence,
856
1125
  reserved: admission.reserved,
857
1126
  held: 0,
@@ -891,6 +1160,9 @@ function createLLMBulkhead(opts) {
891
1160
  admissionId,
892
1161
  limitRevision,
893
1162
  priority: admission.priority,
1163
+ ...(admission.admissionClass !== undefined
1164
+ ? { admissionClass: admission.admissionClass.id }
1165
+ : {}),
894
1166
  reason,
895
1167
  sequence: usageSequence,
896
1168
  reservation,
@@ -912,6 +1184,9 @@ function createLLMBulkhead(opts) {
912
1184
  const context = {
913
1185
  admissionId,
914
1186
  limitRevision,
1187
+ ...(admission.admissionClass !== undefined
1188
+ ? { admissionClass: admission.admissionClass.id }
1189
+ : {}),
915
1190
  reservation,
916
1191
  admission: "bypassed",
917
1192
  bypassReason: reason,
@@ -932,6 +1207,9 @@ function createLLMBulkhead(opts) {
932
1207
  admissionId,
933
1208
  limitRevision,
934
1209
  priority: admission.priority,
1210
+ ...(admission.admissionClass !== undefined
1211
+ ? { admissionClass: admission.admissionClass.id }
1212
+ : {}),
935
1213
  reason,
936
1214
  reservation,
937
1215
  usageSequence,
@@ -979,6 +1257,11 @@ function createLLMBulkhead(opts) {
979
1257
  const { getUsage, mode: requestedMode, shadowReasons: requestedShadowReasons, dedupScope, dedup: perCallDedup, ...acquireOpts } = ao;
980
1258
  const mode = resolveAdmissionMode(requestedMode);
981
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);
982
1265
  // ---- Deduplication ----
983
1266
  let dedupKey = "";
984
1267
  if (dedup.enabled && perCallDedup !== false) {
@@ -991,7 +1274,10 @@ function createLLMBulkhead(opts) {
991
1274
  }
992
1275
  // "" opts out; only real keys are scoped + hashed.
993
1276
  if (rawKey !== "") {
994
- 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);
995
1281
  }
996
1282
  }
997
1283
  let deferred;
@@ -1000,9 +1286,14 @@ function createLLMBulkhead(opts) {
1000
1286
  const existing = dedupMap.get(dedupKey);
1001
1287
  if (existing) {
1002
1288
  dedupHits++;
1003
- emit("dedup", { request });
1289
+ emit("dedup", {
1290
+ request,
1291
+ ...(selectedAdmissionClass !== undefined
1292
+ ? { admissionClass: selectedAdmissionClass.id }
1293
+ : {}),
1294
+ });
1004
1295
  try {
1005
- return await waitForSharedDedup(existing, request, acquireOpts);
1296
+ return await waitForSharedDedup(existing, request, acquireOpts, selectedAdmissionClass);
1006
1297
  }
1007
1298
  catch (error) {
1008
1299
  if (mode === "observe" &&
@@ -1012,7 +1303,7 @@ function createLLMBulkhead(opts) {
1012
1303
  return runBypassed(request, fn, {
1013
1304
  ...(ao.signal !== undefined && { signal: ao.signal }),
1014
1305
  ...(getUsage !== undefined && { getUsage }),
1015
- }, 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);
1016
1307
  }
1017
1308
  throw error;
1018
1309
  }
@@ -1043,7 +1334,7 @@ function createLLMBulkhead(opts) {
1043
1334
  let resolved;
1044
1335
  let advisory;
1045
1336
  if (mode === "observe") {
1046
- resolved = resolveAdmission(request, acquireOpts);
1337
+ resolved = resolveAdmission(request, acquireOpts, selectedAdmissionClass);
1047
1338
  advisory = wouldAdmitResolved(resolved, true);
1048
1339
  if (!advisory.admit &&
1049
1340
  advisory.reason !== undefined &&
@@ -1054,19 +1345,24 @@ function createLLMBulkhead(opts) {
1054
1345
  }, resolved, advisory.reason, advisory.detail, advisory.detail?.limitRevision ?? currentRevision, false));
1055
1346
  }
1056
1347
  }
1057
- const r = await _acquire(request, acquireOpts, resolved);
1348
+ const r = await _acquire(request, acquireOpts, resolved ??
1349
+ resolveAdmission(request, acquireOpts, selectedAdmissionClass));
1058
1350
  if (!r.ok) {
1059
1351
  if (mode === "observe" && shouldBypass(r.reason, shadowReasons)) {
1060
1352
  return publish(runBypassed(request, fn, {
1061
1353
  ...(ao.signal !== undefined && { signal: ao.signal }),
1062
1354
  ...(getUsage !== undefined && { getUsage }),
1063
- }, 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));
1064
1357
  }
1065
1358
  throw new errors_js_1.LLMBulkheadRejectedError(r.reason, r.detail);
1066
1359
  }
1067
1360
  const ctx = {
1068
1361
  admissionId: r.admissionId,
1069
1362
  limitRevision: r.limitRevision,
1363
+ ...(r.admissionClass !== undefined
1364
+ ? { admissionClass: r.admissionClass }
1365
+ : {}),
1070
1366
  reservation: r.reservation,
1071
1367
  admission: "admitted",
1072
1368
  reportUsage: (usage, reconciliation) => r.token.reportUsage(usage, reconciliation),
@@ -1146,6 +1442,34 @@ function createLLMBulkhead(opts) {
1146
1442
  hits: dedupHits,
1147
1443
  };
1148
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
+ }
1149
1473
  return result;
1150
1474
  }
1151
1475
  /**