deepline 0.3.536 → 0.3.538

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 (204) hide show
  1. package/dist/bundling-sources/sdk/src/client-core.ts +22 -5
  2. package/dist/bundling-sources/sdk/src/index.ts +2 -0
  3. package/dist/bundling-sources/sdk/src/plays/client-core.ts +18 -1
  4. package/dist/bundling-sources/sdk/src/release.ts +1 -1
  5. package/dist/bundling-sources/sdk/src/runs/watch-polling.ts +33 -4
  6. package/dist/bundling-sources/shared_libs/integration-contracts/billing-entitlements.ts +1 -1
  7. package/dist/bundling-sources/shared_libs/observability/scheduled-jobs.json +36 -0
  8. package/dist/bundling-sources/shared_libs/play-runtime/app-runtime-api.ts +1 -0
  9. package/dist/bundling-sources/shared_libs/play-runtime/baked-runner-image.ts +330 -0
  10. package/dist/bundling-sources/shared_libs/play-runtime/context.ts +717 -133
  11. package/dist/bundling-sources/shared_libs/play-runtime/coordinator-headers.ts +7 -0
  12. package/dist/bundling-sources/shared_libs/play-runtime/daytona-payload-contract.ts +22 -1
  13. package/dist/bundling-sources/shared_libs/play-runtime/durable-runs-rollout.ts +123 -0
  14. package/dist/bundling-sources/shared_libs/play-runtime/experiment-switches.ts +480 -0
  15. package/dist/bundling-sources/shared_libs/play-runtime/fixture-egress-fetch.ts +24 -16
  16. package/dist/bundling-sources/shared_libs/play-runtime/freshness-receipt-execution.ts +293 -53
  17. package/dist/bundling-sources/shared_libs/play-runtime/governor/block-reserving-budget-state-backend.ts +57 -2
  18. package/dist/bundling-sources/shared_libs/play-runtime/governor/budget-state-backend.ts +43 -0
  19. package/dist/bundling-sources/shared_libs/play-runtime/governor/governor.ts +141 -9
  20. package/dist/bundling-sources/shared_libs/play-runtime/launch-identity.ts +2 -0
  21. package/dist/bundling-sources/shared_libs/play-runtime/modal-runtime-config.ts +6 -0
  22. package/dist/bundling-sources/shared_libs/play-runtime/modal-supervisor-sidecar.ts +556 -0
  23. package/dist/bundling-sources/shared_libs/play-runtime/protocol.ts +27 -0
  24. package/dist/bundling-sources/shared_libs/play-runtime/resource-governor.ts +19 -0
  25. package/dist/bundling-sources/shared_libs/play-runtime/run-ledger.ts +54 -0
  26. package/dist/bundling-sources/shared_libs/play-runtime/run-snapshot-stream.ts +5 -0
  27. package/dist/bundling-sources/shared_libs/play-runtime/runner-app/index.ts +155 -3
  28. package/dist/bundling-sources/shared_libs/play-runtime/runner-app/relay-connection-counter.ts +103 -0
  29. package/dist/bundling-sources/shared_libs/play-runtime/runner-app/runtime-heartbeat.ts +75 -6
  30. package/dist/bundling-sources/shared_libs/play-runtime/runner-app/runtime-terminal-push.ts +59 -0
  31. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona-payload-transport.ts +544 -73
  32. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona-runtime-watchdog.ts +8 -1
  33. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/detached-runner-readiness-pacing.ts +19 -1
  34. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/modal.ts +2390 -110
  35. package/dist/bundling-sources/shared_libs/play-runtime/runtime-flow.ts +42 -8
  36. package/dist/bundling-sources/shared_libs/play-runtime/runtime-read-through.ts +287 -0
  37. package/dist/bundling-sources/shared_libs/play-runtime/runtime-receipt-finish.ts +606 -0
  38. package/dist/bundling-sources/shared_libs/play-runtime/runtime-receipt-writer.ts +274 -119
  39. package/dist/bundling-sources/shared_libs/play-runtime/runtime-traffic-policy.ts +54 -0
  40. package/dist/bundling-sources/shared_libs/play-runtime/runtime-work-counters.ts +10 -1
  41. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backend.ts +15 -0
  42. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-play-run-task.ts +18 -1
  43. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-pool.ts +18 -4
  44. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-runtime-worker.ts +219 -7
  45. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-shared.ts +3 -0
  46. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/early-sandbox-claim-affinity.ts +340 -0
  47. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/play-run-recovery.ts +1 -0
  48. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres-progress.ts +10 -1
  49. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres-rate-state.ts +623 -7
  50. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres.ts +340 -5
  51. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runner-push.ts +61 -0
  52. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-event-search.ts +2 -1
  53. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-sandbox-ledger-reconciliation.ts +269 -2
  54. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-worker-wake.ts +238 -5
  55. package/dist/bundling-sources/shared_libs/play-runtime/startup-read-tool-ids.ts +47 -0
  56. package/dist/bundling-sources/shared_libs/play-runtime/tool-call/runtime-step-receipts-adapter.ts +5 -4
  57. package/dist/bundling-sources/shared_libs/play-runtime/tool-result.ts +6 -0
  58. package/dist/bundling-sources/shared_libs/play-runtime/transient-service-error.ts +11 -0
  59. package/dist/cli/auth-4WEVLYK4.js +43 -0
  60. package/dist/cli/{auth-KCTCUO7P.mjs → auth-KYH7N7RQ.mjs} +5 -5
  61. package/dist/cli/{billing-4VBGZ3CT.js → billing-4KTUVZ4S.js} +114 -90
  62. package/dist/cli/{billing-OOJHKLNS.mjs → billing-WK346KAI.mjs} +31 -7
  63. package/dist/cli/{chunk-4E5JXZ3W.js → chunk-25RGHJQL.js} +15 -15
  64. package/dist/cli/{chunk-MSP4DTSD.js → chunk-34PLG5OE.js} +13 -13
  65. package/dist/cli/{chunk-DQHUJMCL.mjs → chunk-35OCRH5C.mjs} +5 -5
  66. package/dist/cli/{chunk-2B4IOGFD.js → chunk-3I5TU5XE.js} +292 -279
  67. package/dist/cli/{chunk-Z7UIOGW4.mjs → chunk-4KZF6OYY.mjs} +3 -3
  68. package/dist/cli/{chunk-2YWJS76L.mjs → chunk-4NEOGPKD.mjs} +1 -1
  69. package/dist/cli/{chunk-LZXZQPA2.mjs → chunk-4WQR4DG4.mjs} +1 -1
  70. package/dist/cli/{chunk-KWYGWO4Y.js → chunk-5VSPRRTI.js} +7 -7
  71. package/dist/cli/{chunk-ANUKBZ6W.mjs → chunk-6JG3MRTM.mjs} +2 -2
  72. package/dist/cli/{chunk-VBDZIMWD.js → chunk-6SLQLWWL.js} +26 -26
  73. package/dist/cli/{chunk-E24UGPGG.mjs → chunk-7XDJKIM2.mjs} +4 -4
  74. package/dist/cli/{chunk-OUDTOMZC.mjs → chunk-A6E7TCK2.mjs} +5 -5
  75. package/dist/cli/{chunk-ZZ4MF2GI.js → chunk-ADLDU2QG.js} +6 -6
  76. package/dist/cli/{chunk-XVZRJJDS.mjs → chunk-ALARRSMZ.mjs} +3 -3
  77. package/dist/cli/{chunk-HWDKRN7L.js → chunk-B2BTBHX2.js} +3 -3
  78. package/dist/cli/{chunk-ZISEH7OL.js → chunk-BBS2BLPV.js} +16 -16
  79. package/dist/cli/{chunk-YRLAUGQY.mjs → chunk-CLO562KG.mjs} +3 -1
  80. package/dist/cli/{chunk-CXTW7SRW.mjs → chunk-E7D37PLM.mjs} +8 -0
  81. package/dist/cli/{chunk-SLPJ3LXI.js → chunk-ESX3H7Q7.js} +22 -22
  82. package/dist/cli/{chunk-AB2GBOD4.mjs → chunk-FJ5KPGCS.mjs} +10 -10
  83. package/dist/cli/{chunk-DUYAMLOC.mjs → chunk-FWE37N2P.mjs} +1 -1
  84. package/dist/cli/{chunk-3PCYV6ZJ.mjs → chunk-ICTA5ICE.mjs} +1 -1
  85. package/dist/cli/{chunk-ZILSRDIN.js → chunk-IMLFB66A.js} +3 -3
  86. package/dist/cli/{chunk-PNY3BWHP.mjs → chunk-IP3XJTWA.mjs} +2 -2
  87. package/dist/cli/{chunk-6VUGBQZQ.js → chunk-JCLRSMUP.js} +5 -5
  88. package/dist/cli/{chunk-YBMHOH6H.mjs → chunk-JPEBKN3K.mjs} +2 -2
  89. package/dist/cli/{chunk-GF32SBST.mjs → chunk-JTOV5RUA.mjs} +1 -1
  90. package/dist/cli/{chunk-Q5CXV3E3.js → chunk-KCUQNH4K.js} +2 -2
  91. package/dist/cli/{chunk-DA2I2M7D.mjs → chunk-KNIYEZVV.mjs} +2 -2
  92. package/dist/cli/{chunk-CWSLUNA6.js → chunk-LPTBHNGB.js} +7 -5
  93. package/dist/cli/{chunk-WC5M3JXE.mjs → chunk-M3NCXGNN.mjs} +2 -2
  94. package/dist/cli/{chunk-TX5TUHJN.js → chunk-MNBIGX6O.js} +10 -10
  95. package/dist/cli/{chunk-ZEV2Y56V.js → chunk-MYSPQUAO.js} +44 -44
  96. package/dist/cli/{chunk-KPQHUVYW.mjs → chunk-N2BCPZVR.mjs} +5 -5
  97. package/dist/cli/{chunk-XBAH3TKU.js → chunk-N5HSG4OV.js} +5 -5
  98. package/dist/cli/{chunk-GTVZKY3F.js → chunk-O765M4LT.js} +2 -2
  99. package/dist/cli/{chunk-2FCSUOYN.js → chunk-OOLBE6FR.js} +53 -53
  100. package/dist/cli/{chunk-W7AEIGZR.js → chunk-P3DP56HB.js} +41 -41
  101. package/dist/cli/{chunk-LN6RXDTB.js → chunk-PQKD5DMT.js} +19 -19
  102. package/dist/cli/{chunk-GHLDCLSC.mjs → chunk-T6GPTJ5F.mjs} +1 -1
  103. package/dist/cli/{chunk-XJD2GYUP.mjs → chunk-TWWYCJJW.mjs} +5 -5
  104. package/dist/cli/{chunk-BASLYGXK.mjs → chunk-UE7JHAZ2.mjs} +29 -16
  105. package/dist/cli/{chunk-Q4MNUOS4.js → chunk-UEZNIPFO.js} +107 -107
  106. package/dist/cli/{chunk-RVSSQPQO.mjs → chunk-VCHV4LS3.mjs} +1 -1
  107. package/dist/cli/{chunk-LDGZFDUB.js → chunk-VIFLWQXS.js} +2 -2
  108. package/dist/cli/{chunk-6BBGUQJJ.js → chunk-XTYHZEJ2.js} +8 -0
  109. package/dist/cli/{chunk-CIDN5K23.js → chunk-YQURGSRB.js} +1 -1
  110. package/dist/cli/{chunk-Y2NTPYGS.js → chunk-YZ2ZPHWR.js} +9 -9
  111. package/dist/cli/{chunk-HAJQGP5V.mjs → chunk-ZDLDCXY3.mjs} +2 -2
  112. package/dist/cli/{chunk-JUHDJNSI.mjs → chunk-ZU6JBRV5.mjs} +4 -4
  113. package/dist/cli/command-docs.js +2 -2
  114. package/dist/cli/command-docs.mjs +1 -1
  115. package/dist/cli/{csv-P3HLK4GO.mjs → csv-2YKLUKDR.mjs} +4 -4
  116. package/dist/cli/{csv-2V2DIFNG.js → csv-LM7FBECI.js} +13 -13
  117. package/dist/cli/{db-ZYOY3QRQ.mjs → db-234UBWJH.mjs} +6 -6
  118. package/dist/cli/{db-MREAQVW6.js → db-5PMA4IVW.js} +27 -27
  119. package/dist/cli/describe-C7GOSGYB.js +49 -0
  120. package/dist/cli/{describe-IKZFOADR.mjs → describe-W26LW5O7.mjs} +17 -17
  121. package/dist/cli/describe-core.d.mts +3 -3
  122. package/dist/cli/describe-core.d.ts +3 -3
  123. package/dist/cli/{executions-H5IJ7QSQ.js → executions-3S736GXX.js} +8 -8
  124. package/dist/cli/{executions-KTSY5M34.mjs → executions-GD7GXTJM.mjs} +6 -6
  125. package/dist/cli/{feedback-724QK3Z5.js → feedback-BUWTDY4R.js} +14 -14
  126. package/dist/cli/{feedback-WWJRIXEU.mjs → feedback-GBV5HJJZ.mjs} +6 -6
  127. package/dist/cli/git-YG36MROC.js +25 -0
  128. package/dist/cli/{git-R5VRG7X6.mjs → git-YXJGTDQL.mjs} +5 -5
  129. package/dist/cli/index.js +143 -143
  130. package/dist/cli/index.mjs +42 -42
  131. package/dist/cli/{legacy-noops-PWZ5XLAO.mjs → legacy-noops-UJM6GBNP.mjs} +6 -6
  132. package/dist/cli/{legacy-noops-C6GDEGPU.js → legacy-noops-ZSF64V2U.js} +9 -9
  133. package/dist/cli/{monitors-WQSKMHAP.mjs → monitors-UERUQ6CT.mjs} +7 -7
  134. package/dist/cli/{monitors-VAVQ4WCE.js → monitors-XQ2GNH6D.js} +100 -100
  135. package/dist/cli/{org-MAL4QPVF.mjs → org-CP4VLH6M.mjs} +6 -6
  136. package/dist/cli/{org-CWWRWXZQ.js → org-IF6MPVNR.js} +86 -86
  137. package/dist/cli/{play-WJOWK5PQ.js → play-2NHQO5MO.js} +317 -317
  138. package/dist/cli/{play-ILW6MSNG.mjs → play-ZWDYYVPI.mjs} +17 -17
  139. package/dist/cli/{providers-4V2NMLZZ.mjs → providers-2CVIATU4.mjs} +6 -6
  140. package/dist/cli/{providers-W662ANCH.js → providers-LOPXQN56.js} +9 -9
  141. package/dist/cli/{quickstart-C22BR743.mjs → quickstart-KVCFXLID.mjs} +4 -4
  142. package/dist/cli/{quickstart-BW6EBUYX.js → quickstart-N4WDEQZY.js} +6 -6
  143. package/dist/cli/{run-KW7KW4FX.js → run-BDT5LK3I.js} +42 -42
  144. package/dist/cli/{run-SPAU5IMW.mjs → run-RUXHYWLF.mjs} +22 -22
  145. package/dist/cli/search-ATDDVADT.js +32 -0
  146. package/dist/cli/{search-XPC75HLM.mjs → search-BFUTNPA5.mjs} +7 -7
  147. package/dist/cli/{search-output-VJYE7USJ.js → search-output-CTXI2QZU.js} +6 -6
  148. package/dist/cli/{search-output-JKYJSEPM.mjs → search-output-WUGH4PZA.mjs} +4 -4
  149. package/dist/cli/{secrets-YB57KGSB.js → secrets-BZJZYFOU.js} +15 -15
  150. package/dist/cli/{secrets-OJG73GXQ.mjs → secrets-Z4XQVTC6.mjs} +6 -6
  151. package/dist/cli/sessions-HNU35AFM.js +22 -0
  152. package/dist/cli/{sessions-7ZL37BW4.mjs → sessions-VZXR3MQZ.mjs} +6 -6
  153. package/dist/cli/{settings-RKSQB7FA.mjs → settings-VYEZFR4L.mjs} +12 -12
  154. package/dist/cli/{settings-A7DD2ZYE.js → settings-WBYA4JMM.js} +85 -85
  155. package/dist/cli/{setup-S3K5YU62.js → setup-FS2RMSS2.js} +49 -49
  156. package/dist/cli/{setup-NXDUTITY.mjs → setup-H7KCI4SO.mjs} +9 -9
  157. package/dist/cli/skills-VPIURCAZ.js +36 -0
  158. package/dist/cli/{skills-VMFAIDO6.mjs → skills-YQNSJUUG.mjs} +7 -7
  159. package/dist/cli/tools-273GS5HU.js +56 -0
  160. package/dist/cli/{tools-52NTHBSJ.mjs → tools-ZF6SVEGW.mjs} +16 -16
  161. package/dist/cli/{update-SAKBEKMV.mjs → update-RKQNNJM4.mjs} +9 -9
  162. package/dist/cli/update-TOD3XY55.js +34 -0
  163. package/dist/cli/{views-ACRV7MD6.mjs → views-JHHOTWDU.mjs} +6 -6
  164. package/dist/cli/{views-C3GJOBDG.js → views-KN7FEDGT.js} +21 -21
  165. package/dist/cli/{workflow-ZNWCZEGN.js → workflow-2WHSKTTV.js} +17 -17
  166. package/dist/cli/{workflow-CS22E7TC.mjs → workflow-AAYLCLWA.mjs} +7 -7
  167. package/dist/{client-BlLYQDNo.d.mts → client-D0uDBybG.d.mts} +1 -1
  168. package/dist/{client-DSQlkIDO.d.ts → client-DZTnAv4B.d.ts} +1 -1
  169. package/dist/{client-core-rX7n2H8U.d.mts → client-core-BhWf8Y1b.d.mts} +15 -2
  170. package/dist/{client-core-CDwapXy5.d.ts → client-core-og3AP1LL.d.ts} +15 -2
  171. package/dist/{compiler-manifest-BHNC4RL-.d.mts → compiler-manifest-Bes3OVA3.d.mts} +1 -1
  172. package/dist/{compiler-manifest-BHNC4RL-.d.ts → compiler-manifest-Bes3OVA3.d.ts} +1 -1
  173. package/dist/{errors-lhtIWG5Z.d.ts → errors-BJm4lLWc.d.ts} +1 -1
  174. package/dist/{errors-D7sPXrvB.d.mts → errors-Dc5r42ks.d.mts} +1 -1
  175. package/dist/{index-CQTBHXHr.d.ts → index-BfV7mRPF.d.ts} +1 -1
  176. package/dist/{index-NaDZq2xf.d.mts → index-DTkiz_Ur.d.mts} +1 -1
  177. package/dist/index.d.mts +7 -7
  178. package/dist/index.d.ts +7 -7
  179. package/dist/index.js +9 -9
  180. package/dist/index.mjs +6 -6
  181. package/dist/install-integrity.json +120 -112
  182. package/dist/plays/bundle-play-file.d.mts +3 -3
  183. package/dist/plays/bundle-play-file.d.ts +3 -3
  184. package/dist/plays/play-description.d.mts +2 -2
  185. package/dist/plays/play-description.d.ts +2 -2
  186. package/dist/plays/run-request.d.mts +2 -2
  187. package/dist/plays/run-request.d.ts +2 -2
  188. package/dist/release.d.mts +1 -1
  189. package/dist/release.d.ts +1 -1
  190. package/dist/release.js +2 -2
  191. package/dist/release.mjs +1 -1
  192. package/dist/server.d.mts +4 -4
  193. package/dist/server.d.ts +4 -4
  194. package/dist/server.js +5 -5
  195. package/dist/server.mjs +3 -3
  196. package/package.json +1 -1
  197. package/dist/cli/auth-6XQKFOLG.js +0 -43
  198. package/dist/cli/describe-WW3OQRLP.js +0 -49
  199. package/dist/cli/git-PHYRD56H.js +0 -25
  200. package/dist/cli/search-HLE54W5G.js +0 -32
  201. package/dist/cli/sessions-VEBYZIEU.js +0 -22
  202. package/dist/cli/skills-NVQ744CN.js +0 -36
  203. package/dist/cli/tools-SBDUL3WB.js +0 -56
  204. package/dist/cli/update-HHVFZPCV.js +0 -34
