async-bulkhead-llm 3.8.0 → 3.9.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 CHANGED
@@ -17,6 +17,7 @@ Designed for services that need to enforce **cost ceilings, concurrency limits,
17
17
  - ✅ **Full-request estimation** — `system` prompts counted natively; `extraInputTokens` carries caller-computed costs (tool schemas, provider-priced media)
18
18
  - ✅ **Per-call reservation override** — gateways with their own estimate can bypass the estimator via `reservation` on `acquire()`/`run()`/`wouldAdmit()`
19
19
  - ✅ **Fail-fast by default** — shed load early, never silently queue
20
+ - ✅ **Observe/shadow mode** — measure capacity-policy impact while still executing selected would-be-rejected calls
20
21
  - ✅ **Opinionated profiles** — `'interactive'` and `'batch'` presets with escape hatch
21
22
  - ✅ **In-flight deduplication** — identical requests share one LLM call; hashed keys, whole-request equality
22
23
  - ✅ **Custom dedup key + per-tenant scope** — bring your own equivalence function; `dedupScope` isolates tenants
@@ -26,7 +27,7 @@ Designed for services that need to enforce **cost ceilings, concurrency limits,
26
27
  - ✅ **Advisory capacity snapshots** — `wouldAdmit(request, { detail: true })` returns the same capacity numbers rejections carry
27
28
  - ✅ **Stable admission IDs** — correlate gateway requests, traces, usage, and release
28
29
  - ✅ **Ordered usage events** — sequence-numbered hold changes for external coordinators
29
- - ✅ **Event hooks** — `on('admit' | 'reject' | 'usage' | 'release' | 'dedup', fn)`
30
+ - ✅ **Event hooks** — admitted and bypassed lifecycles have separate telemetry events
30
31
  - ✅ **Graceful shutdown** — `close()` + `drain()`, with an optional bounded wait: `drain({ timeoutMs })`
31
32
  - ✅ Optional **AbortSignal** and **timeout** cancellation
32
33
  - ✅ `bulkhead.run(request, fn)` — acquire + release handled automatically
@@ -55,6 +56,7 @@ Non-goals (by design):
55
56
  | **Concurrency limits** | ✅ Yes | ⚠️ Indirect | ❌ No | ✅ Yes | ⚠️ Indirect |
56
57
  | **Bounded queue (optional)** | ✅ Yes | ⚠️ Internal | ❌ No | ✅ Yes | ⚠️ Indirect |
57
58
  | **Fail-fast overload handling** | ✅ Core feature | ❌ No | ❌ No | ❌ No | ⚠️ Indirect |
59
+ | **Observe/shadow rollout mode** | ✅ Yes | ❌ No | ❌ No | ❌ No | ❌ No |
58
60
  | **In-flight deduplication** | ✅ Yes | ⚠️ Partial caching | ❌ No | ❌ No | ❌ No |
59
61
  | **Custom dedup key** | ✅ Yes | ❌ No | ❌ No | ❌ No | ❌ No |
60
62
  | **Model-aware estimation** | ✅ Yes | ❌ No | ❌ No | ❌ No | ❌ No |
