async-bulkhead-llm 3.16.0 → 3.17.1

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.
Files changed (173) hide show
  1. package/CHANGELOG.md +127 -4
  2. package/README.md +28 -2
  3. package/dist/cjs/bulkhead.cjs +119 -1666
  4. package/dist/cjs/bulkhead.cjs.map +1 -1
  5. package/dist/cjs/engine/acquire.cjs +144 -0
  6. package/dist/cjs/engine/acquire.cjs.map +1 -0
  7. package/dist/cjs/engine/admission-counts.cjs +92 -0
  8. package/dist/cjs/engine/admission-counts.cjs.map +1 -0
  9. package/dist/cjs/engine/admission-request.cjs +28 -0
  10. package/dist/cjs/engine/admission-request.cjs.map +1 -0
  11. package/dist/cjs/engine/admitted-run.cjs +100 -0
  12. package/dist/cjs/engine/admitted-run.cjs.map +1 -0
  13. package/dist/cjs/engine/admitted-token.cjs +192 -0
  14. package/dist/cjs/engine/admitted-token.cjs.map +1 -0
  15. package/dist/cjs/engine/bypass.cjs +162 -0
  16. package/dist/cjs/engine/bypass.cjs.map +1 -0
  17. package/dist/cjs/engine/capacity.cjs +89 -0
  18. package/dist/cjs/engine/capacity.cjs.map +1 -0
  19. package/dist/cjs/engine/class-limits.cjs +101 -0
  20. package/dist/cjs/engine/class-limits.cjs.map +1 -0
  21. package/dist/cjs/engine/class-slots.cjs +49 -0
  22. package/dist/cjs/engine/class-slots.cjs.map +1 -0
  23. package/dist/cjs/engine/dedup-flow.cjs +207 -0
  24. package/dist/cjs/engine/dedup-flow.cjs.map +1 -0
  25. package/dist/cjs/engine/events.cjs +35 -0
  26. package/dist/cjs/engine/events.cjs.map +1 -0
  27. package/dist/cjs/engine/limits.cjs +313 -0
  28. package/dist/cjs/engine/limits.cjs.map +1 -0
  29. package/dist/cjs/engine/observe-stats.cjs +43 -0
  30. package/dist/cjs/engine/observe-stats.cjs.map +1 -0
  31. package/dist/cjs/engine/options.cjs +79 -0
  32. package/dist/cjs/engine/options.cjs.map +1 -0
  33. package/dist/cjs/engine/reject-detail.cjs +103 -0
  34. package/dist/cjs/engine/reject-detail.cjs.map +1 -0
  35. package/dist/cjs/engine/reservation.cjs +55 -0
  36. package/dist/cjs/engine/reservation.cjs.map +1 -0
  37. package/dist/cjs/engine/run-options.cjs +59 -0
  38. package/dist/cjs/engine/run-options.cjs.map +1 -0
  39. package/dist/cjs/engine/run.cjs +76 -0
  40. package/dist/cjs/engine/run.cjs.map +1 -0
  41. package/dist/cjs/engine/shared-usage.cjs +70 -0
  42. package/dist/cjs/engine/shared-usage.cjs.map +1 -0
  43. package/dist/cjs/engine/shared.cjs +17 -0
  44. package/dist/cjs/engine/shared.cjs.map +1 -0
  45. package/dist/cjs/engine/shutdown.cjs +58 -0
  46. package/dist/cjs/engine/shutdown.cjs.map +1 -0
  47. package/dist/cjs/engine/stats.cjs +92 -0
  48. package/dist/cjs/engine/stats.cjs.map +1 -0
  49. package/dist/cjs/engine/token-ledger.cjs +117 -0
  50. package/dist/cjs/engine/token-ledger.cjs.map +1 -0
  51. package/dist/cjs/engine/usage-report.cjs +95 -0
  52. package/dist/cjs/engine/usage-report.cjs.map +1 -0
  53. package/dist/cjs/engine/would-admit.cjs +37 -0
  54. package/dist/cjs/engine/would-admit.cjs.map +1 -0
  55. package/dist/cjs/errors.cjs +22 -1
  56. package/dist/cjs/errors.cjs.map +1 -1
  57. package/dist/cjs/index.cjs +11 -2
  58. package/dist/cjs/index.cjs.map +1 -1
  59. package/dist/esm/bulkhead.js +119 -1666
  60. package/dist/esm/bulkhead.js.map +1 -1
  61. package/dist/esm/engine/acquire.js +141 -0
  62. package/dist/esm/engine/acquire.js.map +1 -0
  63. package/dist/esm/engine/admission-counts.js +89 -0
  64. package/dist/esm/engine/admission-counts.js.map +1 -0
  65. package/dist/esm/engine/admission-request.js +25 -0
  66. package/dist/esm/engine/admission-request.js.map +1 -0
  67. package/dist/esm/engine/admitted-run.js +97 -0
  68. package/dist/esm/engine/admitted-run.js.map +1 -0
  69. package/dist/esm/engine/admitted-token.js +189 -0
  70. package/dist/esm/engine/admitted-token.js.map +1 -0
  71. package/dist/esm/engine/bypass.js +159 -0
  72. package/dist/esm/engine/bypass.js.map +1 -0
  73. package/dist/esm/engine/capacity.js +86 -0
  74. package/dist/esm/engine/capacity.js.map +1 -0
  75. package/dist/esm/engine/class-limits.js +95 -0
  76. package/dist/esm/engine/class-limits.js.map +1 -0
  77. package/dist/esm/engine/class-slots.js +46 -0
  78. package/dist/esm/engine/class-slots.js.map +1 -0
  79. package/dist/esm/engine/dedup-flow.js +204 -0
  80. package/dist/esm/engine/dedup-flow.js.map +1 -0
  81. package/dist/esm/engine/events.js +32 -0
  82. package/dist/esm/engine/events.js.map +1 -0
  83. package/dist/esm/engine/limits.js +310 -0
  84. package/dist/esm/engine/limits.js.map +1 -0
  85. package/dist/esm/engine/observe-stats.js +40 -0
  86. package/dist/esm/engine/observe-stats.js.map +1 -0
  87. package/dist/esm/engine/options.js +76 -0
  88. package/dist/esm/engine/options.js.map +1 -0
  89. package/dist/esm/engine/reject-detail.js +100 -0
  90. package/dist/esm/engine/reject-detail.js.map +1 -0
  91. package/dist/esm/engine/reservation.js +52 -0
  92. package/dist/esm/engine/reservation.js.map +1 -0
  93. package/dist/esm/engine/run-options.js +55 -0
  94. package/dist/esm/engine/run-options.js.map +1 -0
  95. package/dist/esm/engine/run.js +73 -0
  96. package/dist/esm/engine/run.js.map +1 -0
  97. package/dist/esm/engine/shared-usage.js +67 -0
  98. package/dist/esm/engine/shared-usage.js.map +1 -0
  99. package/dist/esm/engine/shared.js +14 -0
  100. package/dist/esm/engine/shared.js.map +1 -0
  101. package/dist/esm/engine/shutdown.js +55 -0
  102. package/dist/esm/engine/shutdown.js.map +1 -0
  103. package/dist/esm/engine/stats.js +89 -0
  104. package/dist/esm/engine/stats.js.map +1 -0
  105. package/dist/esm/engine/token-ledger.js +114 -0
  106. package/dist/esm/engine/token-ledger.js.map +1 -0
  107. package/dist/esm/engine/usage-report.js +86 -0
  108. package/dist/esm/engine/usage-report.js.map +1 -0
  109. package/dist/esm/engine/would-admit.js +34 -0
  110. package/dist/esm/engine/would-admit.js.map +1 -0
  111. package/dist/esm/errors.js +20 -0
  112. package/dist/esm/errors.js.map +1 -1
  113. package/dist/esm/index.js +10 -2
  114. package/dist/esm/index.js.map +1 -1
  115. package/dist/types/bulkhead.d.ts +33 -6
  116. package/dist/types/bulkhead.d.ts.map +1 -1
  117. package/dist/types/engine/acquire.d.ts +25 -0
  118. package/dist/types/engine/acquire.d.ts.map +1 -0
  119. package/dist/types/engine/admission-counts.d.ts +30 -0
  120. package/dist/types/engine/admission-counts.d.ts.map +1 -0
  121. package/dist/types/engine/admission-request.d.ts +12 -0
  122. package/dist/types/engine/admission-request.d.ts.map +1 -0
  123. package/dist/types/engine/admitted-run.d.ts +19 -0
  124. package/dist/types/engine/admitted-run.d.ts.map +1 -0
  125. package/dist/types/engine/admitted-token.d.ts +42 -0
  126. package/dist/types/engine/admitted-token.d.ts.map +1 -0
  127. package/dist/types/engine/bypass.d.ts +17 -0
  128. package/dist/types/engine/bypass.d.ts.map +1 -0
  129. package/dist/types/engine/capacity.d.ts +36 -0
  130. package/dist/types/engine/capacity.d.ts.map +1 -0
  131. package/dist/types/engine/class-limits.d.ts +20 -0
  132. package/dist/types/engine/class-limits.d.ts.map +1 -0
  133. package/dist/types/engine/class-slots.d.ts +20 -0
  134. package/dist/types/engine/class-slots.d.ts.map +1 -0
  135. package/dist/types/engine/dedup-flow.d.ts +41 -0
  136. package/dist/types/engine/dedup-flow.d.ts.map +1 -0
  137. package/dist/types/engine/events.d.ts +13 -0
  138. package/dist/types/engine/events.d.ts.map +1 -0
  139. package/dist/types/engine/limits.d.ts +45 -0
  140. package/dist/types/engine/limits.d.ts.map +1 -0
  141. package/dist/types/engine/observe-stats.d.ts +14 -0
  142. package/dist/types/engine/observe-stats.d.ts.map +1 -0
  143. package/dist/types/engine/options.d.ts +21 -0
  144. package/dist/types/engine/options.d.ts.map +1 -0
  145. package/dist/types/engine/reject-detail.d.ts +25 -0
  146. package/dist/types/engine/reject-detail.d.ts.map +1 -0
  147. package/dist/types/engine/reservation.d.ts +13 -0
  148. package/dist/types/engine/reservation.d.ts.map +1 -0
  149. package/dist/types/engine/run-options.d.ts +25 -0
  150. package/dist/types/engine/run-options.d.ts.map +1 -0
  151. package/dist/types/engine/run.d.ts +28 -0
  152. package/dist/types/engine/run.d.ts.map +1 -0
  153. package/dist/types/engine/shared-usage.d.ts +28 -0
  154. package/dist/types/engine/shared-usage.d.ts.map +1 -0
  155. package/dist/types/engine/shared.d.ts +63 -0
  156. package/dist/types/engine/shared.d.ts.map +1 -0
  157. package/dist/types/engine/shutdown.d.ts +20 -0
  158. package/dist/types/engine/shutdown.d.ts.map +1 -0
  159. package/dist/types/engine/stats.d.ts +28 -0
  160. package/dist/types/engine/stats.d.ts.map +1 -0
  161. package/dist/types/engine/token-ledger.d.ts +40 -0
  162. package/dist/types/engine/token-ledger.d.ts.map +1 -0
  163. package/dist/types/engine/usage-report.d.ts +63 -0
  164. package/dist/types/engine/usage-report.d.ts.map +1 -0
  165. package/dist/types/engine/would-admit.d.ts +16 -0
  166. package/dist/types/engine/would-admit.d.ts.map +1 -0
  167. package/dist/types/errors.d.ts +15 -2
  168. package/dist/types/errors.d.ts.map +1 -1
  169. package/dist/types/index.d.ts +11 -3
  170. package/dist/types/index.d.ts.map +1 -1
  171. package/dist/types/types.d.ts +74 -1
  172. package/dist/types/types.d.ts.map +1 -1
  173. package/package.json +2 -2