@@ -11,6 +11,11 @@ const MAX_RETRY_JITTER_RATIO = 0.25;
11
11
 
12
12
  type PendingWrite<Input, Output> = {
13
13
  input: Input;
14
+ /** Queue order: assigned when the write is accepted. */
15
+ seq: number;
16
+ /** Its transport lane and ordering-key identities, computed once. */
17
+ lane: string;
18
+ keyIds: readonly unknown[];
14
19
  bytes: number;
15
20
  signal: AbortSignal | null;
16
21
  state: 'queued' | 'active' | 'settled';
@@ -20,12 +25,28 @@ type PendingWrite<Input, Output> = {
20
25
  reject: (error: unknown) => void;
21
26
  };
22
27
 
28
+ /**
29
+ * One caller waiting for buffer room, oldest first. Its size and lane are
30
+ * computed once, so a release wakes only the callers that now fit.
31
+ */
23
32
  type CapacityWaiter = {
24
- promise: Promise<void>;
33
+ bytes: number;
34
+ lane: string;
25
35
  resolve: () => void;
26
36
  reject: (error: unknown) => void;
37
+ detach: () => void;
27
38
  };
28
39
 
40
+ /**
41
+ * Ordering keys compare with `Object.is`. A Set or Map compares with
42
+ * SameValueZero, which differs only for -0; give -0 its own identity so a
43
+ * lookup means exactly what the linear `Object.is` search meant.
44
+ */
45
+ const NEGATIVE_ZERO_ORDERING_KEY = Symbol('negative-zero-ordering-key');
46
+ function orderingKeyIdentity(key: unknown): unknown {
47
+ return Object.is(key, -0) ? NEGATIVE_ZERO_ORDERING_KEY : key;
48
+ }
49
+
29
50
  export type RuntimeReceiptWriterStats = {
30
51
  /** True while at least one batch is in flight. */
31
52
  active: boolean;
@@ -170,7 +191,18 @@ export class RuntimeReceiptWriter<Input, Output> {
170
191
  * cannot influence admission or durable delivery.
171
192
  */
172
193
  readonly #onStatsChanged: ((stats: RuntimeReceiptWriterStats) => void) | null;
173
- readonly #queued: Array<PendingWrite<Input, Output>> = [];
194
+ /** Queued writes, oldest first. */
195
+ readonly #queued = new Set<PendingWrite<Input, Output>>();
196
+ /** The same writes per lane, oldest first: a pass reads only open lanes. */
197
+ readonly #queuedByLane = new Map<string, PendingWrite<Input, Output>[]>();
198
+ /**
199
+ * The same writes per ordering key, oldest first. A write behind an earlier
200
+ * write on its receipt that sits in a full lane is found here, without
201
+ * walking that lane.
202
+ */
203
+ readonly #queuedByKey = new Map<unknown, PendingWrite<Input, Output>[]>();
204
+ #nextSeq = 0;
205
+ #selectionExamined = 0;
174
206
  readonly #closeController = new AbortController();
175
207
 
176
208
  #bufferedItems = 0;
@@ -182,11 +214,12 @@ export class RuntimeReceiptWriter<Input, Output> {
182
214
  string,
183
215
  Required<RuntimeReceiptWriterLaneBufferLimit>
184
216
  >();
185
- readonly #activeOrderingKeys: unknown[] = [];
217
+ /** Ordering keys of in-flight batches, by identity, with their count. */
218
+ readonly #activeOrderingKeys = new Map<unknown, number>();
186
219
  #flushTimer: ReturnType<typeof setTimeout> | null = null;
187
220
  #closed = false;
188
221
  #closeReason: unknown = null;
189
- #capacityWaiter: CapacityWaiter | null = null;
222
+ #capacityWaiters: CapacityWaiter[] = [];
190
223
  #drainWaiters: Array<{
191
224
  resolve: () => void;
192
225
  reject: (error: unknown) => void;
@@ -418,6 +451,11 @@ export class RuntimeReceiptWriter<Input, Output> {
418
451
  return new Promise<Output>((resolve, reject) => {
419
452
  const pending: PendingWrite<Input, Output> = {
420
453
  input,
454
+ seq: 0,
455
+ lane,
456
+ keyIds: [
457
+ ...new Set(this.#orderingKeys(input).map(orderingKeyIdentity)),
458
+ ],
421
459
  bytes,
422
460
  signal: options.signal ?? null,
423
461
  state: 'queued',
@@ -437,7 +475,9 @@ export class RuntimeReceiptWriter<Input, Output> {
437
475
 
438
476
  /**
439
477
  * Wait until a rejected caller may retry its own input without making the
440
- * writer retain that input. All callers share one progress promise; the
478
+ * writer retain that input. Callers wait oldest first, each with its size
479
+ * computed once here; a release wakes only the callers that now fit, so a
480
+ * deep backlog never re-runs every caller's write on every batch. The
441
481
  * caller continues to own its command and abort signal.
442
482
  */
443
483
  waitForCapacity(
@@ -469,12 +509,28 @@ export class RuntimeReceiptWriter<Input, Output> {
469
509
  new RuntimeReceiptWriterBufferLimitError(bytes, laneLimit.bytes),
470
510
  );
471
511
  }
472
- this.#startPump();
512
+ // Batch completions and flush windows pump on their own. Only a writer
513
+ // with neither in progress needs this caller to start one.
514
+ if (this.#inFlight.size === 0 && !this.#flushTimer) this.#startPump();
473
515
  if (this.#canAccept(bytes, lane)) return Promise.resolve();
474
516
 
475
- const waiter = this.#capacityWaiter ?? this.#createCapacityWaiter();
476
- if (!options.signal) return waiter.promise;
477
- return this.#waitForCapacityOrAbort(waiter.promise, options.signal);
517
+ const signal = options.signal ?? null;
518
+ return new Promise<void>((resolve, reject) => {
519
+ const onAbort = () => {
520
+ const index = this.#capacityWaiters.indexOf(waiter);
521
+ if (index >= 0) this.#capacityWaiters.splice(index, 1);
522
+ reject(abortReason(signal));
523
+ };
524
+ const waiter: CapacityWaiter = {
525
+ bytes,
526
+ lane,
527
+ resolve,
528
+ reject,
529
+ detach: () => signal?.removeEventListener('abort', onAbort),
530
+ };
531
+ this.#capacityWaiters.push(waiter);
532
+ signal?.addEventListener('abort', onAbort, { once: true });
533
+ });
478
534
  }
479
535
 
480
536
  async flush(): Promise<void> {
@@ -491,9 +547,12 @@ export class RuntimeReceiptWriter<Input, Output> {
491
547
  this.#closed = true;
492
548
  this.#closeReason =
493
549
  reason === undefined ? new RuntimeReceiptWriterClosedError() : reason;
550
+ // A closed writer admits no write, so a parked caller can never fit
551
+ // again: a release wakes only the callers that fit, and after a
552
+ // graceful drain nothing would wake the rest.
553
+ this.#rejectCapacityWaiters(this.#closeReason);
494
554
  if (reason !== undefined) {
495
555
  this.#closeController.abort(reason);
496
- this.#rejectCapacityWaiter(reason);
497
556
  this.#rejectWaiting(reason);
498
557
  }
499
558
  }
@@ -511,12 +570,21 @@ export class RuntimeReceiptWriter<Input, Output> {
511
570
  return {
512
571
  active: this.#inFlight.size > 0,
513
572
  inFlightBatches: this.#inFlight.size,
514
- queued: this.#queued.length,
573
+ queued: this.#queued.size,
515
574
  bufferedItems: this.#bufferedItems,
516
575
  bufferedBytes: this.#bufferedBytes,
517
576
  };
518
577
  }
519
578
 
579
+ /**
580
+ * Commands examined by batch selection since the writer started: a running
581
+ * count of selection work. It grows with the commands written, never with
582
+ * the backlog behind a full lane.
583
+ */
584
+ selectionWork(): number {
585
+ return this.#selectionExamined;
586
+ }
587
+
520
588
  #notifyStatsChanged(): void {
521
589
  if (!this.#onStatsChanged) return;
522
590
  try {
@@ -547,14 +615,14 @@ export class RuntimeReceiptWriter<Input, Output> {
547
615
 
548
616
  #accept(pending: PendingWrite<Input, Output>): void {
549
617
  pending.state = 'queued';
550
- this.#queued.push(pending);
551
- const lane = this.#laneFor(pending.input);
618
+ this.#enqueue(pending);
619
+ const lane = pending.lane;
552
620
  this.#adjustBufferedItems(1, lane);
553
621
  this.#adjustBufferedBytes(pending.bytes);
554
622
  this.#adjustBufferedLane(lane, { items: 0, bytes: pending.bytes });
555
623
  this.#notifyStatsChanged();
556
624
  if (
557
- this.#queued.length >= this.#maxBatchSize ||
625
+ this.#queued.size >= this.#maxBatchSize ||
558
626
  this.#nextBatchBytes() >= this.#targetBatchBytes
559
627
  ) {
560
628
  this.#clearFlushTimer();
@@ -573,7 +641,7 @@ export class RuntimeReceiptWriter<Input, Output> {
573
641
  * `#startPump`, so under load the window adds no latency.
574
642
  */
575
643
  #scheduleFlush(): void {
576
- if (this.#flushTimer || this.#queued.length === 0) return;
644
+ if (this.#flushTimer || this.#queued.size === 0) return;
577
645
  if (!this.#hasFlightCapacity()) return;
578
646
  this.#flushTimer = setTimeout(() => {
579
647
  this.#flushTimer = null;
@@ -582,7 +650,11 @@ export class RuntimeReceiptWriter<Input, Output> {
582
650
  }
583
651
 
584
652
  #startPump(): void {
585
- while (this.#queued.length > 0 && this.#hasFlightCapacity()) {
653
+ while (
654
+ this.#queued.size > 0 &&
655
+ this.#hasFlightCapacity() &&
656
+ this.#queuedLaneHasFlightCapacity()
657
+ ) {
586
658
  const batch = this.#takeBatchIfOrderAllows();
587
659
  // An empty batch means every queued receipt conflicts with an active
588
660
  // ordering key or belongs to a lane whose bounded capacity is full.
@@ -596,7 +668,12 @@ export class RuntimeReceiptWriter<Input, Output> {
596
668
  const batchId = ++this.#nextBatchId;
597
669
  const lane = this.#laneFor(batch[0]!.input);
598
670
  const orderingKeys = this.#orderingKeysFor(batch);
599
- this.#activeOrderingKeys.push(...orderingKeys);
671
+ for (const key of orderingKeys) {
672
+ this.#activeOrderingKeys.set(
673
+ key,
674
+ (this.#activeOrderingKeys.get(key) ?? 0) + 1,
675
+ );
676
+ }
600
677
  this.#incrementInFlightLane(lane);
601
678
  // Annotated: the callback below closes over `inFlight`, so inference
602
679
  // would otherwise be circular.
@@ -604,10 +681,9 @@ export class RuntimeReceiptWriter<Input, Output> {
604
681
  () => {
605
682
  this.#inFlight.delete(inFlight);
606
683
  for (const key of orderingKeys) {
607
- const index = this.#activeOrderingKeys.findIndex((active) =>
608
- Object.is(active, key),
609
- );
610
- if (index >= 0) this.#activeOrderingKeys.splice(index, 1);
684
+ const count = this.#activeOrderingKeys.get(key) ?? 0;
685
+ if (count <= 1) this.#activeOrderingKeys.delete(key);
686
+ else this.#activeOrderingKeys.set(key, count - 1);
611
687
  }
612
688
  for (const pending of batch) {
613
689
  this.#adjustBufferedItems(-1, this.#laneFor(pending.input));
@@ -619,8 +695,8 @@ export class RuntimeReceiptWriter<Input, Output> {
619
695
  }
620
696
  this.#decrementInFlightLane(lane);
621
697
  this.#notifyStatsChanged();
622
- this.#resolveCapacityWaiter();
623
- if (this.#queued.length > 0) this.#startPump();
698
+ this.#wakeCapacityWaiters();
699
+ if (this.#queued.size > 0) this.#startPump();
624
700
  else if (this.#inFlight.size === 0) this.#notifyDrained();
625
701
  },
626
702
  );
@@ -659,13 +735,11 @@ export class RuntimeReceiptWriter<Input, Output> {
659
735
 
660
736
  #takeBatchIfOrderAllows(): Array<PendingWrite<Input, Output>> {
661
737
  this.#rejectAbortedQueued();
662
- const indices = this.#selectRunnableBatchIndices();
663
- if (indices.length === 0) return [];
664
- const batch = indices.map((index) => this.#queued[index]!);
665
- for (let index = indices.length - 1; index >= 0; index -= 1) {
666
- this.#queued.splice(indices[index]!, 1);
738
+ const batch = this.#selectRunnableBatch();
739
+ for (const pending of batch) {
740
+ this.#dequeue(pending);
741
+ pending.state = 'active';
667
742
  }
668
- for (const pending of batch) pending.state = 'active';
669
743
  return batch;
670
744
  }
671
745
 
@@ -674,70 +748,108 @@ export class RuntimeReceiptWriter<Input, Output> {
674
748
  * receipt is active may be bypassed so an independent receipt can use a
675
749
  * free flight. A normally ready command is never bypassed: that keeps the
676
750
  * historical FIFO ordering for callers that did not provide ordering keys.
751
+ *
752
+ * This reads the queue in order, but only the lanes with a free flight: a
753
+ * command in a full lane can only be skipped, and the one thing that skip
754
+ * changes, that a later command on the same receipt may not overtake it,
755
+ * is answered from the per-key index. A pass therefore costs the open
756
+ * lanes' commands, not the whole backlog of a saturated lane.
677
757
  */
678
- #selectRunnableBatchIndices(): number[] {
679
- const skippedOrderingKeys: unknown[] = [];
680
- const selected: number[] = [];
758
+ #selectRunnableBatch(): Array<PendingWrite<Input, Output>> {
759
+ const cursors: Array<{
760
+ lane: string;
761
+ list: PendingWrite<Input, Output>[];
762
+ at: number;
763
+ }> = [];
764
+ for (const [lane, list] of this.#queuedByLane) {
765
+ if (this.#hasFlightCapacity(lane)) cursors.push({ lane, list, at: 0 });
766
+ }
767
+ if (cursors.length === 0) return [];
768
+ // Keys of earlier open-lane commands this pass skipped.
769
+ const skippedOrderingKeys = new Set<unknown>();
770
+ const selected: Array<PendingWrite<Input, Output>> = [];
681
771
  let selectedBatchKey: unknown;
682
772
  let selectedLane: string | null = null;
683
773
  let batchBytes = 0;
684
774
 
685
- for (let index = 0; index < this.#queued.length; index += 1) {
686
- const pending = this.#queued[index]!;
775
+ for (;;) {
776
+ // The oldest command among the open lanes.
777
+ let next: (typeof cursors)[number] | null = null;
778
+ for (const cursor of cursors) {
779
+ if (cursor.at >= cursor.list.length) continue;
780
+ if (!next || cursor.list[cursor.at]!.seq < next.list[next.at]!.seq) {
781
+ next = cursor;
782
+ }
783
+ }
784
+ if (!next) break;
785
+ const pending = next.list[next.at]!;
786
+ next.at += 1;
787
+ this.#selectionExamined += 1;
687
788
  if (pending.aborted !== null) continue;
688
- const orderingKeys = this.#orderingKeys(pending.input);
689
- const blockedByOrder = this.#orderingKeysConflict(
690
- orderingKeys,
691
- skippedOrderingKeys,
692
- );
789
+ const blockedByOrder =
790
+ this.#orderingKeysConflict(pending.keyIds, skippedOrderingKeys) ||
791
+ this.#behindFullLaneCommand(pending);
693
792
  const blockedByActive = this.#orderingKeysConflict(
694
- orderingKeys,
793
+ pending.keyIds,
695
794
  this.#activeOrderingKeys,
696
795
  );
697
- const lane = this.#laneFor(pending.input);
698
- const laneAvailable = this.#hasFlightCapacity(lane);
699
796
 
700
797
  if (selected.length === 0) {
701
- if (blockedByOrder || blockedByActive || !laneAvailable) {
702
- skippedOrderingKeys.push(...orderingKeys);
798
+ if (blockedByOrder || blockedByActive) {
799
+ for (const key of pending.keyIds) skippedOrderingKeys.add(key);
703
800
  continue;
704
801
  }
705
- selected.push(index);
802
+ selected.push(pending);
706
803
  selectedBatchKey = this.#batchKey(pending.input);
707
- selectedLane = lane;
804
+ selectedLane = pending.lane;
708
805
  batchBytes = pending.bytes;
709
806
  continue;
710
807
  }
711
808
 
712
809
  // A ready, incompatible command is an ordinary FIFO boundary. It must
713
810
  // run before any later command, even one that could share this batch.
714
- if (blockedByOrder || blockedByActive || !laneAvailable) {
715
- skippedOrderingKeys.push(...orderingKeys);
811
+ if (blockedByOrder || blockedByActive) {
812
+ for (const key of pending.keyIds) skippedOrderingKeys.add(key);
716
813
  continue;
717
814
  }
718
815
  if (
719
- selectedLane !== lane ||
816
+ selectedLane !== pending.lane ||
720
817
  !Object.is(this.#batchKey(pending.input), selectedBatchKey) ||
721
818
  selected.length >= this.#maxBatchSize ||
722
819
  batchBytes + pending.bytes > this.#targetBatchBytes
723
820
  ) {
724
821
  break;
725
822
  }
726
- selected.push(index);
823
+ selected.push(pending);
727
824
  batchBytes += pending.bytes;
728
825
  }
729
826
  return selected;
730
827
  }
731
828
 
829
+ /**
830
+ * Whether an earlier, live command on one of this command's receipts sits
831
+ * in a lane with no free flight: the full-lane commands every pass skips.
832
+ */
833
+ #behindFullLaneCommand(pending: PendingWrite<Input, Output>): boolean {
834
+ for (const key of pending.keyIds) {
835
+ for (const earlier of this.#queuedByKey.get(key) ?? []) {
836
+ if (earlier.seq >= pending.seq) break;
837
+ this.#selectionExamined += 1;
838
+ if (earlier.aborted !== null) continue;
839
+ if (!this.#hasFlightCapacity(earlier.lane)) return true;
840
+ }
841
+ }
842
+ return false;
843
+ }
844
+
732
845
  #rejectAbortedQueued(): void {
733
846
  let changed = false;
734
- for (let index = this.#queued.length - 1; index >= 0; index -= 1) {
735
- const pending = this.#queued[index]!;
847
+ for (const pending of this.#queued) {
736
848
  if (pending.aborted === null) continue;
737
- this.#queued.splice(index, 1);
738
- this.#adjustBufferedItems(-1, this.#laneFor(pending.input));
849
+ this.#dequeue(pending);
850
+ this.#adjustBufferedItems(-1, pending.lane);
739
851
  this.#adjustBufferedBytes(-pending.bytes);
740
- this.#adjustBufferedLane(this.#laneFor(pending.input), {
852
+ this.#adjustBufferedLane(pending.lane, {
741
853
  items: 0,
742
854
  bytes: -pending.bytes,
743
855
  });
@@ -749,19 +861,47 @@ export class RuntimeReceiptWriter<Input, Output> {
749
861
 
750
862
  #nextBatchBytes(): number {
751
863
  this.#rejectAbortedQueued();
752
- return this.#selectRunnableBatchIndices().reduce(
753
- (total, index) => total + this.#queued[index]!.bytes,
864
+ return this.#selectRunnableBatch().reduce(
865
+ (total, pending) => total + pending.bytes,
754
866
  0,
755
867
  );
756
868
  }
757
869
 
870
+ #enqueue(pending: PendingWrite<Input, Output>): void {
871
+ pending.seq = ++this.#nextSeq;
872
+ this.#queued.add(pending);
873
+ const lane = this.#queuedByLane.get(pending.lane);
874
+ if (lane) lane.push(pending);
875
+ else this.#queuedByLane.set(pending.lane, [pending]);
876
+ for (const key of pending.keyIds) {
877
+ const list = this.#queuedByKey.get(key);
878
+ if (list) list.push(pending);
879
+ else this.#queuedByKey.set(key, [pending]);
880
+ }
881
+ }
882
+
883
+ #dequeue(pending: PendingWrite<Input, Output>): void {
884
+ if (!this.#queued.delete(pending)) return;
885
+ removeFromList(this.#queuedByLane, pending.lane, pending);
886
+ for (const key of pending.keyIds) {
887
+ removeFromList(this.#queuedByKey, key, pending);
888
+ }
889
+ }
890
+
891
+ /** Whether any of these key identities is in the given set. */
758
892
  #orderingKeysConflict(
759
- candidate: readonly unknown[],
760
- existing: readonly unknown[],
893
+ candidateIds: readonly unknown[],
894
+ existing: ReadonlySet<unknown> | ReadonlyMap<unknown, number>,
761
895
  ): boolean {
762
- return candidate.some((key) =>
763
- existing.some((active) => Object.is(active, key)),
764
- );
896
+ return candidateIds.some((key) => existing.has(key));
897
+ }
898
+
899
+ /** Whether any lane holding queued writes has a free flight. */
900
+ #queuedLaneHasFlightCapacity(): boolean {
901
+ for (const lane of this.#queuedByLane.keys()) {
902
+ if (this.#hasFlightCapacity(lane)) return true;
903
+ }
904
+ return false;
765
905
  }
766
906
 
767
907
  #laneFor(input: Input): string {
@@ -791,16 +931,13 @@ export class RuntimeReceiptWriter<Input, Output> {
791
931
  else this.#inFlightBatchesByLane.set(lane, current - 1);
792
932
  }
793
933
 
934
+ /** The batch's distinct ordering-key identities. */
794
935
  #orderingKeysFor(batch: readonly PendingWrite<Input, Output>[]): unknown[] {
795
- const keys: unknown[] = [];
936
+ const keys = new Set<unknown>();
796
937
  for (const pending of batch) {
797
- for (const key of this.#orderingKeys(pending.input)) {
798
- if (!keys.some((existing) => Object.is(existing, key))) {
799
- keys.push(key);
800
- }
801
- }
938
+ for (const key of pending.keyIds) keys.add(key);
802
939
  }
803
- return keys;
940
+ return [...keys];
804
941
  }
805
942
 
806
943
  async #sendWithRetry(
@@ -903,7 +1040,7 @@ export class RuntimeReceiptWriter<Input, Output> {
903
1040
  firstInput,
904
1041
  elapsedMs: Date.now() - input.startedAt,
905
1042
  retryAfterMs: input.retryAfterMs,
906
- queued: this.#queued.length,
1043
+ queued: this.#queued.size,
907
1044
  bufferedItems: this.#bufferedItems,
908
1045
  bufferedBytes: this.#bufferedBytes,
909
1046
  ...(input.error === undefined ? {} : { error: input.error }),
@@ -960,9 +1097,7 @@ export class RuntimeReceiptWriter<Input, Output> {
960
1097
  pending.aborted = abortReason(pending.signal);
961
1098
  if (pending.state === 'active') return;
962
1099
 
963
- const collection = pending.state === 'queued' ? this.#queued : [];
964
- const index = collection.indexOf(pending);
965
- if (index >= 0) collection.splice(index, 1);
1100
+ if (pending.state === 'queued') this.#dequeue(pending);
966
1101
  if (pending.state === 'queued') {
967
1102
  this.#adjustBufferedItems(-1, this.#laneFor(pending.input));
968
1103
  this.#adjustBufferedBytes(-pending.bytes);
@@ -973,7 +1108,7 @@ export class RuntimeReceiptWriter<Input, Output> {
973
1108
  this.#notifyStatsChanged();
974
1109
  }
975
1110
  this.#settleRejected(pending, pending.aborted);
976
- this.#resolveCapacityWaiter();
1111
+ this.#wakeCapacityWaiters();
977
1112
  this.#notifyDrained();
978
1113
  }
979
1114
 
@@ -1000,7 +1135,11 @@ export class RuntimeReceiptWriter<Input, Output> {
1000
1135
  #rejectWaiting(reason: unknown): void {
1001
1136
  this.#clearFlushTimer();
1002
1137
  let changed = false;
1003
- for (const pending of this.#queued.splice(0)) {
1138
+ const queued = [...this.#queued];
1139
+ this.#queued.clear();
1140
+ this.#queuedByLane.clear();
1141
+ this.#queuedByKey.clear();
1142
+ for (const pending of queued) {
1004
1143
  this.#adjustBufferedItems(-1, this.#laneFor(pending.input));
1005
1144
  this.#adjustBufferedBytes(-pending.bytes);
1006
1145
  this.#adjustBufferedLane(this.#laneFor(pending.input), {
@@ -1011,58 +1150,62 @@ export class RuntimeReceiptWriter<Input, Output> {
1011
1150
  changed = true;
1012
1151
  }
1013
1152
  if (changed) this.#notifyStatsChanged();
1014
- this.#resolveCapacityWaiter();
1153
+ this.#wakeCapacityWaiters();
1015
1154
  this.#notifyDrained(reason);
1016
1155
  }
1017
1156
 
1018
- #createCapacityWaiter(): CapacityWaiter {
1019
- let resolve!: () => void;
1020
- let reject!: (error: unknown) => void;
1021
- const promise = new Promise<void>((resolvePromise, rejectPromise) => {
1022
- resolve = resolvePromise;
1023
- reject = rejectPromise;
1024
- });
1025
- const waiter = { promise, resolve, reject };
1026
- this.#capacityWaiter = waiter;
1027
- return waiter;
1028
- }
1029
-
1030
- #resolveCapacityWaiter(): void {
1031
- const waiter = this.#capacityWaiter;
1032
- if (!waiter) return;
1033
- this.#capacityWaiter = null;
1034
- waiter.resolve();
1035
- }
1036
-
1037
- #rejectCapacityWaiter(reason: unknown): void {
1038
- const waiter = this.#capacityWaiter;
1039
- if (!waiter) return;
1040
- this.#capacityWaiter = null;
1041
- waiter.reject(reason);
1157
+ /**
1158
+ * Wake, oldest first, only the waiting callers that fit the room now free,
1159
+ * counting each woken caller against it. A caller that does not fit stays
1160
+ * queued; a smaller later caller that fits may go first.
1161
+ */
1162
+ #wakeCapacityWaiters(): void {
1163
+ if (this.#capacityWaiters.length === 0) return;
1164
+ let freeItems = this.#maxBufferedItems - this.#bufferedItems;
1165
+ let freeBytes = this.#maxBufferedBytes - this.#bufferedBytes;
1166
+ const laneTaken = new Map<string, { items: number; bytes: number }>();
1167
+ const stillWaiting: CapacityWaiter[] = [];
1168
+ for (const waiter of this.#capacityWaiters) {
1169
+ const laneLimit = this.#maxBufferedByLane.get(waiter.lane);
1170
+ const laneBuffered = this.#bufferedByLane.get(waiter.lane) ?? {
1171
+ items: 0,
1172
+ bytes: 0,
1173
+ };
1174
+ const taken = laneTaken.get(waiter.lane) ?? { items: 0, bytes: 0 };
1175
+ const fits =
1176
+ freeItems >= 1 &&
1177
+ freeBytes >= waiter.bytes &&
1178
+ (!laneLimit ||
1179
+ (laneBuffered.items + taken.items < laneLimit.items &&
1180
+ laneBuffered.bytes + taken.bytes + waiter.bytes <=
1181
+ laneLimit.bytes));
1182
+ if (!fits) {
1183
+ stillWaiting.push(waiter);
1184
+ continue;
1185
+ }
1186
+ freeItems -= 1;
1187
+ freeBytes -= waiter.bytes;
1188
+ laneTaken.set(waiter.lane, {
1189
+ items: taken.items + 1,
1190
+ bytes: taken.bytes + waiter.bytes,
1191
+ });
1192
+ waiter.detach();
1193
+ waiter.resolve();
1194
+ }
1195
+ this.#capacityWaiters = stillWaiting;
1042
1196
  }
1043
1197
 
1044
- async #waitForCapacityOrAbort(
1045
- capacity: Promise<void>,
1046
- signal: AbortSignal,
1047
- ): Promise<void> {
1048
- await new Promise<void>((resolve, reject) => {
1049
- const finish = (error?: unknown): void => {
1050
- signal.removeEventListener('abort', onAbort);
1051
- if (error === undefined) resolve();
1052
- else reject(error);
1053
- };
1054
- const onAbort = () => finish(abortReason(signal));
1055
- capacity.then(
1056
- () => finish(),
1057
- (error) => finish(error),
1058
- );
1059
- signal.addEventListener('abort', onAbort, { once: true });
1060
- if (signal.aborted) onAbort();
1061
- });
1198
+ #rejectCapacityWaiters(reason: unknown): void {
1199
+ const waiters = this.#capacityWaiters;
1200
+ this.#capacityWaiters = [];
1201
+ for (const waiter of waiters) {
1202
+ waiter.detach();
1203
+ waiter.reject(reason);
1204
+ }
1062
1205
  }
1063
1206
 
1064
1207
  #isDrained(): boolean {
1065
- return this.#inFlight.size === 0 && this.#queued.length === 0;
1208
+ return this.#inFlight.size === 0 && this.#queued.size === 0;
1066
1209
  }
1067
1210
 
1068
1211
  #notifyDrained(error?: unknown): void {
@@ -1107,6 +1250,18 @@ export async function writeRuntimeReceiptWithBackpressure<Input, Output>(
1107
1250
  }
1108
1251
  }
1109
1252
 
1253
+ function removeFromList<Key, Item>(
1254
+ index: Map<Key, Item[]>,
1255
+ key: Key,
1256
+ item: Item,
1257
+ ): void {
1258
+ const list = index.get(key);
1259
+ if (!list) return;
1260
+ const at = list.indexOf(item);
1261
+ if (at >= 0) list.splice(at, 1);
1262
+ if (list.length === 0) index.delete(key);
1263
+ }
1264
+
1110
1265
  const textEncoder = new TextEncoder();
1111
1266
 
1112
1267
  function estimateJsonBytes(input: unknown): number {