async-bulkhead-llm 3.15.3 → 3.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,102 @@ and adheres to [Semantic Versioning](https://semver.org/).
7
7
 
8
8
  ---
9
9
 
10
+ ## [3.17.0] - 2026-09-03
11
+
12
+ ### Added
13
+
14
+ * **Resource attribution for admitted work.** Successful acquire results,
15
+ tokens, run contexts, and admission/release events now expose immutable
16
+ `resources` with exact borrowed-concurrency and borrowed-token attribution.
17
+
18
+ * **Borrowed local-slot abandonment.** `LLMToken` and admitted run contexts add
19
+ idempotent `abandonBorrowedConcurrency()`. It returns only a concurrency slot
20
+ that came from shared class capacity; token holds remain charged until final
21
+ release. New global and per-class counters plus the
22
+ `borrowedConcurrencyAbandon` event expose the split lifecycle. The event
23
+ carries a `cause` of `manual` or `deadline`, and
24
+ `llm.borrowedConcurrencyAbandonedByCause` counts each separately, so
25
+ deliberate shedding is distinguishable from a lease configured too tight.
26
+
27
+ * **Wall-clock borrowed-slot deadline.** `run()` accepts
28
+ `borrowedConcurrencyDeadlineMs`. The post-admission timer applies only to a
29
+ borrowed local slot. Expiry returns that slot, aborts the callback signal,
30
+ and rejects the caller with `LLMBorrowedConcurrencyDeadlineError` while the
31
+ underlying callback retains responsibility for token settlement.
32
+
33
+ ### Fixed
34
+
35
+ * `drain()` now waits for final LLM settlement even after local concurrency was
36
+ abandoned. Timed drain results report outstanding token-holding admissions
37
+ instead of incorrectly declaring the bulkhead drained when only the local
38
+ slot has returned.
39
+
40
+ ### Contract
41
+
42
+ * A client-side deadline is an enforceable restoration bound for the local
43
+ admission slot only. It does not prove that a provider account, model queue,
44
+ or accelerator stopped work. Consumers needing a hard upstream guarantee
45
+ must keep an unlent floor or use authoritative provider-side reclamation.
46
+
47
+ ### Compatibility
48
+
49
+ * Existing methods and event names remain available. Exact object-equality
50
+ consumers should account for new resource fields and counters. Callers that
51
+ do not use borrowed-slot abandonment retain their previous lifecycle.
52
+
53
+ * After `abandonBorrowedConcurrency()`, `drain()` without `timeoutMs` waits for
54
+ the matching token settlement even though the local slot is already free.
55
+ Manual `acquire()` callers must eventually call `release()` or an unbounded
56
+ drain remains pending; bounded drain reports the admission as outstanding.
57
+ This split lifecycle is new in 3.17 and prevents shutdown from reporting
58
+ false completion.
59
+
60
+ * `Listener` and `LLMBorrowedConcurrencyAbandonCause` are new entry-point type
61
+ exports. `Listener` was previously reachable only through `on()` without
62
+ being nameable by consumers.
63
+
64
+ * The runtime dependency remains `async-bulkhead-ts@^1.0.1`.
65
+
66
+ ## [3.16.0] - 2026-08-25
67
+
68
+ ### Added
69
+
70
+ * **Admission-decision timing on lifecycle events.** Instrumented `admit` and
71
+ admission-decision `reject` events now carry additive optional integer
72
+ nanosecond fields: `decisionDurationNs` and `queueWaitNs`. Timing uses
73
+ Node's monotonic `process.hrtime.bigint()` clock.
74
+
75
+ * **Decision time is separated from queue wait.** `queueWaitNs` measures the
76
+ complete awaited `bulkhead.acquire()` span. `decisionDurationNs` excludes
77
+ that await and measures only synchronous admission work, so queue contention
78
+ cannot be misreported as local decision cost. Precheck rejects report
79
+ `queueWaitNs === 0` exactly.
80
+
81
+ * **Admission timing coverage tests and clock-overhead microbenchmark.** Tests
82
+ cover precheck rejection, immediate and queued admission, acquire timeout,
83
+ queue-limit rejection, postcheck rejection after a limits race, and both
84
+ observe-mode bypass shapes. The suite also records the cost of the four
85
+ `process.hrtime.bigint()` reads required on paths that cross the acquire
86
+ await; it is diagnostic rather than a timing-sensitive CI gate.
87
+
88
+ ### Behavior
89
+
90
+ * Observe-mode calls that are actually bypassed do not expose admission timing.
91
+ The advisory bypass path never enters admission. When a race causes
92
+ `_acquire()` to reject and observe mode converts that result to a bypass, the
93
+ existing `reject` event remains for backward compatibility but its timing
94
+ fields are absent.
95
+
96
+ * Deduplication-follower rejections remain untimed because they are waits on an
97
+ existing admission rather than new admission decisions.
98
+
99
+ ### Compatibility
100
+
101
+ * Additive minor release. Existing event fields and event names are unchanged.
102
+ Consumers that use exact event-object equality should account for the new
103
+ optional timing fields on instrumented `admit` / `reject` events.
104
+ * No runtime dependency changes.
105
+
10
106
  ## [3.15.3] - 2026-08-18
11
107
 
12
108
  Documentation and package-metadata patch. No runtime code, public API, or
@@ -37,8 +133,9 @@ dependency behavior changed.
37
133
 
38
134
  ## [3.15.2] - 2026-08-17
39
135
 
40
- Documentation-only release. No runtime code changed and the public API is
41
- identical to 3.15.1; no upgrade action is required.
136
+ Documentation release, with one development-only dependency update. No runtime
137
+ code changed and the public API is identical to 3.15.1; no upgrade action is
138
+ required.
42
139
 
43
140
  ### Changed
44
141
 
@@ -96,9 +193,22 @@ identical to 3.15.1; no upgrade action is required.
96
193
  use absolute repository URLs so they work from GitHub, npm, and the
97
194
  documentation site.
98
195
 
196
+ ### Security
197
+
198
+ * **Resolved GHSA-2v37-7h3g-55p8 in `nanoid` (development-only).** `npm audit`
199
+ reported this high-severity advisory -- custom generators can loop
200
+ indefinitely when `size` is zero -- against every `nanoid` before 3.3.18. The
201
+ lockfile now resolves 3.3.18, which carries the fix. `nanoid` reaches this
202
+ repository only as a development-time transitive dependency (`vitest` ->
203
+ `vite` -> `postcss` -> `nanoid`); it has never been a runtime dependency and
204
+ is not part of the published tarball, so consumers of `async-bulkhead-llm`
205
+ were never exposed. `npm audit` now reports no known vulnerabilities at any
206
+ severity.
207
+
99
208
  ### Compatibility
100
209
 
101
- * No API, behavior, or dependency changes for consumers. The published tarball
210
+ * No API, behavior, or runtime dependency changes for consumers; the `nanoid`
211
+ bump is confined to development-only tooling. The published tarball
102
212
  contents are unchanged apart from the rewritten `README.md`. `guides/` and
103
213
  the documentation tooling are development-only and are not published.
104
214
 
@@ -992,4 +1102,4 @@ Changes required only if you:
992
1102
  * `tryAcquire()` from the base library is not exposed — synchronous non-blocking admission is not meaningful for LLM workloads where token budget requires the full request object
993
1103
  * Zero dependencies beyond `async-bulkhead-ts`
994
1104
 
995
- ---
1105
+ ---
package/README.md CHANGED
@@ -156,6 +156,29 @@ s.tokenBudget?.available; // budget headroom
156
156
  bulkhead.on('reject', ({ reason, detail }) => metrics.increment(reason));
157
157
  ```
158
158
 
159
+ `admit` and admission-decision `reject` events also expose optional
160
+ `decisionDurationNs` and `queueWaitNs` fields. Decision time excludes the
161
+ underlying concurrency wait, so local admission cost and queue contention stay
162
+ separate.
163
+
164
+ Admissions also expose exact resource attribution through `resources`.
165
+ For class policies that lend shared concurrency, `run()` can enforce a
166
+ wall-clock lease on the borrowed local slot:
167
+
168
+ ```ts
169
+ await bulkhead.run(request, callProvider, {
170
+ admissionClass: 'background',
171
+ borrowedConcurrencyDeadlineMs: 30_000,
172
+ });
173
+ ```
174
+
175
+ Expiry returns that local concurrency slot, aborts the callback signal, and
176
+ rejects with `LLMBorrowedConcurrencyDeadlineError`. It deliberately retains
177
+ the token hold until the callback settles. This is a local restoration bound,
178
+ not proof that a provider account, accelerator queue, or remote generation was
179
+ reclaimed. Keep an unlent floor or a real provider-side partition for upstream
180
+ capacity that client cancellation cannot authoritatively release.
181
+
159
182
  → [Stats and events](guides/telemetry.md)
160
183
 
161
184
  ## Shutting down cleanly
@@ -166,8 +189,16 @@ bulkhead.close(); // stop admitting
166
189
  await bulkhead.drain({ timeoutMs: 10_000 }); // wait, but not forever
167
190
  ```
168
191
 
169
- `drain()` with a deadline always resolves and tells you what it abandoned, so
170
- one stuck upstream stream can't hold your deploy hostage.
192
+ `drain()` with a deadline always resolves and reports what remains outstanding;
193
+ it does not abandon or release that work. One stuck upstream stream therefore
194
+ cannot hold the shutdown decision open indefinitely.
195
+
196
+ Without `timeoutMs`, `drain()` waits for final token settlement as well as base
197
+ concurrency. In particular, returning a borrowed slot with
198
+ `abandonBorrowedConcurrency()` does not complete the admission: a manual
199
+ `acquire()` caller must still call `release()`, or the unbounded drain remains
200
+ pending. This preserves the distinction between restoring a local slot and
201
+ settling the resource accounting for the work behind it.
171
202
 
172
203
  ---
173
204
 
@@ -25,6 +25,18 @@ function resolvePreset(profile) {
25
25
  return profiles_js_1.PROFILES[profile];
26
26
  return profile;
27
27
  }
28
+ const NO_ADMISSION_RESOURCES = Object.freeze({
29
+ borrowedConcurrency: false,
30
+ borrowedTokens: 0,
31
+ });
32
+ /**
33
+ * Internal view of a wrapped token. `run()` must attribute a lease expiry
34
+ * distinctly from an application's own abandonment without widening the
35
+ * public `LLMToken` surface, where a caller-supplied cause would be
36
+ * unverifiable telemetry. The key is a module-private symbol so the
37
+ * capability is unreachable from a published token.
38
+ */
39
+ const ABANDON_WITH_CAUSE = Symbol("abandonBorrowedConcurrencyWithCause");
28
40
  function validateAdmissionClassId(value, label) {
29
41
  if (typeof value !== "string" || value.trim() === "") {
30
42
  throw new Error(`${label} must be a non-empty string`);
@@ -140,6 +152,7 @@ function createLLMBulkhead(opts) {
140
152
  inFlightTokens: 0,
141
153
  admitted: 0,
142
154
  released: 0,
155
+ borrowedConcurrencyAbandoned: 0,
143
156
  rejected: 0,
144
157
  rejectedByReason: {},
145
158
  totalReserved: 0,
@@ -179,8 +192,11 @@ function createLLMBulkhead(opts) {
179
192
  let totalOverrun = 0;
180
193
  let llmAdmitted = 0;
181
194
  let llmReleased = 0;
195
+ let llmBorrowedConcurrencyAbandoned = 0;
196
+ const llmBorrowedConcurrencyAbandonedByCause = {};
182
197
  let llmRejected = 0;
183
198
  const llmRejectedByReason = {};
199
+ const llmDrainWaiters = new Set();
184
200
  let observeBypassed = 0;
185
201
  let observeRaceBypassed = 0;
186
202
  const observeBypassedByReason = {};
@@ -195,6 +211,7 @@ function createLLMBulkhead(opts) {
195
211
  // ---- Event emitter state ----
196
212
  const listeners = {
197
213
  admit: new Set(),
214
+ borrowedConcurrencyAbandon: new Set(),
198
215
  reject: new Set(),
199
216
  release: new Set(),
200
217
  usage: new Set(),
@@ -219,6 +236,24 @@ function createLLMBulkhead(opts) {
219
236
  }
220
237
  function noteLLMRelease() {
221
238
  llmReleased++;
239
+ settleLLMDrainWaiters();
240
+ }
241
+ function llmInFlight() {
242
+ return Math.max(0, llmAdmitted - llmReleased);
243
+ }
244
+ function settleLLMDrainWaiters() {
245
+ if (llmInFlight() !== 0)
246
+ return;
247
+ for (const resolve of llmDrainWaiters)
248
+ resolve();
249
+ llmDrainWaiters.clear();
250
+ }
251
+ function waitForLLMDrain() {
252
+ if (llmInFlight() === 0)
253
+ return Promise.resolve();
254
+ return new Promise((resolve) => {
255
+ llmDrainWaiters.add(resolve);
256
+ });
222
257
  }
223
258
  function noteLLMReject(reason) {
224
259
  llmRejected++;
@@ -515,26 +550,39 @@ function createLLMBulkhead(opts) {
515
550
  function tryReserveCapacity(reserved, priority, admissionClass) {
516
551
  const failure = checkAdmissionCapacity(reserved, priority, admissionClass, true);
517
552
  if (failure !== undefined)
518
- return failure;
553
+ return { ok: false, failure };
554
+ const resources = Object.freeze({
555
+ borrowedConcurrency: admissionClass === undefined
556
+ ? false
557
+ : requestedBorrowedConcurrent(admissionClass) > 0,
558
+ borrowedTokens: admissionClass === undefined
559
+ ? 0
560
+ : requestedBorrowedTokens(admissionClass, reserved),
561
+ });
519
562
  if (budget) {
520
563
  inFlightTokens += reserved;
521
564
  totalReserved += reserved;
522
565
  }
523
566
  if (admissionClass !== undefined) {
524
- const borrowedConcurrent = requestedBorrowedConcurrent(admissionClass);
525
- const borrowedTokens = requestedBorrowedTokens(admissionClass, reserved);
526
567
  admissionClass.inFlight++;
527
568
  admissionClass.admitted++;
528
- admissionClass.totalBorrowedAdmissions += borrowedConcurrent;
529
- admissionClass.totalBorrowedTokensReserved += borrowedTokens;
569
+ admissionClass.totalBorrowedAdmissions += resources.borrowedConcurrency
570
+ ? 1
571
+ : 0;
572
+ admissionClass.totalBorrowedTokensReserved += resources.borrowedTokens;
530
573
  if (budget) {
531
574
  admissionClass.inFlightTokens += reserved;
532
575
  admissionClass.totalReserved += reserved;
533
576
  }
534
577
  }
535
- return undefined;
578
+ return { ok: true, resources };
579
+ }
580
+ function releaseConcurrency(admissionClass) {
581
+ if (admissionClass !== undefined) {
582
+ admissionClass.inFlight = Math.max(0, admissionClass.inFlight - 1);
583
+ }
536
584
  }
537
- function releaseCapacity(held, usage, admissionClass) {
585
+ function settleTokenCapacity(held, usage, admissionClass) {
538
586
  let refunded = 0;
539
587
  if (usage && held > 0) {
540
588
  const actual = usage.input + usage.output;
@@ -553,7 +601,6 @@ function createLLMBulkhead(opts) {
553
601
  inFlightTokens = Math.max(0, inFlightTokens - held);
554
602
  if (admissionClass !== undefined) {
555
603
  admissionClass.inFlightTokens = Math.max(0, admissionClass.inFlightTokens - held);
556
- admissionClass.inFlight = Math.max(0, admissionClass.inFlight - 1);
557
604
  admissionClass.released++;
558
605
  }
559
606
  return refunded;
@@ -942,8 +989,9 @@ function createLLMBulkhead(opts) {
942
989
  * reservation and optionally applies the refund, and so that
943
990
  * streaming callers can report cumulative usage mid-flight.
944
991
  */
945
- function wrapToken(base, parts, request, admissionId, limitRevision, priority, admissionClass) {
992
+ function wrapToken(base, parts, request, admissionId, limitRevision, priority, admissionClass, resources) {
946
993
  let released = false;
994
+ let concurrencyReleased = false;
947
995
  /** Tokens currently held against the budget for this request. */
948
996
  let held = parts?.reserved ?? 0;
949
997
  /** Last reported cumulative usage (monotonically clamped). */
@@ -1064,6 +1112,37 @@ function createLLMBulkhead(opts) {
1064
1112
  }
1065
1113
  return report;
1066
1114
  };
1115
+ const abandonBorrowedConcurrency = (cause) => {
1116
+ if (released || concurrencyReleased || !resources.borrowedConcurrency) {
1117
+ return false;
1118
+ }
1119
+ concurrencyReleased = true;
1120
+ try {
1121
+ base.release();
1122
+ }
1123
+ finally {
1124
+ releaseConcurrency(admissionClass);
1125
+ }
1126
+ llmBorrowedConcurrencyAbandoned++;
1127
+ llmBorrowedConcurrencyAbandonedByCause[cause] =
1128
+ (llmBorrowedConcurrencyAbandonedByCause[cause] ?? 0) + 1;
1129
+ if (admissionClass !== undefined) {
1130
+ admissionClass.borrowedConcurrencyAbandoned++;
1131
+ }
1132
+ emit("borrowedConcurrencyAbandon", {
1133
+ request,
1134
+ admissionId,
1135
+ limitRevision,
1136
+ priority,
1137
+ ...(admissionClass !== undefined
1138
+ ? { admissionClass: admissionClass.id }
1139
+ : {}),
1140
+ resources,
1141
+ cause,
1142
+ heldTokens: held,
1143
+ });
1144
+ return true;
1145
+ };
1067
1146
  return {
1068
1147
  admissionId,
1069
1148
  limitRevision,
@@ -1071,7 +1150,10 @@ function createLLMBulkhead(opts) {
1071
1150
  ? { admissionClass: admissionClass.id }
1072
1151
  : {}),
1073
1152
  reservation,
1153
+ resources,
1074
1154
  reportUsage,
1155
+ abandonBorrowedConcurrency: () => abandonBorrowedConcurrency("manual"),
1156
+ [ABANDON_WITH_CAUSE]: abandonBorrowedConcurrency,
1075
1157
  release(usage) {
1076
1158
  if (released)
1077
1159
  return;
@@ -1092,7 +1174,15 @@ function createLLMBulkhead(opts) {
1092
1174
  validUsage = reported;
1093
1175
  }
1094
1176
  try {
1095
- base.release();
1177
+ if (!concurrencyReleased) {
1178
+ concurrencyReleased = true;
1179
+ try {
1180
+ base.release();
1181
+ }
1182
+ finally {
1183
+ releaseConcurrency(admissionClass);
1184
+ }
1185
+ }
1096
1186
  }
1097
1187
  finally {
1098
1188
  // Zero `held` before returning tokens: nothing is held against
@@ -1101,7 +1191,7 @@ function createLLMBulkhead(opts) {
1101
1191
  // stale pre-release hold).
1102
1192
  const heldAtRelease = held;
1103
1193
  held = 0;
1104
- const refunded = releaseCapacity(heldAtRelease, validUsage, admissionClass);
1194
+ const refunded = settleTokenCapacity(heldAtRelease, validUsage, admissionClass);
1105
1195
  noteLLMRelease();
1106
1196
  emit("release", {
1107
1197
  request,
@@ -1112,6 +1202,7 @@ function createLLMBulkhead(opts) {
1112
1202
  ? { admissionClass: admissionClass.id }
1113
1203
  : {}),
1114
1204
  reservedTokens: parts?.reserved ?? 0,
1205
+ resources,
1115
1206
  heldTokens: heldAtRelease,
1116
1207
  refundedTokens: refunded,
1117
1208
  usageSequence,
@@ -1124,13 +1215,29 @@ function createLLMBulkhead(opts) {
1124
1215
  };
1125
1216
  }
1126
1217
  // ---- Internal acquire ----
1127
- async function _acquire(request, ao, resolved = resolveAdmission(request, ao)) {
1218
+ async function _acquire(request, ao, resolved = resolveAdmission(request, ao), untimedRejectReasons) {
1128
1219
  const { priority, admissionClass, parts, reserved } = resolved;
1129
- const rejectWith = (reason, constraint) => {
1220
+ // Admission timing deliberately separates synchronous decision work from
1221
+ // the awaited concurrency acquire. Exact accounting requires four
1222
+ // monotonic clock reads on paths that reach the acquire: decision start,
1223
+ // wait start, wait end, and decision end. Precheck rejects use two reads.
1224
+ const decisionStartedNs = process.hrtime.bigint();
1225
+ let waitStartedNs = 0n;
1226
+ let waitEndedNs = 0n;
1227
+ let queueWaitNs = 0;
1228
+ const rejectWith = (reason, constraint, precheckDecisionDurationNs) => {
1130
1229
  const detail = buildRejectDetail(reserved, priority, admissionClass, constraint);
1230
+ const includeTiming = untimedRejectReasons === undefined ||
1231
+ !untimedRejectReasons.has(reason);
1232
+ const decisionDurationNs = includeTiming
1233
+ ? precheckDecisionDurationNs ??
1234
+ Number(waitStartedNs -
1235
+ decisionStartedNs +
1236
+ (process.hrtime.bigint() - waitEndedNs))
1237
+ : undefined;
1131
1238
  noteLLMReject(reason);
1132
1239
  noteAdmissionClassReject(admissionClass, reason);
1133
- emit("reject", {
1240
+ const event = {
1134
1241
  request,
1135
1242
  reason,
1136
1243
  limitRevision: detail.limitRevision,
@@ -1138,17 +1245,30 @@ function createLLMBulkhead(opts) {
1138
1245
  ...(admissionClass !== undefined
1139
1246
  ? { admissionClass: admissionClass.id }
1140
1247
  : {}),
1141
- });
1248
+ };
1249
+ if (decisionDurationNs !== undefined) {
1250
+ event.decisionDurationNs = decisionDurationNs;
1251
+ event.queueWaitNs = queueWaitNs;
1252
+ }
1253
+ emit("reject", event);
1142
1254
  return { ok: false, reason, detail };
1143
1255
  };
1144
1256
  // Every class ceiling is fail-fast and checked before entering the global
1145
1257
  // queue. A second atomic check runs after the global slot is acquired.
1146
1258
  const precheck = checkAdmissionCapacity(reserved, priority, admissionClass);
1147
1259
  if (precheck !== undefined) {
1148
- return rejectWith(precheck.reason, precheck.constraint);
1260
+ const includeTiming = untimedRejectReasons === undefined ||
1261
+ !untimedRejectReasons.has(precheck.reason);
1262
+ const precheckDecisionDurationNs = includeTiming
1263
+ ? Number(process.hrtime.bigint() - decisionStartedNs)
1264
+ : undefined;
1265
+ return rejectWith(precheck.reason, precheck.constraint, precheckDecisionDurationNs);
1149
1266
  }
1150
1267
  const mergedOptions = normalizeAcquireOptions(ao);
1268
+ waitStartedNs = process.hrtime.bigint();
1151
1269
  const r = await bulkhead.acquire(mergedOptions);
1270
+ waitEndedNs = process.hrtime.bigint();
1271
+ queueWaitNs = Number(waitEndedNs - waitStartedNs);
1152
1272
  if (!r.ok) {
1153
1273
  const constraint = r.reason === "concurrency_limit" ||
1154
1274
  r.reason === "queue_limit" ||
@@ -1159,9 +1279,9 @@ function createLLMBulkhead(opts) {
1159
1279
  }
1160
1280
  // Post-admission: atomically reserve global token and class capacity.
1161
1281
  const postcheck = tryReserveCapacity(reserved, priority, admissionClass);
1162
- if (postcheck !== undefined) {
1282
+ if (!postcheck.ok) {
1163
1283
  r.token.release();
1164
- return rejectWith(postcheck.reason, postcheck.constraint);
1284
+ return rejectWith(postcheck.failure.reason, postcheck.failure.constraint);
1165
1285
  }
1166
1286
  // Capture the revision at the admission linearization point: both the
1167
1287
  // concurrency slot and token reservation are held, and no listener or
@@ -1169,7 +1289,10 @@ function createLLMBulkhead(opts) {
1169
1289
  // provenance of this admitted work.
1170
1290
  const limitRevision = currentRevision;
1171
1291
  const admissionId = (0, node_crypto_1.randomUUID)();
1172
- const token = wrapToken(r.token, parts, request, admissionId, limitRevision, priority, admissionClass);
1292
+ const token = wrapToken(r.token, parts, request, admissionId, limitRevision, priority, admissionClass, postcheck.resources);
1293
+ const decisionDurationNs = Number(waitStartedNs -
1294
+ decisionStartedNs +
1295
+ (process.hrtime.bigint() - waitEndedNs));
1173
1296
  noteLLMAdmit();
1174
1297
  emit("admit", {
1175
1298
  request,
@@ -1180,6 +1303,9 @@ function createLLMBulkhead(opts) {
1180
1303
  ? { admissionClass: admissionClass.id }
1181
1304
  : {}),
1182
1305
  reservedTokens: reserved,
1306
+ resources: postcheck.resources,
1307
+ decisionDurationNs,
1308
+ queueWaitNs,
1183
1309
  });
1184
1310
  return {
1185
1311
  ok: true,
@@ -1189,6 +1315,7 @@ function createLLMBulkhead(opts) {
1189
1315
  ? { admissionClass: admissionClass.id }
1190
1316
  : {}),
1191
1317
  reservation: token.reservation,
1318
+ resources: token.resources,
1192
1319
  token,
1193
1320
  };
1194
1321
  }
@@ -1356,10 +1483,12 @@ function createLLMBulkhead(opts) {
1356
1483
  ? { admissionClass: admission.admissionClass.id }
1357
1484
  : {}),
1358
1485
  reservation,
1486
+ resources: NO_ADMISSION_RESOURCES,
1359
1487
  admission: "bypassed",
1360
1488
  bypassReason: reason,
1361
1489
  ...(detail !== undefined && { bypassDetail: detail }),
1362
1490
  reportUsage,
1491
+ abandonBorrowedConcurrency: () => false,
1363
1492
  };
1364
1493
  const finish = (usage) => {
1365
1494
  if (settled)
@@ -1422,7 +1551,13 @@ function createLLMBulkhead(opts) {
1422
1551
  * timeout) does not apply to that wait.
1423
1552
  */
1424
1553
  async function run(request, fn, ao = {}) {
1425
- const { getUsage, mode: requestedMode, shadowReasons: requestedShadowReasons, dedupScope, dedup: perCallDedup, ...acquireOpts } = ao;
1554
+ const { getUsage, mode: requestedMode, shadowReasons: requestedShadowReasons, dedupScope, dedup: perCallDedup, borrowedConcurrencyDeadlineMs, ...acquireOpts } = ao;
1555
+ if (borrowedConcurrencyDeadlineMs !== undefined &&
1556
+ (!Number.isSafeInteger(borrowedConcurrencyDeadlineMs) ||
1557
+ borrowedConcurrencyDeadlineMs < 1 ||
1558
+ borrowedConcurrencyDeadlineMs > 2_147_483_647)) {
1559
+ throw new Error("borrowedConcurrencyDeadlineMs must be a safe integer from 1 through 2147483647");
1560
+ }
1426
1561
  const mode = resolveAdmissionMode(requestedMode);
1427
1562
  const shadowReasons = resolveShadowReasons(requestedShadowReasons);
1428
1563
  // Resolve before the dedup fast path so unknown class IDs cannot join an
@@ -1514,7 +1649,7 @@ function createLLMBulkhead(opts) {
1514
1649
  }
1515
1650
  }
1516
1651
  const r = await _acquire(request, acquireOpts, resolved ??
1517
- resolveAdmission(request, acquireOpts, selectedAdmissionClass));
1652
+ resolveAdmission(request, acquireOpts, selectedAdmissionClass), mode === "observe" ? shadowReasons : undefined);
1518
1653
  if (!r.ok) {
1519
1654
  if (mode === "observe" && shouldBypass(r.reason, shadowReasons)) {
1520
1655
  return publish(runBypassed(request, fn, {
@@ -1532,13 +1667,32 @@ function createLLMBulkhead(opts) {
1532
1667
  ? { admissionClass: r.admissionClass }
1533
1668
  : {}),
1534
1669
  reservation: r.reservation,
1670
+ resources: r.resources,
1535
1671
  admission: "admitted",
1536
1672
  reportUsage: (usage, reconciliation) => r.token.reportUsage(usage, reconciliation),
1673
+ abandonBorrowedConcurrency: () => r.token.abandonBorrowedConcurrency(),
1537
1674
  };
1675
+ const deadlineApplies = borrowedConcurrencyDeadlineMs !== undefined &&
1676
+ r.resources.borrowedConcurrency;
1677
+ const callbackAbort = deadlineApplies
1678
+ ? new AbortController()
1679
+ : undefined;
1680
+ const sourceSignal = ao.signal;
1681
+ let removeSourceAbortListener;
1682
+ if (callbackAbort !== undefined && sourceSignal !== undefined) {
1683
+ const forwardAbort = () => callbackAbort.abort(sourceSignal.reason);
1684
+ if (sourceSignal.aborted) {
1685
+ forwardAbort();
1686
+ }
1687
+ else {
1688
+ sourceSignal.addEventListener("abort", forwardAbort, { once: true });
1689
+ removeSourceAbortListener = () => sourceSignal.removeEventListener("abort", forwardAbort);
1690
+ }
1691
+ }
1538
1692
  const work = (async () => {
1539
1693
  let result;
1540
1694
  try {
1541
- result = await fn(ao.signal, ctx);
1695
+ result = await fn(callbackAbort?.signal ?? ao.signal, ctx);
1542
1696
  }
1543
1697
  catch (err) {
1544
1698
  r.token.release(); // no usage on error
@@ -1559,7 +1713,30 @@ function createLLMBulkhead(opts) {
1559
1713
  r.token.release(usage);
1560
1714
  return result;
1561
1715
  })();
1562
- return publish(work);
1716
+ if (!deadlineApplies)
1717
+ return publish(work);
1718
+ const deadlineMs = borrowedConcurrencyDeadlineMs;
1719
+ const publicWork = new Promise((resolve, reject) => {
1720
+ let publicSettled = false;
1721
+ const settle = (fn) => {
1722
+ if (publicSettled)
1723
+ return;
1724
+ publicSettled = true;
1725
+ fn();
1726
+ };
1727
+ const deadline = setTimeout(() => {
1728
+ const error = new errors_js_1.LLMBorrowedConcurrencyDeadlineError(deadlineMs, r.admissionId, r.resources, r.admissionClass);
1729
+ if (!r.token[ABANDON_WITH_CAUSE]("deadline"))
1730
+ return;
1731
+ callbackAbort.abort(error);
1732
+ settle(() => reject(error));
1733
+ }, deadlineMs);
1734
+ void work.then((value) => settle(() => resolve(value)), (error) => settle(() => reject(error))).finally(() => {
1735
+ clearTimeout(deadline);
1736
+ removeSourceAbortListener?.();
1737
+ });
1738
+ });
1739
+ return publish(publicWork);
1563
1740
  }
1564
1741
  catch (err) {
1565
1742
  if (deferred) {
@@ -1576,8 +1753,13 @@ function createLLMBulkhead(opts) {
1576
1753
  limits: limits(),
1577
1754
  bulkhead: base,
1578
1755
  llm: {
1756
+ inFlight: llmInFlight(),
1579
1757
  admitted: llmAdmitted,
1580
1758
  released: llmReleased,
1759
+ borrowedConcurrencyAbandoned: llmBorrowedConcurrencyAbandoned,
1760
+ borrowedConcurrencyAbandonedByCause: {
1761
+ ...llmBorrowedConcurrencyAbandonedByCause,
1762
+ },
1581
1763
  rejected: llmRejected,
1582
1764
  rejectedByReason: { ...llmRejectedByReason },
1583
1765
  },
@@ -1659,6 +1841,7 @@ function createLLMBulkhead(opts) {
1659
1841
  borrowedInFlightTokens: Math.max(0, state.inFlightTokens - protectedTokens),
1660
1842
  admitted: state.admitted,
1661
1843
  released: state.released,
1844
+ borrowedConcurrencyAbandoned: state.borrowedConcurrencyAbandoned,
1662
1845
  rejected: state.rejected,
1663
1846
  rejectedByReason: { ...state.rejectedByReason },
1664
1847
  totalReserved: state.totalReserved,
@@ -1684,8 +1867,11 @@ function createLLMBulkhead(opts) {
1684
1867
  }
1685
1868
  function drain(opts) {
1686
1869
  const timeoutMs = opts?.timeoutMs;
1870
+ const completeDrain = async () => {
1871
+ await Promise.all([bulkhead.drain(), waitForLLMDrain()]);
1872
+ };
1687
1873
  if (timeoutMs === undefined) {
1688
- return bulkhead.drain();
1874
+ return completeDrain();
1689
1875
  }
1690
1876
  (0, validation_js_1.assertNonNegativeInteger)(timeoutMs, "timeoutMs");
1691
1877
  return new Promise((resolve) => {
@@ -1697,11 +1883,11 @@ function createLLMBulkhead(opts) {
1697
1883
  const base = bulkhead.stats();
1698
1884
  resolve({
1699
1885
  drained: false,
1700
- inFlight: base.inFlight,
1886
+ inFlight: Math.max(base.inFlight, llmInFlight()),
1701
1887
  pending: base.pending,
1702
1888
  });
1703
1889
  }, timeoutMs);
1704
- void bulkhead.drain().then(() => {
1890
+ void completeDrain().then(() => {
1705
1891
  if (settled)
1706
1892
  return;
1707
1893
  settled = true;