@@ -130,6 +132,104 @@ const result = await bulkhead.run(request, async () => {
130
132
 
131
133
  ---
132
134
 
135
+ ## What's New in v3.9 — First-class observe mode
136
+
137
+ v3.9 adds an explicit rollout mode for measuring admission policy before fully
138
+ enforcing it. `run()` still attempts normal admission first. When a configured
139
+ capacity-related rejection occurs, observe mode executes the callback without
140
+ holding a concurrency slot or token reservation and records the bypass on a
141
+ separate telemetry surface.
142
+
143
+ ```ts
144
+ const result = await bulkhead.run(
145
+ request,
146
+ async (signal, ctx) => {
147
+ logger.info({
148
+ admissionId: ctx?.admissionId,
149
+ admission: ctx?.admission, // "admitted" | "bypassed"
150
+ bypassReason: ctx?.bypassReason, // set only for bypassed work
151
+ bypassDetail: ctx?.bypassDetail, // capacity snapshot, when available
152
+ });
153
+
154
+ return callYourLLMProvider(request, {
155
+ signal,
156
+ onUsage: (usage) => ctx?.reportUsage(usage),
157
+ });
158
+ },
159
+ { mode: "observe" },
160
+ );
161
+ ```
162
+
163
+ By default, observe mode may bypass these capacity outcomes:
164
+
165
+ ```ts
166
+ "budget_limit" | "concurrency_limit" | "queue_limit" | "timeout"
167
+ ```
168
+
169
+ Shutdown, caller cancellation, and unsafe deduplication fan-out remain hard
170
+ failures. Observe mode is therefore not a global "ignore every rejection"
171
+ switch.
172
+
173
+ ### Restrict which outcomes may be bypassed
174
+
175
+ Use `shadowReasons` to roll out one policy at a time:
176
+
177
+ ```ts
178
+ await bulkhead.run(request, fn, {
179
+ mode: "observe",
180
+ shadowReasons: ["budget_limit"],
181
+ });
182
+ ```
183
+
184
+ An empty `shadowReasons` array keeps normal enforcement while still exposing
185
+ `ctx.admission === "admitted"` to callbacks.
186
+
187
+ ### Admitted and bypassed callback context
188
+
189
+ Normally admitted calls receive the same context with:
190
+
191
+ ```ts
192
+ ctx.admission === "admitted"
193
+ ctx.bypassReason === undefined
194
+ ```
195
+
196
+ Bypassed calls receive a `shadow-`-prefixed `admissionId`, the exact evaluated
197
+ reservation, the bypass reason, and the associated capacity detail. Their
198
+ `reportUsage()` snapshots always report `held: 0`, because observed work does
199
+ not consume bulkhead accounting capacity.
200
+
201
+ ### Separate observe telemetry
202
+
203
+ Bypassed work does not increment normal `admit`/`release` counters. It is
204
+ reported through:
205
+
206
+ ```ts
207
+ bulkhead.on("bypass", listener);
208
+ bulkhead.on("bypassUsage", listener);
209
+ bulkhead.on("bypassRelease", listener);
210
+
211
+ const observe = bulkhead.stats().observe;
212
+ // {
213
+ // bypassed,
214
+ // raceBypassed,
215
+ // bypassedByReason,
216
+ // usageReported,
217
+ // totalInputTokens,
218
+ // totalOutputTokens,
219
+ // }
220
+ ```
221
+
222
+ `raceBypassed` counts calls whose advisory check passed but whose authoritative
223
+ acquisition later rejected—for example, a queued request that timed out while
224
+ capacity changed. This makes preview-to-admission races visible instead of
225
+ silently merging them into ordinary bypasses.
226
+
227
+ > Observe mode intentionally allows work to proceed without capacity
228
+ > protection. Use it for policy calibration, migration, and audit periods—not
229
+ > as the steady-state overload posture of a saturated service.
230
+
231
+ ---
232
+
133
233
  ## What's New in v3.8 — Feedback and shutdown ergonomics
134
234
 
135
235
  ### Bounded drain
@@ -818,7 +918,14 @@ s.bulkhead.closed // true after close()
818
918
  s.llm.admitted
819
919
  s.llm.released
820
920
  s.llm.rejected
821
- s.llm.rejectedByReason?.budget_limit // true after close()
921
+ s.llm.rejectedByReason?.budget_limit
922
+
923
+ s.observe?.bypassed // v3.9: callbacks run without capacity
924
+ s.observe?.raceBypassed // advisory admit raced with rejection
925
+ s.observe?.bypassedByReason
926
+ s.observe?.usageReported
927
+ s.observe?.totalInputTokens
928
+ s.observe?.totalOutputTokens
822
929
 
823
930
  s.tokenBudget?.budget
824
931
  s.tokenBudget?.inFlightTokens
@@ -848,6 +955,17 @@ type LLMStats = {
848
955
  totalConsumed: number;
849
956
  totalRefunded: number;
850
957
  };
958
+ observe?: {
959
+ bypassed: number;
960
+ raceBypassed: number;
961
+ bypassedByReason: Partial<Record<
962
+ 'budget_limit' | 'concurrency_limit' | 'queue_limit' | 'timeout',
963
+ number
964
+ >>;
965
+ usageReported: number;
966
+ totalInputTokens: number;
967
+ totalOutputTokens: number;
968
+ };
851
969
  deduplication?: {
852
970
  active: number;
853
971
  hits: number;
@@ -875,6 +993,9 @@ off();
875
993
  | `reject` | `{ request, reason, detail? }` |
876
994
  | `usage` | `{ request, admissionId, priority, sequence, reservedTokens, previousHeldTokens, heldTokens, deltaTokens, usage, outputCap, outputRemaining, overReservation }` |
877
995
  | `release` | `{ request, admissionId, priority, reservedTokens, heldTokens, refundedTokens, usageSequence, usage? }` |
996
+ | `bypass` | `{ request, admissionId, priority, reason, detail?, reservation, raced }` |
997
+ | `bypassUsage` | `{ request, admissionId, priority, reason, sequence, reservation, usage, outputCap, outputRemaining, overReservation }` |
998
+ | `bypassRelease` | `{ request, admissionId, priority, reason, reservation, usageSequence, usage? }` |
878
999
  | `dedup` | `{ request }` |
879
1000
 
880
1001
  Listeners are synchronous and fire-and-forget. Exceptions are silently caught.
@@ -931,15 +1052,26 @@ run<T>(
931
1052
  timeoutMs?: number; // integer >= 0
932
1053
  priority?: 'normal' | 'high';
933
1054
  getUsage?: (result: T) => TokenUsage | undefined;
1055
+ mode?: 'enforce' | 'observe'; // default: 'enforce' (v3.9)
1056
+ shadowReasons?: readonly (
1057
+ | 'budget_limit'
1058
+ | 'concurrency_limit'
1059
+ | 'queue_limit'
1060
+ | 'timeout'
1061
+ )[];
934
1062
  dedupScope?: string; // dedup isolation scope (e.g. tenant / API key)
935
1063
  dedup?: boolean; // false = opt this call out of dedup (v3.5)
936
1064
  },
937
1065
  ): Promise<T>
938
1066
  ```
939
1067
 
940
- `ctx.admissionId` is the stable admission identifier. `ctx.reservation` is
941
- the exact reservation used at admission (or `null` when token budgeting is
942
- disabled), and `ctx.reportUsage()` reports cumulative streaming usage.
1068
+ `ctx.admissionId` is the stable execution identifier. In observe-mode
1069
+ bypasses it uses a `shadow-` prefix. `ctx.reservation` is the exact evaluated
1070
+ reservation (or `null` when token budgeting is disabled),
1071
+ `ctx.admission` distinguishes `"admitted"` from `"bypassed"`, and
1072
+ `ctx.bypassReason` / `ctx.bypassDetail` describe a bypass.
1073
+ `ctx.reportUsage()` reports cumulative streaming usage; bypassed usage is
1074
+ recorded for telemetry but never changes bulkhead capacity accounting.
943
1075
 
944
1076
  ### `bulkhead.estimate(request)`
945
1077
 
@@ -13,6 +13,13 @@ const profiles_js_1 = require("./profiles.cjs");
13
13
  const estimators_js_1 = require("./estimators.cjs");
14
14
  const validation_js_1 = require("./validation.cjs");
15
15
  const dedup_js_1 = require("./dedup.cjs");
16
+ const DEFAULT_SHADOW_REASONS = [
17
+ "budget_limit",
18
+ "concurrency_limit",
19
+ "queue_limit",
20
+ "timeout",
21
+ ];
22
+ const SHADOWABLE_REASONS = new Set(DEFAULT_SHADOW_REASONS);
16
23
  // ────────────────────────────────────────────
17
24
  // Option resolution
18
25
  // ────────────────────────────────────────────
@@ -78,9 +85,16 @@ function createLLMBulkhead(opts) {
78
85
  let llmReleased = 0;
79
86
  let llmRejected = 0;
80
87
  const llmRejectedByReason = {};
88
+ let observeBypassed = 0;
89
+ let observeRaceBypassed = 0;
90
+ const observeBypassedByReason = {};
91
+ let observeUsageReported = 0;
92
+ let observeTotalInputTokens = 0;
93
+ let observeTotalOutputTokens = 0;
81
94
  // ---- Deduplication state ----
82
95
  const dedup = (0, dedup_js_1.resolveDedup)(opts.deduplication);
83
96
  const dedupMap = new Map();
97
+ const dedupWaitErrors = new WeakSet();
84
98
  let dedupHits = 0;
85
99
  // ---- Event emitter state ----
86
100
  const listeners = {
@@ -88,6 +102,9 @@ function createLLMBulkhead(opts) {
88
102
  reject: new Set(),
89
103
  release: new Set(),
90
104
  usage: new Set(),
105
+ bypass: new Set(),
106
+ bypassUsage: new Set(),
107
+ bypassRelease: new Set(),
91
108
  dedup: new Set(),
92
109
  };
93
110
  function emit(event, payload) {
@@ -188,6 +205,32 @@ function createLLMBulkhead(opts) {
188
205
  }
189
206
  return priority;
190
207
  }
208
+ function resolveAdmissionMode(mode) {
209
+ if (mode === undefined)
210
+ return "enforce";
211
+ if (mode !== "enforce" && mode !== "observe") {
212
+ throw new Error(`mode must be "enforce" or "observe"`);
213
+ }
214
+ return mode;
215
+ }
216
+ function resolveShadowReasons(reasons) {
217
+ if (reasons === undefined)
218
+ return SHADOWABLE_REASONS;
219
+ const resolved = new Set();
220
+ for (const reason of reasons) {
221
+ if (!SHADOWABLE_REASONS.has(reason)) {
222
+ throw new Error(`shadowReasons may contain only budget_limit, concurrency_limit, ` +
223
+ `queue_limit, or timeout`);
224
+ }
225
+ resolved.add(reason);
226
+ }
227
+ return resolved;
228
+ }
229
+ function resolveAdmission(request, ao) {
230
+ const priority = resolvePriority(ao.priority);
231
+ const parts = resolveReservation(request, ao.reservation);
232
+ return { priority, parts, reserved: parts?.reserved ?? 0 };
233
+ }
191
234
  /**
192
235
  * Budget ceiling applicable to a request at the given priority.
193
236
  *
@@ -267,6 +310,32 @@ function createLLMBulkhead(opts) {
267
310
  }
268
311
  return detail;
269
312
  }
313
+ function wouldAdmitResolved(admission, includeDetail) {
314
+ const { priority, reserved } = admission;
315
+ const withDetail = (result) => {
316
+ if (includeDetail) {
317
+ result.detail = buildRejectDetail(reserved, priority);
318
+ }
319
+ return result;
320
+ };
321
+ const base = bulkhead.stats();
322
+ if (base.closed) {
323
+ return withDetail({ admit: false, reason: "shutdown" });
324
+ }
325
+ if (budget && inFlightTokens + reserved > effectiveBudget(priority)) {
326
+ return withDetail({ admit: false, reason: "budget_limit" });
327
+ }
328
+ if (base.inFlight < base.maxConcurrent) {
329
+ return withDetail({ admit: true });
330
+ }
331
+ if (base.pending < base.maxQueue) {
332
+ return withDetail({ admit: true });
333
+ }
334
+ return withDetail({
335
+ admit: false,
336
+ reason: base.maxQueue > 0 ? "queue_limit" : "concurrency_limit",
337
+ });
338
+ }
270
339
  /**
271
340
  * Update the token budget ceiling at runtime.
272
341
  *
@@ -308,7 +377,9 @@ function createLLMBulkhead(opts) {
308
377
  function noteDedupWaitRejection(request, reason) {
309
378
  noteLLMReject(reason);
310
379
  emit("reject", { request, reason });
311
- return new errors_js_1.LLMBulkheadRejectedError(reason);
380
+ const error = new errors_js_1.LLMBulkheadRejectedError(reason);
381
+ dedupWaitErrors.add(error);
382
+ return error;
312
383
  }
313
384
  /**
314
385
  * Deliver a shared in-flight result to a deduplication follower.
@@ -539,10 +610,8 @@ function createLLMBulkhead(opts) {
539
610
  };
540
611
  }
541
612
  // ---- Internal acquire ----
542
- async function _acquire(request, ao) {
543
- const priority = resolvePriority(ao.priority);
544
- const parts = resolveReservation(request, ao.reservation);
545
- const reserved = parts?.reserved ?? 0;
613
+ async function _acquire(request, ao, resolved = resolveAdmission(request, ao)) {
614
+ const { priority, parts, reserved } = resolved;
546
615
  const rejectWith = (reason) => {
547
616
  const detail = buildRejectDetail(reserved, priority);
548
617
  noteLLMReject(reason);
@@ -610,32 +679,138 @@ function createLLMBulkhead(opts) {
610
679
  * request now throws even when the bulkhead is closed.
611
680
  */
612
681
  function wouldAdmit(request, opts = {}) {
613
- const priority = resolvePriority(opts.priority);
614
- const parts = resolveReservation(request, opts.reservation);
615
- const reserved = parts?.reserved ?? 0;
616
- const withDetail = (result) => {
617
- if (opts.detail === true) {
618
- result.detail = buildRejectDetail(reserved, priority);
682
+ return wouldAdmitResolved(resolveAdmission(request, opts), opts.detail === true);
683
+ }
684
+ function shouldBypass(reason, configured) {
685
+ return (SHADOWABLE_REASONS.has(reason) &&
686
+ configured.has(reason));
687
+ }
688
+ async function runBypassed(request, fn, opts, admission, reason, detail, raced) {
689
+ const hardReason = opts.signal?.aborted
690
+ ? "aborted"
691
+ : bulkhead.stats().closed
692
+ ? "shutdown"
693
+ : undefined;
694
+ if (hardReason !== undefined) {
695
+ const hardDetail = buildRejectDetail(admission.reserved, admission.priority);
696
+ noteLLMReject(hardReason);
697
+ emit("reject", { request, reason: hardReason, detail: hardDetail });
698
+ throw new errors_js_1.LLMBulkheadRejectedError(hardReason, hardDetail);
699
+ }
700
+ const admissionId = `shadow-${(0, node_crypto_1.randomUUID)()}`;
701
+ const reservation = admission.parts === null
702
+ ? null
703
+ : Object.freeze({ ...admission.parts });
704
+ let reported;
705
+ let usageSequence = 0;
706
+ let settled = false;
707
+ observeBypassed++;
708
+ if (raced)
709
+ observeRaceBypassed++;
710
+ observeBypassedByReason[reason] =
711
+ (observeBypassedByReason[reason] ?? 0) + 1;
712
+ emit("bypass", {
713
+ request,
714
+ admissionId,
715
+ priority: admission.priority,
716
+ reason,
717
+ ...(detail !== undefined && { detail }),
718
+ reservation,
719
+ raced,
720
+ });
721
+ const snapshot = () => {
722
+ const consumed = reported ? reported.input + reported.output : 0;
723
+ const outputCap = admission.parts?.maxOutput ?? null;
724
+ return {
725
+ admissionId,
726
+ sequence: usageSequence,
727
+ reserved: admission.reserved,
728
+ held: 0,
729
+ consumed,
730
+ outputCap,
731
+ outputRemaining: outputCap === null
732
+ ? null
733
+ : Math.max(0, outputCap - (reported?.output ?? 0)),
734
+ overReservation: admission.parts !== null && consumed > admission.parts.reserved,
735
+ };
736
+ };
737
+ const reportUsage = (usage) => {
738
+ const valid = (0, validation_js_1.validateTokenUsage)(usage);
739
+ const previous = reported;
740
+ reported = previous
741
+ ? {
742
+ input: Math.max(previous.input, valid.input),
743
+ output: Math.max(previous.output, valid.output),
744
+ }
745
+ : valid;
746
+ const changed = previous === undefined ||
747
+ reported.input !== previous.input ||
748
+ reported.output !== previous.output;
749
+ if (!settled && changed) {
750
+ usageSequence++;
751
+ const current = snapshot();
752
+ emit("bypassUsage", {
753
+ request,
754
+ admissionId,
755
+ priority: admission.priority,
756
+ reason,
757
+ sequence: usageSequence,
758
+ reservation,
759
+ usage: { ...reported },
760
+ outputCap: current.outputCap,
761
+ outputRemaining: current.outputRemaining,
762
+ overReservation: current.overReservation,
763
+ });
619
764
  }
620
- return result;
765
+ return snapshot();
621
766
  };
622
- const base = bulkhead.stats();
623
- if (base.closed) {
624
- return withDetail({ admit: false, reason: "shutdown" });
625
- }
626
- if (budget && inFlightTokens + reserved > effectiveBudget(priority)) {
627
- return withDetail({ admit: false, reason: "budget_limit" });
628
- }
629
- if (base.inFlight < base.maxConcurrent) {
630
- return withDetail({ admit: true });
767
+ const context = {
768
+ admissionId,
769
+ reservation,
770
+ admission: "bypassed",
771
+ bypassReason: reason,
772
+ ...(detail !== undefined && { bypassDetail: detail }),
773
+ reportUsage,
774
+ };
775
+ const finish = (usage) => {
776
+ if (settled)
777
+ return;
778
+ settled = true;
779
+ if (usage !== undefined) {
780
+ observeUsageReported++;
781
+ observeTotalInputTokens += usage.input;
782
+ observeTotalOutputTokens += usage.output;
783
+ }
784
+ emit("bypassRelease", {
785
+ request,
786
+ admissionId,
787
+ priority: admission.priority,
788
+ reason,
789
+ reservation,
790
+ usageSequence,
791
+ ...(usage !== undefined && { usage }),
792
+ });
793
+ };
794
+ try {
795
+ const result = await fn(opts.signal, context);
796
+ let finalUsage;
797
+ if (opts.getUsage !== undefined) {
798
+ try {
799
+ const extracted = opts.getUsage(result);
800
+ finalUsage =
801
+ extracted === undefined ? undefined : (0, validation_js_1.validateTokenUsage)(extracted);
802
+ }
803
+ catch {
804
+ // A bad extractor must not turn observed work into a failure.
805
+ }
806
+ }
807
+ finish(finalUsage ?? reported);
808
+ return result;
631
809
  }
632
- if (base.pending < base.maxQueue) {
633
- return withDetail({ admit: true });
810
+ catch (error) {
811
+ finish(reported);
812
+ throw error;
634
813
  }
635
- return withDetail({
636
- admit: false,
637
- reason: base.maxQueue > 0 ? "queue_limit" : "concurrency_limit",
638
- });
639
814
  }
640
815
  /**
641
816
  * Primary API. Acquire → call `fn` → release, automatically.
@@ -654,7 +829,9 @@ function createLLMBulkhead(opts) {
654
829
  * timeout) does not apply to that wait.
655
830
  */
656
831
  async function run(request, fn, ao = {}) {
657
- const { getUsage, dedupScope, dedup: perCallDedup, ...acquireOpts } = ao;
832
+ const { getUsage, mode: requestedMode, shadowReasons: requestedShadowReasons, dedupScope, dedup: perCallDedup, ...acquireOpts } = ao;
833
+ const mode = resolveAdmissionMode(requestedMode);
834
+ const shadowReasons = resolveShadowReasons(requestedShadowReasons);
658
835
  // ---- Deduplication ----
659
836
  let dedupKey = "";
660
837
  if (dedup.enabled && perCallDedup !== false) {
@@ -677,7 +854,21 @@ function createLLMBulkhead(opts) {
677
854
  if (existing) {
678
855
  dedupHits++;
679
856
  emit("dedup", { request });
680
- return waitForSharedDedup(existing, request, acquireOpts);
857
+ try {
858
+ return await waitForSharedDedup(existing, request, acquireOpts);
859
+ }
860
+ catch (error) {
861
+ if (mode === "observe" &&
862
+ error instanceof errors_js_1.LLMBulkheadRejectedError &&
863
+ dedupWaitErrors.has(error) &&
864
+ shouldBypass(error.reason, shadowReasons)) {
865
+ return runBypassed(request, fn, {
866
+ ...(ao.signal !== undefined && { signal: ao.signal }),
867
+ ...(getUsage !== undefined && { getUsage }),
868
+ }, resolveAdmission(request, acquireOpts), error.reason, error.detail, false);
869
+ }
870
+ throw error;
871
+ }
681
872
  }
682
873
  deferred = createDeferred();
683
874
  resultPromise = deferred.promise;
@@ -694,14 +885,42 @@ function createLLMBulkhead(opts) {
694
885
  };
695
886
  void deferred.promise.then(cleanup, cleanup);
696
887
  }
888
+ const publish = (work) => {
889
+ if (deferred) {
890
+ void work.then((value) => deferred.resolve(value), (error) => deferred.reject(error));
891
+ return resultPromise;
892
+ }
893
+ return work;
894
+ };
697
895
  try {
698
- const r = await _acquire(request, acquireOpts);
896
+ let resolved;
897
+ let advisory;
898
+ if (mode === "observe") {
899
+ resolved = resolveAdmission(request, acquireOpts);
900
+ advisory = wouldAdmitResolved(resolved, true);
901
+ if (!advisory.admit &&
902
+ advisory.reason !== undefined &&
903
+ shouldBypass(advisory.reason, shadowReasons)) {
904
+ return publish(runBypassed(request, fn, {
905
+ ...(ao.signal !== undefined && { signal: ao.signal }),
906
+ ...(getUsage !== undefined && { getUsage }),
907
+ }, resolved, advisory.reason, advisory.detail, false));
908
+ }
909
+ }
910
+ const r = await _acquire(request, acquireOpts, resolved);
699
911
  if (!r.ok) {
912
+ if (mode === "observe" && shouldBypass(r.reason, shadowReasons)) {
913
+ return publish(runBypassed(request, fn, {
914
+ ...(ao.signal !== undefined && { signal: ao.signal }),
915
+ ...(getUsage !== undefined && { getUsage }),
916
+ }, resolved ?? resolveAdmission(request, acquireOpts), r.reason, r.detail, advisory?.admit === true));
917
+ }
700
918
  throw new errors_js_1.LLMBulkheadRejectedError(r.reason, r.detail);
701
919
  }
702
920
  const ctx = {
703
921
  admissionId: r.admissionId,
704
922
  reservation: r.reservation,
923
+ admission: "admitted",
705
924
  reportUsage: (usage) => r.token.reportUsage(usage),
706
925
  };
707
926
  const work = (async () => {
@@ -728,11 +947,7 @@ function createLLMBulkhead(opts) {
728
947
  r.token.release(usage);
729
948
  return result;
730
949
  })();
731
- if (deferred) {
732
- void work.then((v) => deferred.resolve(v), (e) => deferred.reject(e));
733
- return resultPromise;
734
- }
735
- return work;
950
+ return publish(work);
736
951
  }
737
952
  catch (err) {
738
953
  if (deferred) {
@@ -766,6 +981,16 @@ function createLLMBulkhead(opts) {
766
981
  highPriorityReserve,
767
982
  };
768
983
  }
984
+ if (observeBypassed > 0) {
985
+ result.observe = {
986
+ bypassed: observeBypassed,
987
+ raceBypassed: observeRaceBypassed,
988
+ bypassedByReason: { ...observeBypassedByReason },
989
+ usageReported: observeUsageReported,
990
+ totalInputTokens: observeTotalInputTokens,
991
+ totalOutputTokens: observeTotalOutputTokens,
992
+ };
993
+ }
769
994
  if (dedup.enabled) {
770
995
  result.deduplication = {
771
996
  active: dedupMap.size,