@@ -1,324 +1,81 @@
1
- import { randomUUID } from "node:crypto";
2
- import { LLMBulkheadRejectedError } from "./errors.js";
3
- import { PROFILES } from "./profiles.js";
4
- import { createModelAwareTokenEstimator } from "./estimators.js";
5
- import { assertNonNegativeInteger, assertOptionalNonNegativeInteger, validateTokenEstimate, validateTokenUsage, } from "./validation.js";
6
- import { hashDedupKey, isUnsafeToShare, resolveDedup } from "./dedup.js";
7
1
  import { createReconfigurableBulkhead } from "./reconfigurable-bulkhead.js";
8
- const DEFAULT_SHADOW_REASONS = [
9
- "budget_limit",
10
- "concurrency_limit",
11
- "queue_limit",
12
- "timeout",
13
- ];
14
- const SHADOWABLE_REASONS = new Set(DEFAULT_SHADOW_REASONS);
15
- // ────────────────────────────────────────────
16
- // Option resolution
17
- // ────────────────────────────────────────────
18
- function resolvePreset(profile) {
19
- if (!profile)
20
- return {};
21
- if (typeof profile === "string")
22
- return PROFILES[profile];
23
- return profile;
24
- }
25
- function validateAdmissionClassId(value, label) {
26
- if (typeof value !== "string" || value.trim() === "") {
27
- throw new Error(`${label} must be a non-empty string`);
28
- }
29
- return value;
30
- }
31
- function readAdmissionClassLimits(value, label, tokenBudgetEnabled) {
32
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
33
- throw new Error(`${label} must be an object`);
34
- }
35
- const source = value;
36
- const protectedConcurrent = source.protectedConcurrent;
37
- const maxConcurrent = source.maxConcurrent;
38
- const protectedInFlightTokens = source.protectedInFlightTokens;
39
- const maxInFlightTokens = source.maxInFlightTokens;
40
- assertOptionalNonNegativeInteger(protectedConcurrent, `${label}.protectedConcurrent`);
41
- assertOptionalNonNegativeInteger(maxConcurrent, `${label}.maxConcurrent`);
42
- assertOptionalNonNegativeInteger(protectedInFlightTokens, `${label}.protectedInFlightTokens`);
43
- assertOptionalNonNegativeInteger(maxInFlightTokens, `${label}.maxInFlightTokens`);
44
- if (maxConcurrent !== undefined &&
45
- (protectedConcurrent ?? 0) > maxConcurrent) {
46
- throw new Error(`${label}.protectedConcurrent must be <= ${label}.maxConcurrent`);
47
- }
48
- if (maxInFlightTokens !== undefined &&
49
- (protectedInFlightTokens ?? 0) > maxInFlightTokens) {
50
- throw new Error(`${label}.protectedInFlightTokens must be <= ${label}.maxInFlightTokens`);
51
- }
52
- if (!tokenBudgetEnabled) {
53
- if (protectedInFlightTokens !== undefined) {
54
- throw new Error(`${label}.protectedInFlightTokens requires tokenBudget to be configured`);
55
- }
56
- if (maxInFlightTokens !== undefined) {
57
- throw new Error(`${label}.maxInFlightTokens requires tokenBudget to be configured`);
58
- }
59
- }
60
- return Object.freeze({
61
- ...(protectedConcurrent !== undefined && { protectedConcurrent }),
62
- ...(maxConcurrent !== undefined && { maxConcurrent }),
63
- ...(protectedInFlightTokens !== undefined && {
64
- protectedInFlightTokens,
65
- }),
66
- ...(maxInFlightTokens !== undefined && { maxInFlightTokens }),
67
- });
68
- }
69
- function validateProtectedCapacity(limits, maxConcurrent, tokenBudget, label) {
70
- let protectedConcurrent = 0;
71
- let protectedTokens = 0;
72
- for (const classLimits of limits) {
73
- protectedConcurrent += classLimits.protectedConcurrent ?? 0;
74
- protectedTokens += classLimits.protectedInFlightTokens ?? 0;
75
- }
76
- if (protectedConcurrent > maxConcurrent) {
77
- throw new Error(`${label} protectedConcurrent sum must be <= maxConcurrent`);
78
- }
79
- if (tokenBudget !== undefined && protectedTokens > tokenBudget) {
80
- throw new Error(`${label} protectedInFlightTokens sum must be <= tokenBudget.budget`);
81
- }
82
- }
2
+ import { createAcquire } from "./engine/acquire.js";
3
+ import { createAdmissionCounts } from "./engine/admission-counts.js";
4
+ import { createAdmissionResolver } from "./engine/admission-request.js";
5
+ import { createTokenWrapper } from "./engine/admitted-token.js";
6
+ import { createBypass } from "./engine/bypass.js";
7
+ import { createCapacity } from "./engine/capacity.js";
8
+ import { createClassSlots } from "./engine/class-slots.js";
9
+ import { createDedup } from "./engine/dedup-flow.js";
10
+ import { createEventHub } from "./engine/events.js";
11
+ import { createLimits } from "./engine/limits.js";
12
+ import { createObserveStats } from "./engine/observe-stats.js";
13
+ import { resolveOptions } from "./engine/options.js";
14
+ import { createRejectDetail } from "./engine/reject-detail.js";
15
+ import { createReservations } from "./engine/reservation.js";
16
+ import { createRun } from "./engine/run.js";
17
+ import { createSharedUsage } from "./engine/shared-usage.js";
18
+ import { createShutdown } from "./engine/shutdown.js";
19
+ import { createStats } from "./engine/stats.js";
20
+ import { createTokenLedger } from "./engine/token-ledger.js";
21
+ import { createWouldAdmit } from "./engine/would-admit.js";
83
22
  // ────────────────────────────────────────────
84
23
  // createLLMBulkhead
85
24
  // ────────────────────────────────────────────
