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
@@ -123,3 +123,57 @@ export function validateRuntimeTrafficOverride(input: {
123
123
  );
124
124
  }
125
125
  }
126
+
127
+ /**
128
+ * Fast mode P1: overlap the worker's pre-create policy read with the executor
129
+ * token mint. Normally the mint acknowledges the policy it read while opening
130
+ * the compute session, and the worker needs no read of its own. When the ack
131
+ * is missing (the route's optional read lost the race on a cold instance) the
132
+ * worker used to start its own read only after the mint returned, so a slow
133
+ * mint and a slow read added up (COLDC7: a 1.9 s read after a 129 ms mint).
134
+ *
135
+ * With this on:
136
+ * - the executor-token route loads the policy reader's modules at request
137
+ * entry and starts the read as soon as the lease and origin checks pass
138
+ * (never for a rejected request), so the ack normally carries the policy;
139
+ * - the worker starts its fallback read during the mint if the mint has not
140
+ * answered within RUNTIME_TRAFFIC_POLICY_HEDGE_AFTER_MS (a delayed hedge:
141
+ * a fast mint costs no extra read).
142
+ * Unchanged: the policy is still enforced before any sandbox create, and the
143
+ * mint/compute-session ordering is untouched (both reads are pure reads).
144
+ * Gives up: one extra policy read per launch whose mint is slower than the
145
+ * hedge delay. Off.
146
+ */
147
+ export const OVERLAP_RUNTIME_TRAFFIC_POLICY_READ = false;
148
+ /** ~p90 of executor_token_mint across the msc cohorts (p50 ~130 ms). */
149
+ export const RUNTIME_TRAFFIC_POLICY_HEDGE_AFTER_MS = 300;
150
+
151
+ export type HedgedRuntimeTrafficPolicyRead = {
152
+ /** The read started during the mint, or null when the mint answered first. */
153
+ started(): Promise<RuntimeTrafficPolicy> | null;
154
+ };
155
+
156
+ /**
157
+ * Start `read` if `mint` has not settled after `delayMs`. The returned read is
158
+ * observed here, so an unused one can never become an unhandled rejection.
159
+ */
160
+ export function hedgeRuntimeTrafficPolicyRead(input: {
161
+ mint: Promise<unknown>;
162
+ read: () => Promise<RuntimeTrafficPolicy>;
163
+ delayMs?: number;
164
+ }): HedgedRuntimeTrafficPolicyRead {
165
+ let started: Promise<RuntimeTrafficPolicy> | null = null;
166
+ let mintSettled = false;
167
+ const timer = setTimeout(() => {
168
+ if (mintSettled) return;
169
+ started = Promise.resolve().then(input.read);
170
+ started.catch(() => undefined);
171
+ }, input.delayMs ?? RUNTIME_TRAFFIC_POLICY_HEDGE_AFTER_MS);
172
+ timer.unref?.();
173
+ const settle = () => {
174
+ mintSettled = true;
175
+ clearTimeout(timer);
176
+ };
177
+ input.mint.then(settle, settle);
178
+ return { started: () => started };
179
+ }
@@ -1,5 +1,7 @@
1
1
  /** Fixed-size terminal accounting retained even when detailed runtime telemetry is too large. */
2
2
  export type RuntimeWorkCounters = {
3
+ /** Absent on historical runners; never imputed as zero. */
4
+ reusableResultCalls?: number;
3
5
  logicalCalls: number;
4
6
  providerRequests: number;
5
7
  /** Older resource snapshots did not retain this scalar. */
@@ -47,7 +49,14 @@ export function runtimeWorkCountersFromStats(
47
49
  providerRequests !== null &&
48
50
  provider429s !== null
49
51
  ) {
50
- return { logicalCalls, providerRequests, provider429s };
52
+ return {
53
+ logicalCalls,
54
+ providerRequests,
55
+ provider429s,
56
+ ...(count(compact.reusableResultCalls) !== null
57
+ ? { reusableResultCalls: count(compact.reusableResultCalls)! }
58
+ : {}),
59
+ };
51
60
  }
52
61
  }
53
62
  return null;
@@ -21,6 +21,7 @@ import type { PreloadedRuntimeDbSession } from './db-session';
21
21
  import type { RuntimeAuthorityDescriptor } from './execution-capabilities';
22
22
  import type { PlayRunnerRuntimeTiming } from './protocol';
