async-bulkhead-llm 3.4.1 → 3.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +209 -21
- package/dist/cjs/index.cjs +171 -21
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/esm/index.js +172 -22
- package/dist/esm/index.js.map +1 -1
- package/dist/types/index.d.ts +129 -1
- package/dist/types/index.d.ts.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -18,7 +18,11 @@ Designed for services that need to enforce **cost ceilings, concurrency limits,
|
|
|
18
18
|
- ✅ **Opinionated profiles** — `'interactive'` and `'batch'` presets with escape hatch
|
|
19
19
|
- ✅ **In-flight deduplication** — identical requests share one LLM call; hashed keys, whole-request equality
|
|
20
20
|
- ✅ **Custom dedup key + per-tenant scope** — bring your own equivalence function; `dedupScope` isolates tenants
|
|
21
|
-
- ✅ **
|
|
21
|
+
- ✅ **Streaming-safe deduplication** — single-consumer results are never silently shared; `shareResult` fan-out hook + per-call `dedup: false` opt-out
|
|
22
|
+
- ✅ **Exact reservation preview** — `estimate()` exposes the reservation admission will use
|
|
23
|
+
- ✅ **Stable admission IDs** — correlate gateway requests, traces, usage, and release
|
|
24
|
+
- ✅ **Ordered usage events** — sequence-numbered hold changes for external coordinators
|
|
25
|
+
- ✅ **Event hooks** — `on('admit' | 'reject' | 'usage' | 'release' | 'dedup', fn)`
|
|
22
26
|
- ✅ **Graceful shutdown** — `close()` + `drain()`
|
|
23
27
|
- ✅ Optional **AbortSignal** and **timeout** cancellation
|
|
24
28
|
- ✅ `bulkhead.run(request, fn)` — acquire + release handled automatically
|
|
@@ -122,6 +126,83 @@ const result = await bulkhead.run(request, async () => {
|
|
|
122
126
|
|
|
123
127
|
---
|
|
124
128
|
|
|
129
|
+
## What's New in v3.6 — Gateway coordination seams
|
|
130
|
+
|
|
131
|
+
### Exact reservation preview
|
|
132
|
+
|
|
133
|
+
`estimate()` runs the same estimator and validation path as admission without
|
|
134
|
+
reserving capacity. This is useful when a gateway must acquire an external
|
|
135
|
+
lease before entering the local bulkhead:
|
|
136
|
+
|
|
137
|
+
```ts
|
|
138
|
+
const reservation = bulkhead.estimate(request);
|
|
139
|
+
const lease = reservation
|
|
140
|
+
? await redisLease.reserve(requestId, reservation.reserved)
|
|
141
|
+
: undefined;
|
|
142
|
+
|
|
143
|
+
const result = await bulkhead.acquire(request);
|
|
144
|
+
if (!result.ok) {
|
|
145
|
+
await lease?.release();
|
|
146
|
+
return reject(result.reason);
|
|
147
|
+
}
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
The preview is advisory until admission occurs: do not mutate the request
|
|
151
|
+
between calls, and keep custom estimators deterministic. `null` means token
|
|
152
|
+
budgeting is disabled and the local bulkhead will reserve no tokens.
|
|
153
|
+
|
|
154
|
+
### Stable admission identity
|
|
155
|
+
|
|
156
|
+
Every successful admission receives a UUID available on the acquire result,
|
|
157
|
+
token, run context, and lifecycle events:
|
|
158
|
+
|
|
159
|
+
```ts
|
|
160
|
+
const result = await bulkhead.acquire(request);
|
|
161
|
+
if (result.ok) {
|
|
162
|
+
console.log(result.admissionId);
|
|
163
|
+
console.log(result.token.admissionId);
|
|
164
|
+
result.token.release();
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
await bulkhead.run(request, async (_signal, ctx) => {
|
|
168
|
+
trace.setAttribute('llm.admission_id', ctx!.admissionId);
|
|
169
|
+
return callYourLLMProvider(request);
|
|
170
|
+
});
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
### Ordered usage-change events
|
|
174
|
+
|
|
175
|
+
Effective cumulative `reportUsage()` updates emit a sequence-numbered event.
|
|
176
|
+
Stale or duplicate reports are clamped as before and do not emit:
|
|
177
|
+
|
|
178
|
+
```ts
|
|
179
|
+
bulkhead.on('usage', (event) => {
|
|
180
|
+
// External stores can ignore an update whose sequence is not newer.
|
|
181
|
+
distributedLedger.adjust({
|
|
182
|
+
admissionId: event.admissionId,
|
|
183
|
+
sequence: event.sequence,
|
|
184
|
+
heldTokens: event.heldTokens,
|
|
185
|
+
});
|
|
186
|
+
});
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
The event includes previous/current hold, delta, cumulative usage, priority,
|
|
190
|
+
output-cap state, and over-reservation status. Listeners remain synchronous;
|
|
191
|
+
enqueue network or storage work rather than blocking inside the callback.
|
|
192
|
+
For admission-critical distributed enforcement, use the returned report and
|
|
193
|
+
await the external update in the gateway's stream loop:
|
|
194
|
+
|
|
195
|
+
```ts
|
|
196
|
+
const report = ctx!.reportUsage(cumulativeUsage);
|
|
197
|
+
await distributedLedger.setHold({
|
|
198
|
+
admissionId: report.admissionId,
|
|
199
|
+
sequence: report.sequence,
|
|
200
|
+
heldTokens: report.held,
|
|
201
|
+
});
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
---
|
|
205
|
+
|
|
125
206
|
## What's New in v3.2 — Gateway readiness
|
|
126
207
|
|
|
127
208
|
v3.2 adds the admission-control primitives an AI gateway needs, all additive:
|
|
@@ -289,7 +370,8 @@ const bulkhead = createLLMBulkhead({
|
|
|
289
370
|
});
|
|
290
371
|
```
|
|
291
372
|
|
|
292
|
-
The default key
|
|
373
|
+
The default key covers the entire request object with stable key ordering.
|
|
374
|
+
Return an empty string to opt a specific request out.
|
|
293
375
|
|
|
294
376
|
### Event Hooks
|
|
295
377
|
|
|
@@ -303,7 +385,7 @@ const off = bulkhead.on('release', ({ reservedTokens, refundedTokens, usage }) =
|
|
|
303
385
|
off(); // unsubscribe
|
|
304
386
|
```
|
|
305
387
|
|
|
306
|
-
Events: `'admit'`, `'reject'`, `'release'`, `'dedup'`.
|
|
388
|
+
Events: `'admit'`, `'reject'`, `'usage'`, `'release'`, `'dedup'`.
|
|
307
389
|
|
|
308
390
|
### Graceful Shutdown
|
|
309
391
|
|
|
@@ -497,6 +579,52 @@ The bulkhead-level `timeoutMs` default does **not** apply to this wait —
|
|
|
497
579
|
it is a queue-wait timeout, and a follower is waiting on a call that is
|
|
498
580
|
already running, not queued.
|
|
499
581
|
|
|
582
|
+
### Streaming results (v3.5)
|
|
583
|
+
|
|
584
|
+
Dedup shares the leader's resolved value with every follower **by
|
|
585
|
+
reference**. For plain JSON results that is correct. For streaming
|
|
586
|
+
results it is not: a `ReadableStream`, Node `Readable`, async iterable,
|
|
587
|
+
or `Response` body can only be consumed once — whichever caller reads
|
|
588
|
+
first wins, and the rest get a locked or drained stream.
|
|
589
|
+
|
|
590
|
+
The bulkhead now refuses to do that silently. When a follower's shared
|
|
591
|
+
result is detected as single-consumer, that follower rejects with
|
|
592
|
+
`LLMBulkheadRejectedError("unshareable_result")`. The **leader always
|
|
593
|
+
receives its original result unaffected**. Detection is shallow — only
|
|
594
|
+
the result value itself is inspected, so a stream nested inside a
|
|
595
|
+
wrapper object is still shared by reference.
|
|
596
|
+
|
|
597
|
+
You have two ways to make streaming and dedup coexist:
|
|
598
|
+
|
|
599
|
+
**1. `shareResult` — make sharing work.** A fan-out hook called once per
|
|
600
|
+
follower with the leader's result; its return value is what that
|
|
601
|
+
follower receives. It runs for *every* follower delivery (safe results
|
|
602
|
+
included) and bypasses the single-consumer detection — the hook owns
|
|
603
|
+
fan-out policy. A throwing hook rejects that follower with the thrown
|
|
604
|
+
error; leader and other followers are unaffected.
|
|
605
|
+
|
|
606
|
+
```ts
|
|
607
|
+
// fetch Response: each follower gets an independent clone.
|
|
608
|
+
// clone() is called at resolution time, before any body is consumed.
|
|
609
|
+
deduplication: {
|
|
610
|
+
shareResult: (r) => (r as Response).clone(),
|
|
611
|
+
}
|
|
612
|
+
```
|
|
613
|
+
|
|
614
|
+
For raw streams, `tee()`/replay choreography is provider-specific, which
|
|
615
|
+
is why this is a hook rather than built in.
|
|
616
|
+
|
|
617
|
+
**2. `dedup: false` — skip dedup for streaming calls.** A per-call
|
|
618
|
+
opt-out on `run()` options: the call neither joins an existing in-flight
|
|
619
|
+
call nor registers as joinable. Use it on streaming routes of a bulkhead
|
|
620
|
+
where dedup is otherwise useful, instead of encoding the exemption in a
|
|
621
|
+
bulkhead-wide `keyFn`. (`dedup: true` cannot enable deduplication when
|
|
622
|
+
it is disabled at the bulkhead level.)
|
|
623
|
+
|
|
624
|
+
```ts
|
|
625
|
+
bulkhead.run(request, streamFromProvider, { dedup: false });
|
|
626
|
+
```
|
|
627
|
+
|
|
500
628
|
---
|
|
501
629
|
|
|
502
630
|
## Cancellation
|
|
@@ -532,6 +660,8 @@ if (!r.ok) {
|
|
|
532
660
|
return respond503(r.reason);
|
|
533
661
|
}
|
|
534
662
|
|
|
663
|
+
console.log(`Admission: ${r.admissionId}`);
|
|
664
|
+
|
|
535
665
|
try {
|
|
536
666
|
const response = await callLLM(request);
|
|
537
667
|
return response;
|
|
@@ -622,8 +752,8 @@ type LLMStats = {
|
|
|
622
752
|
|
|
623
753
|
```ts
|
|
624
754
|
// Subscribe
|
|
625
|
-
const off = bulkhead.on('admit', ({
|
|
626
|
-
console.log(
|
|
755
|
+
const off = bulkhead.on('admit', ({ admissionId, reservedTokens }) => {
|
|
756
|
+
console.log(`${admissionId}: ${reservedTokens} tokens reserved`);
|
|
627
757
|
});
|
|
628
758
|
|
|
629
759
|
// Unsubscribe
|
|
@@ -632,12 +762,15 @@ off();
|
|
|
632
762
|
|
|
633
763
|
| Event | Payload |
|
|
634
764
|
|-----------|---------|
|
|
635
|
-
| `admit` | `{ request, reservedTokens }` |
|
|
636
|
-
| `reject` | `{ request, reason }` |
|
|
637
|
-
| `
|
|
765
|
+
| `admit` | `{ request, admissionId, priority, reservedTokens }` |
|
|
766
|
+
| `reject` | `{ request, reason, detail? }` |
|
|
767
|
+
| `usage` | `{ request, admissionId, priority, sequence, reservedTokens, previousHeldTokens, heldTokens, deltaTokens, usage, outputCap, outputRemaining, overReservation }` |
|
|
768
|
+
| `release` | `{ request, admissionId, priority, reservedTokens, heldTokens, refundedTokens, usageSequence, usage? }` |
|
|
638
769
|
| `dedup` | `{ request }` |
|
|
639
770
|
|
|
640
771
|
Listeners are synchronous and fire-and-forget. Exceptions are silently caught.
|
|
772
|
+
Do not perform blocking network I/O in a listener; enqueue telemetry or lease
|
|
773
|
+
updates for asynchronous delivery.
|
|
641
774
|
|
|
642
775
|
---
|
|
643
776
|
|
|
@@ -664,16 +797,17 @@ type LLMBulkheadOptions = {
|
|
|
664
797
|
timeoutMs?: number; // integer >= 0
|
|
665
798
|
profile?: 'interactive' | 'batch' | LLMBulkheadPreset;
|
|
666
799
|
tokenBudget?: {
|
|
667
|
-
budget:
|
|
668
|
-
estimator?:
|
|
669
|
-
|
|
670
|
-
|
|
800
|
+
budget: number; // non-negative integer; 0 rejects all budget-gated admissions
|
|
801
|
+
estimator?: TokenEstimator;
|
|
802
|
+
outputCap?: number; // integer >= 0
|
|
803
|
+
highPriorityReserve?: number; // integer >= 0 and <= initial budget
|
|
671
804
|
};
|
|
672
805
|
deduplication?: boolean | DeduplicationOptions;
|
|
673
806
|
};
|
|
674
807
|
|
|
675
808
|
type DeduplicationOptions = {
|
|
676
|
-
keyFn?:
|
|
809
|
+
keyFn?: (request: LLMRequest) => string;
|
|
810
|
+
shareResult?: (result: unknown) => unknown; // per-follower fan-out (v3.5)
|
|
677
811
|
};
|
|
678
812
|
```
|
|
679
813
|
|
|
@@ -682,28 +816,64 @@ type DeduplicationOptions = {
|
|
|
682
816
|
```ts
|
|
683
817
|
run<T>(
|
|
684
818
|
request: LLMRequest,
|
|
685
|
-
fn: (signal?: AbortSignal) => Promise<T>,
|
|
819
|
+
fn: (signal?: AbortSignal, ctx?: LLMRunContext) => Promise<T>,
|
|
686
820
|
options?: {
|
|
687
|
-
signal?:
|
|
688
|
-
timeoutMs?:
|
|
689
|
-
|
|
821
|
+
signal?: AbortSignal;
|
|
822
|
+
timeoutMs?: number; // integer >= 0
|
|
823
|
+
priority?: 'normal' | 'high';
|
|
824
|
+
getUsage?: (result: T) => TokenUsage | undefined;
|
|
825
|
+
dedupScope?: string; // dedup isolation scope (e.g. tenant / API key)
|
|
826
|
+
dedup?: boolean; // false = opt this call out of dedup (v3.5)
|
|
690
827
|
},
|
|
691
828
|
): Promise<T>
|
|
692
829
|
```
|
|
693
830
|
|
|
831
|
+
`ctx.admissionId` is the stable admission identifier. `ctx.reservation` is
|
|
832
|
+
the exact reservation used at admission (or `null` when token budgeting is
|
|
833
|
+
disabled), and `ctx.reportUsage()` reports cumulative streaming usage.
|
|
834
|
+
|
|
835
|
+
### `bulkhead.estimate(request)`
|
|
836
|
+
|
|
837
|
+
```ts
|
|
838
|
+
estimate(request: LLMRequest): LLMReservationEstimate | null
|
|
839
|
+
|
|
840
|
+
type LLMReservationEstimate = {
|
|
841
|
+
readonly input: number;
|
|
842
|
+
readonly maxOutput: number;
|
|
843
|
+
readonly reserved: number;
|
|
844
|
+
};
|
|
845
|
+
```
|
|
846
|
+
|
|
847
|
+
Runs the same estimator and validation path as admission but does not reserve
|
|
848
|
+
capacity. Returns `null` when `tokenBudget` is not configured.
|
|
849
|
+
|
|
694
850
|
### `bulkhead.acquire(request, options?)`
|
|
695
851
|
|
|
696
852
|
```ts
|
|
697
853
|
acquire(
|
|
698
854
|
request: LLMRequest,
|
|
699
|
-
options?: {
|
|
855
|
+
options?: {
|
|
856
|
+
signal?: AbortSignal;
|
|
857
|
+
timeoutMs?: number; // integer >= 0
|
|
858
|
+
priority?: 'normal' | 'high';
|
|
859
|
+
},
|
|
700
860
|
): Promise<LLMAcquireResult>
|
|
701
861
|
|
|
702
862
|
type LLMAcquireResult =
|
|
703
|
-
| {
|
|
863
|
+
| {
|
|
864
|
+
ok: true;
|
|
865
|
+
admissionId: string;
|
|
866
|
+
reservation: LLMReservationEstimate | null;
|
|
867
|
+
token: LLMToken;
|
|
868
|
+
}
|
|
704
869
|
| { ok: false; reason: LLMRejectReason };
|
|
705
870
|
|
|
706
|
-
type LLMToken = {
|
|
871
|
+
type LLMToken = {
|
|
872
|
+
readonly admissionId: string;
|
|
873
|
+
readonly reservation: LLMReservationEstimate | null;
|
|
874
|
+
reportUsage(usage: TokenUsage): UsageReport;
|
|
875
|
+
release(usage?: TokenUsage): void;
|
|
876
|
+
};
|
|
707
877
|
```
|
|
708
878
|
|
|
709
879
|
### `bulkhead.stats()`
|
|
@@ -742,8 +912,19 @@ type TextContentBlock = { type: 'text'; text: string };
|
|
|
742
912
|
type OpaqueContentBlock = { type: string; [key: string]: unknown };
|
|
743
913
|
|
|
744
914
|
type TokenEstimate = { input: number; maxOutput: number };
|
|
915
|
+
type LLMReservationEstimate = TokenEstimate & { reserved: number };
|
|
745
916
|
type TokenEstimator = (request: LLMRequest) => TokenEstimate;
|
|
746
917
|
type TokenUsage = { input: number; output: number };
|
|
918
|
+
type UsageReport = {
|
|
919
|
+
admissionId: string;
|
|
920
|
+
sequence: number;
|
|
921
|
+
reserved: number;
|
|
922
|
+
held: number;
|
|
923
|
+
consumed: number;
|
|
924
|
+
outputCap: number | null;
|
|
925
|
+
outputRemaining: number | null;
|
|
926
|
+
overReservation: boolean;
|
|
927
|
+
};
|
|
747
928
|
|
|
748
929
|
type LLMRejectReason =
|
|
749
930
|
| 'concurrency_limit'
|
|
@@ -751,13 +932,20 @@ type LLMRejectReason =
|
|
|
751
932
|
| 'budget_limit'
|
|
752
933
|
| 'timeout'
|
|
753
934
|
| 'aborted'
|
|
754
|
-
| 'shutdown'
|
|
935
|
+
| 'shutdown'
|
|
936
|
+
| 'unshareable_result';
|
|
755
937
|
```
|
|
756
938
|
|
|
757
939
|
---
|
|
758
940
|
|
|
759
941
|
## Migration
|
|
760
942
|
|
|
943
|
+
### v3.5 → v3.6
|
|
944
|
+
|
|
945
|
+
No call-site changes are required. `admit` and `release` event payloads gained
|
|
946
|
+
additional fields, and `usage` is a new event type. Code that exhaustively
|
|
947
|
+
enumerates `LLMEventType` should add the new `usage` case.
|
|
948
|
+
|
|
761
949
|
### v2 → v3
|
|
762
950
|
|
|
763
951
|
Update stats access from top-level fields to the `bulkhead` block:
|
package/dist/cjs/index.cjs
CHANGED
|
@@ -198,11 +198,54 @@ function resolvePreset(profile) {
|
|
|
198
198
|
return profile;
|
|
199
199
|
}
|
|
200
200
|
function resolveDedup(opt) {
|
|
201
|
-
if (!opt)
|
|
202
|
-
return { enabled: false, keyFn: defaultDedupKey };
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
201
|
+
if (!opt) {
|
|
202
|
+
return { enabled: false, keyFn: defaultDedupKey, shareResult: undefined };
|
|
203
|
+
}
|
|
204
|
+
if (opt === true) {
|
|
205
|
+
return { enabled: true, keyFn: defaultDedupKey, shareResult: undefined };
|
|
206
|
+
}
|
|
207
|
+
return {
|
|
208
|
+
enabled: true,
|
|
209
|
+
keyFn: opt.keyFn ?? defaultDedupKey,
|
|
210
|
+
shareResult: opt.shareResult,
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Shallow detection of single-consumer values that must not be handed
|
|
215
|
+
* to more than one deduplication caller by reference:
|
|
216
|
+
*
|
|
217
|
+
* - Web `ReadableStream` (also matched structurally via `getReader`)
|
|
218
|
+
* - Node streams (`pipe`)
|
|
219
|
+
* - Async iterables (async generators, SDK stream wrappers) — plain
|
|
220
|
+
* arrays/strings/objects are sync-iterable at most, so they never match
|
|
221
|
+
* - `Response` with a non-null body (`fetch` responses; the body is a
|
|
222
|
+
* `ReadableStream` and `.json()`/`.text()` can be called once)
|
|
223
|
+
*
|
|
224
|
+
* Deliberately shallow: only the value itself is inspected, never
|
|
225
|
+
* nested properties. False negatives (a stream inside a wrapper
|
|
226
|
+
* object) fall back to today's share-by-reference behavior; false
|
|
227
|
+
* positives are limited to caller types that genuinely advertise
|
|
228
|
+
* stream/iterator protocols.
|
|
229
|
+
*/
|
|
230
|
+
function isUnsafeToShare(value) {
|
|
231
|
+
if (value === null || typeof value !== "object")
|
|
232
|
+
return false;
|
|
233
|
+
const v = value;
|
|
234
|
+
if (typeof globalThis.ReadableStream === "function" &&
|
|
235
|
+
value instanceof globalThis.ReadableStream) {
|
|
236
|
+
return true;
|
|
237
|
+
}
|
|
238
|
+
if (typeof v["getReader"] === "function")
|
|
239
|
+
return true;
|
|
240
|
+
if (typeof v["pipe"] === "function")
|
|
241
|
+
return true;
|
|
242
|
+
if (Symbol.asyncIterator in v)
|
|
243
|
+
return true;
|
|
244
|
+
if (typeof globalThis.Response === "function" &&
|
|
245
|
+
value instanceof globalThis.Response) {
|
|
246
|
+
return value.body !== null;
|
|
247
|
+
}
|
|
248
|
+
return false;
|
|
206
249
|
}
|
|
207
250
|
/**
|
|
208
251
|
* JSON.stringify with recursively sorted object keys, so structurally
|
|
@@ -317,6 +360,7 @@ function createLLMBulkhead(opts) {
|
|
|
317
360
|
admit: new Set(),
|
|
318
361
|
reject: new Set(),
|
|
319
362
|
release: new Set(),
|
|
363
|
+
usage: new Set(),
|
|
320
364
|
dedup: new Set(),
|
|
321
365
|
};
|
|
322
366
|
function emit(event, payload) {
|
|
@@ -351,11 +395,32 @@ function createLLMBulkhead(opts) {
|
|
|
351
395
|
return { promise, resolve, reject };
|
|
352
396
|
}
|
|
353
397
|
function estimateParts(request) {
|
|
398
|
+
assertOptionalNonNegativeInteger(request.max_tokens, "request.max_tokens");
|
|
354
399
|
if (!budget)
|
|
355
400
|
return null;
|
|
356
401
|
const estimate = estimator(request);
|
|
357
402
|
const reserved = validateTokenEstimate(estimate);
|
|
358
|
-
return {
|
|
403
|
+
return {
|
|
404
|
+
input: estimate.input,
|
|
405
|
+
maxOutput: estimate.maxOutput,
|
|
406
|
+
reserved,
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* Preview the exact token reservation that admission will calculate.
|
|
411
|
+
*
|
|
412
|
+
* This calls the same estimator and validation path as `acquire()`,
|
|
413
|
+
* `run()`, and `wouldAdmit()`. It does not reserve capacity. Returns
|
|
414
|
+
* `null` when `tokenBudget` is disabled because admission does not hold
|
|
415
|
+
* tokens in that mode.
|
|
416
|
+
*
|
|
417
|
+
* Custom estimators should be deterministic: if either the request or
|
|
418
|
+
* estimator output changes between `estimate()` and admission, the later
|
|
419
|
+
* admission will correctly use the newly calculated value.
|
|
420
|
+
*/
|
|
421
|
+
function estimate(request) {
|
|
422
|
+
const parts = estimateParts(request);
|
|
423
|
+
return parts === null ? null : { ...parts };
|
|
359
424
|
}
|
|
360
425
|
function resolvePriority(priority) {
|
|
361
426
|
if (priority === undefined)
|
|
@@ -487,6 +552,29 @@ function createLLMBulkhead(opts) {
|
|
|
487
552
|
emit("reject", { request, reason });
|
|
488
553
|
return new LLMBulkheadRejectedError(reason);
|
|
489
554
|
}
|
|
555
|
+
/**
|
|
556
|
+
* Deliver a shared in-flight result to a deduplication follower.
|
|
557
|
+
*
|
|
558
|
+
* - With a `shareResult` hook: the hook decides what the follower
|
|
559
|
+
* receives (called for every follower, safe results included).
|
|
560
|
+
* Hook exceptions propagate to the follower as-is.
|
|
561
|
+
* - Without a hook: single-consumer values (streams, `Response`
|
|
562
|
+
* bodies, async iterables) are refused with
|
|
563
|
+
* `"unshareable_result"` instead of being handed out by
|
|
564
|
+
* reference — a locked stream downstream is a silent correctness
|
|
565
|
+
* bug; a typed rejection at the bulkhead is actionable.
|
|
566
|
+
*
|
|
567
|
+
* The leader never passes through this function.
|
|
568
|
+
*/
|
|
569
|
+
function deliverShared(value, request) {
|
|
570
|
+
if (dedup.shareResult) {
|
|
571
|
+
return dedup.shareResult(value);
|
|
572
|
+
}
|
|
573
|
+
if (isUnsafeToShare(value)) {
|
|
574
|
+
throw noteDedupWaitRejection(request, "unshareable_result");
|
|
575
|
+
}
|
|
576
|
+
return value;
|
|
577
|
+
}
|
|
490
578
|
/**
|
|
491
579
|
* Wait on another caller's in-flight shared call.
|
|
492
580
|
*
|
|
@@ -509,7 +597,7 @@ function createLLMBulkhead(opts) {
|
|
|
509
597
|
return Promise.reject(noteDedupWaitRejection(request, "aborted"));
|
|
510
598
|
}
|
|
511
599
|
if (signal === undefined && effectiveTimeoutMs === undefined) {
|
|
512
|
-
return shared;
|
|
600
|
+
return shared.then((value) => deliverShared(value, request));
|
|
513
601
|
}
|
|
514
602
|
return new Promise((resolve, reject) => {
|
|
515
603
|
let timeoutId;
|
|
@@ -543,7 +631,14 @@ function createLLMBulkhead(opts) {
|
|
|
543
631
|
});
|
|
544
632
|
}, effectiveTimeoutMs);
|
|
545
633
|
}
|
|
546
|
-
void shared.then((value) => settle(() =>
|
|
634
|
+
void shared.then((value) => settle(() => {
|
|
635
|
+
try {
|
|
636
|
+
resolve(deliverShared(value, request));
|
|
637
|
+
}
|
|
638
|
+
catch (err) {
|
|
639
|
+
reject(err);
|
|
640
|
+
}
|
|
641
|
+
}), (err) => settle(() => reject(err)));
|
|
547
642
|
});
|
|
548
643
|
}
|
|
549
644
|
/**
|
|
@@ -551,18 +646,24 @@ function createLLMBulkhead(opts) {
|
|
|
551
646
|
* reservation and optionally applies the refund, and so that
|
|
552
647
|
* streaming callers can report cumulative usage mid-flight.
|
|
553
648
|
*/
|
|
554
|
-
function wrapToken(base, parts, request) {
|
|
649
|
+
function wrapToken(base, parts, request, admissionId, priority) {
|
|
555
650
|
let released = false;
|
|
556
651
|
/** Tokens currently held against the budget for this request. */
|
|
557
652
|
let held = parts?.reserved ?? 0;
|
|
558
653
|
/** Last reported cumulative usage (monotonically clamped). */
|
|
559
654
|
let reported;
|
|
655
|
+
/** Monotonic sequence of effective pre-release usage updates. */
|
|
656
|
+
let usageSequence = 0;
|
|
657
|
+
/** Public copy: callers cannot mutate internal accounting parts. */
|
|
658
|
+
const reservation = parts === null ? null : Object.freeze({ ...parts });
|
|
560
659
|
const snapshot = () => {
|
|
561
660
|
const consumed = reported
|
|
562
661
|
? reported.input + reported.output
|
|
563
662
|
: 0;
|
|
564
|
-
const outputCap = parts ? parts.
|
|
663
|
+
const outputCap = parts ? parts.maxOutput : null;
|
|
565
664
|
return {
|
|
665
|
+
admissionId,
|
|
666
|
+
sequence: usageSequence,
|
|
566
667
|
reserved: parts?.reserved ?? 0,
|
|
567
668
|
held,
|
|
568
669
|
consumed,
|
|
@@ -575,20 +676,25 @@ function createLLMBulkhead(opts) {
|
|
|
575
676
|
};
|
|
576
677
|
const reportUsage = (usage) => {
|
|
577
678
|
const valid = validateTokenUsage(usage);
|
|
679
|
+
const previousReported = reported;
|
|
578
680
|
// Clamp to monotonic non-decreasing per field — cumulative
|
|
579
681
|
// stream usage never shrinks; a lower report is stale.
|
|
580
|
-
reported =
|
|
682
|
+
reported = previousReported
|
|
581
683
|
? {
|
|
582
|
-
input: Math.max(
|
|
583
|
-
output: Math.max(
|
|
684
|
+
input: Math.max(previousReported.input, valid.input),
|
|
685
|
+
output: Math.max(previousReported.output, valid.output),
|
|
584
686
|
}
|
|
585
687
|
: valid;
|
|
688
|
+
const usageChanged = previousReported === undefined ||
|
|
689
|
+
reported.input !== previousReported.input ||
|
|
690
|
+
reported.output !== previousReported.output;
|
|
691
|
+
const previousHeldTokens = held;
|
|
586
692
|
// Accounting only applies pre-release with a budget configured.
|
|
587
693
|
if (!released && parts && budget) {
|
|
588
694
|
// Hold = known input + the larger of (output ceiling, actual output).
|
|
589
695
|
// Keeps the full output reservation while refunding input
|
|
590
696
|
// over-estimates immediately; expands on output overrun.
|
|
591
|
-
const newHold = reported.input + Math.max(parts.
|
|
697
|
+
const newHold = reported.input + Math.max(parts.maxOutput, reported.output);
|
|
592
698
|
const delta = newHold - held;
|
|
593
699
|
if (delta > 0) {
|
|
594
700
|
inFlightTokens += delta;
|
|
@@ -601,9 +707,31 @@ function createLLMBulkhead(opts) {
|
|
|
601
707
|
}
|
|
602
708
|
held = newHold;
|
|
603
709
|
}
|
|
604
|
-
|
|
710
|
+
if (!released && usageChanged) {
|
|
711
|
+
usageSequence++;
|
|
712
|
+
}
|
|
713
|
+
const report = snapshot();
|
|
714
|
+
if (!released && usageChanged) {
|
|
715
|
+
emit("usage", {
|
|
716
|
+
request,
|
|
717
|
+
admissionId,
|
|
718
|
+
priority,
|
|
719
|
+
sequence: usageSequence,
|
|
720
|
+
reservedTokens: parts?.reserved ?? 0,
|
|
721
|
+
previousHeldTokens,
|
|
722
|
+
heldTokens: held,
|
|
723
|
+
deltaTokens: held - previousHeldTokens,
|
|
724
|
+
usage: { ...reported },
|
|
725
|
+
outputCap: report.outputCap,
|
|
726
|
+
outputRemaining: report.outputRemaining,
|
|
727
|
+
overReservation: report.overReservation,
|
|
728
|
+
});
|
|
729
|
+
}
|
|
730
|
+
return report;
|
|
605
731
|
};
|
|
606
732
|
return {
|
|
733
|
+
admissionId,
|
|
734
|
+
reservation,
|
|
607
735
|
reportUsage,
|
|
608
736
|
release(usage) {
|
|
609
737
|
if (released)
|
|
@@ -638,8 +766,12 @@ function createLLMBulkhead(opts) {
|
|
|
638
766
|
noteLLMRelease();
|
|
639
767
|
emit("release", {
|
|
640
768
|
request,
|
|
769
|
+
admissionId,
|
|
770
|
+
priority,
|
|
641
771
|
reservedTokens: parts?.reserved ?? 0,
|
|
772
|
+
heldTokens: heldAtRelease,
|
|
642
773
|
refundedTokens: refunded,
|
|
774
|
+
usageSequence,
|
|
643
775
|
...(validUsage !== undefined && { usage: validUsage }),
|
|
644
776
|
});
|
|
645
777
|
}
|
|
@@ -650,7 +782,6 @@ function createLLMBulkhead(opts) {
|
|
|
650
782
|
}
|
|
651
783
|
// ---- Internal acquire ----
|
|
652
784
|
async function _acquire(request, ao) {
|
|
653
|
-
assertOptionalNonNegativeInteger(request.max_tokens, "request.max_tokens");
|
|
654
785
|
const priority = resolvePriority(ao.priority);
|
|
655
786
|
const parts = estimateParts(request);
|
|
656
787
|
const reserved = parts?.reserved ?? 0;
|
|
@@ -674,9 +805,16 @@ function createLLMBulkhead(opts) {
|
|
|
674
805
|
r.token.release();
|
|
675
806
|
return rejectWith("budget_limit");
|
|
676
807
|
}
|
|
808
|
+
const admissionId = (0, node_crypto_1.randomUUID)();
|
|
809
|
+
const token = wrapToken(r.token, parts, request, admissionId, priority);
|
|
677
810
|
noteLLMAdmit();
|
|
678
|
-
emit("admit", { request, reservedTokens: reserved });
|
|
679
|
-
return {
|
|
811
|
+
emit("admit", { request, admissionId, priority, reservedTokens: reserved });
|
|
812
|
+
return {
|
|
813
|
+
ok: true,
|
|
814
|
+
admissionId,
|
|
815
|
+
reservation: token.reservation,
|
|
816
|
+
token,
|
|
817
|
+
};
|
|
680
818
|
}
|
|
681
819
|
// ---- Public API ----
|
|
682
820
|
/**
|
|
@@ -733,10 +871,10 @@ function createLLMBulkhead(opts) {
|
|
|
733
871
|
* timeout) does not apply to that wait.
|
|
734
872
|
*/
|
|
735
873
|
async function run(request, fn, ao = {}) {
|
|
736
|
-
const { getUsage, dedupScope, ...acquireOpts } = ao;
|
|
874
|
+
const { getUsage, dedupScope, dedup: perCallDedup, ...acquireOpts } = ao;
|
|
737
875
|
// ---- Deduplication ----
|
|
738
876
|
let dedupKey = "";
|
|
739
|
-
if (dedup.enabled) {
|
|
877
|
+
if (dedup.enabled && perCallDedup !== false) {
|
|
740
878
|
let rawKey;
|
|
741
879
|
try {
|
|
742
880
|
rawKey = dedup.keyFn(request);
|
|
@@ -779,6 +917,8 @@ function createLLMBulkhead(opts) {
|
|
|
779
917
|
throw new LLMBulkheadRejectedError(r.reason, r.detail);
|
|
780
918
|
}
|
|
781
919
|
const ctx = {
|
|
920
|
+
admissionId: r.admissionId,
|
|
921
|
+
reservation: r.reservation,
|
|
782
922
|
reportUsage: (usage) => r.token.reportUsage(usage),
|
|
783
923
|
};
|
|
784
924
|
const work = (async () => {
|
|
@@ -880,6 +1020,16 @@ function createLLMBulkhead(opts) {
|
|
|
880
1020
|
listeners[event].delete(listener);
|
|
881
1021
|
};
|
|
882
1022
|
}
|
|
883
|
-
return {
|
|
1023
|
+
return {
|
|
1024
|
+
estimate,
|
|
1025
|
+
acquire,
|
|
1026
|
+
run,
|
|
1027
|
+
wouldAdmit,
|
|
1028
|
+
stats,
|
|
1029
|
+
setBudget,
|
|
1030
|
+
close,
|
|
1031
|
+
drain,
|
|
1032
|
+
on,
|
|
1033
|
+
};
|
|
884
1034
|
}
|
|
885
1035
|
//# sourceMappingURL=index.cjs.map
|