86
25
  export function createLLMBulkhead(opts) {
87
- // ---- Validate ----
88
- if (typeof opts.model !== "string" || opts.model.trim() === "") {
89
- throw new Error("model must be a non-empty string");
90
- }
91
- assertNonNegativeInteger(opts.maxConcurrent, "maxConcurrent");
92
- const initialRevision = opts.initialRevision ?? 0;
93
- if (!Number.isSafeInteger(initialRevision) || initialRevision < 0) {
94
- throw new Error("initialRevision must be a non-negative safe integer");
95
- }
96
- // ---- Resolve profile defaults ----
97
- const preset = resolvePreset(opts.profile);
98
- const maxQueue = opts.maxQueue ?? preset.maxQueue ?? 0;
99
- const timeoutMs = opts.timeoutMs ?? preset.timeoutMs;
100
- assertNonNegativeInteger(maxQueue, "maxQueue");
101
- assertOptionalNonNegativeInteger(timeoutMs, "timeoutMs");
102
- if (opts.tokenBudget) {
103
- assertNonNegativeInteger(opts.tokenBudget.budget, "tokenBudget.budget");
104
- assertOptionalNonNegativeInteger(opts.tokenBudget.outputCap, "tokenBudget.outputCap");
105
- assertOptionalNonNegativeInteger(opts.tokenBudget.highPriorityReserve, "tokenBudget.highPriorityReserve");
106
- if (opts.tokenBudget.highPriorityReserve !== undefined &&
107
- opts.tokenBudget.highPriorityReserve > opts.tokenBudget.budget) {
108
- throw new Error("tokenBudget.highPriorityReserve must be <= tokenBudget.budget");
109
- }
110
- }
111
- // ---- Bounded admission-class configuration ----
112
- const admissionClassOptions = opts.admissionClasses;
113
- let defaultAdmissionClass;
114
- const admissionClassStates = new Map();
115
- if (admissionClassOptions !== undefined) {
116
- defaultAdmissionClass = validateAdmissionClassId(admissionClassOptions.defaultClass, "admissionClasses.defaultClass");
117
- const classes = admissionClassOptions.classes;
118
- if (typeof classes !== "object" || classes === null || Array.isArray(classes)) {
119
- throw new Error("admissionClasses.classes must be an object");
120
- }
121
- const entries = Object.entries(classes);
122
- const validatedClassLimits = [];
123
- if (entries.length === 0) {
124
- throw new Error("admissionClasses.classes must contain at least one class");
125
- }
126
- for (const [id, rawLimits] of entries) {
127
- validateAdmissionClassId(id, "admissionClasses class id");
128
- const limits = readAdmissionClassLimits(rawLimits, `admissionClasses.classes[${JSON.stringify(id)}]`, opts.tokenBudget !== undefined);
129
- validatedClassLimits.push(limits);
130
- admissionClassStates.set(id, {
131
- id,
132
- protectedConcurrent: limits.protectedConcurrent ?? 0,
133
- maxConcurrent: limits.maxConcurrent,
134
- protectedInFlightTokens: limits.protectedInFlightTokens ?? 0,
135
- maxInFlightTokens: limits.maxInFlightTokens,
136
- inFlight: 0,
137
- inFlightTokens: 0,
138
- admitted: 0,
139
- released: 0,
140
- rejected: 0,
141
- rejectedByReason: {},
142
- totalReserved: 0,
143
- totalConsumed: 0,
144
- totalRefunded: 0,
145
- totalOverrun: 0,
146
- totalBorrowedAdmissions: 0,
147
- totalBorrowedTokensReserved: 0,
148
- });
149
- }
150
- if (!admissionClassStates.has(defaultAdmissionClass)) {
151
- throw new Error(`admissionClasses.defaultClass ${JSON.stringify(defaultAdmissionClass)} ` +
152
- `must name a configured class`);
153
- }
154
- validateProtectedCapacity(validatedClassLimits, opts.maxConcurrent, opts.tokenBudget?.budget, "admissionClasses");
155
- }
26
+ // ---- Validate and resolve options ----
27
+ const config = resolveOptions(opts);
156
28
  // ---- Internal reconfigurable concurrency bulkhead ----
157
- const bulkhead = createReconfigurableBulkhead({
29
+ const concurrency = createReconfigurableBulkhead({
158
30
  maxConcurrent: opts.maxConcurrent,
159
- maxQueue,
31
+ maxQueue: config.maxQueue,
160
32
  });
161
- // ---- Token budget state ----
33
+ // ---- Token budget: accounting is on when `tokenBudget` is set ----
162
34
  const budget = opts.tokenBudget;
163
- const estimator = budget?.estimator ??
164
- createModelAwareTokenEstimator(undefined, {
165
- defaultModel: opts.model,
166
- outputCap: budget?.outputCap,
167
- });
168
- /** Current versioned admission-limit state. */
169
- let currentRevision = initialRevision;
170
- let currentBudget = budget?.budget;
171
- let currentHighPriorityReserve = budget?.highPriorityReserve ?? 0;
172
- let inFlightTokens = 0;
173
- let totalReserved = 0;
174
- let totalConsumed = 0;
175
- let totalRefunded = 0;
176
- let totalOverrun = 0;
177
- let llmAdmitted = 0;
178
- let llmReleased = 0;
179
- let llmRejected = 0;
180
- const llmRejectedByReason = {};
181
- let observeBypassed = 0;
182
- let observeRaceBypassed = 0;
183
- const observeBypassedByReason = {};
184
- let observeUsageReported = 0;
185
- let observeTotalInputTokens = 0;
186
- let observeTotalOutputTokens = 0;
187
- // ---- Deduplication state ----
188
- const dedup = resolveDedup(opts.deduplication);
189
- const dedupMap = new Map();
190
- const dedupWaitErrors = new WeakSet();
191
- let dedupHits = 0;
192
- // ---- Event emitter state ----
193
- const listeners = {
194
- admit: new Set(),
195
- reject: new Set(),
196
- release: new Set(),
197
- usage: new Set(),
198
- bypass: new Set(),
199
- bypassUsage: new Set(),
200
- bypassRelease: new Set(),
201
- reconfigure: new Set(),
202
- dedup: new Set(),
35
+ const budgetEnabled = Boolean(budget);
36
+ const reservations = createReservations(budget, opts);
37
+ const events = createEventHub();
38
+ // ---- Owners: every limit and counter has exactly one of these ----
39
+ const admissionLimits = createLimits(config, budget, concurrency, events);
40
+ const classIds = admissionLimits.classIds;
41
+ const owners = {
42
+ budgetEnabled,
43
+ concurrency,
44
+ events,
45
+ limits: admissionLimits,
46
+ ledger: createTokenLedger(budgetEnabled, classIds),
47
+ slots: createClassSlots(classIds),
48
+ counts: createAdmissionCounts(classIds),
49
+ observeStats: createObserveStats(),
203
50
  };
204
- function emit(event, payload) {
205
- for (const fn of listeners[event]) {
206
- try {
207
- fn(payload);
208
- }
209
- catch {
210
- // listeners must not throw into the bulkhead
211
- }
212
- }
213
- }
214
- function noteLLMAdmit() {
215
- llmAdmitted++;
216
- }
217
- function noteLLMRelease() {
218
- llmReleased++;
219
- }
220
- function noteLLMReject(reason) {
221
- llmRejected++;
222
- llmRejectedByReason[reason] =
223
- (llmRejectedByReason[reason] ?? 0) + 1;
224
- }
225
- function resolveAdmissionClass(requested) {
226
- if (defaultAdmissionClass === undefined) {
227
- if (requested !== undefined) {
228
- throw new Error("admissionClass requires admissionClasses to be configured");
229
- }
230
- return undefined;
231
- }
232
- const id = requested === undefined
233
- ? defaultAdmissionClass
234
- : validateAdmissionClassId(requested, "admissionClass");
235
- const state = admissionClassStates.get(id);
236
- if (state === undefined) {
237
- throw new Error(`unknown admissionClass ${JSON.stringify(id)}`);
238
- }
239
- return state;
240
- }
241
- function noteAdmissionClassReject(admissionClass, reason) {
242
- if (admissionClass === undefined)
243
- return;
244
- admissionClass.rejected++;
245
- admissionClass.rejectedByReason[reason] =
246
- (admissionClass.rejectedByReason[reason] ?? 0) + 1;
247
- }
248
- function admissionClassLimitsSnapshot() {
249
- if (defaultAdmissionClass === undefined)
250
- return undefined;
251
- const entries = [];
252
- for (const [id, state] of admissionClassStates) {
253
- entries.push([
254
- id,
255
- Object.freeze({
256
- ...(state.protectedConcurrent > 0 && {
257
- protectedConcurrent: state.protectedConcurrent,
258
- }),
259
- ...(state.maxConcurrent !== undefined && {
260
- maxConcurrent: state.maxConcurrent,
261
- }),
262
- ...(state.protectedInFlightTokens > 0 && {
263
- protectedInFlightTokens: state.protectedInFlightTokens,
264
- }),
265
- ...(state.maxInFlightTokens !== undefined && {
266
- maxInFlightTokens: state.maxInFlightTokens,
267
- }),
268
- }),
269
- ]);
270
- }
271
- return Object.freeze(Object.fromEntries(entries));
272
- }
273
- // ---- Internal helpers ----
274
- function createDeferred() {
275
- let resolve;
276
- let reject;
277
- const promise = new Promise((res, rej) => {
278
- resolve = res;
279
- reject = rej;
280
- });
281
- return { promise, resolve, reject };
282
- }
283
- function estimateParts(request) {
284
- return resolveReservation(request, undefined);
285
- }
286
- /**
287
- * Reservation used for admission: the caller's per-call `reservation`
288
- * override verbatim when provided, otherwise the estimator's output.
289
- * Both paths validate as non-negative integers. `null` when
290
- * `tokenBudget` is disabled (no reservation participates then, and
291
- * the override is deliberately ignored).
292
- */
293
- function resolveReservation(request, override) {
294
- assertOptionalNonNegativeInteger(request.max_tokens, "request.max_tokens");
295
- if (!budget)
296
- return null;
297
- if (override !== undefined) {
298
- const reserved = validateTokenEstimate(override);
299
- // v3.8: `reserved`, when present (e.g. an `estimate()` result passed
300
- // back verbatim), is a consistency check — not an independent input.
301
- if (override.reserved !== undefined) {
302
- assertNonNegativeInteger(override.reserved, "reservation.reserved");
303
- if (override.reserved !== reserved) {
304
- throw new Error(`reservation.reserved (${override.reserved}) must equal ` +
305
- `reservation.input + reservation.maxOutput (${reserved})`);
306
- }
307
- }
308
- return {
309
- input: override.input,
310
- maxOutput: override.maxOutput,
311
- reserved,
312
- };
313
- }
314
- const estimate = estimator(request);
315
- const reserved = validateTokenEstimate(estimate);
316
- return {
317
- input: estimate.input,
318
- maxOutput: estimate.maxOutput,
319
- reserved,
320
- };
321
- }
51
+ const dedup = createDedup({ ...owners, options: opts.deduplication });
52
+ // ---- Capacity decisions: they read the owners and keep no state ----
53
+ const usage = createSharedUsage(owners);
54
+ const capacity = createCapacity({ ...owners, usage });
55
+ const buildRejectDetail = createRejectDetail({ ...owners, usage });
56
+ const resolveAdmission = createAdmissionResolver(admissionLimits, reservations);
57
+ const wouldAdmitResolved = createWouldAdmit({
58
+ concurrency,
59
+ capacity,
60
+ buildRejectDetail,
61
+ });
62
+ // ---- Admission, execution, stats and shutdown ----
63
+ const shutdown = createShutdown(concurrency, owners.counts);
64
+ const wrapToken = createTokenWrapper({
65
+ ...owners,
66
+ settleDrainWaiters: shutdown.settleDrainWaiters,
67
+ });
68
+ const admit = createAcquire({
69
+ ...owners,
70
+ capacity,
71
+ buildRejectDetail,
72
+ resolveAdmission,
73
+ wrapToken,
74
+ timeoutMs: config.timeoutMs,
75
+ });
76
+ const runBypassed = createBypass({ ...owners, buildRejectDetail });
77
+ const readStats = createStats({ ...owners, usage, dedup });
78
+ // ---- Public API ----
322
79
  /**
323
80
  * Preview the exact token reservation that admission will calculate.
324
81
  *
@@ -336,903 +93,41 @@ export function createLLMBulkhead(opts) {
336
93
  * `estimate()` always previews the estimator path.
337
94
  */
338
95
  function estimate(request) {
339
- const parts = estimateParts(request);
340
- return parts === null ? null : { ...parts };
341
- }
342
- function resolvePriority(priority) {
343
- if (priority === undefined)
344
- return "normal";
345
- if (priority !== "high" && priority !== "normal") {
346
- throw new Error(`priority must be "high" or "normal"`);
347
- }
348
- return priority;
349
- }
350
- function resolveAdmissionMode(mode) {
351
- if (mode === undefined)
352
- return "enforce";
353
- if (mode !== "enforce" && mode !== "observe") {
354
- throw new Error(`mode must be "enforce" or "observe"`);
355
- }
356
- return mode;
357
- }
358
- function resolveShadowReasons(reasons) {
359
- if (reasons === undefined)
360
- return SHADOWABLE_REASONS;
361
- const resolved = new Set();
362
- for (const reason of reasons) {
363
- if (!SHADOWABLE_REASONS.has(reason)) {
364
- throw new Error(`shadowReasons may contain only budget_limit, concurrency_limit, ` +
365
- `queue_limit, or timeout`);
366
- }
367
- resolved.add(reason);
368
- }
369
- return resolved;
370
- }
371
- function resolveAdmission(request, ao, resolvedAdmissionClass = resolveAdmissionClass(ao.admissionClass)) {
372
- const priority = resolvePriority(ao.priority);
373
- const admissionClass = resolvedAdmissionClass;
374
- const parts = resolveReservation(request, ao.reservation);
375
- return {
376
- priority,
377
- admissionClass,
378
- parts,
379
- reserved: parts?.reserved ?? 0,
380
- };
381
- }
382
- /**
383
- * Budget ceiling applicable to a request at the given priority.
384
- *
385
- * Construction validates `0 <= highPriorityReserve <= budget` (see the
386
- * `tokenBudget` validation block above) — that check catches config
387
- * typos once, at startup. It intentionally does *not* run again here.
388
- *
389
- * `applyLimits()` or `setBudget()` can lower `currentBudget` below
390
- * `highPriorityReserve` at
391
- * runtime (e.g. a lease-renewal ledger reporting a shrunk grant), and
392
- * that is allowed, not re-validated. Rejecting a renewal-driven update
393
- * would be wrong: the ledger's grant is reality — the bulkhead has no
394
- * standing to refuse it. So `currentBudget` can legitimately end up
395
- * smaller than `highPriorityReserve`.
396
- *
397
- * Consequence, deliberately embraced: `currentBudget! - currentHighPriorityReserve`
398
- * would go negative in that state, so it is clamped to `0` here. That
399
- * means normal-priority admission is fully rejected (nothing fits under
400
- * a `0` ceiling) while high-priority admission is still checked against
401
- * the full (shrunk) `currentBudget` and can keep admitting whatever
402
- * capacity remains. That is exactly the right degraded behavior — the
403
- * entire purpose of `highPriorityReserve` is protecting interactive
404
- * traffic when capacity is scarce, and capacity has never been scarcer
405
- * than when the grant itself drops below the reserve.
406
- */
407
- function effectiveBudget(priority) {
408
- if (!budget)
409
- return Infinity;
410
- return priority === "high"
411
- ? currentBudget
412
- : Math.max(0, currentBudget - currentHighPriorityReserve);
413
- }
414
- function protectedConcurrentTotal() {
415
- let total = 0;
416
- for (const state of admissionClassStates.values()) {
417
- total += state.protectedConcurrent;
418
- }
419
- return total;
420
- }
421
- function protectedTokensTotal() {
422
- let total = 0;
423
- for (const state of admissionClassStates.values()) {
424
- total += state.protectedInFlightTokens;
425
- }
426
- return total;
427
- }
428
- function protectedConcurrentInUse(state) {
429
- return Math.min(state.inFlight, state.protectedConcurrent);
430
- }
431
- function protectedTokensInUse(state) {
432
- return Math.min(state.inFlightTokens, state.protectedInFlightTokens);
433
- }
434
- function sharedConcurrentInUse() {
435
- let protectedInUse = 0;
436
- for (const state of admissionClassStates.values()) {
437
- protectedInUse += protectedConcurrentInUse(state);
438
- }
439
- return Math.max(0, bulkhead.stats().inFlight - protectedInUse);
440
- }
441
- function sharedTokensInUse() {
442
- let protectedInUse = 0;
443
- for (const state of admissionClassStates.values()) {
444
- protectedInUse += protectedTokensInUse(state);
445
- }
446
- return Math.max(0, inFlightTokens - protectedInUse);
447
- }
448
- function requestedBorrowedConcurrent(admissionClass) {
449
- if (admissionClass === undefined)
450
- return 0;
451
- return admissionClass.inFlight < admissionClass.protectedConcurrent ? 0 : 1;
452
- }
453
- function requestedBorrowedTokens(admissionClass, reserved) {
454
- if (admissionClass === undefined || reserved === 0)
455
- return 0;
456
- const protectedAvailable = Math.max(0, admissionClass.protectedInFlightTokens - admissionClass.inFlightTokens);
457
- return Math.max(0, reserved - protectedAvailable);
458
- }
459
- function checkAdmissionCapacity(reserved, priority, admissionClass, globalSlotHeld = false) {
460
- if (budget && inFlightTokens + reserved > effectiveBudget(priority)) {
461
- return { reason: "budget_limit", constraint: "global" };
462
- }
463
- if (admissionClass?.maxInFlightTokens !== undefined &&
464
- admissionClass.inFlightTokens + reserved >
465
- admissionClass.maxInFlightTokens) {
466
- return { reason: "budget_limit", constraint: "admission_class" };
467
- }
468
- if (admissionClass?.maxConcurrent !== undefined &&
469
- admissionClass.inFlight >= admissionClass.maxConcurrent) {
470
- return { reason: "concurrency_limit", constraint: "admission_class" };
471
- }
472
- if (admissionClass !== undefined) {
473
- const totalProtectedConcurrent = protectedConcurrentTotal();
474
- if (totalProtectedConcurrent > 0) {
475
- const sharedConcurrentCapacity = Math.max(0, bulkhead.stats().maxConcurrent - totalProtectedConcurrent);
476
- const globalInFlightBefore = Math.max(0, bulkhead.stats().inFlight - (globalSlotHeld ? 1 : 0));
477
- let protectedConcurrentUsed = 0;
478
- for (const state of admissionClassStates.values()) {
479
- protectedConcurrentUsed += protectedConcurrentInUse(state);
480
- }
481
- const sharedConcurrentBefore = Math.max(0, globalInFlightBefore - protectedConcurrentUsed);
482
- const borrowedConcurrentRequested = requestedBorrowedConcurrent(admissionClass);
483
- if (borrowedConcurrentRequested > 0 &&
484
- sharedConcurrentBefore + borrowedConcurrentRequested >
485
- sharedConcurrentCapacity) {
486
- return {
487
- reason: "concurrency_limit",
488
- constraint: "admission_class_protection",
489
- };
490
- }
491
- }
492
- const totalProtectedTokens = protectedTokensTotal();
493
- if (budget && totalProtectedTokens > 0) {
494
- const sharedTokenCapacity = Math.max(0, effectiveBudget(priority) - totalProtectedTokens);
495
- const borrowedTokensRequested = requestedBorrowedTokens(admissionClass, reserved);
496
- if (borrowedTokensRequested > 0 &&
497
- sharedTokensInUse() + borrowedTokensRequested >
498
- sharedTokenCapacity) {
499
- return {
500
- reason: "budget_limit",
501
- constraint: "admission_class_protection",
502
- };
503
- }
504
- }
505
- }
506
- return undefined;
507
- }
508
- /**
509
- * Atomically reserve every non-queue capacity layer after the global
510
- * concurrency slot is held. No counters are changed unless all checks pass.
511
- */
512
- function tryReserveCapacity(reserved, priority, admissionClass) {
513
- const failure = checkAdmissionCapacity(reserved, priority, admissionClass, true);
514
- if (failure !== undefined)
515
- return failure;
516
- if (budget) {
517
- inFlightTokens += reserved;
518
- totalReserved += reserved;
519
- }
520
- if (admissionClass !== undefined) {
521
- const borrowedConcurrent = requestedBorrowedConcurrent(admissionClass);
522
- const borrowedTokens = requestedBorrowedTokens(admissionClass, reserved);
523
- admissionClass.inFlight++;
524
- admissionClass.admitted++;
525
- admissionClass.totalBorrowedAdmissions += borrowedConcurrent;
526
- admissionClass.totalBorrowedTokensReserved += borrowedTokens;
527
- if (budget) {
528
- admissionClass.inFlightTokens += reserved;
529
- admissionClass.totalReserved += reserved;
530
- }
531
- }
532
- return undefined;
533
- }
534
- function releaseCapacity(held, usage, admissionClass) {
535
- let refunded = 0;
536
- if (usage && held > 0) {
537
- const actual = usage.input + usage.output;
538
- totalConsumed += actual;
539
- if (admissionClass !== undefined) {
540
- admissionClass.totalConsumed += actual;
541
- }
542
- if (actual < held) {
543
- refunded = held - actual;
544
- totalRefunded += refunded;
545
- if (admissionClass !== undefined) {
546
- admissionClass.totalRefunded += refunded;
547
- }
548
- }
549
- }
550
- inFlightTokens = Math.max(0, inFlightTokens - held);
551
- if (admissionClass !== undefined) {
552
- admissionClass.inFlightTokens = Math.max(0, admissionClass.inFlightTokens - held);
553
- admissionClass.inFlight = Math.max(0, admissionClass.inFlight - 1);
554
- admissionClass.released++;
555
- }
556
- return refunded;
557
- }
558
- /** Capacity snapshot for rejection results, events, and errors. */
559
- function buildRejectDetail(requested, priority, admissionClass, constraint) {
560
- const base = bulkhead.stats();
561
- const detail = {
562
- limitRevision: currentRevision,
563
- ...(admissionClass !== undefined && constraint !== undefined
564
- ? { constraint }
565
- : {}),
566
- inFlight: base.inFlight,
567
- pending: base.pending,
568
- maxConcurrent: base.maxConcurrent,
569
- maxQueue: base.maxQueue,
570
- };
571
- if (budget) {
572
- const eff = effectiveBudget(priority);
573
- detail.tokenBudget = {
574
- budget: currentBudget,
575
- inFlightTokens,
576
- effectiveBudget: eff,
577
- available: Math.max(0, eff - inFlightTokens),
578
- requested,
579
- };
580
- }
581
- if (admissionClass !== undefined) {
582
- const classProtectedConcurrentInUse = protectedConcurrentInUse(admissionClass);
583
- const classProtectedTokensInUse = protectedTokensInUse(admissionClass);
584
- const sharedConcurrentCapacity = Math.max(0, base.maxConcurrent - protectedConcurrentTotal());
585
- const sharedConcurrentUsed = sharedConcurrentInUse();
586
- detail.sharedCapacity = {
587
- concurrency: {
588
- capacity: sharedConcurrentCapacity,
589
- inUse: sharedConcurrentUsed,
590
- available: Math.max(0, sharedConcurrentCapacity - sharedConcurrentUsed),
591
- requestedBorrowed: requestedBorrowedConcurrent(admissionClass),
592
- },
593
- ...(budget
594
- ? {
595
- tokenBudget: {
596
- capacity: Math.max(0, effectiveBudget(priority) - protectedTokensTotal()),
597
- inUse: sharedTokensInUse(),
598
- available: Math.max(0, Math.max(0, effectiveBudget(priority) - protectedTokensTotal()) - sharedTokensInUse()),
599
- requestedBorrowed: requestedBorrowedTokens(admissionClass, requested),
600
- },
601
- }
602
- : {}),
603
- };
604
- detail.admissionClass = {
605
- id: admissionClass.id,
606
- inFlight: admissionClass.inFlight,
607
- protectedConcurrent: admissionClass.protectedConcurrent,
608
- protectedConcurrentInUse: classProtectedConcurrentInUse,
609
- borrowedConcurrent: Math.max(0, admissionClass.inFlight - classProtectedConcurrentInUse),
610
- availableProtectedConcurrent: Math.max(0, admissionClass.protectedConcurrent - admissionClass.inFlight),
611
- maxConcurrent: admissionClass.maxConcurrent ?? null,
612
- availableConcurrent: admissionClass.maxConcurrent === undefined
613
- ? null
614
- : Math.max(0, admissionClass.maxConcurrent - admissionClass.inFlight),
615
- ...(budget
616
- ? {
617
- tokenBudget: {
618
- inFlightTokens: admissionClass.inFlightTokens,
619
- protectedInFlightTokens: admissionClass.protectedInFlightTokens,
620
- protectedTokensInUse: classProtectedTokensInUse,
621
- borrowedInFlightTokens: Math.max(0, admissionClass.inFlightTokens - classProtectedTokensInUse),
622
- availableProtectedTokens: Math.max(0, admissionClass.protectedInFlightTokens -
623
- admissionClass.inFlightTokens),
624
- maxInFlightTokens: admissionClass.maxInFlightTokens ?? null,
625
- available: admissionClass.maxInFlightTokens === undefined
626
- ? null
627
- : Math.max(0, admissionClass.maxInFlightTokens -
628
- admissionClass.inFlightTokens),
629
- requested,
630
- },
631
- }
632
- : {}),
633
- };
634
- }
635
- return detail;
636
- }
637
- function wouldAdmitResolved(admission, includeDetail) {
638
- const { priority, admissionClass, reserved } = admission;
639
- const withDetail = (result, constraint) => {
640
- if (includeDetail) {
641
- result.detail = buildRejectDetail(reserved, priority, admissionClass, constraint);
642
- }
643
- return result;
644
- };
645
- const base = bulkhead.stats();
646
- if (base.closed) {
647
- return withDetail({ admit: false, reason: "shutdown" });
648
- }
649
- const capacityFailure = checkAdmissionCapacity(reserved, priority, admissionClass);
650
- if (capacityFailure !== undefined) {
651
- return withDetail({ admit: false, reason: capacityFailure.reason }, capacityFailure.constraint);
652
- }
653
- if (base.inFlight < base.maxConcurrent) {
654
- return withDetail({ admit: true });
655
- }
656
- if (base.maxConcurrent === 0) {
657
- return withDetail({ admit: false, reason: "concurrency_limit" }, "global");
658
- }
659
- if (base.pending < base.maxQueue) {
660
- return withDetail({ admit: true });
661
- }
662
- return withDetail({
663
- admit: false,
664
- reason: base.maxQueue > 0 ? "queue_limit" : "concurrency_limit",
665
- }, "global");
666
- }
667
- /** Return a detached snapshot of the currently applied limits. */
668
- function limits() {
669
- const base = bulkhead.stats();
670
- const classLimits = admissionClassLimitsSnapshot();
671
- const snapshot = {
672
- revision: currentRevision,
673
- maxConcurrent: base.maxConcurrent,
674
- maxQueue: base.maxQueue,
675
- ...(budget
676
- ? {
677
- tokenBudget: {
678
- budget: currentBudget,
679
- highPriorityReserve: currentHighPriorityReserve,
680
- },
681
- }
682
- : {}),
683
- ...(classLimits !== undefined
684
- ? { admissionClasses: classLimits }
685
- : {}),
686
- };
687
- return Object.freeze({
688
- ...snapshot,
689
- ...(snapshot.tokenBudget
690
- ? { tokenBudget: Object.freeze({ ...snapshot.tokenBudget }) }
691
- : {}),
692
- ...(snapshot.admissionClasses
693
- ? { admissionClasses: snapshot.admissionClasses }
694
- : {}),
695
- });
696
- }
697
- /**
698
- * Atomically apply a complete, higher-revision admission-limit snapshot.
699
- *
700
- * All fields are validated before any state changes. Equal or lower
701
- * revisions are rejected as stale without mutation. Lower concurrency,
702
- * queue, or token ceilings use shrink-by-attrition: in-flight work and
703
- * already accepted waiters are not cancelled. Raising concurrency pumps
704
- * accepted waiters immediately after the complete snapshot is installed.
705
- */
706
- function applyLimits(next) {
707
- // Read each externally supplied property once. This prevents accessor
708
- // objects from returning one value during validation and another during
709
- // installation.
710
- const revision = next.revision;
711
- const maxConcurrent = next.maxConcurrent;
712
- const maxQueue = next.maxQueue;
713
- const nextTokenBudget = next.tokenBudget;
714
- const nextAdmissionClasses = next.admissionClasses;
715
- if (!Number.isSafeInteger(revision) || revision < 0) {
716
- throw new Error("limits.revision must be a non-negative safe integer");
717
- }
718
- if (revision <= currentRevision) {
719
- return {
720
- applied: false,
721
- reason: "stale_revision",
722
- current: limits(),
723
- };
724
- }
725
- assertNonNegativeInteger(maxConcurrent, "limits.maxConcurrent");
726
- assertNonNegativeInteger(maxQueue, "limits.maxQueue");
727
- let nextBudget;
728
- let nextHighPriorityReserve;
729
- if (budget) {
730
- if (nextTokenBudget === undefined) {
731
- throw new Error("limits.tokenBudget is required because tokenBudget was configured at construction");
732
- }
733
- nextBudget = nextTokenBudget.budget;
734
- nextHighPriorityReserve = nextTokenBudget.highPriorityReserve;
735
- assertNonNegativeInteger(nextBudget, "limits.tokenBudget.budget");
736
- assertNonNegativeInteger(nextHighPriorityReserve, "limits.tokenBudget.highPriorityReserve");
737
- }
738
- else if (nextTokenBudget !== undefined) {
739
- throw new Error("limits.tokenBudget must be omitted because tokenBudget was not configured at construction");
740
- }
741
- let preparedAdmissionClassLimits;
742
- if (defaultAdmissionClass !== undefined) {
743
- if (nextAdmissionClasses === undefined) {
744
- throw new Error("limits.admissionClasses is required because admissionClasses was configured at construction");
745
- }
746
- if (typeof nextAdmissionClasses !== "object" ||
747
- nextAdmissionClasses === null ||
748
- Array.isArray(nextAdmissionClasses)) {
749
- throw new Error("limits.admissionClasses must be an object");
750
- }
751
- const suppliedKeys = Object.keys(nextAdmissionClasses);
752
- if (suppliedKeys.length !== admissionClassStates.size) {
753
- throw new Error("limits.admissionClasses must contain exactly the construction-time class keys");
754
- }
755
- preparedAdmissionClassLimits = new Map();
756
- for (const id of admissionClassStates.keys()) {
757
- if (!Object.prototype.hasOwnProperty.call(nextAdmissionClasses, id)) {
758
- throw new Error("limits.admissionClasses must contain exactly the construction-time class keys");
759
- }
760
- preparedAdmissionClassLimits.set(id, readAdmissionClassLimits(nextAdmissionClasses[id], `limits.admissionClasses[${JSON.stringify(id)}]`, budget !== undefined));
761
- }
762
- }
763
- else if (nextAdmissionClasses !== undefined) {
764
- throw new Error("limits.admissionClasses must be omitted because admissionClasses was not configured at construction");
765
- }
766
- if (preparedAdmissionClassLimits !== undefined) {
767
- validateProtectedCapacity(preparedAdmissionClassLimits.values(), maxConcurrent, nextBudget, "limits.admissionClasses");
768
- }
769
- const previous = limits();
770
- // Install every LLM-layer value before pumping the concurrency queue.
771
- // Promise continuations from admitted waiters run only after this
772
- // synchronous operation returns, so they observe one coherent revision.
773
- currentRevision = revision;
774
- if (budget) {
775
- currentBudget = nextBudget;
776
- currentHighPriorityReserve = nextHighPriorityReserve;
777
- }
778
- if (preparedAdmissionClassLimits !== undefined) {
779
- for (const [id, nextLimits] of preparedAdmissionClassLimits) {
780
- const state = admissionClassStates.get(id);
781
- state.protectedConcurrent = nextLimits.protectedConcurrent ?? 0;
782
- state.maxConcurrent = nextLimits.maxConcurrent;
783
- state.protectedInFlightTokens =
784
- nextLimits.protectedInFlightTokens ?? 0;
785
- state.maxInFlightTokens = nextLimits.maxInFlightTokens;
786
- }
787
- }
788
- bulkhead.applyLimits({ maxConcurrent, maxQueue });
789
- const current = limits();
790
- emit("reconfigure", { previous, current });
791
- return { applied: true, previous, current };
96
+ return reservations.estimate(request);
792
97
  }
793
98
  /**
794
- * Backward-compatible budget-only setter.
99
+ * Acquire a slot manually.
795
100
  *
796
- * This is implemented as a complete local reconfiguration at
797
- * `currentRevision + 1`. Externally managed deployments should use
798
- * `applyLimits()` exclusively so one authority owns the revision stream.
101
+ * The returned token accepts optional `TokenUsage` at release time
102
+ * to trigger the refund mechanism. For most use cases, prefer `run()`.
799
103
  */
800
- function setBudget(tokens) {
801
- if (!budget) {
802
- throw new Error("setBudget requires tokenBudget to be configured at construction");
803
- }
804
- assertNonNegativeInteger(tokens, "tokens");
805
- if (currentRevision >= Number.MAX_SAFE_INTEGER) {
806
- throw new Error("cannot advance admission-limit revision beyond MAX_SAFE_INTEGER");
807
- }
808
- const current = limits();
809
- applyLimits({
810
- revision: currentRevision + 1,
811
- maxConcurrent: current.maxConcurrent,
812
- maxQueue: current.maxQueue,
813
- tokenBudget: {
814
- budget: tokens,
815
- highPriorityReserve: currentHighPriorityReserve,
816
- },
817
- ...(current.admissionClasses !== undefined
818
- ? { admissionClasses: current.admissionClasses }
819
- : {}),
820
- });
821
- }
822
- function normalizeAcquireOptions(ao) {
823
- const normalized = {};
824
- if (ao.signal !== undefined)
825
- normalized.signal = ao.signal;
826
- const effectiveTimeoutMs = ao.timeoutMs ?? timeoutMs;
827
- if (effectiveTimeoutMs !== undefined) {
828
- assertNonNegativeInteger(effectiveTimeoutMs, "timeoutMs");
829
- normalized.timeoutMs = effectiveTimeoutMs;
830
- }
831
- return normalized;
832
- }
833
- function noteDedupWaitRejection(request, reason, admissionClass) {
834
- noteLLMReject(reason);
835
- noteAdmissionClassReject(admissionClass, reason);
836
- emit("reject", {
837
- request,
838
- reason,
839
- limitRevision: currentRevision,
840
- ...(admissionClass !== undefined
841
- ? { admissionClass: admissionClass.id }
842
- : {}),
843
- });
844
- const error = new LLMBulkheadRejectedError(reason);
845
- dedupWaitErrors.add(error);
846
- return error;
104
+ async function acquire(request, ao = {}) {
105
+ return admit(request, ao);
847
106
  }
848
107
  /**
849
- * Deliver a shared in-flight result to a deduplication follower.
850
- *
851
- * - With a `shareResult` hook: the hook decides what the follower
852
- * receives (called for every follower, safe results included).
853
- * Hook exceptions propagate to the follower as-is.
854
- * - Without a hook: single-consumer values (streams, `Response`
855
- * bodies, async iterables) are refused with
856
- * `"unshareable_result"` instead of being handed out by
857
- * reference — a locked stream downstream is a silent correctness
858
- * bug; a typed rejection at the bulkhead is actionable.
108
+ * Primary API. Acquire → call `fn` → release, automatically.
859
109
  *
860
- * The leader never passes through this function.
861
- */
862
- function deliverShared(value, request, admissionClass) {
863
- if (dedup.shareResult) {
864
- return dedup.shareResult(value);
865
- }
866
- if (isUnsafeToShare(value)) {
867
- throw noteDedupWaitRejection(request, "unshareable_result", admissionClass);
868
- }
869
- return value;
870
- }
871
- /**
872
- * Wait on another caller's in-flight shared call.
110
+ * Throws `LLMBulkheadRejectedError` on rejection.
873
111
  *
874
- * v3.4: only an *explicitly passed* per-call `timeoutMs` caps this
875
- * wait. The bulkhead-level `timeoutMs` default is deliberately NOT
876
- * applied here — it is documented as a *queue-wait* timeout, and a
877
- * follower is not queued; it is waiting on a call that is already
878
- * running. Applying the default (e.g. the `batch` profile's 30s) made
879
- * every follower of a slow LLM call fail with `"timeout"` while the
880
- * leader succeeded, defeating deduplication exactly when calls are
881
- * long. `signal` continues to apply as before.
882
- */
883
- function waitForSharedDedup(shared, request, ao, admissionClass) {
884
- const signal = ao.signal;
885
- const effectiveTimeoutMs = ao.timeoutMs;
886
- if (effectiveTimeoutMs !== undefined) {
887
- assertNonNegativeInteger(effectiveTimeoutMs, "timeoutMs");
888
- }
889
- if (signal?.aborted) {
890
- return Promise.reject(noteDedupWaitRejection(request, "aborted", admissionClass));
891
- }
892
- if (signal === undefined && effectiveTimeoutMs === undefined) {
893
- return shared.then((value) => deliverShared(value, request, admissionClass));
894
- }
895
- return new Promise((resolve, reject) => {
896
- let timeoutId;
897
- let settled = false;
898
- const cleanup = () => {
899
- if (timeoutId !== undefined)
900
- clearTimeout(timeoutId);
901
- if (signal !== undefined) {
902
- signal.removeEventListener("abort", onAbort);
903
- }
904
- };
905
- const settle = (fn) => {
906
- if (settled)
907
- return;
908
- settled = true;
909
- cleanup();
910
- fn();
911
- };
912
- const onAbort = () => {
913
- settle(() => {
914
- reject(noteDedupWaitRejection(request, "aborted", admissionClass));
915
- });
916
- };
917
- if (signal !== undefined) {
918
- signal.addEventListener("abort", onAbort, { once: true });
919
- }
920
- if (effectiveTimeoutMs !== undefined) {
921
- timeoutId = setTimeout(() => {
922
- settle(() => {
923
- reject(noteDedupWaitRejection(request, "timeout", admissionClass));
924
- });
925
- }, effectiveTimeoutMs);
926
- }
927
- void shared.then((value) => settle(() => {
928
- try {
929
- resolve(deliverShared(value, request, admissionClass));
930
- }
931
- catch (err) {
932
- reject(err);
933
- }
934
- }), (err) => settle(() => reject(err)));
935
- });
936
- }
937
- /**
938
- * Wraps a base Token so that release() also returns the token
939
- * reservation and optionally applies the refund, and so that
940
- * streaming callers can report cumulative usage mid-flight.
941
- */
942
- function wrapToken(base, parts, request, admissionId, limitRevision, priority, admissionClass) {
943
- let released = false;
944
- /** Tokens currently held against the budget for this request. */
945
- let held = parts?.reserved ?? 0;
946
- /** Last reported cumulative usage (monotonically clamped). */
947
- let reported;
948
- /** Monotonic sequence of effective pre-release usage updates. */
949
- let usageSequence = 0;
950
- /** Public copy: callers cannot mutate internal accounting parts. */
951
- const reservation = parts === null ? null : Object.freeze({ ...parts });
952
- const snapshot = () => {
953
- const consumed = reported
954
- ? reported.input + reported.output
955
- : 0;
956
- const outputCap = parts ? parts.maxOutput : null;
957
- return {
958
- admissionId,
959
- limitRevision,
960
- ...(admissionClass !== undefined
961
- ? { admissionClass: admissionClass.id }
962
- : {}),
963
- sequence: usageSequence,
964
- reserved: parts?.reserved ?? 0,
965
- held,
966
- consumed,
967
- outputCap,
968
- outputRemaining: outputCap === null
969
- ? null
970
- : Math.max(0, outputCap - (reported?.output ?? 0)),
971
- overReservation: parts ? consumed > parts.reserved : false,
972
- };
973
- };
974
- const reportUsage = (usage, reconciliation) => {
975
- const valid = validateTokenUsage(usage);
976
- if (reconciliation !== undefined) {
977
- assertNonNegativeInteger(reconciliation.remainingOutputTokens, "progressive reconciliation remainingOutputTokens");
978
- assertOptionalNonNegativeInteger(reconciliation.safetyMarginTokens, "progressive reconciliation safetyMarginTokens");
979
- if (parts !== null &&
980
- reconciliation.remainingOutputTokens > parts.maxOutput) {
981
- throw new RangeError("progressive reconciliation remainingOutputTokens must not exceed the reserved output cap");
982
- }
983
- }
984
- const previousReported = reported;
985
- // Clamp to monotonic non-decreasing per field — cumulative
986
- // stream usage never shrinks; a lower report is stale.
987
- reported = previousReported
988
- ? {
989
- input: Math.max(previousReported.input, valid.input),
990
- output: Math.max(previousReported.output, valid.output),
991
- }
992
- : valid;
993
- const usageChanged = previousReported === undefined ||
994
- reported.input !== previousReported.input ||
995
- reported.output !== previousReported.output;
996
- const previousHeldTokens = held;
997
- // Accounting only applies pre-release with a budget configured.
998
- if (!released && parts && budget) {
999
- // Legacy mode holds known input plus the full output reservation.
1000
- // Progressive mode is opt-in and may be used only after prefill is
1001
- // known complete: it holds the caller-declared future output plus an
1002
- // explicit safety margin. Output beyond the configured cap is added
1003
- // back as overrun protection.
1004
- const outputOverrun = Math.max(0, reported.output - parts.maxOutput);
1005
- const newHold = reconciliation === undefined
1006
- ? reported.input + Math.max(parts.maxOutput, reported.output)
1007
- : reconciliation.remainingOutputTokens +
1008
- (reconciliation.safetyMarginTokens ?? 0) +
1009
- outputOverrun;
1010
- const delta = newHold - held;
1011
- if (delta > 0) {
1012
- inFlightTokens += delta;
1013
- totalOverrun += delta;
1014
- if (admissionClass !== undefined) {
1015
- admissionClass.inFlightTokens += delta;
1016
- admissionClass.totalOverrun += delta;
1017
- }
1018
- }
1019
- else if (delta < 0) {
1020
- const refund = -delta;
1021
- inFlightTokens = Math.max(0, inFlightTokens - refund);
1022
- totalRefunded += refund;
1023
- if (admissionClass !== undefined) {
1024
- admissionClass.inFlightTokens = Math.max(0, admissionClass.inFlightTokens - refund);
1025
- admissionClass.totalRefunded += refund;
1026
- }
1027
- }
1028
- held = newHold;
1029
- }
1030
- const holdChanged = held !== previousHeldTokens;
1031
- if (!released && (usageChanged || holdChanged)) {
1032
- usageSequence++;
1033
- }
1034
- const report = snapshot();
1035
- if (!released && (usageChanged || holdChanged)) {
1036
- emit("usage", {
1037
- request,
1038
- admissionId,
1039
- limitRevision,
1040
- priority,
1041
- ...(admissionClass !== undefined
1042
- ? { admissionClass: admissionClass.id }
1043
- : {}),
1044
- sequence: usageSequence,
1045
- reservedTokens: parts?.reserved ?? 0,
1046
- previousHeldTokens,
1047
- heldTokens: held,
1048
- deltaTokens: held - previousHeldTokens,
1049
- usage: { ...reported },
1050
- outputCap: report.outputCap,
1051
- outputRemaining: report.outputRemaining,
1052
- overReservation: report.overReservation,
1053
- ...(reconciliation === undefined
1054
- ? {}
1055
- : {
1056
- progressive: true,
1057
- remainingOutputTokens: reconciliation.remainingOutputTokens,
1058
- safetyMarginTokens: reconciliation.safetyMarginTokens ?? 0,
1059
- }),
1060
- });
1061
- }
1062
- return report;
1063
- };
1064
- return {
1065
- admissionId,
1066
- limitRevision,
1067
- ...(admissionClass !== undefined
1068
- ? { admissionClass: admissionClass.id }
1069
- : {}),
1070
- reservation,
1071
- reportUsage,
1072
- release(usage) {
1073
- if (released)
1074
- return;
1075
- released = true;
1076
- let validUsage;
1077
- let usageError;
1078
- if (usage !== undefined) {
1079
- try {
1080
- validUsage = validateTokenUsage(usage);
1081
- }
1082
- catch (err) {
1083
- usageError = err;
1084
- }
1085
- }
1086
- // Fall back to the last mid-flight report when no (valid)
1087
- // explicit usage is provided at release.
1088
- if (validUsage === undefined && reported !== undefined) {
1089
- validUsage = reported;
1090
- }
1091
- try {
1092
- base.release();
1093
- }
1094
- finally {
1095
- // Zero `held` before returning tokens: nothing is held against
1096
- // the budget after release, and post-release `reportUsage()`
1097
- // snapshots must reflect that (previously they reported the
1098
- // stale pre-release hold).
1099
- const heldAtRelease = held;
1100
- held = 0;
1101
- const refunded = releaseCapacity(heldAtRelease, validUsage, admissionClass);
1102
- noteLLMRelease();
1103
- emit("release", {
1104
- request,
1105
- admissionId,
1106
- limitRevision,
1107
- priority,
1108
- ...(admissionClass !== undefined
1109
- ? { admissionClass: admissionClass.id }
1110
- : {}),
1111
- reservedTokens: parts?.reserved ?? 0,
1112
- heldTokens: heldAtRelease,
1113
- refundedTokens: refunded,
1114
- usageSequence,
1115
- ...(validUsage !== undefined && { usage: validUsage }),
1116
- });
1117
- }
1118
- if (usageError !== undefined)
1119
- throw usageError;
1120
- },
1121
- };
1122
- }
1123
- // ---- Internal acquire ----
1124
- async function _acquire(request, ao, resolved = resolveAdmission(request, ao), untimedRejectReasons) {
1125
- const { priority, admissionClass, parts, reserved } = resolved;
1126
- // Admission timing deliberately separates synchronous decision work from
1127
- // the awaited concurrency acquire. Exact accounting requires four
1128
- // monotonic clock reads on paths that reach the acquire: decision start,
1129
- // wait start, wait end, and decision end. Precheck rejects use two reads.
1130
- const decisionStartedNs = process.hrtime.bigint();
1131
- let waitStartedNs = 0n;
1132
- let waitEndedNs = 0n;
1133
- let queueWaitNs = 0;
1134
- const rejectWith = (reason, constraint, precheckDecisionDurationNs) => {
1135
- const detail = buildRejectDetail(reserved, priority, admissionClass, constraint);
1136
- const includeTiming = untimedRejectReasons === undefined ||
1137
- !untimedRejectReasons.has(reason);
1138
- const decisionDurationNs = includeTiming
1139
- ? precheckDecisionDurationNs ??
1140
- Number(waitStartedNs -
1141
- decisionStartedNs +
1142
- (process.hrtime.bigint() - waitEndedNs))
1143
- : undefined;
1144
- noteLLMReject(reason);
1145
- noteAdmissionClassReject(admissionClass, reason);
1146
- const event = {
1147
- request,
1148
- reason,
1149
- limitRevision: detail.limitRevision,
1150
- detail,
1151
- ...(admissionClass !== undefined
1152
- ? { admissionClass: admissionClass.id }
1153
- : {}),
1154
- };
1155
- if (decisionDurationNs !== undefined) {
1156
- event.decisionDurationNs = decisionDurationNs;
1157
- event.queueWaitNs = queueWaitNs;
1158
- }
1159
- emit("reject", event);
1160
- return { ok: false, reason, detail };
1161
- };
1162
- // Every class ceiling is fail-fast and checked before entering the global
1163
- // queue. A second atomic check runs after the global slot is acquired.
1164
- const precheck = checkAdmissionCapacity(reserved, priority, admissionClass);
1165
- if (precheck !== undefined) {
1166
- const includeTiming = untimedRejectReasons === undefined ||
1167
- !untimedRejectReasons.has(precheck.reason);
1168
- const precheckDecisionDurationNs = includeTiming
1169
- ? Number(process.hrtime.bigint() - decisionStartedNs)
1170
- : undefined;
1171
- return rejectWith(precheck.reason, precheck.constraint, precheckDecisionDurationNs);
1172
- }
1173
- const mergedOptions = normalizeAcquireOptions(ao);
1174
- waitStartedNs = process.hrtime.bigint();
1175
- const r = await bulkhead.acquire(mergedOptions);
1176
- waitEndedNs = process.hrtime.bigint();
1177
- queueWaitNs = Number(waitEndedNs - waitStartedNs);
1178
- if (!r.ok) {
1179
- const constraint = r.reason === "concurrency_limit" ||
1180
- r.reason === "queue_limit" ||
1181
- r.reason === "timeout"
1182
- ? "global"
1183
- : undefined;
1184
- return rejectWith(r.reason, constraint);
1185
- }
1186
- // Post-admission: atomically reserve global token and class capacity.
1187
- const postcheck = tryReserveCapacity(reserved, priority, admissionClass);
1188
- if (postcheck !== undefined) {
1189
- r.token.release();
1190
- return rejectWith(postcheck.reason, postcheck.constraint);
1191
- }
1192
- // Capture the revision at the admission linearization point: both the
1193
- // concurrency slot and token reservation are held, and no listener or
1194
- // callback has run yet. Later reconfiguration must not rewrite the
1195
- // provenance of this admitted work.
1196
- const limitRevision = currentRevision;
1197
- const admissionId = randomUUID();
1198
- const token = wrapToken(r.token, parts, request, admissionId, limitRevision, priority, admissionClass);
1199
- const decisionDurationNs = Number(waitStartedNs -
1200
- decisionStartedNs +
1201
- (process.hrtime.bigint() - waitEndedNs));
1202
- noteLLMAdmit();
1203
- emit("admit", {
1204
- request,
1205
- admissionId,
1206
- limitRevision,
1207
- priority,
1208
- ...(admissionClass !== undefined
1209
- ? { admissionClass: admissionClass.id }
1210
- : {}),
1211
- reservedTokens: reserved,
1212
- decisionDurationNs,
1213
- queueWaitNs,
1214
- });
1215
- return {
1216
- ok: true,
1217
- admissionId,
1218
- limitRevision,
1219
- ...(admissionClass !== undefined
1220
- ? { admissionClass: admissionClass.id }
1221
- : {}),
1222
- reservation: token.reservation,
1223
- token,
1224
- };
1225
- }
1226
- // ---- Public API ----
1227
- /**
1228
- * Acquire a slot manually.
112
+ * When `getUsage` is provided in options, it is called with the result
113
+ * of `fn` to extract actual token usage. The refund mechanism then
114
+ * returns the difference between the reservation and actual consumption
115
+ * to the budget.
1229
116
  *
1230
- * The returned token accepts optional `TokenUsage` at release time
1231
- * to trigger the refund mechanism. For most use cases, prefer `run()`.
117
+ * Deduplication (when enabled) applies to `run()` only; `acquire()`
118
+ * never deduplicates. A caller that joins an existing in-flight call
119
+ * is capped only by its own `signal` and an *explicitly passed*
120
+ * per-call `timeoutMs` — the bulkhead-level `timeoutMs` (a queue-wait
121
+ * timeout) does not apply to that wait.
1232
122
  */
1233
- async function acquire(request, ao = {}) {
1234
- return _acquire(request, ao);
1235
- }
123
+ const run = createRun({
124
+ limits: admissionLimits,
125
+ dedup,
126
+ resolveAdmission,
127
+ wouldAdmitResolved,
128
+ acquire: admit,
129
+ runBypassed,
130
+ });
1236
131
  /**
1237
132
  * Advisory dry-run: would a request of this shape be admitted right
1238
133
  * now at the given priority?
@@ -1261,449 +156,35 @@ export function createLLMBulkhead(opts) {
1261
156
  function wouldAdmit(request, opts = {}) {
1262
157
  return wouldAdmitResolved(resolveAdmission(request, opts), opts.detail === true);
1263
158
  }
1264
- function shouldBypass(reason, configured) {
1265
- return (SHADOWABLE_REASONS.has(reason) &&
1266
- configured.has(reason));
159
+ /** Runtime stats. Optional fields are present only when the feature is enabled. */
160
+ function stats() {
161
+ return readStats();
1267
162
  }
1268
- async function runBypassed(request, fn, opts, admission, reason, detail, limitRevision, raced) {
1269
- const hardReason = opts.signal?.aborted
1270
- ? "aborted"
1271
- : bulkhead.stats().closed
1272
- ? "shutdown"
1273
- : undefined;
1274
- if (hardReason !== undefined) {
1275
- const hardDetail = buildRejectDetail(admission.reserved, admission.priority, admission.admissionClass);
1276
- noteLLMReject(hardReason);
1277
- noteAdmissionClassReject(admission.admissionClass, hardReason);
1278
- emit("reject", {
1279
- request,
1280
- reason: hardReason,
1281
- limitRevision: hardDetail.limitRevision,
1282
- detail: hardDetail,
1283
- ...(admission.admissionClass !== undefined
1284
- ? { admissionClass: admission.admissionClass.id }
1285
- : {}),
1286
- });
1287
- throw new LLMBulkheadRejectedError(hardReason, hardDetail);
1288
- }
1289
- const admissionId = `shadow-${randomUUID()}`;
1290
- const reservation = admission.parts === null
1291
- ? null
1292
- : Object.freeze({ ...admission.parts });
1293
- let reported;
1294
- let usageSequence = 0;
1295
- let settled = false;
1296
- observeBypassed++;
1297
- if (raced)
1298
- observeRaceBypassed++;
1299
- observeBypassedByReason[reason] =
1300
- (observeBypassedByReason[reason] ?? 0) + 1;
1301
- emit("bypass", {
1302
- request,
1303
- admissionId,
1304
- limitRevision,
1305
- priority: admission.priority,
1306
- ...(admission.admissionClass !== undefined
1307
- ? { admissionClass: admission.admissionClass.id }
1308
- : {}),
1309
- reason,
1310
- ...(detail !== undefined && { detail }),
1311
- reservation,
1312
- raced,
1313
- });
1314
- const snapshot = () => {
1315
- const consumed = reported ? reported.input + reported.output : 0;
1316
- const outputCap = admission.parts?.maxOutput ?? null;
1317
- return {
1318
- admissionId,
1319
- limitRevision,
1320
- ...(admission.admissionClass !== undefined
1321
- ? { admissionClass: admission.admissionClass.id }
1322
- : {}),
1323
- sequence: usageSequence,
1324
- reserved: admission.reserved,
1325
- held: 0,
1326
- consumed,
1327
- outputCap,
1328
- outputRemaining: outputCap === null
1329
- ? null
1330
- : Math.max(0, outputCap - (reported?.output ?? 0)),
1331
- overReservation: admission.parts !== null && consumed > admission.parts.reserved,
1332
- };
1333
- };
1334
- const reportUsage = (usage, reconciliation) => {
1335
- const valid = validateTokenUsage(usage);
1336
- if (reconciliation !== undefined) {
1337
- assertNonNegativeInteger(reconciliation.remainingOutputTokens, "progressive reconciliation remainingOutputTokens");
1338
- assertOptionalNonNegativeInteger(reconciliation.safetyMarginTokens, "progressive reconciliation safetyMarginTokens");
1339
- if (admission.parts !== null &&
1340
- reconciliation.remainingOutputTokens > admission.parts.maxOutput) {
1341
- throw new RangeError("progressive reconciliation remainingOutputTokens must not exceed the reserved output cap");
1342
- }
1343
- }
1344
- const previous = reported;
1345
- reported = previous
1346
- ? {
1347
- input: Math.max(previous.input, valid.input),
1348
- output: Math.max(previous.output, valid.output),
1349
- }
1350
- : valid;
1351
- const changed = previous === undefined ||
1352
- reported.input !== previous.input ||
1353
- reported.output !== previous.output;
1354
- if (!settled && changed) {
1355
- usageSequence++;
1356
- const current = snapshot();
1357
- emit("bypassUsage", {
1358
- request,
1359
- admissionId,
1360
- limitRevision,
1361
- priority: admission.priority,
1362
- ...(admission.admissionClass !== undefined
1363
- ? { admissionClass: admission.admissionClass.id }
1364
- : {}),
1365
- reason,
1366
- sequence: usageSequence,
1367
- reservation,
1368
- usage: { ...reported },
1369
- outputCap: current.outputCap,
1370
- outputRemaining: current.outputRemaining,
1371
- overReservation: current.overReservation,
1372
- ...(reconciliation === undefined
1373
- ? {}
1374
- : {
1375
- progressive: true,
1376
- remainingOutputTokens: reconciliation.remainingOutputTokens,
1377
- safetyMarginTokens: reconciliation.safetyMarginTokens ?? 0,
1378
- }),
1379
- });
1380
- }
1381
- return snapshot();
1382
- };
1383
- const context = {
1384
- admissionId,
1385
- limitRevision,
1386
- ...(admission.admissionClass !== undefined
1387
- ? { admissionClass: admission.admissionClass.id }
1388
- : {}),
1389
- reservation,
1390
- admission: "bypassed",
1391
- bypassReason: reason,
1392
- ...(detail !== undefined && { bypassDetail: detail }),
1393
- reportUsage,
1394
- };
1395
- const finish = (usage) => {
1396
- if (settled)
1397
- return;
1398
- settled = true;
1399
- if (usage !== undefined) {
1400
- observeUsageReported++;
1401
- observeTotalInputTokens += usage.input;
1402
- observeTotalOutputTokens += usage.output;
1403
- }
1404
- emit("bypassRelease", {
1405
- request,
1406
- admissionId,
1407
- limitRevision,
1408
- priority: admission.priority,
1409
- ...(admission.admissionClass !== undefined
1410
- ? { admissionClass: admission.admissionClass.id }
1411
- : {}),
1412
- reason,
1413
- reservation,
1414
- usageSequence,
1415
- ...(usage !== undefined && { usage }),
1416
- });
1417
- };
1418
- try {
1419
- const result = await fn(opts.signal, context);
1420
- let finalUsage;
1421
- if (opts.getUsage !== undefined) {
1422
- try {
1423
- const extracted = opts.getUsage(result);
1424
- finalUsage =
1425
- extracted === undefined ? undefined : validateTokenUsage(extracted);
1426
- }
1427
- catch {
1428
- // A bad extractor must not turn observed work into a failure.
1429
- }
1430
- }
1431
- finish(finalUsage ?? reported);
1432
- return result;
1433
- }
1434
- catch (error) {
1435
- finish(reported);
1436
- throw error;
1437
- }
163
+ /** Return a detached snapshot of the currently applied limits. */
164
+ function limits() {
165
+ return admissionLimits.snapshot();
1438
166
  }
1439
167
  /**
1440
- * Primary API. Acquire → call `fn` → release, automatically.
1441
- *
1442
- * Throws `LLMBulkheadRejectedError` on rejection.
1443
- *
1444
- * When `getUsage` is provided in options, it is called with the result
1445
- * of `fn` to extract actual token usage. The refund mechanism then
1446
- * returns the difference between the reservation and actual consumption
1447
- * to the budget.
168
+ * Atomically apply a complete, higher-revision admission-limit snapshot.
1448
169
  *
1449
- * Deduplication (when enabled) applies to `run()` only; `acquire()`
1450
- * never deduplicates. A caller that joins an existing in-flight call
1451
- * is capped only by its own `signal` and an *explicitly passed*
1452
- * per-call `timeoutMs` — the bulkhead-level `timeoutMs` (a queue-wait
1453
- * timeout) does not apply to that wait.
170
+ * All fields are validated before any state changes. Equal or lower
171
+ * revisions are rejected as stale without mutation. Lower concurrency,
172
+ * queue, or token ceilings use shrink-by-attrition: in-flight work and
173
+ * already accepted waiters are not canceled. Raising concurrency pumps
174
+ * accepted waiters immediately after the complete snapshot is installed.
1454
175
  */
1455
- async function run(request, fn, ao = {}) {
1456
- const { getUsage, mode: requestedMode, shadowReasons: requestedShadowReasons, dedupScope, dedup: perCallDedup, ...acquireOpts } = ao;
1457
- const mode = resolveAdmissionMode(requestedMode);
1458
- const shadowReasons = resolveShadowReasons(requestedShadowReasons);
1459
- // Resolve before the dedup fast path so unknown class IDs cannot join an
1460
- // existing call without validation. The resolved class also partitions
1461
- // deduplication, preventing one policy class from inheriting another
1462
- // class's admission decision or queue position.
1463
- const selectedAdmissionClass = resolveAdmissionClass(acquireOpts.admissionClass);
1464
- // ---- Deduplication ----
1465
- let dedupKey = "";
1466
- if (dedup.enabled && perCallDedup !== false) {
1467
- let rawKey;
1468
- try {
1469
- rawKey = dedup.keyFn(request);
1470
- }
1471
- catch {
1472
- rawKey = "";
1473
- }
1474
- // "" opts out; only real keys are scoped + hashed.
1475
- if (rawKey !== "") {
1476
- const effectiveScope = selectedAdmissionClass === undefined
1477
- ? dedupScope ?? ""
1478
- : JSON.stringify([dedupScope ?? "", selectedAdmissionClass.id]);
1479
- dedupKey = hashDedupKey(effectiveScope, rawKey);
1480
- }
1481
- }
1482
- let deferred;
1483
- let resultPromise;
1484
- if (dedup.enabled && dedupKey !== "") {
1485
- const existing = dedupMap.get(dedupKey);
1486
- if (existing) {
1487
- dedupHits++;
1488
- emit("dedup", {
1489
- request,
1490
- ...(selectedAdmissionClass !== undefined
1491
- ? { admissionClass: selectedAdmissionClass.id }
1492
- : {}),
1493
- });
1494
- try {
1495
- return await waitForSharedDedup(existing, request, acquireOpts, selectedAdmissionClass);
1496
- }
1497
- catch (error) {
1498
- if (mode === "observe" &&
1499
- error instanceof LLMBulkheadRejectedError &&
1500
- dedupWaitErrors.has(error) &&
1501
- shouldBypass(error.reason, shadowReasons)) {
1502
- return runBypassed(request, fn, {
1503
- ...(ao.signal !== undefined && { signal: ao.signal }),
1504
- ...(getUsage !== undefined && { getUsage }),
1505
- }, resolveAdmission(request, acquireOpts, selectedAdmissionClass), error.reason, error.detail, error.detail?.limitRevision ?? currentRevision, false);
1506
- }
1507
- throw error;
1508
- }
1509
- }
1510
- deferred = createDeferred();
1511
- resultPromise = deferred.promise;
1512
- dedupMap.set(dedupKey, deferred.promise);
1513
- const cleanup = () => {
1514
- try {
1515
- const p = dedupMap.get(dedupKey);
1516
- if (p === deferred.promise)
1517
- dedupMap.delete(dedupKey);
1518
- }
1519
- catch {
1520
- // never throw from cleanup
1521
- }
1522
- };
1523
- void deferred.promise.then(cleanup, cleanup);
1524
- }
1525
- const publish = (work) => {
1526
- if (deferred) {
1527
- void work.then((value) => deferred.resolve(value), (error) => deferred.reject(error));
1528
- return resultPromise;
1529
- }
1530
- return work;
1531
- };
1532
- try {
1533
- let resolved;
1534
- let advisory;
1535
- if (mode === "observe") {
1536
- resolved = resolveAdmission(request, acquireOpts, selectedAdmissionClass);
1537
- advisory = wouldAdmitResolved(resolved, true);
1538
- if (!advisory.admit &&
1539
- advisory.reason !== undefined &&
1540
- shouldBypass(advisory.reason, shadowReasons)) {
1541
- return publish(runBypassed(request, fn, {
1542
- ...(ao.signal !== undefined && { signal: ao.signal }),
1543
- ...(getUsage !== undefined && { getUsage }),
1544
- }, resolved, advisory.reason, advisory.detail, advisory.detail?.limitRevision ?? currentRevision, false));
1545
- }
1546
- }
1547
- const r = await _acquire(request, acquireOpts, resolved ??
1548
- resolveAdmission(request, acquireOpts, selectedAdmissionClass), mode === "observe" ? shadowReasons : undefined);
1549
- if (!r.ok) {
1550
- if (mode === "observe" && shouldBypass(r.reason, shadowReasons)) {
1551
- return publish(runBypassed(request, fn, {
1552
- ...(ao.signal !== undefined && { signal: ao.signal }),
1553
- ...(getUsage !== undefined && { getUsage }),
1554
- }, resolved ??
1555
- resolveAdmission(request, acquireOpts, selectedAdmissionClass), r.reason, r.detail, r.detail?.limitRevision ?? currentRevision, advisory?.admit === true));
1556
- }
1557
- throw new LLMBulkheadRejectedError(r.reason, r.detail);
1558
- }
1559
- const ctx = {
1560
- admissionId: r.admissionId,
1561
- limitRevision: r.limitRevision,
1562
- ...(r.admissionClass !== undefined
1563
- ? { admissionClass: r.admissionClass }
1564
- : {}),
1565
- reservation: r.reservation,
1566
- admission: "admitted",
1567
- reportUsage: (usage, reconciliation) => r.token.reportUsage(usage, reconciliation),
1568
- };
1569
- const work = (async () => {
1570
- let result;
1571
- try {
1572
- result = await fn(ao.signal, ctx);
1573
- }
1574
- catch (err) {
1575
- r.token.release(); // no usage on error
1576
- throw err;
1577
- }
1578
- // Extract usage for refund.
1579
- let usage;
1580
- if (getUsage) {
1581
- try {
1582
- const extracted = getUsage(result);
1583
- usage =
1584
- extracted === undefined ? undefined : validateTokenUsage(extracted);
1585
- }
1586
- catch {
1587
- // bad getUsage must not break release
1588
- }
1589
- }
1590
- r.token.release(usage);
1591
- return result;
1592
- })();
1593
- return publish(work);
1594
- }
1595
- catch (err) {
1596
- if (deferred) {
1597
- deferred.reject(err);
1598
- return resultPromise;
1599
- }
1600
- throw err;
1601
- }
176
+ function applyLimits(next) {
177
+ return admissionLimits.apply(next);
1602
178
  }
1603
- /** Runtime stats. Optional fields are present only when the feature is enabled. */
1604
- function stats() {
1605
- const base = bulkhead.stats();
1606
- const result = {
1607
- limits: limits(),
1608
- bulkhead: base,
1609
- llm: {
1610
- admitted: llmAdmitted,
1611
- released: llmReleased,
1612
- rejected: llmRejected,
1613
- rejectedByReason: { ...llmRejectedByReason },
1614
- },
1615
- };
1616
- if (budget) {
1617
- result.tokenBudget = {
1618
- budget: currentBudget,
1619
- inFlightTokens,
1620
- available: Math.max(0, currentBudget - inFlightTokens),
1621
- totalReserved,
1622
- totalConsumed,
1623
- totalRefunded,
1624
- totalOverrun,
1625
- highPriorityReserve: currentHighPriorityReserve,
1626
- };
1627
- }
1628
- if (observeBypassed > 0) {
1629
- result.observe = {
1630
- bypassed: observeBypassed,
1631
- raceBypassed: observeRaceBypassed,
1632
- bypassedByReason: { ...observeBypassedByReason },
1633
- usageReported: observeUsageReported,
1634
- totalInputTokens: observeTotalInputTokens,
1635
- totalOutputTokens: observeTotalOutputTokens,
1636
- };
1637
- }
1638
- if (dedup.enabled) {
1639
- result.deduplication = {
1640
- active: dedupMap.size,
1641
- hits: dedupHits,
1642
- };
1643
- }
1644
- if (defaultAdmissionClass !== undefined) {
1645
- const sharedConcurrentCapacity = Math.max(0, base.maxConcurrent - protectedConcurrentTotal());
1646
- const sharedConcurrentUsed = sharedConcurrentInUse();
1647
- const shared = {
1648
- maxConcurrent: sharedConcurrentCapacity,
1649
- inFlight: sharedConcurrentUsed,
1650
- availableConcurrent: Math.max(0, sharedConcurrentCapacity - sharedConcurrentUsed),
1651
- ...(budget
1652
- ? {
1653
- tokenBudget: {
1654
- budget: Math.max(0, currentBudget - protectedTokensTotal()),
1655
- inFlightTokens: sharedTokensInUse(),
1656
- available: Math.max(0, Math.max(0, currentBudget - protectedTokensTotal()) -
1657
- sharedTokensInUse()),
1658
- },
1659
- }
1660
- : {}),
1661
- };
1662
- result.admissionClasses = {
1663
- defaultClass: defaultAdmissionClass,
1664
- shared,
1665
- classes: Object.fromEntries(Array.from(admissionClassStates, ([id, state]) => {
1666
- const protectedConcurrency = protectedConcurrentInUse(state);
1667
- const protectedTokens = protectedTokensInUse(state);
1668
- return [
1669
- id,
1670
- {
1671
- limits: {
1672
- ...(state.protectedConcurrent > 0 && {
1673
- protectedConcurrent: state.protectedConcurrent,
1674
- }),
1675
- ...(state.maxConcurrent !== undefined && {
1676
- maxConcurrent: state.maxConcurrent,
1677
- }),
1678
- ...(state.protectedInFlightTokens > 0 && {
1679
- protectedInFlightTokens: state.protectedInFlightTokens,
1680
- }),
1681
- ...(state.maxInFlightTokens !== undefined && {
1682
- maxInFlightTokens: state.maxInFlightTokens,
1683
- }),
1684
- },
1685
- inFlight: state.inFlight,
1686
- protectedConcurrentInUse: protectedConcurrency,
1687
- borrowedConcurrent: Math.max(0, state.inFlight - protectedConcurrency),
1688
- inFlightTokens: state.inFlightTokens,
1689
- protectedTokensInUse: protectedTokens,
1690
- borrowedInFlightTokens: Math.max(0, state.inFlightTokens - protectedTokens),
1691
- admitted: state.admitted,
1692
- released: state.released,
1693
- rejected: state.rejected,
1694
- rejectedByReason: { ...state.rejectedByReason },
1695
- totalReserved: state.totalReserved,
1696
- totalConsumed: state.totalConsumed,
1697
- totalRefunded: state.totalRefunded,
1698
- totalOverrun: state.totalOverrun,
1699
- totalBorrowedAdmissions: state.totalBorrowedAdmissions,
1700
- totalBorrowedTokensReserved: state.totalBorrowedTokensReserved,
1701
- },
1702
- ];
1703
- })),
1704
- };
1705
- }
1706
- return result;
179
+ /**
180
+ * Backward-compatible budget-only setter.
181
+ *
182
+ * This is implemented as a complete local reconfiguration at
183
+ * `currentRevision + 1`. Externally managed deployments should use
184
+ * `applyLimits()` exclusively so one authority owns the revision stream.
185
+ */
186
+ function setBudget(tokens) {
187
+ admissionLimits.setBudget(tokens);
1707
188
  }
1708
189
  /**
1709
190
  * Stop admission permanently. All pending waiters in the underlying
@@ -1711,35 +192,10 @@ export function createLLMBulkhead(opts) {
1711
192
  * calls reject immediately. In-flight work is not interrupted.
1712
193
  */
1713
194
  function close() {
1714
- bulkhead.close();
195
+ shutdown.close();
1715
196
  }
1716
197
  function drain(opts) {
1717
- const timeoutMs = opts?.timeoutMs;
1718
- if (timeoutMs === undefined) {
1719
- return bulkhead.drain();
1720
- }
1721
- assertNonNegativeInteger(timeoutMs, "timeoutMs");
1722
- return new Promise((resolve) => {
1723
- let settled = false;
1724
- const timer = setTimeout(() => {
1725
- if (settled)
1726
- return;
1727
- settled = true;
1728
- const base = bulkhead.stats();
1729
- resolve({
1730
- drained: false,
1731
- inFlight: base.inFlight,
1732
- pending: base.pending,
1733
- });
1734
- }, timeoutMs);
1735
- void bulkhead.drain().then(() => {
1736
- if (settled)
1737
- return;
1738
- settled = true;
1739
- clearTimeout(timer);
1740
- resolve({ drained: true, inFlight: 0, pending: 0 });
1741
- });
1742
- });
198
+ return shutdown.drain(opts);
1743
199
  }
1744
200
  /**
1745
201
  * Subscribe to a bulkhead lifecycle event.
@@ -1749,10 +205,7 @@ export function createLLMBulkhead(opts) {
1749
205
  * control flow. They must not throw — exceptions are silently caught.
1750
206
  */
1751
207
  function on(event, listener) {
1752
- listeners[event].add(listener);
1753
- return () => {
1754
- listeners[event].delete(listener);
1755
- };
208
+ return events.on(event, listener);
1756
209
  }
1757
210
  return {
1758
211
  estimate,