23
23
  import type { RuntimeTestPolicyOverrides } from './test-runtime-seams';
24
+ import type { ExperimentSwitchOverrides } from './experiment-switches';
24
25
  import type { PlayRunInputPayload } from './play-input';
25
26
  import type { RuntimeSandboxPlacementPolicyId } from './runtime-sandbox-placement-policy';
26
27
  import type { PlayRuntimeProtocolVersion } from './execution-protocol';
@@ -258,6 +259,20 @@ export type PlaySchedulerSubmitInput = RetainedPipelineCarrier & {
258
259
  runtimeTestFaultHeader?: string | null;
259
260
  /** Request-scoped, dev-only runtime policy overrides for black-box durability tests. */
260
261
  testPolicyOverrides?: RuntimeTestPolicyOverrides | null;
262
+ /**
263
+ * EXPERIMENT: per-run switch overrides validated and authorized at
264
+ * admission (`experiment-switches.ts`). Present only on a run whose request
265
+ * carried `x-deepline-experiment-switches`; absent means every switch keeps
266
+ * its static default, so old launches and old workers are unaffected.
267
+ */
268
+ experimentSwitchOverrides?: ExperimentSwitchOverrides | null;
269
+ /**
270
+ * EXPERIMENT CA: the worker that started this run's early sandbox, as named
271
+ * in its hint reply. Copied onto the run's task params, where other workers'
272
+ * claim gates read it (see early-sandbox-claim-affinity.ts). Absent on every
273
+ * other run; readers treat absence as "no affinity".
274
+ */
275
+ earlySandboxClaimOwner?: string | null;
261
276
  /**
262
277
  * Digest of the named intent behind this launch. Runtime admission compares
263
278
  * this optional field instead of treating transport and execution details as
@@ -1,6 +1,7 @@
1
1
  import type { RetryStrategy } from '@deepline/absurd/sdk';
2
2
  import type { PlaySchedulerSubmitInput } from '../scheduler-backend';
3
3
  import { RUNTIME_RELIABILITY_POLICY } from '../runtime-reliability-policy';
4
+ import { parseEarlySandboxClaimOwner } from './early-sandbox-claim-affinity';
4
5
 
5
6
  export const ABSURD_PLAY_RUN_TASK = 'play-run';
6
7
 
@@ -23,6 +24,12 @@ export type AbsurdPlayRunTaskParams = {
23
24
  */
24
25
  nestingDepth: number;
25
26
  schedulerSchema?: string | null;
27
+ /**
28
+ * EXPERIMENT CA (optional, reader-first): the worker that started the run's
29
+ * early sandbox. Other workers yield the first claim for a bounded window
30
+ * (`early-sandbox-claim-affinity.ts`). Absent: claimed as before.
31
+ */
32
+ earlySandboxClaimOwner?: string;
26
33
  };
27
34
 
28
35
  /**
@@ -34,7 +41,11 @@ export type AbsurdPlayRunTaskParams = {
34
41
  export function buildAbsurdPlayRunTask(input: {
35
42
  launch: Pick<
36
43
  PlaySchedulerSubmitInput,
37
- 'runId' | 'orgId' | 'queueMaxDelaySeconds' | 'queuePriority'
44
+ | 'runId'
45
+ | 'orgId'
46
+ | 'queueMaxDelaySeconds'
47
+ | 'queuePriority'
48
+ | 'earlySandboxClaimOwner'
38
49
  >;
39
50
  schedulerSchema?: string | null;
40
51
  }) {
@@ -44,6 +55,12 @@ export function buildAbsurdPlayRunTask(input: {
44
55
  nestingDepth: 0,
45
56
  schedulerSchema: input.schedulerSchema ?? null,
46
57
  };
58
+ const earlySandboxClaimOwner = parseEarlySandboxClaimOwner(
59
+ input.launch.earlySandboxClaimOwner,
60
+ );
61
+ if (earlySandboxClaimOwner) {
62
+ params.earlySandboxClaimOwner = earlySandboxClaimOwner;
63
+ }
47
64
  const maxDelaySeconds = input.launch.queueMaxDelaySeconds;
48
65
  const priority = input.launch.queuePriority;
49
66
  return {
@@ -29,6 +29,10 @@ import {
29
29
  withRuntimeSchedulerClient,
30
30
  type RuntimeSchedulerPoolOptions,
31
31
  } from './postgres-pool';
32
+ import {
33
+ runGatedAbsurdClaimQuery,
34
+ type EarlySandboxClaimGate,
35
+ } from './early-sandbox-claim-affinity';
32
36
 
33
37
  export { ABSURD_SCHEMA_VERSION };
34
38
 
@@ -73,6 +77,8 @@ const ABSURD_CLAIM_TASK_SQL = 'absurd.claim_task(';
73
77
  export function absurdQueryableForRuntimeScheduler(
74
78
  poolOptions: RuntimeSchedulerPoolOptions,
75
79
  observer?: AbsurdSchedulerQueryObserver,
80
+ /** CA: may skip a claim on the claim's own client (see early-sandbox-claim-affinity). */
81
+ claimGate?: EarlySandboxClaimGate,
76
82
  ): Queryable {
77
83
  return {
78
84
  query: async <Row = Record<string, unknown>>(
@@ -88,11 +94,18 @@ export function absurdQueryableForRuntimeScheduler(
88
94
  poolOptions,
89
95
  async (client) => {
90
96
  if (timed) clientAt ??= performance.now();
91
- const queried = await client.query<Row & Record<string, unknown>>(
97
+ return runGatedAbsurdClaimQuery<Row>({
92
98
  sql,
93
99
  params,
94
- );
95
- return { rows: queried.rows as Row[] };
100
+ client,
101
+ gate: claimGate,
102
+ run: async () => {
103
+ const queried = await client.query<
104
+ Row & Record<string, unknown>
105
+ >(sql, params);
106
+ return { rows: queried.rows as Row[] };
107
+ },
108
+ });
96
109
  },
97
110
  undefined,
98
111
  { signal },
@@ -123,10 +136,11 @@ export function createAbsurdForRuntimeScheduler(
123
136
  poolOptions: RuntimeSchedulerPoolOptions,
124
137
  options: Omit<AbsurdOptions, 'db'> = {},
125
138
  observer?: AbsurdSchedulerQueryObserver,
139
+ claimGate?: EarlySandboxClaimGate,
126
140
  ): Absurd {
127
141
  return new Absurd({
128
142
  ...options,
129
- db: absurdQueryableForRuntimeScheduler(poolOptions, observer),
143
+ db: absurdQueryableForRuntimeScheduler(poolOptions, observer, claimGate),
130
144
  });
131
145
  }
132
146
 
@@ -54,10 +54,18 @@ import {
54
54
  import { RUNTIME_CAPACITY_POLICY } from '../runtime-capacity-policy';
55
55
  import { RUNTIME_RELIABILITY_POLICY } from '../runtime-reliability-policy';
56
56
  import {
57
+ hedgeRuntimeTrafficPolicyRead,
57
58
  isRuntimeTrafficPolicy,
59
+ OVERLAP_RUNTIME_TRAFFIC_POLICY_READ,
60
+ RUNTIME_TRAFFIC_POLICY_HEDGE_AFTER_MS,
58
61
  type RuntimeTrafficPolicy,
59
62
  } from '../runtime-traffic-policy';
60
63
  import type { PreloadedRuntimeDbSession } from '../db-session';
64
+ import {
65
+ formatExperimentSwitchOverrides,
66
+ readCarriedExperimentSwitchOverrides,
67
+ resolveExperimentSwitch,
68
+ } from '../experiment-switches';
61
69
  import { parseRenewedPreloadedRuntimeDbSessions } from '../db-session-renewal';
62
70
  import { RUNTIME_CLAIM_HEARTBEAT_DIVISOR } from '../runtime-constants';
63
71
  import {
@@ -137,7 +145,11 @@ import {
137
145
  type DaytonaCrashDiagnostic,
138
146
  type DaytonaSandboxDeleteOutcome,
139
147
  } from '../runner-backends/backends/daytona';
140
- import { findModalSandboxIdsByTags } from '../runner-backends/backends/modal';
148
+ import {
149
+ EARLY_MODAL_SANDBOX_SWEEP_INTERVAL_MS,
150
+ findModalSandboxIdsByTags,
151
+ sweepOrphanEarlyModalSandboxesForWorker,
152
+ } from '../runner-backends/backends/modal';
141
153
  import {
142
154
  resolveDetachedRunnerRuntimeLimitSeconds,
143
155
  type DetachedRunnerSuspension,
@@ -259,6 +271,7 @@ import {
259
271
  } from '../play-runs/attempts';
260
272
  import { transitionPreCodePlayRunRecovery } from './play-run-recovery';
261
273
  import { DURABLE_RUNS_ROLLOUT } from '../durable-runs-rollout';
274
+ import { staticPipelineStartupReadToolIds } from '../startup-read-tool-ids';
262
275
  import {
263
276
  POST_CODE_RECOVERY_BUDGET,
264
277
  classifyPostCodeAttemptOutcome,
@@ -299,6 +312,12 @@ import {
299
312
  withRuntimeSchedulerClient,
300
313
  } from './postgres-pool';
301
314
  import { runWithAbsurdSchedulerQuerySignal } from './absurd-pool';
315
+ import {
316
+ createEarlySandboxClaimGate,
317
+ EARLY_SANDBOX_CLAIM_AFFINITY_READER,
318
+ hasPendingEarlySandboxClaim,
319
+ runEarlySandboxOwnerClaimProbe,
320
+ } from './early-sandbox-claim-affinity';
302
321
  import {
303
322
  createAbsurdClaimLoopTiming,
304
323
  type AbsurdClaimLoopTiming,
@@ -592,6 +611,18 @@ export const ABSURD_DAYTONA_PRE_PARK_TIMEOUT_MS = 5 * 60 * 1_000;
592
611
  const RUNTIME_CLAIM_LEASE_SECONDS =
593
612
  RUNTIME_RELIABILITY_POLICY.worker.claimLeaseSeconds;
594
613
  const HEARTBEAT_CLAIM_TIMEOUT_SECONDS = RUNTIME_CLAIM_LEASE_SECONDS;
614
+
615
+ /** `startupReadToolIds` for the runner context, from the launch's contract plan; empty when it names none. */
616
+ export function startupReadToolIdsContext(
617
+ contractSnapshot: unknown,
618
+ ): { startupReadToolIds?: string[] } {
619
+ const pipeline =
620
+ contractSnapshot && typeof contractSnapshot === 'object'
621
+ ? (contractSnapshot as { staticPipeline?: unknown }).staticPipeline
622
+ : undefined;
623
+ const ids = staticPipelineStartupReadToolIds(pipeline);
624
+ return ids.length > 0 ? { startupReadToolIds: ids } : {};
625
+ }
595
626
  /**
596
627
  * A direct LISTEN wake normally makes an idle claim immediate. This is the
597
628
  * durable safety fallback for missed notifications, an unavailable listener,
@@ -995,6 +1026,12 @@ export type AbsurdRuntimeWorkerDeps = {
995
1026
  sessions: PreloadedRuntimeDbSession[],
996
1027
  ) => void;
997
1028
  }) => Promise<string>;
1029
+ /**
1030
+ * P1 seam: start the pre-create policy read if the mint has not answered
1031
+ * after this many ms. Absent: OVERLAP_RUNTIME_TRAFFIC_POLICY_READ decides
1032
+ * (RUNTIME_TRAFFIC_POLICY_HEDGE_AFTER_MS when on, never when off).
1033
+ */
1034
+ trafficPolicyHedgeAfterMs?: number | null;
998
1035
  /** This worker's release lane id. Seam so tests can drive the belt-and-
999
1036
  * suspenders lane-mismatch guard without mutating process env. Defaults to
1000
1037
  * `currentAbsurdReleaseId()`. */
@@ -1339,6 +1376,14 @@ export async function requestAttemptExecutorToken(input: {
1339
1376
  ...(input.initializeComputeSession
1340
1377
  ? { initializeComputeSession: true }
1341
1378
  : {}),
1379
+ // EXPERIMENT: the run's overrides, so the route resolves P1 for
1380
+ // this run. Only a run that carries overrides sends the field.
1381
+ ...(input.launch.experimentSwitchOverrides
1382
+ ? {
1383
+ experimentSwitchOverrides:
1384
+ input.launch.experimentSwitchOverrides,
1385
+ }
1386
+ : {}),
1342
1387
  // Expand-before-enable rollout fence. An old worker never sends this,
1343
1388
  // so a newly deployed app cannot activate direct terminal reduction
1344
1389
  // before the owning Fly lane has the cleanup controller.
@@ -3765,9 +3810,23 @@ async function executeAbsurdAttemptAdapter(
3765
3810
  });
3766
3811
  if (gated) return gated;
3767
3812
  }
3813
+ const carriedExperimentSwitches = readCarriedExperimentSwitchOverrides(
3814
+ launch.experimentSwitchOverrides,
3815
+ );
3816
+ if (carriedExperimentSwitches) {
3817
+ // The worker-side join line for a run that carries overrides.
3818
+ console.info(
3819
+ '[absurd-runtime.worker.experiment_switches]',
3820
+ JSON.stringify({
3821
+ runId,
3822
+ attempt: generation,
3823
+ overrides: formatExperimentSwitchOverrides(carriedExperimentSwitches),
3824
+ }),
3825
+ );
3826
+ }
3768
3827
  const tokenStartedAt = performance.now();
3769
3828
  let renewedDbSessions: PreloadedRuntimeDbSession[] | null = null;
3770
- const executorToken = await runWithAbsurdExecutionLeaseHeartbeat({
3829
+ const executorTokenMint = runWithAbsurdExecutionLeaseHeartbeat({
3771
3830
  ctx,
3772
3831
  runId,
3773
3832
  operation: async () => {
@@ -3818,6 +3877,36 @@ async function executeAbsurdAttemptAdapter(
3818
3877
  }),
3819
3878
  );
3820
3879
  });
3880
+ // P1 (off): a mint slower than the hedge delay no longer serializes the
3881
+ // worker's own pre-create policy read behind it. A pure read, made with
3882
+ // the run's admission token; the minted-token read below stays the
3883
+ // fallback if it fails.
3884
+ const trafficPolicyHedgeAfterMs =
3885
+ deps.trafficPolicyHedgeAfterMs !== undefined
3886
+ ? deps.trafficPolicyHedgeAfterMs
3887
+ : resolveExperimentSwitch(
3888
+ 'P1',
3889
+ launch.experimentSwitchOverrides,
3890
+ OVERLAP_RUNTIME_TRAFFIC_POLICY_READ,
3891
+ )
3892
+ ? RUNTIME_TRAFFIC_POLICY_HEDGE_AFTER_MS
3893
+ : null;
3894
+ const trafficPolicyHedge =
3895
+ trafficPolicyHedgeAfterMs !== null &&
3896
+ prepared.kind === 'fresh_claimed' &&
3897
+ assigned.checkpoint == null &&
3898
+ assigned.suspension == null &&
3899
+ isManagedSandboxRuntimeBackend(launch.runtimeBackend)
3900
+ ? hedgeRuntimeTrafficPolicyRead({
3901
+ mint: executorTokenMint,
3902
+ delayMs: trafficPolicyHedgeAfterMs,
3903
+ read: () =>
3904
+ getRuntimeTrafficPolicyViaAppRuntime(
3905
+ deps.runtimeApiFromLaunch(launch),
3906
+ ),
3907
+ })
3908
+ : null;
3909
+ const executorToken = await executorTokenMint;
3821
3910
  // Assigned inside the mint callback; widen past control-flow narrowing.
3822
3911
  const renewedSessions = renewedDbSessions as
3823
3912
  | PreloadedRuntimeDbSession[]
@@ -3843,6 +3932,7 @@ async function executeAbsurdAttemptAdapter(
3843
3932
  computeSessionIntentPersisted,
3844
3933
  computeSessionInitialized,
3845
3934
  runtimeTrafficPolicy,
3935
+ hedgedTrafficPolicyRead: trafficPolicyHedge?.started() ?? null,
3846
3936
  runtimeApi,
3847
3937
  });
3848
3938
  } catch (error) {
@@ -4098,6 +4188,8 @@ async function executeAssignedAbsurdAttempt(input: {
4098
4188
  computeSessionIntentPersisted: boolean;
4099
4189
  computeSessionInitialized: boolean;
4100
4190
  runtimeTrafficPolicy: RuntimeTrafficPolicy | null;
4191
+ /** P1 (off): the policy read started during a slow mint, if any. */
4192
+ hedgedTrafficPolicyRead?: Promise<RuntimeTrafficPolicy> | null;
4101
4193
  runtimeApi: WorkerRuntimeApiContext;
4102
4194
  }): Promise<AbsurdRuntimeResult> {
4103
4195
  const {
@@ -4837,6 +4929,11 @@ async function executeAssignedAbsurdAttempt(input: {
4837
4929
  kind: 'app_runtime_postgres' as const,
4838
4930
  schedulerSchema: absurdSchema,
4839
4931
  },
4932
+ // Optional, switch off: name the static plan's tools so the runner's
4933
+ // park-fence startup prefetch can run (read-only lookups only).
4934
+ ...(DURABLE_RUNS_ROLLOUT.workerStartupReadToolIds
4935
+ ? startupReadToolIdsContext(launch.contractSnapshot)
4936
+ : {}),
4840
4937
  // Push execution: the Daytona sandbox runner keeps the Absurd run claim
4841
4938
  // alive itself by heartbeating the receipt gateway. The local-process
4842
4939
  // backend stays worker-babysat, so it gets no push config.
@@ -5183,8 +5280,15 @@ async function executeAssignedAbsurdAttempt(input: {
5183
5280
  ok: true as const,
5184
5281
  policy: input.runtimeTrafficPolicy,
5185
5282
  })
5186
- : measureLaunchPhase('traffic_policy_read', () =>
5187
- getRuntimeTrafficPolicyViaAppRuntime(runtimeApi),
5283
+ : (input.hedgedTrafficPolicyRead
5284
+ ? measureLaunchPhase('traffic_policy_read_hedged', () =>
5285
+ input.hedgedTrafficPolicyRead!.catch(() =>
5286
+ getRuntimeTrafficPolicyViaAppRuntime(runtimeApi),
5287
+ ),
5288
+ )
5289
+ : measureLaunchPhase('traffic_policy_read', () =>
5290
+ getRuntimeTrafficPolicyViaAppRuntime(runtimeApi),
5291
+ )
5188
5292
  ).then(
5189
5293
  (policy) => ({ ok: true as const, policy }),
5190
5294
  (error: unknown) => ({ ok: false as const, error }),
@@ -10810,6 +10914,8 @@ export async function runPostgresSchedulerSandboxCleanupController(input: {
10810
10914
  });
10811
10915
  let reservedRecovery: Promise<void> | null = null;
10812
10916
  let nextReservedRecoveryAt = 0;
10917
+ let earlyModalSweep: Promise<void> | null = null;
10918
+ let nextEarlyModalSweepAt = 0;
10813
10919
 
10814
10920
  const startJob = (job: PostgresSchedulerSandboxCleanupJob): void => {
10815
10921
  const task = processPostgresSchedulerSandboxCleanupJob({
@@ -10886,6 +10992,37 @@ export async function runPostgresSchedulerSandboxCleanupController(input: {
10886
10992
  { error: error instanceof Error ? error.message : String(error) },
10887
10993
  );
10888
10994
  }
10995
+ if (
10996
+ input.providers?.includes('modal') &&
10997
+ !earlyModalSweep &&
10998
+ Date.now() >= nextEarlyModalSweepAt
10999
+ ) {
11000
+ // Durable orphan cleanup for early (E2) sandboxes, which are created
11001
+ // before any run row exists; their create tags are the obligation.
11002
+ // Not awaited: a slow provider never holds up cleanup claims.
11003
+ nextEarlyModalSweepAt = Date.now() + EARLY_MODAL_SANDBOX_SWEEP_INTERVAL_MS;
11004
+ const sweep = sweepOrphanEarlyModalSandboxesForWorker({
11005
+ runtimeSchedulerSchema: input.schedulerOptions.schema ?? null,
11006
+ })
11007
+ .then((outcome) => {
11008
+ if ('observed' in outcome && outcome.observed > 0) {
11009
+ console.info(
11010
+ '[absurd-runtime.worker] early_modal_sandbox_sweep_observed',
11011
+ outcome,
11012
+ );
11013
+ }
11014
+ })
11015
+ .catch((error) => {
11016
+ reportReconciliationPollFailure(
11017
+ '[absurd-runtime.worker] early_modal_sandbox_sweep_failed',
11018
+ { error: error instanceof Error ? error.message : String(error) },
11019
+ );
11020
+ })
11021
+ .finally(() => {
11022
+ if (earlyModalSweep === sweep) earlyModalSweep = null;
11023
+ });
11024
+ earlyModalSweep = sweep;
11025
+ }
10889
11026
  if (input.providers?.includes('modal')) {
10890
11027
  try {
10891
11028
  const reconciliation =
@@ -11179,6 +11316,15 @@ export function resolveAbsurdIdlePollFallbackMs(
11179
11316
  return onWake?.idlePollFallbackMs ?? ABSURD_WAKE_UNAVAILABLE_POLL_INTERVAL_MS;
11180
11317
  }
11181
11318
 
11319
+ /**
11320
+ * Preview experiment E5: let an isolated (Preview) worker lane hold the one
11321
+ * elected direct LISTEN session for its queue, as Production does, so the
11322
+ * transactional `absurd_wake` NOTIFY wakes it instead of the 1 s durable poll.
11323
+ * Polling still owns correctness. Costs one direct Postgres session per lane
11324
+ * from the shared Preview budget. Off.
11325
+ */
11326
+ const PREVIEW_WORKER_DIRECT_NOTIFY_WAKE = false;
11327
+
11182
11328
  export function createAbsurdWorkerWakeHook(input: {
11183
11329
  poolOptions: RuntimeSchedulerPoolOptions;
11184
11330
  queue: string;
@@ -11373,6 +11519,15 @@ export type RuntimeWorkerHost = {
11373
11519
  close(): Promise<void>;
11374
11520
  /** A lossy hint to re-read this host's durable queue, never task admission. */
11375
11521
  wake?(): boolean;
11522
+ /**
11523
+ * CA: present only while the claim-affinity reader is on. `id` is the name
11524
+ * this worker claims under; `startOwnerProbe` runs after this worker accepts
11525
+ * a CA early-sandbox hint, so it claims the run it was named owner of.
11526
+ */
11527
+ earlySandboxClaimOwner?: {
11528
+ id: string;
11529
+ startOwnerProbe(): void;
11530
+ };
11376
11531
  };
11377
11532
 
11378
11533
  /** Own shutdown ordering across the primary queue, listener and maintenance.
@@ -11382,6 +11537,7 @@ export function createAbsurdRuntimeWorkerHostLifecycle(input: {
11382
11537
  worker: RuntimeWorkerHost;
11383
11538
  closeWake: () => void;
11384
11539
  wake?: () => boolean;
11540
+ earlySandboxClaimOwner?: RuntimeWorkerHost['earlySandboxClaimOwner'];
11385
11541
  stopControllers: () => void;
11386
11542
  controllers: readonly (Promise<unknown> | null)[];
11387
11543
  }): RuntimeWorkerHost {
@@ -11389,6 +11545,9 @@ export function createAbsurdRuntimeWorkerHostLifecycle(input: {
11389
11545
  let wake = input.wake;
11390
11546
  return {
11391
11547
  ...(wake ? { wake: () => wake?.() ?? false } : {}),
11548
+ ...(input.earlySandboxClaimOwner
11549
+ ? { earlySandboxClaimOwner: input.earlySandboxClaimOwner }
11550
+ : {}),
11392
11551
  close: () => {
11393
11552
  if (closing) return closing;
11394
11553
  wake = undefined;
@@ -11520,10 +11679,21 @@ export async function startRuntimeWorkerHost(
11520
11679
  // Times the claim query, the afterClaim hook, task setup and handler end
11521
11680
  // on the active lane (`absurd-claim-loop-timing.ts`).
11522
11681
  const claimLoopTiming = createAbsurdClaimLoopTiming({ queue });
11682
+ // CA: the claim gate needs the wake hook, which is created after the
11683
+ // client; it reads it late. Off unless the reader switch is on.
11684
+ let claimAffinityWake: (() => boolean) | null = null;
11685
+ const claimAffinityGate = EARLY_SANDBOX_CLAIM_AFFINITY_READER
11686
+ ? createEarlySandboxClaimGate({
11687
+ self: workerBase,
11688
+ queue,
11689
+ wake: () => claimAffinityWake?.() ?? false,
11690
+ })
11691
+ : undefined;
11523
11692
  const absurdClient = createAbsurdRuntimeClient(
11524
11693
  poolOptions,
11525
11694
  queue,
11526
11695
  claimLoopTiming.observer,
11696
+ claimAffinityGate,
11527
11697
  );
11528
11698
  const workerDeps: AbsurdRuntimeWorkerDeps = {
11529
11699
  ...buildDefaultDeps(absurdClient),
@@ -11548,9 +11718,14 @@ export async function startRuntimeWorkerHost(
11548
11718
  ...recovered,
11549
11719
  });
11550
11720
  }
11551
- const useDirectNotify = shouldUseRuntimeSchedulerDirectNotify(
11552
- schedulerOptions.schema,
11553
- );
11721
+ const useDirectNotify =
11722
+ PREVIEW_WORKER_DIRECT_NOTIFY_WAKE ||
11723
+ shouldUseRuntimeSchedulerDirectNotify(schedulerOptions.schema);
11724
+ console.info('[absurd-runtime.worker] wake_config', {
11725
+ queue,
11726
+ useDirectNotify,
11727
+ previewDirectNotifyWake: PREVIEW_WORKER_DIRECT_NOTIFY_WAKE,
11728
+ });
11554
11729
  const onWake = createAbsurdWorkerWakeHook({
11555
11730
  poolOptions,
11556
11731
  queue,
@@ -11560,6 +11735,41 @@ export async function startRuntimeWorkerHost(
11560
11735
  useDirectNotify,
11561
11736
  enableWakeHints: true,
11562
11737
  });
11738
+ claimAffinityWake = onWake ? () => onWake.wake() : null;
11739
+ let ownerProbeStopped = false;
11740
+ const earlySandboxClaimOwner: RuntimeWorkerHost['earlySandboxClaimOwner'] =
11741
+ claimAffinityGate && onWake
11742
+ ? {
11743
+ id: workerBase,
11744
+ startOwnerProbe: () => {
11745
+ // The elected listener is woken by the run's own NOTIFY.
11746
+ if (onWake.isListening() || ownerProbeStopped) return;
11747
+ const startedAt = Date.now();
11748
+ void runEarlySandboxOwnerClaimProbe({
11749
+ probe: () =>
11750
+ withRuntimeSchedulerClient(poolOptions, (client) =>
11751
+ hasPendingEarlySandboxClaim({
11752
+ client,
11753
+ queue,
11754
+ owner: workerBase,
11755
+ }),
11756
+ ),
11757
+ wake: () => !ownerProbeStopped && onWake.wake(),
11758
+ onError: (error) =>
11759
+ console.warn('[runtime.claim_affinity]', {
11760
+ event: 'owner_probe_failed',
11761
+ error: error instanceof Error ? error.message : String(error),
11762
+ }),
11763
+ }).then((result) =>
11764
+ console.info('[runtime.claim_affinity]', {
11765
+ event: 'owner_probe_done',
11766
+ ...result,
11767
+ elapsedMs: Date.now() - startedAt,
11768
+ }),
11769
+ );
11770
+ },
11771
+ }
11772
+ : undefined;
11563
11773
  const reportCancellationProgress = createRateLimitedRuntimeLogger({
11564
11774
  log: (...args) => console.info(...args),
11565
11775
  });
@@ -11870,11 +12080,13 @@ export async function startRuntimeWorkerHost(
11870
12080
  return createAbsurdRuntimeWorkerHostLifecycle({
11871
12081
  worker,
11872
12082
  ...(onWake ? { wake: () => onWake.wake() } : {}),
12083
+ ...(earlySandboxClaimOwner ? { earlySandboxClaimOwner } : {}),
11873
12084
  // Release LISTEN before joining accepted work, so a replacement can elect
11874
12085
  // its listener without exhausting primary scheduler sessions.
11875
12086
  closeWake: () => onWake?.close(),
11876
12087
  stopControllers: () => {
11877
12088
  standbyProbeStopped = true;
12089
+ ownerProbeStopped = true;
11878
12090
  drainStopped = true;
11879
12091
  billingStopped = true;
11880
12092
  cleanupStopped = true;
@@ -33,6 +33,7 @@ import {
33
33
  createAbsurdForRuntimeScheduler,
34
34
  type AbsurdSchedulerQueryObserver,
35
35
  } from './absurd-pool';
36
+ import type { EarlySandboxClaimGate } from './early-sandbox-claim-affinity';
36
37
  import {
37
38
  withRuntimeSchedulerClient,
38
39
  type RuntimeSchedulerPoolOptions,
@@ -543,6 +544,7 @@ export function createAbsurdRuntimeClient(
543
544
  poolOptions: RuntimeSchedulerPoolOptions,
544
545
  queueName: string = ABSURD_RUNS_QUEUE,
545
546
  observer?: AbsurdSchedulerQueryObserver,
547
+ claimGate?: EarlySandboxClaimGate,
546
548
  ): Absurd {
547
549
  return createAbsurdForRuntimeScheduler(
548
550
  poolOptions,
@@ -551,6 +553,7 @@ export function createAbsurdRuntimeClient(
551
553
  log: absurdLog,
552
554
  },
553
555
  observer,
556
+ claimGate,
554
557
  );
555
558
  }
556
559