deepline 0.3.537 → 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 +18 -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-4SUPGDIM.mjs → auth-KYH7N7RQ.mjs} +5 -5
  61. package/dist/cli/{billing-SQU726P7.js → billing-4KTUVZ4S.js} +114 -90
  62. package/dist/cli/{billing-5JUA3ZM3.mjs → billing-WK346KAI.mjs} +31 -7
  63. package/dist/cli/{chunk-KULT6O5K.js → chunk-25RGHJQL.js} +15 -15
  64. package/dist/cli/{chunk-PJ4ZGZAN.js → chunk-34PLG5OE.js} +13 -13
  65. package/dist/cli/{chunk-37AZHCTP.mjs → chunk-35OCRH5C.mjs} +5 -5
  66. package/dist/cli/{chunk-JMHYDDBQ.js → chunk-3I5TU5XE.js} +292 -279
  67. package/dist/cli/{chunk-Y6AMMXWS.mjs → chunk-4KZF6OYY.mjs} +3 -3
  68. package/dist/cli/{chunk-BRRCWUOW.mjs → chunk-4NEOGPKD.mjs} +1 -1
  69. package/dist/cli/{chunk-NU7B5X6J.mjs → chunk-4WQR4DG4.mjs} +1 -1
  70. package/dist/cli/{chunk-AVQET3NR.js → chunk-5VSPRRTI.js} +7 -7
  71. package/dist/cli/{chunk-EEFSUCYP.mjs → chunk-6JG3MRTM.mjs} +2 -2
  72. package/dist/cli/{chunk-D77W6Q67.js → chunk-6SLQLWWL.js} +26 -26
  73. package/dist/cli/{chunk-ZUAMXZXC.mjs → chunk-7XDJKIM2.mjs} +4 -4
  74. package/dist/cli/{chunk-C37VELBR.mjs → chunk-A6E7TCK2.mjs} +5 -5
  75. package/dist/cli/{chunk-JS2SBCWD.js → chunk-ADLDU2QG.js} +6 -6
  76. package/dist/cli/{chunk-VP2K5B3R.mjs → chunk-ALARRSMZ.mjs} +3 -3
  77. package/dist/cli/{chunk-CHIGEDAE.js → chunk-B2BTBHX2.js} +3 -3
  78. package/dist/cli/{chunk-CFND2ACL.js → chunk-BBS2BLPV.js} +16 -16
  79. package/dist/cli/{chunk-QDBGPRR2.mjs → chunk-CLO562KG.mjs} +3 -1
  80. package/dist/cli/{chunk-CXTW7SRW.mjs → chunk-E7D37PLM.mjs} +8 -0
  81. package/dist/cli/{chunk-UGA5KI4A.js → chunk-ESX3H7Q7.js} +22 -22
  82. package/dist/cli/{chunk-BFHR7IC2.mjs → chunk-FJ5KPGCS.mjs} +10 -10
  83. package/dist/cli/{chunk-R7JYG6XO.mjs → chunk-FWE37N2P.mjs} +1 -1
  84. package/dist/cli/{chunk-K4WJ4BYO.mjs → chunk-ICTA5ICE.mjs} +1 -1
  85. package/dist/cli/{chunk-PU42VOBI.js → chunk-IMLFB66A.js} +3 -3
  86. package/dist/cli/{chunk-GI3V4D7K.mjs → chunk-IP3XJTWA.mjs} +2 -2
  87. package/dist/cli/{chunk-WBFOV5HT.js → chunk-JCLRSMUP.js} +5 -5
  88. package/dist/cli/{chunk-L3JVGNAT.mjs → chunk-JPEBKN3K.mjs} +2 -2
  89. package/dist/cli/{chunk-Z2PPB3IO.mjs → chunk-JTOV5RUA.mjs} +1 -1
  90. package/dist/cli/{chunk-WBTYWJLN.js → chunk-KCUQNH4K.js} +2 -2
  91. package/dist/cli/{chunk-C3XD2WHM.mjs → chunk-KNIYEZVV.mjs} +2 -2
  92. package/dist/cli/{chunk-3PMCQ3LK.js → chunk-LPTBHNGB.js} +7 -5
  93. package/dist/cli/{chunk-KH27B2HJ.mjs → chunk-M3NCXGNN.mjs} +2 -2
  94. package/dist/cli/{chunk-XDS26J7Z.js → chunk-MNBIGX6O.js} +10 -10
  95. package/dist/cli/{chunk-L6QAIZNZ.js → chunk-MYSPQUAO.js} +44 -44
  96. package/dist/cli/{chunk-W3J3LT22.mjs → chunk-N2BCPZVR.mjs} +5 -5
  97. package/dist/cli/{chunk-ZFSB7GXF.js → chunk-N5HSG4OV.js} +5 -5
  98. package/dist/cli/{chunk-2Q7VXTMS.js → chunk-O765M4LT.js} +2 -2
  99. package/dist/cli/{chunk-QPDLG7DQ.js → chunk-OOLBE6FR.js} +53 -53
  100. package/dist/cli/{chunk-IQOIT6E3.js → chunk-P3DP56HB.js} +41 -41
  101. package/dist/cli/{chunk-BGXEMTIG.js → chunk-PQKD5DMT.js} +19 -19
  102. package/dist/cli/{chunk-V5IIBG2E.mjs → chunk-T6GPTJ5F.mjs} +1 -1
  103. package/dist/cli/{chunk-GPMS6OPX.mjs → chunk-TWWYCJJW.mjs} +5 -5
  104. package/dist/cli/{chunk-ZHPSJ3LJ.mjs → chunk-UE7JHAZ2.mjs} +29 -16
  105. package/dist/cli/{chunk-VRYX2BR4.js → chunk-UEZNIPFO.js} +107 -107
  106. package/dist/cli/{chunk-AX2OAXDL.mjs → chunk-VCHV4LS3.mjs} +1 -1
  107. package/dist/cli/{chunk-NXGLJGPB.js → chunk-VIFLWQXS.js} +2 -2
  108. package/dist/cli/{chunk-6BBGUQJJ.js → chunk-XTYHZEJ2.js} +8 -0
  109. package/dist/cli/{chunk-5EOEJKSV.js → chunk-YQURGSRB.js} +1 -1
  110. package/dist/cli/{chunk-ALHKB3AE.js → chunk-YZ2ZPHWR.js} +9 -9
  111. package/dist/cli/{chunk-CGDW2CRR.mjs → chunk-ZDLDCXY3.mjs} +2 -2
  112. package/dist/cli/{chunk-RMVZTBI5.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-HZP6QMG7.mjs → csv-2YKLUKDR.mjs} +4 -4
  116. package/dist/cli/{csv-JITYN27L.js → csv-LM7FBECI.js} +13 -13
  117. package/dist/cli/{db-QRIRTOMM.mjs → db-234UBWJH.mjs} +6 -6
  118. package/dist/cli/{db-FYSRB7O4.js → db-5PMA4IVW.js} +27 -27
  119. package/dist/cli/describe-C7GOSGYB.js +49 -0
  120. package/dist/cli/{describe-REXJVJC3.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-BSTF4DDS.js → executions-3S736GXX.js} +8 -8
  124. package/dist/cli/{executions-53KJAFOW.mjs → executions-GD7GXTJM.mjs} +6 -6
  125. package/dist/cli/{feedback-6MW3QOXX.js → feedback-BUWTDY4R.js} +14 -14
  126. package/dist/cli/{feedback-CWUJJF3J.mjs → feedback-GBV5HJJZ.mjs} +6 -6
  127. package/dist/cli/git-YG36MROC.js +25 -0
  128. package/dist/cli/{git-CKVZTJFS.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-USTBRFRX.mjs → legacy-noops-UJM6GBNP.mjs} +6 -6
  132. package/dist/cli/{legacy-noops-QBL4PNGB.js → legacy-noops-ZSF64V2U.js} +9 -9
  133. package/dist/cli/{monitors-6UCG5D7W.mjs → monitors-UERUQ6CT.mjs} +7 -7
  134. package/dist/cli/{monitors-VCR6SUZD.js → monitors-XQ2GNH6D.js} +100 -100
  135. package/dist/cli/{org-GSRBOJVO.mjs → org-CP4VLH6M.mjs} +6 -6
  136. package/dist/cli/{org-HPILTEG4.js → org-IF6MPVNR.js} +86 -86
  137. package/dist/cli/{play-TK7WOP5H.js → play-2NHQO5MO.js} +317 -317
  138. package/dist/cli/{play-QRTYQNG4.mjs → play-ZWDYYVPI.mjs} +17 -17
  139. package/dist/cli/{providers-OAQJWVBS.mjs → providers-2CVIATU4.mjs} +6 -6
  140. package/dist/cli/{providers-HEXNJ5QC.js → providers-LOPXQN56.js} +9 -9
  141. package/dist/cli/{quickstart-FFVHTPSP.mjs → quickstart-KVCFXLID.mjs} +4 -4
  142. package/dist/cli/{quickstart-PYZTFXZX.js → quickstart-N4WDEQZY.js} +6 -6
  143. package/dist/cli/{run-4DWJXJRO.js → run-BDT5LK3I.js} +42 -42
  144. package/dist/cli/{run-HLN6YYZH.mjs → run-RUXHYWLF.mjs} +22 -22
  145. package/dist/cli/search-ATDDVADT.js +32 -0
  146. package/dist/cli/{search-ZHRCXGEL.mjs → search-BFUTNPA5.mjs} +7 -7
  147. package/dist/cli/{search-output-2KY6PFDH.js → search-output-CTXI2QZU.js} +6 -6
  148. package/dist/cli/{search-output-N7QXACVK.mjs → search-output-WUGH4PZA.mjs} +4 -4
  149. package/dist/cli/{secrets-WXQ7XO5C.js → secrets-BZJZYFOU.js} +15 -15
  150. package/dist/cli/{secrets-FKMWBLHU.mjs → secrets-Z4XQVTC6.mjs} +6 -6
  151. package/dist/cli/sessions-HNU35AFM.js +22 -0
  152. package/dist/cli/{sessions-3YDTEDA5.mjs → sessions-VZXR3MQZ.mjs} +6 -6
  153. package/dist/cli/{settings-JTPASUZN.mjs → settings-VYEZFR4L.mjs} +12 -12
  154. package/dist/cli/{settings-67TWLQ6E.js → settings-WBYA4JMM.js} +85 -85
  155. package/dist/cli/{setup-KUERQJUX.js → setup-FS2RMSS2.js} +49 -49
  156. package/dist/cli/{setup-VYNGXUJ6.mjs → setup-H7KCI4SO.mjs} +9 -9
  157. package/dist/cli/skills-VPIURCAZ.js +36 -0
  158. package/dist/cli/{skills-KI4KYHH6.mjs → skills-YQNSJUUG.mjs} +7 -7
  159. package/dist/cli/tools-273GS5HU.js +56 -0
  160. package/dist/cli/{tools-UQDJS2RS.mjs → tools-ZF6SVEGW.mjs} +16 -16
  161. package/dist/cli/{update-7FQQUBOD.mjs → update-RKQNNJM4.mjs} +9 -9
  162. package/dist/cli/update-TOD3XY55.js +34 -0
  163. package/dist/cli/{views-JAM4MNNV.mjs → views-JHHOTWDU.mjs} +6 -6
  164. package/dist/cli/{views-MJK7JGZG.js → views-KN7FEDGT.js} +21 -21
  165. package/dist/cli/{workflow-AQPRIWQX.js → workflow-2WHSKTTV.js} +17 -17
  166. package/dist/cli/{workflow-TQRV5FGO.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.ts → compiler-manifest-Bes3OVA3.d.mts} +1 -1
  172. package/dist/{compiler-manifest-BHNC4RL-.d.mts → 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-Y2K2ZYYA.js +0 -43
  198. package/dist/cli/describe-LSOHOLFI.js +0 -49
  199. package/dist/cli/git-S7SWUZ3T.js +0 -25
  200. package/dist/cli/search-WERQBC6V.js +0 -32
  201. package/dist/cli/sessions-LXQ4Q6BS.js +0 -22
  202. package/dist/cli/skills-EFRLHY3F.js +0 -36
  203. package/dist/cli/tools-C3EIGFFP.js +0 -56
  204. package/dist/cli/update-KCY72RXH.js +0 -34
@@ -1,4 +1,5 @@
1
- import type { ModalClient } from 'modal';
1
+ import { createHash } from 'node:crypto';
2
+ import type { ModalClient, SidecarCreateParams } from 'modal';
2
3
  import type { PlayRunnerBackend, PlayRunnerCallbacks } from '../types';
3
4
  import {
4
5
  isRuntimeSandboxCapacityLimitError,
@@ -26,13 +27,32 @@ import {
26
27
  withModalCallSignal,
27
28
  } from '../../modal-runtime-config';
28
29
  import type { PlaySandboxRuntimeLimits } from '../../../plays/sandbox-runtime-limits';
30
+ import {
31
+ bakedRunnerPlanForLaunch,
32
+ configuredBakedRunnerHash,
33
+ bakedVerdictRequiresFallback,
34
+ parseBakedRunnerVerdict,
35
+ type BakedRunnerVerdict,
36
+ resolveModalRunnerImage,
37
+ } from '../../baked-runner-image';
29
38
  import { validateDaytonaExecutionContext } from './daytona-lifecycle';
30
39
  import {
40
+ buildPrebootedRunnerLaunch,
41
+ INLINE_BAKED_RUNNER_UNVERIFIED_EXIT_CODE,
42
+ INLINE_ENVELOPE_INCOMPLETE_EXIT_CODE,
43
+ PrebootedRunnerLimitsMismatchError,
44
+ samePlaySandboxRuntimeLimits,
31
45
  stageRunnerPayload,
46
+ type BakedRunnerExpectation,
47
+ type PrebootedRunnerLaunch,
48
+ type StagedDaytonaPayload,
32
49
  withRunnerSandboxProvider,
33
50
  } from './daytona-payload-transport';
34
51
  import { captureDetachedDaytonaRunnerReadinessBaseline } from './daytona-session-execution';
35
- import { createDetachedRunnerReadinessPacer } from './detached-runner-readiness-pacing';
52
+ import {
53
+ createDetachedRunnerReadinessPacer,
54
+ EXTENDED_FAST_READINESS_WINDOW,
55
+ } from './detached-runner-readiness-pacing';
36
56
  import {
37
57
  isPlayRunRecoveryError,
38
58
  recoveryForOpenModalCircuit,
@@ -41,6 +61,26 @@ import {
41
61
  } from '../../play-run-recovery-policy';
42
62
  import { shouldInjectModalSandboxCreateResourceExhausted } from '../../test-runtime-seams';
43
63
  import { RUNTIME_RELIABILITY_POLICY } from '../../runtime-reliability-policy';
64
+ import { DURABLE_RUNS_ROLLOUT } from '../../durable-runs-rollout';
65
+ import {
66
+ MODAL_SUPERVISOR_RUN_PIN_ENV,
67
+ MODAL_SUPERVISOR_SIDECAR_NAME,
68
+ configuredModalSupervisorHash,
69
+ modalSupervisorCommand,
70
+ modalSupervisorEnvironment,
71
+ modalSupervisorImageRef,
72
+ modalSupervisorLaunch,
73
+ modalSupervisorRunnerContext,
74
+ modalSupervisorRunPin,
75
+ modalSupervisorRunPinCommand,
76
+ modalSupervisorTrustedAppOrigins,
77
+ executePrewarmSentAtAdmission,
78
+ type ModalSupervisorRunPin,
79
+ } from '../../modal-supervisor-sidecar';
80
+ import {
81
+ resolveExperimentSwitch,
82
+ type ExperimentSwitchOverrides,
83
+ } from '../../experiment-switches';
44
84
 
45
85
  const MODAL_RUNNER_READY_TIMEOUT_MS =
46
86
  RUNTIME_RELIABILITY_POLICY.sandbox.runnerReadyTimeoutMs;
@@ -131,6 +171,462 @@ async function writeModalFileWithDeadline(input: {
131
171
  }
132
172
  }
133
173
 
174
+ const MODAL_INLINE_STDIN_TIMEOUT_MS = 30_000;
175
+ /**
176
+ * Each stdin write is one Modal RPC. The envelope goes in writes of at most
177
+ * this many base64 characters (1 MiB), the same order as the SDK's own
178
+ * filesystem write chunk, so a large envelope never becomes one oversized
179
+ * message.
180
+ */
181
+ export const MODAL_INLINE_STDIN_CHUNK_CHARS = 1024 * 1024;
182
+
183
+ async function waitForExit(input: {
184
+ launched: { wait(): Promise<number> };
185
+ cancellation: Promise<never>;
186
+ timeoutMs: number;
187
+ }): Promise<number> {
188
+ let timer: ReturnType<typeof setTimeout> | undefined;
189
+ try {
190
+ return await Promise.race([
191
+ input.launched.wait(),
192
+ input.cancellation,
193
+ new Promise<never>((_resolve, reject) => {
194
+ timer = setTimeout(
195
+ () =>
196
+ reject(
197
+ new Error(
198
+ 'Modal inline launch did not exit after stdin EOF; not falling back.',
199
+ ),
200
+ ),
201
+ input.timeoutMs,
202
+ );
203
+ }),
204
+ ]);
205
+ } finally {
206
+ if (timer) clearTimeout(timer);
207
+ }
208
+ }
209
+
210
+ class BakedRunnerVerdictLineTimeoutError extends Error {
211
+ constructor() {
212
+ super('Baked runner verdict line timed out.');
213
+ this.name = 'BakedRunnerVerdictLineTimeoutError';
214
+ }
215
+ }
216
+
217
+ /** First stdout line of a launched command, without consuming the rest. */
218
+ async function readFirstStdoutLine(input: {
219
+ stdout: ReadableStream<string>;
220
+ cancellation: Promise<never>;
221
+ timeoutMs: number;
222
+ }): Promise<string> {
223
+ const reader = input.stdout.getReader();
224
+ let timer: ReturnType<typeof setTimeout> | undefined;
225
+ let text = '';
226
+ try {
227
+ return await Promise.race([
228
+ (async () => {
229
+ for (;;) {
230
+ const { value, done } = await reader.read();
231
+ if (value) text += value;
232
+ const newline = text.indexOf('\n');
233
+ if (newline >= 0) return text.slice(0, newline);
234
+ if (done) return text;
235
+ }
236
+ })(),
237
+ input.cancellation,
238
+ new Promise<never>((_resolve, reject) => {
239
+ timer = setTimeout(
240
+ () => reject(new BakedRunnerVerdictLineTimeoutError()),
241
+ input.timeoutMs,
242
+ );
243
+ }),
244
+ ]);
245
+ } finally {
246
+ if (timer) clearTimeout(timer);
247
+ try {
248
+ reader.releaseLock();
249
+ } catch {
250
+ // A read still pending after a timeout; the stream is not used again.
251
+ }
252
+ }
253
+ }
254
+
255
+ /**
256
+ * Writes the base64 envelope to a launched command's stdin in bounded chunks,
257
+ * then closes it (EOF), within one deadline.
258
+ */
259
+ async function writeInlineEnvelopeToStdin(input: {
260
+ stdin: { writeText(text: string): Promise<void>; close(): Promise<void> };
261
+ base64: string;
262
+ cancellation: Promise<never>;
263
+ timeoutMs: number;
264
+ }): Promise<void> {
265
+ let timer: ReturnType<typeof setTimeout> | undefined;
266
+ try {
267
+ await Promise.race([
268
+ (async () => {
269
+ for (
270
+ let offset = 0;
271
+ offset < input.base64.length;
272
+ offset += MODAL_INLINE_STDIN_CHUNK_CHARS
273
+ ) {
274
+ await input.stdin.writeText(
275
+ input.base64.slice(offset, offset + MODAL_INLINE_STDIN_CHUNK_CHARS),
276
+ );
277
+ }
278
+ await input.stdin.close();
279
+ })(),
280
+ input.cancellation,
281
+ new Promise<never>((_resolve, reject) => {
282
+ timer = setTimeout(
283
+ () => reject(new Error('Modal inline envelope stdin timed out.')),
284
+ input.timeoutMs,
285
+ );
286
+ }),
287
+ ]);
288
+ } finally {
289
+ if (timer) clearTimeout(timer);
290
+ }
291
+ }
292
+
293
+ /**
294
+ * Starts the staged runner command. With an inline envelope the command reads
295
+ * it from its own stdin (secret-safe: never argv or env), so the launch is one
296
+ * exec instead of a filesystem write plus an exec. If stdin delivery fails,
297
+ * the inline command exits before running anything (its byte-count guard), and
298
+ * this falls back loudly to the original path: upload the envelope, then exec
299
+ * the unchanged command. Without an inline envelope this is exactly one exec.
300
+ */
301
+ export async function launchModalRunnerCommand(input: {
302
+ sandbox: Pick<ModalSandbox, 'exec' | 'sandboxId'> & {
303
+ filesystem: Pick<ModalSandbox['filesystem'], 'writeBytes'>;
304
+ };
305
+ payload: Pick<StagedDaytonaPayload, 'command' | 'inlineEnvelope'>;
306
+ cancellation: Promise<never>;
307
+ emitStage: (stage: string, extra?: Record<string, unknown>) => void;
308
+ stdinTimeoutMs?: number;
309
+ /**
310
+ * Required when the inline command verifies the baked runner itself: stages
311
+ * today's full upload (runner included) on the same sandbox, used only when
312
+ * the in-command verdict is not `ok`.
313
+ */
314
+ stageFullUpload?: () => Promise<ModalRestagedRunnerPayload>;
315
+ }): Promise<ModalRunnerLaunch> {
316
+ const inline = input.payload.inlineEnvelope;
317
+ if (!inline) {
318
+ await input.sandbox.exec(['bash', '-lc', input.payload.command]);
319
+ return {};
320
+ }
321
+ const startedAt = Date.now();
322
+ const launched = await input.sandbox.exec([
323
+ 'bash',
324
+ '-lc',
325
+ inline.inlineCommand,
326
+ ]);
327
+ // The envelope goes onto stdin right away: the in-sandbox guard reads it
328
+ // only after an `ok` verdict, so the worker need not wait for that verdict
329
+ // (about one log-stream round trip) before the runner can start. The
330
+ // verdict is still read, and a non-`ok` verdict still selects today's full
331
+ // upload; the caller awaits both before treating the launch as ready.
332
+ const bakedVerdict: Promise<BakedRunnerVerdict> | undefined =
333
+ inline.verifiesBakedRunner
334
+ ? readFirstStdoutLine({
335
+ stdout: launched.stdout,
336
+ cancellation: input.cancellation,
337
+ timeoutMs: input.stdinTimeoutMs ?? MODAL_INLINE_STDIN_TIMEOUT_MS,
338
+ }).then(
339
+ (line) => parseBakedRunnerVerdict(line),
340
+ // A slow log stream is not a refusal: the guard has the envelope
341
+ // and decides for itself, and readiness confirms the runner.
342
+ (error: unknown): BakedRunnerVerdict =>
343
+ error instanceof BakedRunnerVerdictLineTimeoutError
344
+ ? 'late'
345
+ : 'no_verdict',
346
+ )
347
+ : undefined;
348
+ const runBakedFallback = async (verdict: BakedRunnerVerdict) => {
349
+ if (!input.stageFullUpload) {
350
+ throw new Error(
351
+ 'Baked runner did not verify and no full upload is staged.',
352
+ );
353
+ }
354
+ // The guard exited 98 before reading stdin; EOF covers a hung probe.
355
+ await launched.closeStdin().catch(() => undefined);
356
+ await waitForExit({
357
+ launched,
358
+ cancellation: input.cancellation,
359
+ timeoutMs: input.stdinTimeoutMs ?? MODAL_INLINE_STDIN_TIMEOUT_MS,
360
+ });
361
+ input.emitStage('runner:placement', {
362
+ sandboxId: input.sandbox.sandboxId,
363
+ source: 'uploaded_fallback',
364
+ bakedRunnerVerdict: verdict,
365
+ });
366
+ const full = await input.stageFullUpload();
367
+ await input.sandbox.exec(['bash', '-lc', full.command]);
368
+ return full;
369
+ };
370
+ try {
371
+ await writeInlineEnvelopeToStdin({
372
+ stdin: launched.stdin,
373
+ base64: inline.base64,
374
+ cancellation: input.cancellation,
375
+ timeoutMs: input.stdinTimeoutMs ?? MODAL_INLINE_STDIN_TIMEOUT_MS,
376
+ });
377
+ input.emitStage('upload:payload:inline_delivered', {
378
+ sandboxId: input.sandbox.sandboxId,
379
+ bytes: inline.envelope.byteLength,
380
+ elapsedMs: Date.now() - startedAt,
381
+ });
382
+ return bakedVerdict ? { bakedVerdict, runBakedFallback, startedAt } : {};
383
+ } catch (error) {
384
+ input.emitStage('upload:payload:inline_failed', {
385
+ sandboxId: input.sandbox.sandboxId,
386
+ error: error instanceof Error ? error.message : String(error),
387
+ });
388
+ // EOF makes the guard exit before any runner work; wait for it so its
389
+ // partial file cannot race the upload below.
390
+ await launched.closeStdin().catch(() => undefined);
391
+ await waitForExit({
392
+ launched,
393
+ cancellation: input.cancellation,
394
+ timeoutMs: input.stdinTimeoutMs ?? MODAL_INLINE_STDIN_TIMEOUT_MS,
395
+ });
396
+ }
397
+ await writeModalFileWithDeadline({
398
+ sandbox: input.sandbox as ModalSandbox,
399
+ content: inline.envelope,
400
+ path: inline.envelopePath,
401
+ cancellation: input.cancellation,
402
+ });
403
+ input.emitStage('upload:payload:done', {
404
+ bytes: inline.envelope.byteLength,
405
+ elapsedMs: Date.now() - startedAt,
406
+ fallbackFromInline: true,
407
+ });
408
+ // The guard that would have checked the baked file did not run (stdin
409
+ // failed before it read anything), so this path verifies nothing: it runs
410
+ // the staged command only when no baked verification is owed.
411
+ if (bakedVerdict) {
412
+ // A guarded inline command names the baked runner path; without a
413
+ // verdict it must not run. Use today's full upload instead.
414
+ await bakedVerdict.catch(() => undefined);
415
+ return { restaged: await runBakedFallback('no_verdict') };
416
+ }
417
+ await input.sandbox.exec(['bash', '-lc', input.payload.command]);
418
+ return {};
419
+ }
420
+
421
+ /**
422
+ * PB delivery: hand a pre-booted runner (already polling for its config in
423
+ * this sandbox) its envelope. One exec reads the envelope from stdin (the same
424
+ * byte-count guard as the inline launch: exit 97 before anything else on a
425
+ * short read) and materializes the run's files, config last via rename; the
426
+ * waiting runner then starts the run. `materialized` settles when that exec
427
+ * exits: a non-zero exit rejects it.
428
+ *
429
+ * If stdin delivery fails, the exec's own exit code decides: 0 means the
430
+ * guard had the whole envelope and the files are written; 97 means nothing
431
+ * was written, so the envelope is uploaded and the same materializer runs from
432
+ * the file; anything else is a loud failure (nothing past the guard is
433
+ * retried over a possibly half-written run).
434
+ */
435
+ export async function deliverPrebootedRunnerEnvelope(input: {
436
+ sandbox: Pick<ModalSandbox, 'exec' | 'sandboxId'> & {
437
+ filesystem: Pick<ModalSandbox['filesystem'], 'writeBytes'>;
438
+ };
439
+ payload: Pick<StagedDaytonaPayload, 'command' | 'inlineEnvelope'>;
440
+ cancellation: Promise<never>;
441
+ emitStage: (stage: string, extra?: Record<string, unknown>) => void;
442
+ stdinTimeoutMs?: number;
443
+ }): Promise<{ materialized: Promise<void> }> {
444
+ const inline = input.payload.inlineEnvelope;
445
+ if (!inline || inline.verifiesBakedRunner) {
446
+ throw new Error(
447
+ 'A pre-booted runner takes its envelope on stdin with no in-command verification.',
448
+ );
449
+ }
450
+ const timeoutMs = input.stdinTimeoutMs ?? MODAL_INLINE_STDIN_TIMEOUT_MS;
451
+ const exitedZero = (
452
+ launched: { wait(): Promise<number> },
453
+ what: string,
454
+ ): Promise<void> =>
455
+ launched.wait().then((code) => {
456
+ if (code !== 0) {
457
+ throw new Error(
458
+ `Pre-booted runner delivery (${what}) exited ${code}; the runner config was not written.`,
459
+ );
460
+ }
461
+ });
462
+ const startedAt = Date.now();
463
+ const launched = await input.sandbox.exec([
464
+ 'bash',
465
+ '-lc',
466
+ inline.inlineCommand,
467
+ ]);
468
+ try {
469
+ await writeInlineEnvelopeToStdin({
470
+ stdin: launched.stdin,
471
+ base64: inline.base64,
472
+ cancellation: input.cancellation,
473
+ timeoutMs,
474
+ });
475
+ input.emitStage('execute:preboot_delivered', {
476
+ sandboxId: input.sandbox.sandboxId,
477
+ bytes: inline.envelope.byteLength,
478
+ elapsedMs: Date.now() - startedAt,
479
+ });
480
+ return { materialized: exitedZero(launched, 'stdin') };
481
+ } catch (error) {
482
+ input.emitStage('upload:payload:inline_failed', {
483
+ sandboxId: input.sandbox.sandboxId,
484
+ preboot: true,
485
+ error: error instanceof Error ? error.message : String(error),
486
+ });
487
+ }
488
+ await launched.closeStdin().catch(() => undefined);
489
+ const code = await waitForExit({
490
+ launched,
491
+ cancellation: input.cancellation,
492
+ timeoutMs,
493
+ });
494
+ if (code === 0) {
495
+ input.emitStage('execute:preboot_delivered', {
496
+ sandboxId: input.sandbox.sandboxId,
497
+ bytes: inline.envelope.byteLength,
498
+ elapsedMs: Date.now() - startedAt,
499
+ stdinErrorAfterDelivery: true,
500
+ });
501
+ return { materialized: Promise.resolve() };
502
+ }
503
+ if (code !== INLINE_ENVELOPE_INCOMPLETE_EXIT_CODE) {
504
+ throw new Error(
505
+ `Pre-booted runner delivery exited ${code} after a stdin failure; not retrying over a possibly partial delivery.`,
506
+ );
507
+ }
508
+ await writeModalFileWithDeadline({
509
+ sandbox: input.sandbox as ModalSandbox,
510
+ content: inline.envelope,
511
+ path: inline.envelopePath,
512
+ cancellation: input.cancellation,
513
+ });
514
+ const fromFile = await input.sandbox.exec([
515
+ 'bash',
516
+ '-lc',
517
+ input.payload.command,
518
+ ]);
519
+ input.emitStage('execute:preboot_delivered', {
520
+ sandboxId: input.sandbox.sandboxId,
521
+ bytes: inline.envelope.byteLength,
522
+ elapsedMs: Date.now() - startedAt,
523
+ fallbackFromInline: true,
524
+ });
525
+ return { materialized: exitedZero(fromFile, 'file') };
526
+ }
527
+
528
+ /**
529
+ * PB: the launch's readiness wait must not outlive a pre-booted runner that
530
+ * can no longer report live. Rejects (with the same not-live recovery the
531
+ * readiness timeout uses, so the scheduler defers to a new attempt on a new
532
+ * sandbox) when the delivery exec failed or the pre-boot chain exited, unless
533
+ * one more readiness read shows the runner did report live (a run that
534
+ * finished before the next poll). Never settles once `isSettled()` is true.
535
+ */
536
+ export function prebootedRunnerNotLive(input: {
537
+ materialized: Promise<void>;
538
+ exited: Promise<number>;
539
+ readiness: NonNullable<PlayRunnerCallbacks['readDetachedRunnerReadiness']>;
540
+ baselineHeartbeatAt: string | null;
541
+ isSettled: () => boolean;
542
+ }): Promise<never> {
543
+ const never = new Promise<never>(() => undefined);
544
+ return (async (): Promise<never> => {
545
+ const why = await Promise.race([
546
+ input.materialized.then(
547
+ () => never,
548
+ (error: unknown) =>
549
+ `delivery failed: ${error instanceof Error ? error.message : String(error)}`,
550
+ ),
551
+ input.exited.then(
552
+ (code) => `pre-boot chain exited ${code}`,
553
+ // A failed wait RPC proves nothing about the process; readiness
554
+ // (and its own deadline) still decides.
555
+ () => never,
556
+ ),
557
+ ]);
558
+ if (input.isSettled()) return never;
559
+ const response = await input
560
+ .readiness(input.baselineHeartbeatAt)
561
+ .catch(() => null);
562
+ if (response?.ready || input.isSettled()) return never;
563
+ throw recoveryForRunnerStartupNotLive(
564
+ new Error(
565
+ `RUNTIME_SANDBOX_START_FAILED: the pre-booted Modal runner cannot report live (${why}). Customer play execution was not parked.`,
566
+ ),
567
+ );
568
+ })();
569
+ }
570
+
571
+ /**
572
+ * A full re-staging after the baked runner did not verify. Its files live at
573
+ * new paths, so the runner's output, exit code and completion marker must be
574
+ * read there, never at the first staging's paths.
575
+ */
576
+ export type ModalRestagedRunnerPayload = Pick<
577
+ StagedDaytonaPayload,
578
+ 'command' | 'outputPath' | 'exitCodePath' | 'runtimeCompletedPath'
579
+ >;
580
+
581
+ export type ModalRunnerLaunch = {
582
+ /** Present when the launch command verifies the baked runner itself. */
583
+ bakedVerdict?: Promise<BakedRunnerVerdict>;
584
+ /** Today's full upload on the same sandbox, for a non-`ok` verdict. */
585
+ runBakedFallback?: (
586
+ verdict: BakedRunnerVerdict,
587
+ ) => Promise<ModalRestagedRunnerPayload>;
588
+ /** Set when the launch itself already fell back to a full re-staging. */
589
+ restaged?: ModalRestagedRunnerPayload;
590
+ startedAt?: number;
591
+ };
592
+
593
+ /**
594
+ * The baked-runner expectation for one Modal launch. Only a sandbox created
595
+ * from the resolved published image can hold the baked file, so without it
596
+ * (hash set but the image missing, cached boundedly by
597
+ * `resolveModalRunnerImage`) the launch goes straight to today's upload
598
+ * instead of running the in-command check only to fall back.
599
+ */
600
+ export async function modalBakedRunnerExpectation(input: {
601
+ imageBaked: boolean;
602
+ bundlePromise: Promise<string>;
603
+ onStale?: Parameters<typeof bakedRunnerPlanForLaunch>[0]['onStale'];
604
+ }): Promise<BakedRunnerExpectation | undefined> {
605
+ if (!input.imageBaked) return undefined;
606
+ const plan = await bakedRunnerPlanForLaunch({
607
+ bundlePromise: input.bundlePromise,
608
+ ...(input.onStale ? { onStale: input.onStale } : {}),
609
+ });
610
+ // The launch command verifies the baked file itself (no separate exec)
611
+ // and prints its verdict before it reads the envelope.
612
+ return plan
613
+ ? { ...plan, verified: Promise.resolve(true), verifyInCommand: true }
614
+ : undefined;
615
+ }
616
+
617
+ /** The paths the runner that actually started writes its results to. */
618
+ export function modalDetachedRunnerPaths(
619
+ staged: Omit<ModalRestagedRunnerPayload, 'command'>,
620
+ restaged: ModalRestagedRunnerPayload | null | undefined,
621
+ ): Omit<ModalRestagedRunnerPayload, 'command'> {
622
+ const source = restaged ?? staged;
623
+ return {
624
+ outputPath: source.outputPath,
625
+ exitCodePath: source.exitCodePath,
626
+ runtimeCompletedPath: source.runtimeCompletedPath,
627
+ };
628
+ }
629
+
134
630
  /**
135
631
  * A create RPC that outlives its client deadline is fundamentally ambiguous:
136
632
  * Modal may still create the sandbox after the caller stops waiting. It is
@@ -274,6 +770,93 @@ function failed(
274
770
  * happened, so a reader never has to use log ingest time. Callers pass only
275
771
  * scalars: ids, counts, durations, booleans, never payloads or credentials.
276
772
  */
773
+ const MODAL_APP_PREWARM_TIMEOUT_MS = 5_000;
774
+
775
+ /**
776
+ * Fire-and-forget boot of the app's execute function (see
777
+ * `ModalSupervisorLaunchOptions.prewarmAppExecuteRoute`). It never throws and
778
+ * is never awaited by the launch: the outcome is a stage line only.
779
+ */
780
+ export function prewarmAppExecuteRoute(input: {
781
+ context: PlayRunnerExecutionConfig['context'];
782
+ fetchImpl?: typeof fetch;
783
+ bypassTokenFromEnv?: string | null;
784
+ /**
785
+ * Authenticated no-op prewarm: needs the run's executor token and the
786
+ * service token, and is sent only to one of `trustedOrigins` (the worker's
787
+ * own app origins); any other `baseUrl` gets the unauthenticated prewarm.
788
+ */
789
+ authenticated?: {
790
+ serviceToken: string | null | undefined;
791
+ trustedOrigins: readonly string[];
792
+ };
793
+ }): void {
794
+ const startedAt = Date.now();
795
+ let url: URL;
796
+ try {
797
+ url = new URL(
798
+ '/api/v2/integrations/prewarm/execute',
799
+ String(input.context.baseUrl ?? ''),
800
+ );
801
+ } catch {
802
+ emitModalStage(input.context, 'app:prewarm', { outcome: 'no_origin' });
803
+ return;
804
+ }
805
+ const headers: Record<string, string> = {};
806
+ const host = url.hostname.toLowerCase();
807
+ const bypass =
808
+ input.context.vercelProtectionBypassToken ??
809
+ input.bypassTokenFromEnv ??
810
+ process.env.VERCEL_PROTECTION_BYPASS_TOKEN ??
811
+ null;
812
+ if (bypass && (host === 'vercel.app' || host.endsWith('.vercel.app'))) {
813
+ headers['x-vercel-protection-bypass'] = bypass;
814
+ }
815
+ const executorToken = input.context.executorToken;
816
+ const serviceToken = input.authenticated?.serviceToken?.trim();
817
+ const trustedOrigin =
818
+ input.authenticated?.trustedOrigins.includes(url.origin) === true;
819
+ if (input.authenticated && serviceToken && !trustedOrigin) {
820
+ // The service token covers every org: never send it to an origin this
821
+ // worker does not itself trust as its app.
822
+ emitModalStage(input.context, 'app:prewarm_auth_refused', {
823
+ reason: 'untrusted_origin',
824
+ host,
825
+ });
826
+ }
827
+ const authenticated = Boolean(
828
+ input.authenticated && executorToken && serviceToken && trustedOrigin,
829
+ );
830
+ if (authenticated) {
831
+ headers.authorization = `Bearer ${executorToken}`;
832
+ headers['x-deepline-internal-token'] = serviceToken!;
833
+ headers['x-deepline-runtime-prewarm'] = '1';
834
+ }
835
+ void (input.fetchImpl ?? fetch)(url, {
836
+ method: authenticated ? 'POST' : 'OPTIONS',
837
+ headers,
838
+ redirect: 'manual',
839
+ signal: AbortSignal.timeout(MODAL_APP_PREWARM_TIMEOUT_MS),
840
+ })
841
+ .then(async (response) => {
842
+ await response.arrayBuffer().catch(() => undefined);
843
+ emitModalStage(input.context, 'app:prewarm', {
844
+ outcome: 'response',
845
+ status: response.status,
846
+ host,
847
+ elapsedMs: Date.now() - startedAt,
848
+ });
849
+ })
850
+ .catch((error: unknown) => {
851
+ emitModalStage(input.context, 'app:prewarm', {
852
+ outcome: 'error',
853
+ error: error instanceof Error ? error.name : 'unknown',
854
+ host,
855
+ elapsedMs: Date.now() - startedAt,
856
+ });
857
+ });
858
+ }
859
+
277
860
  function emitModalStage(
278
861
  context: PlayRunnerExecutionConfig['context'],
279
862
  stage: string,
@@ -301,11 +884,18 @@ export async function confirmDetachedModalRunnerReady(input: {
301
884
  baselineHeartbeatAt: string | null;
302
885
  cancellation?: Promise<never>;
303
886
  timeoutMs?: number;
887
+ /** H1 for this run; absent keeps the pacer's static default. */
888
+ extendedFastWindow?: boolean;
304
889
  }): Promise<void> {
305
890
  const cancellation = input.cancellation ?? new Promise<never>(() => {});
306
891
  const timeoutMs = input.timeoutMs ?? MODAL_RUNNER_READY_TIMEOUT_MS;
307
892
  const deadline = Date.now() + timeoutMs;
308
- const nextDelayMs = createDetachedRunnerReadinessPacer({ now: Date.now });
893
+ const nextDelayMs = createDetachedRunnerReadinessPacer({
894
+ now: Date.now,
895
+ ...(input.extendedFastWindow === undefined
896
+ ? {}
897
+ : { extendedFastWindow: input.extendedFastWindow }),
898
+ });
309
899
  while (Date.now() < deadline) {
310
900
  const response = await Promise.race([
311
901
  input.readiness(input.baselineHeartbeatAt).catch(() => null),
@@ -319,90 +909,1415 @@ export async function confirmDetachedModalRunnerReady(input: {
319
909
  cancellation,
320
910
  ]);
321
911
  }
322
- throw recoveryForRunnerStartupNotLive(
323
- new Error(
324
- `RUNTIME_SANDBOX_START_FAILED: Modal accepted the runner command, but the scheduler did not observe play-runner liveness within ${timeoutMs}ms. Customer play execution was not parked.`,
325
- ),
912
+ throw recoveryForRunnerStartupNotLive(
913
+ new Error(
914
+ `RUNTIME_SANDBOX_START_FAILED: Modal accepted the runner command, but the scheduler did not observe play-runner liveness within ${timeoutMs}ms. Customer play execution was not parked.`,
915
+ ),
916
+ );
917
+ }
918
+
919
+ async function terminateModalSandbox(sandbox: ModalSandbox): Promise<boolean> {
920
+ let timer: ReturnType<typeof setTimeout> | undefined;
921
+ try {
922
+ // The default terminate call only acknowledges the request. Capacity may
923
+ // be released only after Modal confirms the sandbox itself has stopped.
924
+ await Promise.race([
925
+ sandbox.terminate({ wait: true }),
926
+ new Promise<never>((_resolve, reject) => {
927
+ timer = setTimeout(() => {
928
+ reject(
929
+ new Error(
930
+ `Modal sandbox termination did not settle within ${MODAL_TERMINATION_TIMEOUT_MS}ms.`,
931
+ ),
932
+ );
933
+ }, MODAL_TERMINATION_TIMEOUT_MS);
934
+ }),
935
+ ]);
936
+ return true;
937
+ } catch (error) {
938
+ console.warn('[play-runner.modal.terminate_failed]', {
939
+ sandboxId: sandbox.sandboxId,
940
+ error: error instanceof Error ? error.message : String(error),
941
+ });
942
+ return false;
943
+ } finally {
944
+ if (timer) clearTimeout(timer);
945
+ }
946
+ }
947
+
948
+ async function releaseModalSandboxCapacityAfterConfirmedTermination(input: {
949
+ leaseId: string;
950
+ release: NonNullable<PlayRunnerCallbacks['releaseSandboxCapacity']>;
951
+ }): Promise<void> {
952
+ let lastError: unknown;
953
+ for (const delayMs of MODAL_CAPACITY_RELEASE_RETRY_DELAYS_MS) {
954
+ if (delayMs > 0) {
955
+ await new Promise<void>((resolve) => setTimeout(resolve, delayMs));
956
+ }
957
+ try {
958
+ await input.release(input.leaseId);
959
+ return;
960
+ } catch (error) {
961
+ lastError = error;
962
+ }
963
+ }
964
+ throw lastError;
965
+ }
966
+
967
+ /**
968
+ * A create that settles after its caller timed out is already an external
969
+ * fact. Persist it before attempting any further provider operation: the
970
+ * durable cleanup controller then owns deletion, capacity release, and the
971
+ * late billing adjustment. A short retry absorbs a transient scheduler-store
972
+ * outage without turning this into a fresh Play attempt.
973
+ */
974
+ async function persistLateModalSandboxResource(input: {
975
+ resource: Parameters<
976
+ NonNullable<PlayRunnerCallbacks['onLateRuntimeResourceAcquired']>
977
+ >[0];
978
+ record: NonNullable<PlayRunnerCallbacks['onLateRuntimeResourceAcquired']>;
979
+ }): Promise<void> {
980
+ let lastError: unknown;
981
+ for (const delayMs of MODAL_LATE_CREATE_PERSIST_RETRY_DELAYS_MS) {
982
+ if (delayMs > 0) {
983
+ await new Promise<void>((resolve) => setTimeout(resolve, delayMs));
984
+ }
985
+ try {
986
+ await input.record(input.resource);
987
+ return;
988
+ } catch (error) {
989
+ lastError = error;
990
+ }
991
+ }
992
+ throw new AggregateError(
993
+ [lastError],
994
+ 'RUNTIME_MODAL_LATE_CREATE_PERSIST_FAILED: Modal created a sandbox after the caller deadline, but its durable cleanup obligation could not be recorded.',
995
+ );
996
+ }
997
+
998
+ /** Sidecar create RPC deadline. */
999
+ const MODAL_SUPERVISOR_READY_TIMEOUT_MS = 30_000;
1000
+ /** The `modal_sidecar` profile's default sandbox region (us-east). */
1001
+ const MODAL_SUPERVISOR_DEFAULT_REGIONS = ['us-east'];
1002
+
1003
+ type ModalSupervisorPlan = {
1004
+ image: Awaited<ReturnType<ModalClient['images']['fromName']>>;
1005
+ secret: Awaited<ReturnType<ModalClient['secrets']['fromObject']>>;
1006
+ env: Record<string, string>;
1007
+ /** The sidecar's outbound domain allowlist (modalSupervisorEnvironment). */
1008
+ egressDomains: string[];
1009
+ };
1010
+
1011
+ const MODAL_LAUNCH_LOOKUP_TTL_MS = 10 * 60_000;
1012
+ const modalLaunchLookups = new WeakMap<
1013
+ object,
1014
+ Map<string, { value: Promise<unknown>; expiresAtMs: number }>
1015
+ >();
1016
+
1017
+ /**
1018
+ * Process-local memo for a Modal launch lookup whose result is a stable named
1019
+ * or content-addressed object (`cacheModalLaunchLookups`). Concurrent callers
1020
+ * share one lookup; a rejected lookup is dropped so the next launch retries.
1021
+ * With the switch off this calls `load` every time, exactly as before.
1022
+ */
1023
+ export function modalLaunchLookup<T>(input: {
1024
+ client: object;
1025
+ key: string;
1026
+ load: () => Promise<T>;
1027
+ enabled: boolean;
1028
+ nowMs?: () => number;
1029
+ }): Promise<T> {
1030
+ if (!input.enabled) return input.load();
1031
+ const now = (input.nowMs ?? Date.now)();
1032
+ let entries = modalLaunchLookups.get(input.client);
1033
+ if (!entries) {
1034
+ entries = new Map();
1035
+ modalLaunchLookups.set(input.client, entries);
1036
+ }
1037
+ const hit = entries.get(input.key);
1038
+ if (hit && hit.expiresAtMs > now) return hit.value as Promise<T>;
1039
+ const value = input.load();
1040
+ const entry = { value, expiresAtMs: now + MODAL_LAUNCH_LOOKUP_TTL_MS };
1041
+ entries.set(input.key, entry);
1042
+ value.catch(() => {
1043
+ if (entries.get(input.key) === entry) entries.delete(input.key);
1044
+ });
1045
+ return value;
1046
+ }
1047
+
1048
+ const modalSupervisorSecrets = new Map<
1049
+ string,
1050
+ Promise<ModalSupervisorPlan['secret']>
1051
+ >();
1052
+
1053
+ /**
1054
+ * Resolve the published supervisor image and its credentials before any
1055
+ * capacity lease or create intent, so a missing image or setting fails
1056
+ * without holding sandbox resources. The ephemeral Modal Secret is reused for
1057
+ * identical worker credentials within this process.
1058
+ */
1059
+ async function resolveModalSupervisorPlan(input: {
1060
+ client: ModalClient;
1061
+ runtimeSchedulerSchema: string | null | undefined;
1062
+ }): Promise<ModalSupervisorPlan> {
1063
+ const hash = configuredModalSupervisorHash();
1064
+ if (!hash) {
1065
+ throw new Error(
1066
+ 'RUNTIME_MODAL_SUPERVISOR_IMAGE_UNSET: the modal_sidecar profile requires DEEPLINE_MODAL_SUPERVISOR_HASH.',
1067
+ );
1068
+ }
1069
+ const { env, secretEnv, egressDomains } = modalSupervisorEnvironment({
1070
+ env: process.env,
1071
+ runtimeSchedulerSchema: input.runtimeSchedulerSchema,
1072
+ });
1073
+ const secretKey = JSON.stringify(
1074
+ Object.entries(secretEnv).sort(([a], [b]) => a.localeCompare(b)),
1075
+ );
1076
+ let secret = modalSupervisorSecrets.get(secretKey);
1077
+ if (!secret) {
1078
+ secret = input.client.secrets.fromObject(secretEnv);
1079
+ modalSupervisorSecrets.set(secretKey, secret);
1080
+ secret.catch(() => modalSupervisorSecrets.delete(secretKey));
1081
+ }
1082
+ const ref = modalSupervisorImageRef(hash);
1083
+ const [image, resolvedSecret] = await Promise.all([
1084
+ modalLaunchLookup({
1085
+ client: input.client,
1086
+ key: `supervisor-image:${ref}`,
1087
+ enabled: modalSupervisorLaunch().cacheModalLaunchLookups === true,
1088
+ load: () => input.client.images.fromName(ref),
1089
+ }),
1090
+ secret,
1091
+ ]);
1092
+ return { image, secret: resolvedSecret, env, egressDomains };
1093
+ }
1094
+
1095
+ /**
1096
+ * The supervisor sidecar's create parameters. Its outbound network is limited
1097
+ * to the plan's domains (app origin, runtime Postgres, R2); Modal applies the
1098
+ * sidecar's allowlist independently of the main container, which keeps no
1099
+ * outbound network at all. A domain allowlist, because the app (Vercel), the
1100
+ * Postgres pooler and R2 have no stable CIDRs. Unproven on Modal until a
1101
+ * Preview probe (required before the profile is benchmarked again): that a
1102
+ * domain allowlist alone refuses raw-IP egress (the SDK leaves CIDRs open
1103
+ * when no CIDR list is set), and that it admits Postgres's TLS, whose SNI
1104
+ * follows the SSLRequest preamble. If either fails, the fallback is a Modal
1105
+ * Proxy (static egress IP) for the sidecar with `outboundCidrAllowlist` set
1106
+ * to the resolved hosts, plus an IP allowlist on the Postgres side.
1107
+ */
1108
+ export function modalSupervisorSidecarCreateParams(
1109
+ plan: Pick<ModalSupervisorPlan, 'env' | 'secret' | 'egressDomains'>,
1110
+ ): SidecarCreateParams & {
1111
+ command: string[];
1112
+ outboundDomainAllowlist: string[];
1113
+ } {
1114
+ if (plan.egressDomains.length === 0) {
1115
+ throw new Error(
1116
+ 'RUNTIME_MODAL_SUPERVISOR_CONFIG_INVALID: the sidecar egress allowlist is empty.',
1117
+ );
1118
+ }
1119
+ return {
1120
+ command: modalSupervisorCommand(),
1121
+ env: plan.env,
1122
+ secrets: [plan.secret],
1123
+ outboundDomainAllowlist: [...plan.egressDomains],
1124
+ };
1125
+ }
1126
+
1127
+ /**
1128
+ * Create the supervisor sidecar. The runner itself waits for both gateway
1129
+ * roles to listen before its first heartbeat (`awaitRuntimeSupervisor`), so
1130
+ * gateway startup overlaps runner startup instead of preceding it. A
1131
+ * supervisor that never listens leaves the runner without a first heartbeat,
1132
+ * which the existing detached-runner readiness deadline recovers. The sidecar
1133
+ * dies with the sandbox, so sandbox termination is its cleanup.
1134
+ */
1135
+ /**
1136
+ * Whether the installed modal SDK applies `outboundDomainAllowlist` on a
1137
+ * sidecar create (0.11 and later). This branch pins main's ^0.9.0, because
1138
+ * 0.11 moves every default sandbox create onto Modal's V2 backend and makes
1139
+ * create wait for scheduling; the upgrade is its own change.
1140
+ */
1141
+ const MODAL_SDK_APPLIES_SIDECAR_EGRESS_ALLOWLIST = false;
1142
+
1143
+ async function startModalSupervisorSidecar(input: {
1144
+ sandbox: ModalSandbox;
1145
+ plan: ModalSupervisorPlan;
1146
+ context: PlayRunnerExecutionConfig['context'];
1147
+ cancellation: Promise<never>;
1148
+ }): Promise<void> {
1149
+ // Created for this run: pinned in its env from the start.
1150
+ const pin = modalSupervisorRunPin(input.context);
1151
+ await createModalSupervisorSidecar({
1152
+ ...input,
1153
+ plan: {
1154
+ ...input.plan,
1155
+ env: {
1156
+ ...input.plan.env,
1157
+ [MODAL_SUPERVISOR_RUN_PIN_ENV]: JSON.stringify(pin),
1158
+ },
1159
+ },
1160
+ });
1161
+ emitModalStage(input.context, 'supervisor:created', {
1162
+ sandboxId: input.sandbox.sandboxId,
1163
+ });
1164
+ }
1165
+
1166
+ async function createModalSupervisorSidecar(input: {
1167
+ sandbox: ModalSandbox;
1168
+ plan: ModalSupervisorPlan;
1169
+ cancellation: Promise<never>;
1170
+ }): Promise<void> {
1171
+ // The sidecar's egress allowlist is a sidecar create parameter only from
1172
+ // modal 0.11; the installed 0.9 SDK would drop it and leave the sidecar's
1173
+ // outbound network open. The profile is off and also blocked on credential
1174
+ // scoping, so refuse instead of creating an unrestricted sidecar.
1175
+ if (!MODAL_SDK_APPLIES_SIDECAR_EGRESS_ALLOWLIST) {
1176
+ throw new Error(
1177
+ 'RUNTIME_MODAL_SUPERVISOR_FAILED: the supervisor sidecar needs its egress allowlist, which the installed modal SDK (^0.9) cannot apply.',
1178
+ );
1179
+ }
1180
+ let timer: ReturnType<typeof setTimeout> | null = null;
1181
+ try {
1182
+ await Promise.race([
1183
+ input.sandbox.experimentalSidecars.create(
1184
+ MODAL_SUPERVISOR_SIDECAR_NAME,
1185
+ input.plan.image,
1186
+ modalSupervisorSidecarCreateParams(input.plan),
1187
+ ),
1188
+ input.cancellation,
1189
+ new Promise<never>((_resolve, reject) => {
1190
+ timer = setTimeout(
1191
+ () =>
1192
+ reject(
1193
+ new Error(
1194
+ `RUNTIME_MODAL_SUPERVISOR_FAILED: sidecar not created within ${MODAL_SUPERVISOR_READY_TIMEOUT_MS} ms.`,
1195
+ ),
1196
+ ),
1197
+ MODAL_SUPERVISOR_READY_TIMEOUT_MS,
1198
+ );
1199
+ }),
1200
+ ]);
1201
+ } finally {
1202
+ if (timer) clearTimeout(timer);
1203
+ }
1204
+ }
1205
+
1206
+ /**
1207
+ * S1: pin an early sidecar (started before its run was known) to the run
1208
+ * that adopted its sandbox, by an exec in the sidecar that writes the pin
1209
+ * file once. Until then its gateway refuses every executor token. Bounded;
1210
+ * a failure fails the launch like a failed sidecar.
1211
+ */
1212
+ export async function pinModalSupervisorSidecar(input: {
1213
+ sandbox: Pick<ModalSandbox, 'experimentalSidecars'>;
1214
+ pin: ModalSupervisorRunPin;
1215
+ cancellation: Promise<never>;
1216
+ }): Promise<void> {
1217
+ let timer: ReturnType<typeof setTimeout> | null = null;
1218
+ try {
1219
+ const exitCode = await Promise.race([
1220
+ (async () => {
1221
+ const sidecar = await input.sandbox.experimentalSidecars.get(
1222
+ MODAL_SUPERVISOR_SIDECAR_NAME,
1223
+ );
1224
+ const pinExec = await sidecar.exec(
1225
+ modalSupervisorRunPinCommand(input.pin),
1226
+ );
1227
+ return await pinExec.wait();
1228
+ })(),
1229
+ input.cancellation,
1230
+ new Promise<never>((_resolve, reject) => {
1231
+ timer = setTimeout(
1232
+ () =>
1233
+ reject(
1234
+ new Error(
1235
+ `RUNTIME_MODAL_SUPERVISOR_FAILED: run pin not written within ${MODAL_SUPERVISOR_READY_TIMEOUT_MS} ms.`,
1236
+ ),
1237
+ ),
1238
+ MODAL_SUPERVISOR_READY_TIMEOUT_MS,
1239
+ );
1240
+ }),
1241
+ ]);
1242
+ if (exitCode !== 0) {
1243
+ throw new Error(
1244
+ `RUNTIME_MODAL_SUPERVISOR_FAILED: run pin exec exited ${exitCode}.`,
1245
+ );
1246
+ }
1247
+ } finally {
1248
+ if (timer) clearTimeout(timer);
1249
+ }
1250
+ }
1251
+
1252
+ /**
1253
+ * Preview experiment E2: start the Modal sandbox for a run right after its
1254
+ * admission authenticated and funded it, before the run is enqueued, claimed
1255
+ * and launched. The early sandbox carries no token, no payload and no
1256
+ * supervisor: only the image, the standard resource profile and a
1257
+ * deterministic per-run tag. The launching worker adopts it by exact sandbox
1258
+ * id (tag lookup, then re-tag with the ordinary create tags so every cleanup
1259
+ * and reconciliation path sees an ordinary sandbox) and then starts the
1260
+ * supervisor and uploads the payload as today; otherwise it creates its own.
1261
+ * Orphans: a short Modal idle timeout, plus an exact-id reaper that
1262
+ * terminates the early sandbox if it is still unadopted after the reap delay.
1263
+ * Off.
1264
+ */
1265
+ export const EARLY_MODAL_SANDBOX_START = false;
1266
+ const EARLY_MODAL_SANDBOX_SOURCE_TAG = 'deepline-play-runner-early';
1267
+ const EARLY_MODAL_SANDBOX_IDLE_TIMEOUT_MS = 60_000;
1268
+ const EARLY_MODAL_SANDBOX_REAP_AFTER_MS = 90_000;
1269
+ /**
1270
+ * No launch adopts an early sandbox older than this (create request -> adopt
1271
+ * check). Kept well under EARLY_MODAL_SANDBOX_REAP_AFTER_MS so a reaper can
1272
+ * never terminate a sandbox that a launch is in the middle of adopting.
1273
+ * Adoption is normally ~1-2 s after create.
1274
+ */
1275
+ export const EARLY_MODAL_SANDBOX_MAX_ADOPTION_AGE_MS = 60_000;
1276
+ /** Create-request time (epoch ms), set in the create tags. */
1277
+ const EARLY_CREATED_AT_TAG = 'earlyCreatedAtMs';
1278
+
1279
+ export type EarlyModalSandboxEntry = {
1280
+ sandbox: ModalSandbox;
1281
+ startedAtMs: number;
1282
+ /** The tags this process last set on the early sandbox. */
1283
+ tags: Record<string, string>;
1284
+ };
1285
+
1286
+ /**
1287
+ * This process's unadopted early sandboxes, by org-scoped key. `take` removes
1288
+ * the entry, so each early sandbox is handed to at most one in-process
1289
+ * adoption; an unadopted entry expires after twice the reap delay.
1290
+ */
1291
+ export class EarlyModalSandboxRegistry {
1292
+ readonly #entries = new Map<string, Promise<EarlyModalSandboxEntry | null>>();
1293
+
1294
+ has(key: string): boolean {
1295
+ return this.#entries.has(key);
1296
+ }
1297
+
1298
+ put(
1299
+ key: string,
1300
+ entry: Promise<EarlyModalSandboxEntry | null>,
1301
+ ttlMs: number = EARLY_MODAL_SANDBOX_REAP_AFTER_MS * 2,
1302
+ ): void {
1303
+ this.#entries.set(key, entry);
1304
+ setTimeout(() => {
1305
+ if (this.#entries.get(key) === entry) this.#entries.delete(key);
1306
+ }, ttlMs).unref?.();
1307
+ }
1308
+
1309
+ take(key: string): Promise<EarlyModalSandboxEntry | null> | undefined {
1310
+ const entry = this.#entries.get(key);
1311
+ this.#entries.delete(key);
1312
+ return entry;
1313
+ }
1314
+ }
1315
+ const earlyModalSandboxes = new EarlyModalSandboxRegistry();
1316
+
1317
+ /**
1318
+ * The early sandbox's key. Org-scoped: a workflow id is chosen by the caller,
1319
+ * so two orgs can name the same one; neither may find the other's sandbox.
1320
+ */
1321
+ export function earlyModalSandboxKey(input: {
1322
+ orgId: string;
1323
+ workflowId: string;
1324
+ }): string {
1325
+ return createHash('sha256')
1326
+ .update(JSON.stringify([input.orgId, input.workflowId]))
1327
+ .digest('hex')
1328
+ .slice(0, 40);
1329
+ }
1330
+
1331
+ /**
1332
+ * Why an early sandbox's tags do not belong to this launch's run, or null.
1333
+ * Checked on every adoption path, before the sandbox is re-tagged or used.
1334
+ */
1335
+ export function earlyModalSandboxIdentityRefusal(
1336
+ tags: Record<string, string>,
1337
+ expected: { key: string; orgId: string; workflowId: string },
1338
+ ): 'key_mismatch' | 'org_mismatch' | 'workflow_mismatch' | null {
1339
+ if (tags.earlyKey !== expected.key) return 'key_mismatch';
1340
+ if (tags.orgId !== expected.orgId) return 'org_mismatch';
1341
+ if (tags.workflowId !== expected.workflowId) return 'workflow_mismatch';
1342
+ return null;
1343
+ }
1344
+
1345
+ /** Age of an early sandbox from its create tag; null when it has none. */
1346
+ function earlyModalSandboxAgeMs(
1347
+ tags: Record<string, string>,
1348
+ nowMs: number,
1349
+ ): number | null {
1350
+ const createdAtMs = Number(tags[EARLY_CREATED_AT_TAG]);
1351
+ return Number.isSafeInteger(createdAtMs) && createdAtMs > 0
1352
+ ? nowMs - createdAtMs
1353
+ : null;
1354
+ }
1355
+
1356
+ function earlyModalLimitsKey(input: {
1357
+ cpu: number;
1358
+ memoryMiB: number;
1359
+ timeoutMs: number;
1360
+ }): string {
1361
+ return `${input.cpu}:${input.memoryMiB}:${input.timeoutMs}`;
1362
+ }
1363
+
1364
+ function logEarlyModalSandbox(event: string, extra: Record<string, unknown>) {
1365
+ console.info(
1366
+ '[play-runner.modal.early]',
1367
+ JSON.stringify({ event, ...extra, atMs: Date.now() }),
1368
+ );
1369
+ }
1370
+
1371
+ /**
1372
+ * Start (fire and forget) the early sandbox for an admitted run. Idempotent
1373
+ * per process; a second hint for the same run is ignored.
1374
+ */
1375
+ /**
1376
+ * Source tag of the retired F2 hedged early create (docs/runtime-speed-
1377
+ * experiments.md). Nothing creates it now; the reaper and the durable sweep
1378
+ * still treat it as unadopted, so a leg left by an older worker is reaped.
1379
+ */
1380
+ const EARLY_MODAL_SANDBOX_HEDGE_TAG = 'deepline-play-runner-early-hedge';
1381
+
1382
+ /**
1383
+ * S1 (off): with E2, start the supervisor sidecar (both gateways) on the early
1384
+ * sandbox right after its create, so the gateways have listened and fetched
1385
+ * JWKS before the runner boots. A launch that adopts that sandbox in this
1386
+ * process awaits the started sidecar instead of creating one. Today the
1387
+ * sidecar create gates execute:start (~50 ms) and gateway startup gates the
1388
+ * runner's first request (p50 25-55 ms, tails 0.4-1.8 s; msc/gwgate.py). The
1389
+ * sidecar holds no run authority: its environment is the worker's (no token),
1390
+ * and every request is still verified against the run's executor token. An
1391
+ * early sandbox whose sidecar another process started is never adopted (the
1392
+ * launch creates its own). A failed early sidecar fails the launch loudly
1393
+ * (deferred to a new attempt on a new sandbox), like a failed create today.
1394
+ * Per-run capable (experiment switch S1).
1395
+ */
1396
+ export const START_SUPERVISOR_WITH_EARLY_SANDBOX = false;
1397
+ const EARLY_SUPERVISOR_TAG = 'earlySupervisor';
1398
+ const earlyModalSupervisors = new WeakMap<ModalSandbox, Promise<void>>();
1399
+ /**
1400
+ * Settles once a tag that makes every other process refuse to adopt the
1401
+ * sandbox (PB at create, S1 once its setTags lands) is on it in Modal. Only
1402
+ * then can this process know, without a read, that nobody else adopted it.
1403
+ */
1404
+ const earlyModalForeignAdoptionClaims = new WeakMap<
1405
+ ModalSandbox,
1406
+ Promise<unknown>
1407
+ >();
1408
+
1409
+ /**
1410
+ * A1 (off): adopting an early sandbox this process created checks the tags
1411
+ * this process set instead of reading them back from Modal (one RPC fewer on
1412
+ * the launch path, ~20 ms). Only for a fresh entry this process created and
1413
+ * has not handed out (the registry's `take`), whose foreign-adoption claim is
1414
+ * confirmed on the sandbox; every other adoption reads the tags back. The
1415
+ * exit-code read, the identity check and the re-tag are unchanged. Per-run
1416
+ * capable (experiment switch A1).
1417
+ */
1418
+ export const ADOPT_IN_PROCESS_EARLY_SANDBOX_WITHOUT_TAG_READ = false;
1419
+
1420
+ /**
1421
+ * PB (off): with E2 and the baked runner image, the early sandbox also starts
1422
+ * the baked runner right after its create, before the run is adopted, so
1423
+ * shell start, watchdog setup and runner bundle evaluation (~200-380 ms) are
1424
+ * off the launch path. One exec runs, in order: the baked-runner verify guard
1425
+ * (verdict line first; a non-ok verdict exits 98 before anything else), the
1426
+ * runtime watchdog starting the runner as `--wait-config <configPath>`, and
1427
+ * the crash-terminal epilogue, all at fixed per-sandbox paths. It holds no
1428
+ * credentials or customer data: no envelope, config or token exists in the
1429
+ * sandbox until the run is adopted. The watchdog's runtime/memory limits and
1430
+ * the runner's V8 flags are fixed at pre-boot from the early sandbox's own
1431
+ * (standard) profile, the same one its `limitsKey` encodes; adoption refuses a
1432
+ * run whose limits differ, and staging asserts it again.
1433
+ *
1434
+ * Adoption (in this process only) delivers the envelope in one exec: stdin to
1435
+ * a file (same guard as the inline launch), then the run's files, config LAST
1436
+ * via rename; the waiting runner picks it up and proceeds exactly as today
1437
+ * (heartbeat, readiness, park fence). Readiness is confirmed as today, and
1438
+ * also fails fast (deferred to a new attempt) if the delivery exec fails or
1439
+ * the pre-boot chain exits first.
1440
+ *
1441
+ * Not adopted (an ordinary sandbox is created and this one is reaped): a
1442
+ * sandbox whose pre-boot another process started (tag), one whose pre-boot
1443
+ * is ambiguous (exec error, late or missing verdict without a confirmed exit
1444
+ * 98), one whose pre-boot already exited, one older than
1445
+ * EARLY_PREBOOT_MAX_ADOPTION_AGE_MS, or a launch whose PB resolves off. A
1446
+ * pre-boot that provably never started (exit 98 confirmed, or no baked plan)
1447
+ * is adopted and launched today's way.
1448
+ *
1449
+ * Orphans: the exact-id reaper (EARLY_MODAL_SANDBOX_REAP_AFTER_MS, 90 s after
1450
+ * create) terminates an unadopted sandbox and the waiting runner with it; the
1451
+ * running exec may keep Modal's idle timeout from firing, so the reaper is the
1452
+ * killer. If the reap itself fails, the runner gives up its config wait at
1453
+ * its own 120 s deadline (runner-app WAIT_CONFIG_TIMEOUT_MS), the chain exits
1454
+ * (the epilogue has no crash pusher or config and pushes nothing), and the
1455
+ * then-idle sandbox ends at the 60 s idle timeout; the watchdog's own 240 s
1456
+ * startup deadline is a later backstop. Adoption itself is ~1-2 s after
1457
+ * create, far inside every bound. Per-run capable (experiment switch PB).
1458
+ */
1459
+ export const PREBOOT_RUNNER_IN_EARLY_SANDBOX = false;
1460
+ const EARLY_PREBOOT_TAG = 'earlyPreboot';
1461
+ /**
1462
+ * A pre-boot older than this is not adopted: its watchdog's startup deadline
1463
+ * runs from pre-boot, and the runner's config wait has a 120 s deadline.
1464
+ */
1465
+ const EARLY_PREBOOT_MAX_ADOPTION_AGE_MS = 30_000;
1466
+ /** Bound on the pre-boot's verdict line, and on its exit after a refusal. */
1467
+ const EARLY_PREBOOT_VERDICT_TIMEOUT_MS = 15_000;
1468
+ export type EarlyModalPreboot =
1469
+ | {
1470
+ status: 'running';
1471
+ runner: PrebootedRunnerLaunch;
1472
+ /** The pre-boot chain's exit code (runner, then epilogue). */
1473
+ exited: Promise<number>;
1474
+ /** Set once `exited` settles with a code. */
1475
+ exitCode: number | null;
1476
+ startedAtMs: number;
1477
+ }
1478
+ /** Provably nothing ran: today's launch may use this sandbox. */
1479
+ | { status: 'not_started'; reason: string }
1480
+ /** Cannot prove what ran: never adopted. */
1481
+ | { status: 'ambiguous'; reason: string };
1482
+ const earlyModalPreboots = new WeakMap<
1483
+ ModalSandbox,
1484
+ Promise<EarlyModalPreboot>
1485
+ >();
1486
+
1487
+ /**
1488
+ * Start the pre-boot exec on a just-created early sandbox (PB). Never throws:
1489
+ * every outcome is a state the in-process adoption reads.
1490
+ */
1491
+ export async function startEarlyModalPreboot(input: {
1492
+ key: string;
1493
+ sandbox: Pick<ModalSandbox, 'exec' | 'sandboxId'>;
1494
+ bakedRunner: Promise<{ hash: string; path: string } | undefined>;
1495
+ workDir: string;
1496
+ sandboxRuntimeLimits: PlaySandboxRuntimeLimits;
1497
+ memoryLimitMiB?: number;
1498
+ verdictTimeoutMs?: number;
1499
+ }): Promise<EarlyModalPreboot> {
1500
+ const startedAtMs = Date.now();
1501
+ const timeoutMs = input.verdictTimeoutMs ?? EARLY_PREBOOT_VERDICT_TIMEOUT_MS;
1502
+ const fail = (
1503
+ status: 'not_started' | 'ambiguous',
1504
+ reason: string,
1505
+ ): EarlyModalPreboot => {
1506
+ logEarlyModalSandbox('preboot_failed', {
1507
+ key: input.key,
1508
+ sandboxId: input.sandbox.sandboxId,
1509
+ status,
1510
+ reason,
1511
+ elapsedMs: Date.now() - startedAtMs,
1512
+ });
1513
+ return { status, reason };
1514
+ };
1515
+ let bakedRunner: { hash: string; path: string } | undefined;
1516
+ try {
1517
+ bakedRunner = await input.bakedRunner;
1518
+ } catch (error) {
1519
+ return fail(
1520
+ 'not_started',
1521
+ `setup: ${error instanceof Error ? error.message : String(error)}`,
1522
+ );
1523
+ }
1524
+ if (!bakedRunner) return fail('not_started', 'no_baked_runner');
1525
+ const runner = buildPrebootedRunnerLaunch({
1526
+ workDir: input.workDir,
1527
+ bakedRunner,
1528
+ sandboxRuntimeLimits: input.sandboxRuntimeLimits,
1529
+ ...(input.memoryLimitMiB === undefined
1530
+ ? {}
1531
+ : { memoryLimitMiB: input.memoryLimitMiB }),
1532
+ });
1533
+ // Text-mode exec (the verdict line is read as a string), typed from the call.
1534
+ const execPreboot = () => input.sandbox.exec(['bash', '-lc', runner.command]);
1535
+ let launched: Awaited<ReturnType<typeof execPreboot>>;
1536
+ try {
1537
+ launched = await execPreboot();
1538
+ } catch (error) {
1539
+ // The exec may or may not have started.
1540
+ return fail(
1541
+ 'ambiguous',
1542
+ `exec: ${error instanceof Error ? error.message : String(error)}`,
1543
+ );
1544
+ }
1545
+ // Nothing is ever written to its stdin.
1546
+ await launched.stdin.close().catch(() => undefined);
1547
+ const exited = launched.wait();
1548
+ exited.catch(() => undefined);
1549
+ const never = new Promise<never>(() => undefined);
1550
+ const verdict = await readFirstStdoutLine({
1551
+ stdout: launched.stdout,
1552
+ cancellation: never,
1553
+ timeoutMs,
1554
+ }).then(
1555
+ (line) => parseBakedRunnerVerdict(line),
1556
+ (error: unknown): BakedRunnerVerdict =>
1557
+ error instanceof BakedRunnerVerdictLineTimeoutError
1558
+ ? 'late'
1559
+ : 'no_verdict',
1560
+ );
1561
+ if (verdict === 'ok') {
1562
+ const state: Extract<EarlyModalPreboot, { status: 'running' }> = {
1563
+ status: 'running',
1564
+ runner,
1565
+ exited,
1566
+ exitCode: null,
1567
+ startedAtMs,
1568
+ };
1569
+ exited.then(
1570
+ (code) => {
1571
+ state.exitCode = code;
1572
+ logEarlyModalSandbox('preboot_exited', {
1573
+ key: input.key,
1574
+ sandboxId: input.sandbox.sandboxId,
1575
+ exitCode: code,
1576
+ aliveMs: Date.now() - startedAtMs,
1577
+ });
1578
+ },
1579
+ () => undefined,
1580
+ );
1581
+ logEarlyModalSandbox('preboot_started', {
1582
+ key: input.key,
1583
+ sandboxId: input.sandbox.sandboxId,
1584
+ elapsedMs: Date.now() - startedAtMs,
1585
+ });
1586
+ return state;
1587
+ }
1588
+ // A refusal exits 98 before the watchdog or runner start; only that exit
1589
+ // proves nothing ran.
1590
+ const code = await waitForExit({
1591
+ launched: { wait: () => exited },
1592
+ cancellation: never,
1593
+ timeoutMs,
1594
+ }).catch(() => null);
1595
+ return code === INLINE_BAKED_RUNNER_UNVERIFIED_EXIT_CODE
1596
+ ? fail('not_started', `verdict_${verdict}`)
1597
+ : fail('ambiguous', `verdict_${verdict}_exit_${code ?? 'unknown'}`);
1598
+ }
1599
+ /**
1600
+ * An early sandbox on a slow host may not have a running container yet when
1601
+ * it is terminated, so its exit code can stay unset for a while (FAST1c: 2 of
1602
+ * 12 unconfirmed after ~11 s). Re-terminate and re-read with a backoff capped at
1603
+ * 2 s, ~60 s in all, before handing it to the 90 s exact-id reaper.
1604
+ */
1605
+ const EARLY_MODAL_SANDBOX_HEDGE_CONFIRM_ATTEMPTS = 35;
1606
+ const earlyHedgeConfirmDelayMs = (attempt: number) =>
1607
+ Math.min(200 * attempt, 2_000);
1608
+
1609
+ /**
1610
+ * Terminate a sandbox by exact id and confirm it by reading its exit code
1611
+ * back, re-terminating with a capped backoff (a not-yet-running sandbox may
1612
+ * miss a terminate). Returns the attempts it took; throws when the read-back
1613
+ * never confirms within `attempts`, or on a provider error.
1614
+ */
1615
+ export async function terminateModalSandboxConfirmed(input: {
1616
+ sandbox: Pick<ModalSandbox, 'terminate' | 'sandboxId'>;
1617
+ readExitCode: (sandboxId: string) => Promise<number | null>;
1618
+ sleep: (ms: number) => Promise<void>;
1619
+ attempts: number;
1620
+ }): Promise<number> {
1621
+ for (let attempt = 1; attempt <= input.attempts; attempt++) {
1622
+ // Idempotent; repeated because a not-yet-running sandbox may miss it.
1623
+ await input.sandbox.terminate();
1624
+ if ((await input.readExitCode(input.sandbox.sandboxId)) !== null)
1625
+ return attempt;
1626
+ await input.sleep(earlyHedgeConfirmDelayMs(attempt));
1627
+ }
1628
+ throw new Error('termination not confirmed by read-back');
1629
+ }
1630
+
1631
+ const sleepMs = (ms: number) =>
1632
+ new Promise<void>((resolve) => setTimeout(resolve, ms));
1633
+
1634
+ const readModalExitCode =
1635
+ (client: Pick<ModalClient, 'sandboxes'>) => async (sandboxId: string) =>
1636
+ await (await client.sandboxes.fromId(sandboxId)).poll();
1637
+
1638
+ function isUnadoptedEarlyModalSandbox(tags: Record<string, string>): boolean {
1639
+ return (
1640
+ tags.source === EARLY_MODAL_SANDBOX_SOURCE_TAG ||
1641
+ tags.source === EARLY_MODAL_SANDBOX_HEDGE_TAG
1642
+ );
1643
+ }
1644
+
1645
+ /**
1646
+ * Reap one early (or hedge) sandbox by exact id if it is still unadopted: a
1647
+ * fresh tag read (an adopted sandbox carries ordinary launch tags), then a
1648
+ * confirmed termination. An unconfirmed one keeps its early tag, so the
1649
+ * durable sweep (sweepOrphanEarlyModalSandboxes) still finds it.
1650
+ */
1651
+ export async function reapEarlyModalSandboxById(input: {
1652
+ client: Pick<ModalClient, 'sandboxes'>;
1653
+ key: string;
1654
+ sandboxId: string;
1655
+ attempts?: number;
1656
+ sleep?: (ms: number) => Promise<void>;
1657
+ }): Promise<'not_early' | 'terminated'> {
1658
+ const fresh = await input.client.sandboxes.fromId(input.sandboxId);
1659
+ if (!isUnadoptedEarlyModalSandbox(await fresh.getTags())) return 'not_early';
1660
+ const confirmAttempts = await terminateModalSandboxConfirmed({
1661
+ sandbox: fresh,
1662
+ readExitCode: readModalExitCode(input.client),
1663
+ sleep: input.sleep ?? sleepMs,
1664
+ attempts: input.attempts ?? EARLY_MODAL_SANDBOX_HEDGE_CONFIRM_ATTEMPTS,
1665
+ });
1666
+ logEarlyModalSandbox('reaped_unadopted', {
1667
+ key: input.key,
1668
+ sandboxId: input.sandboxId,
1669
+ confirmAttempts,
1670
+ });
1671
+ return 'terminated';
1672
+ }
1673
+
1674
+ function logEarlyModalSandboxReapUnconfirmed(input: {
1675
+ event: string;
1676
+ key: string;
1677
+ sandboxId: string;
1678
+ error: unknown;
1679
+ }) {
1680
+ // Loud: the sandbox keeps its early tag, so the durable sweep retries it.
1681
+ console.error(
1682
+ JSON.stringify({
1683
+ event: `play-runner.modal.early.${input.event}`,
1684
+ key: input.key,
1685
+ sandboxId: input.sandboxId,
1686
+ error:
1687
+ input.error instanceof Error
1688
+ ? input.error.message
1689
+ : String(input.error),
1690
+ }),
1691
+ );
1692
+ }
1693
+
1694
+ /**
1695
+ * In-process exact-id reaper: after EARLY_MODAL_SANDBOX_REAP_AFTER_MS,
1696
+ * terminate the sandbox (confirmed) if it still carries an early (or hedge)
1697
+ * tag, i.e. no launch adopted it. The fast path only: the durable guarantee is
1698
+ * the early tag itself, set by the create call, which the worker's sweep reads
1699
+ * even after this process is gone.
1700
+ */
1701
+ function scheduleEarlyModalSandboxReap(input: {
1702
+ client: ModalClient;
1703
+ key: string;
1704
+ sandboxId: string;
1705
+ }): void {
1706
+ const reap = setTimeout(() => {
1707
+ void reapEarlyModalSandboxById(input).catch((error: unknown) =>
1708
+ logEarlyModalSandboxReapUnconfirmed({
1709
+ event: 'reap_unconfirmed',
1710
+ key: input.key,
1711
+ sandboxId: input.sandboxId,
1712
+ error,
1713
+ }),
1714
+ );
1715
+ }, EARLY_MODAL_SANDBOX_REAP_AFTER_MS);
1716
+ reap.unref?.();
1717
+ }
1718
+
1719
+ /**
1720
+ * Durable orphan cleanup for E2/PB early sandboxes (and retired F2 legs). The cleanup
1721
+ * obligation is recorded before (atomically with) every early create: the
1722
+ * create request itself carries the early (or hedge) source tag and its
1723
+ * create time, and Modal holds those tags for the sandbox's life. The main
1724
+ * path's `ambiguous_modal_creates` row cannot be used here: the hint arrives
1725
+ * before the run is enqueued, so there is no run row or attempt lease to
1726
+ * fence it to. Once adopted, a sandbox carries the run's create tags and the
1727
+ * main path's obligation (recorded before adoption) covers it.
1728
+ *
1729
+ * This pass lists only unadopted early sandboxes (the source-tag selector),
1730
+ * skips any younger than EARLY_MODAL_SANDBOX_REAP_AFTER_MS, re-reads each
1731
+ * one's tags by exact id, and terminates it with a bounded confirmation. No
1732
+ * launch adopts past EARLY_MODAL_SANDBOX_MAX_ADOPTION_AGE_MS (60 s < 90 s), so
1733
+ * whichever worker created it, an early sandbox this old is an orphan. One
1734
+ * not confirmed this pass keeps its tag and is retried by the next.
1735
+ */
1736
+ export const EARLY_MODAL_SANDBOX_SWEEP_INTERVAL_MS = 60_000;
1737
+ const EARLY_MODAL_SANDBOX_SWEEP_LIMIT = 20;
1738
+ const EARLY_MODAL_SANDBOX_SWEEP_CONFIRM_ATTEMPTS = 5;
1739
+
1740
+ export async function sweepOrphanEarlyModalSandboxes(input: {
1741
+ client: Pick<ModalClient, 'sandboxes'>;
1742
+ modalAppId: string;
1743
+ nowMs?: () => number;
1744
+ sleep?: (ms: number) => Promise<void>;
1745
+ limit?: number;
1746
+ }): Promise<{
1747
+ observed: number;
1748
+ terminated: number;
1749
+ unconfirmed: number;
1750
+ young: number;
1751
+ }> {
1752
+ const nowMs = input.nowMs ?? Date.now;
1753
+ const limit = input.limit ?? EARLY_MODAL_SANDBOX_SWEEP_LIMIT;
1754
+ const ids = new Set<string>();
1755
+ for (const source of [
1756
+ EARLY_MODAL_SANDBOX_SOURCE_TAG,
1757
+ EARLY_MODAL_SANDBOX_HEDGE_TAG,
1758
+ ]) {
1759
+ for await (const listed of input.client.sandboxes.list({
1760
+ appId: input.modalAppId,
1761
+ tags: { source },
1762
+ })) {
1763
+ if (ids.size >= limit) break;
1764
+ if (listed.sandboxId?.trim()) ids.add(listed.sandboxId.trim());
1765
+ }
1766
+ }
1767
+ let terminated = 0;
1768
+ let unconfirmed = 0;
1769
+ let young = 0;
1770
+ await Promise.all(
1771
+ [...ids].map(async (sandboxId) => {
1772
+ try {
1773
+ const fresh = await input.client.sandboxes.fromId(sandboxId);
1774
+ const tags = await fresh.getTags();
1775
+ if (!isUnadoptedEarlyModalSandbox(tags)) return;
1776
+ const ageMs = earlyModalSandboxAgeMs(tags, nowMs());
1777
+ // A sandbox without a create time predates the tag and is past any
1778
+ // adoption (adoption refuses it), so it is reaped.
1779
+ if (ageMs !== null && ageMs < EARLY_MODAL_SANDBOX_REAP_AFTER_MS) {
1780
+ young += 1;
1781
+ return;
1782
+ }
1783
+ const confirmAttempts = await terminateModalSandboxConfirmed({
1784
+ sandbox: fresh,
1785
+ readExitCode: readModalExitCode(input.client),
1786
+ sleep: input.sleep ?? sleepMs,
1787
+ attempts: EARLY_MODAL_SANDBOX_SWEEP_CONFIRM_ATTEMPTS,
1788
+ });
1789
+ terminated += 1;
1790
+ logEarlyModalSandbox('swept_orphan', {
1791
+ key: tags.earlyKey ?? null,
1792
+ sandboxId,
1793
+ ageMs,
1794
+ confirmAttempts,
1795
+ });
1796
+ } catch (error) {
1797
+ unconfirmed += 1;
1798
+ logEarlyModalSandboxReapUnconfirmed({
1799
+ event: 'sweep_unconfirmed',
1800
+ key: 'sweep',
1801
+ sandboxId,
1802
+ error,
1803
+ });
1804
+ }
1805
+ }),
326
1806
  );
1807
+ return { observed: ids.size, terminated, unconfirmed, young };
327
1808
  }
328
1809
 
329
- async function terminateModalSandbox(sandbox: ModalSandbox): Promise<boolean> {
330
- let timer: ReturnType<typeof setTimeout> | undefined;
1810
+ /**
1811
+ * The worker's sweep pass. Early sandboxes exist only under the
1812
+ * modal_sidecar profile (startEarlyModalSandbox refuses otherwise), so with it
1813
+ * off this makes no provider call.
1814
+ */
1815
+ export async function sweepOrphanEarlyModalSandboxesForWorker(input: {
1816
+ runtimeSchedulerSchema: string | null;
1817
+ }): Promise<
1818
+ | Awaited<ReturnType<typeof sweepOrphanEarlyModalSandboxes>>
1819
+ | { skipped: 'sidecar_profile_off' | 'app_missing' }
1820
+ > {
1821
+ if (!DURABLE_RUNS_ROLLOUT.modalSupervisorSidecar)
1822
+ return { skipped: 'sidecar_profile_off' };
1823
+ const modalConfig = await loadModalRequiredConfig({
1824
+ runtimeSchedulerSchema: input.runtimeSchedulerSchema,
1825
+ limits: null,
1826
+ });
1827
+ let modalAppId: string;
331
1828
  try {
332
- // The default terminate call only acknowledges the request. Capacity may
333
- // be released only after Modal confirms the sandbox itself has stopped.
334
- await Promise.race([
335
- sandbox.terminate({ wait: true }),
336
- new Promise<never>((_resolve, reject) => {
337
- timer = setTimeout(() => {
338
- reject(
339
- new Error(
340
- `Modal sandbox termination did not settle within ${MODAL_TERMINATION_TIMEOUT_MS}ms.`,
1829
+ modalAppId = (await modalConfig.client.apps.fromName(modalConfig.appName))
1830
+ .appId;
1831
+ } catch (error) {
1832
+ if (error instanceof Error && error.name === 'NotFoundError')
1833
+ return { skipped: 'app_missing' };
1834
+ throw error;
1835
+ }
1836
+ return await sweepOrphanEarlyModalSandboxes({
1837
+ client: modalConfig.client,
1838
+ modalAppId,
1839
+ });
1840
+ }
1841
+
1842
+ export function startEarlyModalSandbox(input: {
1843
+ workflowId: string;
1844
+ orgId?: string | null;
1845
+ runtimeSchedulerSchema: string | null;
1846
+ /** EXPERIMENT: the hinted run's overrides (E2, PB, S1); absent: static. */
1847
+ experimentSwitchOverrides?: ExperimentSwitchOverrides | null;
1848
+ }): boolean {
1849
+ if (
1850
+ !resolveExperimentSwitch(
1851
+ 'E2',
1852
+ input.experimentSwitchOverrides,
1853
+ EARLY_MODAL_SANDBOX_START,
1854
+ ) ||
1855
+ !DURABLE_RUNS_ROLLOUT.modalSupervisorSidecar
1856
+ )
1857
+ return false;
1858
+ // The key and the adoption check are org-scoped; a hint without an org
1859
+ // cannot start a sandbox any launch could safely adopt.
1860
+ const orgId = input.orgId?.trim();
1861
+ if (!orgId) {
1862
+ logEarlyModalSandbox('hint_refused', { reason: 'no_org' });
1863
+ return false;
1864
+ }
1865
+ const key = earlyModalSandboxKey({ orgId, workflowId: input.workflowId });
1866
+ if (earlyModalSandboxes.has(key)) return false;
1867
+ const hintAtMs = Date.now();
1868
+ const started = (async () => {
1869
+ const modalConfig = await loadModalRequiredConfig({
1870
+ runtimeSchedulerSchema: input.runtimeSchedulerSchema,
1871
+ limits: null,
1872
+ });
1873
+ const resources = modalSandboxResourcesForPlay(modalConfig.limits);
1874
+ const memoryPolicy = resolveModalSandboxMemoryPolicy({
1875
+ limits: modalConfig.limits,
1876
+ runtimeSchedulerSchema: input.runtimeSchedulerSchema,
1877
+ });
1878
+ const app = await modalLaunchLookup({
1879
+ client: modalConfig.client,
1880
+ key: `app:${modalConfig.appName}`,
1881
+ enabled: true,
1882
+ load: () =>
1883
+ modalConfig.client.apps.fromName(modalConfig.appName, {
1884
+ createIfMissing: true,
1885
+ }),
1886
+ });
1887
+ const runnerImage = await resolveModalRunnerImage({
1888
+ client: modalConfig.client,
1889
+ configuredHash: configuredBakedRunnerHash(),
1890
+ explicitImage: modalConfig.imageExplicit === true,
1891
+ defaultImage: () =>
1892
+ modalConfig.client.images.fromRegistry(modalConfig.image),
1893
+ lookupPublished: (ref) => modalConfig.client.images.fromName(ref),
1894
+ });
1895
+ const baseImage = runnerImage.image;
1896
+ const image = isModalPreviewEvaluation({
1897
+ runtimeSchedulerSchema: input.runtimeSchedulerSchema,
1898
+ })
1899
+ ? await modalLaunchLookup({
1900
+ client: modalConfig.client,
1901
+ key: `preview-python-image:${app.appId}:${runnerImage.ref ?? modalConfig.image}`,
1902
+ enabled: true,
1903
+ load: () =>
1904
+ withModalCallSignal(
1905
+ AbortSignal.timeout(MODAL_SANDBOX_CREATE_TIMEOUT_MS),
1906
+ () =>
1907
+ baseImage
1908
+ .dockerfileCommands([
1909
+ 'RUN apt-get update && apt-get install -y --no-install-recommends python3 python-is-python3 && rm -rf /var/lib/apt/lists/*',
1910
+ ])
1911
+ .build(app),
341
1912
  ),
342
- );
343
- }, MODAL_TERMINATION_TIMEOUT_MS);
1913
+ })
1914
+ : baseImage;
1915
+ const cpu = modalSupervisorLaunch().cpu || resources.physicalCpuCores;
1916
+ const timeoutMs = modalSandboxLifetimeMs(modalConfig.limits);
1917
+ const createRequestedAtMs = Date.now();
1918
+ const earlyParams = {
1919
+ cpu,
1920
+ cpuLimit: cpu,
1921
+ timeoutMs,
1922
+ // Orphan guard: an unadopted early sandbox runs no command and
1923
+ // terminates after this idle window (PB runs one; the exact-id reaper
1924
+ // ends that sandbox, see PREBOOT_RUNNER_IN_EARLY_SANDBOX).
1925
+ idleTimeoutMs: EARLY_MODAL_SANDBOX_IDLE_TIMEOUT_MS,
1926
+ workdir: modalConfig.workdir,
1927
+ memoryMiB: memoryPolicy.reservationMemoryMiB,
1928
+ memoryLimitMiB: memoryPolicy.memoryLimitMiB,
1929
+ outboundCidrAllowlist: [],
1930
+ regions:
1931
+ modalSupervisorLaunch().regions ?? MODAL_SUPERVISOR_DEFAULT_REGIONS,
1932
+ };
1933
+ // PB: the pre-boot claim rides on the create tags, so no other process
1934
+ // can see this sandbox without it.
1935
+ const preboot =
1936
+ runnerImage.baked &&
1937
+ resolveExperimentSwitch(
1938
+ 'PB',
1939
+ input.experimentSwitchOverrides,
1940
+ PREBOOT_RUNNER_IN_EARLY_SANDBOX,
1941
+ );
1942
+ const earlyTags = {
1943
+ source: EARLY_MODAL_SANDBOX_SOURCE_TAG,
1944
+ earlyKey: key,
1945
+ // Identity, checked at adoption against the launching run.
1946
+ orgId,
1947
+ workflowId: input.workflowId,
1948
+ [EARLY_CREATED_AT_TAG]: String(createRequestedAtMs),
1949
+ limitsKey: earlyModalLimitsKey({
1950
+ cpu,
1951
+ memoryMiB: earlyParams.memoryMiB,
1952
+ timeoutMs,
344
1953
  }),
345
- ]);
346
- return true;
347
- } catch (error) {
348
- console.warn('[play-runner.modal.terminate_failed]', {
1954
+ ...(preboot ? { [EARLY_PREBOOT_TAG]: '1' } : {}),
1955
+ };
1956
+ const createEarly = () =>
1957
+ modalConfig.client.sandboxes.create(app, image, {
1958
+ ...earlyParams,
1959
+ tags: earlyTags,
1960
+ });
1961
+ const awaitEarlyCreate = (create: Promise<ModalSandbox>) =>
1962
+ awaitModalSandboxCreate({
1963
+ create,
1964
+ onLateSuccess: async (late) => {
1965
+ try {
1966
+ const confirmAttempts = await terminateModalSandboxConfirmed({
1967
+ sandbox: late,
1968
+ readExitCode: readModalExitCode(modalConfig.client),
1969
+ sleep: sleepMs,
1970
+ attempts: EARLY_MODAL_SANDBOX_HEDGE_CONFIRM_ATTEMPTS,
1971
+ });
1972
+ logEarlyModalSandbox('late_create_terminated', {
1973
+ key,
1974
+ sandboxId: late.sandboxId,
1975
+ confirmAttempts,
1976
+ });
1977
+ } catch (error) {
1978
+ // Its early tag (from the create) keeps it in the durable sweep.
1979
+ logEarlyModalSandboxReapUnconfirmed({
1980
+ event: 'late_create_terminate_unconfirmed',
1981
+ key,
1982
+ sandboxId: late.sandboxId,
1983
+ error,
1984
+ });
1985
+ }
1986
+ },
1987
+ onLateFailure: async () => undefined,
1988
+ });
1989
+ const sandbox = await awaitEarlyCreate(createEarly());
1990
+ logEarlyModalSandbox('created', {
1991
+ key,
1992
+ workflowId: input.workflowId,
349
1993
  sandboxId: sandbox.sandboxId,
1994
+ hintToRequestMs: createRequestedAtMs - hintAtMs,
1995
+ createMs: Date.now() - createRequestedAtMs,
1996
+ });
1997
+ // Arm the early sandbox: exact-id reaper, PB pre-boot, S1 supervisor.
1998
+ const armEarlySandbox = (sandbox: ModalSandbox) => {
1999
+ // Exact-id reaper: if no launch adopted it, terminate it by id.
2000
+ scheduleEarlyModalSandboxReap({
2001
+ client: modalConfig.client,
2002
+ key,
2003
+ sandboxId: sandbox.sandboxId,
2004
+ });
2005
+ if (preboot) {
2006
+ earlyModalPreboots.set(
2007
+ sandbox,
2008
+ startEarlyModalPreboot({
2009
+ key,
2010
+ sandbox,
2011
+ bakedRunner: modalBakedRunnerExpectation({
2012
+ imageBaked: true,
2013
+ bundlePromise: buildPlayRunnerBundle(),
2014
+ }),
2015
+ workDir: modalConfig.workdir,
2016
+ sandboxRuntimeLimits: modalConfig.limits,
2017
+ ...(memoryPolicy.memoryLimitMiB > memoryPolicy.reservationMemoryMiB
2018
+ ? { memoryLimitMiB: memoryPolicy.memoryLimitMiB }
2019
+ : {}),
2020
+ }),
2021
+ );
2022
+ }
2023
+ const earlySupervisor = resolveExperimentSwitch(
2024
+ 'S1',
2025
+ input.experimentSwitchOverrides,
2026
+ START_SUPERVISOR_WITH_EARLY_SANDBOX,
2027
+ );
2028
+ // PB's claim rode on the create tags, so it is already on the sandbox.
2029
+ if (preboot)
2030
+ earlyModalForeignAdoptionClaims.set(sandbox, Promise.resolve());
2031
+ let tags: Record<string, string> = earlyTags;
2032
+ if (earlySupervisor) {
2033
+ tags = { ...earlyTags, [EARLY_SUPERVISOR_TAG]: '1' };
2034
+ const supervisorStartedAtMs = Date.now();
2035
+ // Tag first (with the plan lookup): a launch in another process sees
2036
+ // the sidecar claim and does not adopt this sandbox.
2037
+ const claimTagged = sandbox.setTags(tags);
2038
+ claimTagged.catch(() => undefined);
2039
+ if (!preboot) earlyModalForeignAdoptionClaims.set(sandbox, claimTagged);
2040
+ const ready = (async () => {
2041
+ const [plan] = await Promise.all([
2042
+ resolveModalSupervisorPlan({
2043
+ client: modalConfig.client,
2044
+ runtimeSchedulerSchema: input.runtimeSchedulerSchema,
2045
+ }),
2046
+ claimTagged,
2047
+ ]);
2048
+ await createModalSupervisorSidecar({
2049
+ sandbox,
2050
+ plan,
2051
+ cancellation: new Promise<never>(() => undefined),
2052
+ });
2053
+ })();
2054
+ ready.then(
2055
+ () =>
2056
+ logEarlyModalSandbox('supervisor_created', {
2057
+ key,
2058
+ sandboxId: sandbox.sandboxId,
2059
+ elapsedMs: Date.now() - supervisorStartedAtMs,
2060
+ }),
2061
+ (error: unknown) =>
2062
+ logEarlyModalSandbox('supervisor_failed', {
2063
+ key,
2064
+ sandboxId: sandbox.sandboxId,
2065
+ error: error instanceof Error ? error.message : String(error),
2066
+ }),
2067
+ );
2068
+ earlyModalSupervisors.set(sandbox, ready);
2069
+ }
2070
+ return tags;
2071
+ };
2072
+ const tags = armEarlySandbox(sandbox);
2073
+ return { sandbox, startedAtMs: createRequestedAtMs, tags };
2074
+ })().catch((error: unknown) => {
2075
+ logEarlyModalSandbox('create_failed', {
2076
+ key,
350
2077
  error: error instanceof Error ? error.message : String(error),
351
2078
  });
352
- return false;
353
- } finally {
354
- if (timer) clearTimeout(timer);
355
- }
2079
+ return null;
2080
+ });
2081
+ earlyModalSandboxes.put(key, started);
2082
+ logEarlyModalSandbox('hint_accepted', { key, workflowId: input.workflowId });
2083
+ return true;
356
2084
  }
357
2085
 
358
- async function releaseModalSandboxCapacityAfterConfirmedTermination(input: {
359
- leaseId: string;
360
- release: NonNullable<PlayRunnerCallbacks['releaseSandboxCapacity']>;
361
- }): Promise<void> {
362
- let lastError: unknown;
363
- for (const delayMs of MODAL_CAPACITY_RELEASE_RETRY_DELAYS_MS) {
364
- if (delayMs > 0) {
365
- await new Promise<void>((resolve) => setTimeout(resolve, delayMs));
366
- }
367
- try {
368
- await input.release(input.leaseId);
369
- return;
370
- } catch (error) {
371
- lastError = error;
372
- }
373
- }
374
- throw lastError;
2086
+ /**
2087
+ * PB: why an in-process early sandbox with a pre-boot must not be adopted by
2088
+ * this launch, or null when it may be (a running pre-boot this launch will
2089
+ * deliver to, or one that provably never started).
2090
+ */
2091
+ export function earlyPrebootAdoptionRefusal(input: {
2092
+ preboot: EarlyModalPreboot;
2093
+ wanted: boolean;
2094
+ sandboxRuntimeLimits: PlaySandboxRuntimeLimits;
2095
+ memoryLimitMiB?: number;
2096
+ nowMs: number;
2097
+ }): string | null {
2098
+ const { preboot } = input;
2099
+ if (preboot.status === 'not_started') return null;
2100
+ if (preboot.status === 'ambiguous') return 'preboot_ambiguous';
2101
+ // A running runner nobody will deliver to would share the sandbox with
2102
+ // today's launch.
2103
+ if (!input.wanted) return 'preboot_unwanted';
2104
+ if (preboot.exitCode !== null) return 'preboot_exited';
2105
+ if (input.nowMs - preboot.startedAtMs > EARLY_PREBOOT_MAX_ADOPTION_AGE_MS)
2106
+ return 'preboot_stale';
2107
+ if (
2108
+ !samePlaySandboxRuntimeLimits(
2109
+ preboot.runner.sandboxRuntimeLimits,
2110
+ input.sandboxRuntimeLimits,
2111
+ ) ||
2112
+ preboot.runner.memoryLimitMiB !== input.memoryLimitMiB
2113
+ )
2114
+ return 'preboot_limits_mismatch';
2115
+ return null;
375
2116
  }
376
2117
 
377
2118
  /**
378
- * A create that settles after its caller timed out is already an external
379
- * fact. Persist it before attempting any further provider operation: the
380
- * durable cleanup controller then owns deletion, capacity release, and the
381
- * late billing adjustment. A short retry absorbs a transient scheduler-store
382
- * outage without turning this into a fresh Play attempt.
2119
+ * Adopt this run's early sandbox by exact id, or return null so the launch
2120
+ * creates its own. The in-process promise is awaited when this worker started
2121
+ * it; otherwise one tag listing finds a sandbox another worker started. The
2122
+ * key is org-scoped, and every path checks the sandbox's org and workflow
2123
+ * tags against this run before re-tagging it; a mismatch is refused loudly.
383
2124
  */
384
- async function persistLateModalSandboxResource(input: {
385
- resource: Parameters<
386
- NonNullable<PlayRunnerCallbacks['onLateRuntimeResourceAcquired']>
387
- >[0];
388
- record: NonNullable<PlayRunnerCallbacks['onLateRuntimeResourceAcquired']>;
389
- }): Promise<void> {
390
- let lastError: unknown;
391
- for (const delayMs of MODAL_LATE_CREATE_PERSIST_RETRY_DELAYS_MS) {
392
- if (delayMs > 0) {
393
- await new Promise<void>((resolve) => setTimeout(resolve, delayMs));
2125
+ export async function adoptEarlyModalSandbox(input: {
2126
+ client: ModalClient;
2127
+ modalAppId: string;
2128
+ workflowId: string;
2129
+ expectedLimitsKey: string;
2130
+ createTags: Record<string, string>;
2131
+ context: PlayRunnerExecutionConfig['context'];
2132
+ /** PB: whether this launch wants a pre-booted runner, and its limits. */
2133
+ preboot: {
2134
+ wanted: boolean;
2135
+ sandboxRuntimeLimits: PlaySandboxRuntimeLimits;
2136
+ memoryLimitMiB?: number;
2137
+ };
2138
+ /** This process's early sandboxes; the module registry unless injected. */
2139
+ registry?: EarlyModalSandboxRegistry;
2140
+ nowMs?: () => number;
2141
+ }): Promise<ModalSandbox | null> {
2142
+ const nowMs = input.nowMs ?? Date.now;
2143
+ const startedAt = nowMs();
2144
+ const orgId = input.context.orgId?.trim();
2145
+ if (!orgId) {
2146
+ emitModalStage(input.context, 'early:adopt_miss', {
2147
+ reason: 'no_org',
2148
+ elapsedMs: 0,
2149
+ });
2150
+ return null;
2151
+ }
2152
+ const key = earlyModalSandboxKey({ orgId, workflowId: input.workflowId });
2153
+ const registry = input.registry ?? earlyModalSandboxes;
2154
+ let sandbox: ModalSandbox | null = null;
2155
+ let localEntry: EarlyModalSandboxEntry | null = null;
2156
+ let how = 'none';
2157
+ try {
2158
+ // Taken, not read: this entry is handed to this one adoption only.
2159
+ const local = registry.take(key);
2160
+ if (local) {
2161
+ localEntry = await local;
2162
+ sandbox = localEntry?.sandbox ?? null;
2163
+ how = 'in_process';
394
2164
  }
395
- try {
396
- await input.record(input.resource);
397
- return;
398
- } catch (error) {
399
- lastError = error;
2165
+ if (!sandbox) {
2166
+ for await (const listed of input.client.sandboxes.list({
2167
+ appId: input.modalAppId,
2168
+ tags: { source: EARLY_MODAL_SANDBOX_SOURCE_TAG, earlyKey: key },
2169
+ })) {
2170
+ sandbox = await input.client.sandboxes.fromId(listed.sandboxId);
2171
+ how = 'by_tag';
2172
+ break;
2173
+ }
2174
+ }
2175
+ if (!sandbox) {
2176
+ emitModalStage(input.context, 'early:adopt_miss', {
2177
+ key,
2178
+ reason: 'not_found',
2179
+ elapsedMs: nowMs() - startedAt,
2180
+ });
2181
+ return null;
2182
+ }
2183
+ // A1 may skip the read only for this process's own, fresh, untaken entry
2184
+ // whose foreign-adoption claim is confirmed on the sandbox: then no other
2185
+ // process can have adopted (re-tagged) it. Everything else is read back.
2186
+ const foreignClaim =
2187
+ how === 'in_process'
2188
+ ? earlyModalForeignAdoptionClaims.get(sandbox)
2189
+ : undefined;
2190
+ const trustLocalTags =
2191
+ how === 'in_process' &&
2192
+ localEntry !== null &&
2193
+ nowMs() - localEntry.startedAtMs <
2194
+ EARLY_MODAL_SANDBOX_MAX_ADOPTION_AGE_MS &&
2195
+ resolveExperimentSwitch(
2196
+ 'A1',
2197
+ input.context.experimentSwitchOverrides,
2198
+ ADOPT_IN_PROCESS_EARLY_SANDBOX_WITHOUT_TAG_READ,
2199
+ ) &&
2200
+ foreignClaim !== undefined &&
2201
+ (await foreignClaim.then(
2202
+ () => true,
2203
+ () => false,
2204
+ ));
2205
+ const tags =
2206
+ trustLocalTags && localEntry ? localEntry.tags : await sandbox.getTags();
2207
+ const identityRefusal = earlyModalSandboxIdentityRefusal(tags, {
2208
+ key,
2209
+ orgId,
2210
+ workflowId: input.workflowId,
2211
+ });
2212
+ if (identityRefusal) {
2213
+ // Never expected: the key already names this org and workflow. Loud,
2214
+ // and the sandbox is left untouched for its own reaper.
2215
+ console.error(
2216
+ JSON.stringify({
2217
+ event: 'play-runner.modal.early.adopt_refused_identity',
2218
+ reason: identityRefusal,
2219
+ key,
2220
+ how,
2221
+ sandboxId: sandbox.sandboxId,
2222
+ runId: input.context.runId ?? null,
2223
+ }),
2224
+ );
2225
+ emitModalStage(input.context, 'early:adopt_miss', {
2226
+ key,
2227
+ reason: identityRefusal,
2228
+ sandboxId: sandbox.sandboxId,
2229
+ elapsedMs: nowMs() - startedAt,
2230
+ });
2231
+ return null;
2232
+ }
2233
+ const ageMs =
2234
+ how === 'in_process' && localEntry
2235
+ ? nowMs() - localEntry.startedAtMs
2236
+ : earlyModalSandboxAgeMs(tags, nowMs());
2237
+ if (ageMs === null || ageMs >= EARLY_MODAL_SANDBOX_MAX_ADOPTION_AGE_MS) {
2238
+ // Past the adoption window the reapers own it.
2239
+ emitModalStage(input.context, 'early:adopt_miss', {
2240
+ key,
2241
+ reason: 'early_stale',
2242
+ sandboxId: sandbox.sandboxId,
2243
+ ageMs,
2244
+ elapsedMs: nowMs() - startedAt,
2245
+ });
2246
+ return null;
2247
+ }
2248
+ if (how !== 'in_process' && tags[EARLY_SUPERVISOR_TAG]) {
2249
+ // S1: another process started this sandbox's supervisor; a second
2250
+ // sidecar create here would collide. Create an ordinary sandbox.
2251
+ emitModalStage(input.context, 'early:adopt_miss', {
2252
+ key,
2253
+ reason: 'early_supervisor_foreign',
2254
+ sandboxId: sandbox.sandboxId,
2255
+ elapsedMs: nowMs() - startedAt,
2256
+ });
2257
+ return null;
2258
+ }
2259
+ if (how !== 'in_process' && tags[EARLY_PREBOOT_TAG]) {
2260
+ // PB: another process started a runner here and holds its delivery
2261
+ // plan; nothing may be delivered to it from this process.
2262
+ emitModalStage(input.context, 'early:adopt_miss', {
2263
+ key,
2264
+ reason: 'early_preboot_foreign',
2265
+ sandboxId: sandbox.sandboxId,
2266
+ elapsedMs: nowMs() - startedAt,
2267
+ });
2268
+ return null;
2269
+ }
2270
+ const prebootPending =
2271
+ how === 'in_process' ? earlyModalPreboots.get(sandbox) : undefined;
2272
+ const prebootRefusal = prebootPending
2273
+ ? earlyPrebootAdoptionRefusal({
2274
+ preboot: await prebootPending,
2275
+ ...input.preboot,
2276
+ nowMs: Date.now(),
2277
+ })
2278
+ : null;
2279
+ if (prebootRefusal) {
2280
+ emitModalStage(input.context, 'early:adopt_miss', {
2281
+ key,
2282
+ reason: prebootRefusal,
2283
+ sandboxId: sandbox.sandboxId,
2284
+ elapsedMs: nowMs() - startedAt,
2285
+ });
2286
+ return null;
2287
+ }
2288
+ if (
2289
+ tags.source !== EARLY_MODAL_SANDBOX_SOURCE_TAG ||
2290
+ tags.earlyKey !== key ||
2291
+ tags.limitsKey !== input.expectedLimitsKey ||
2292
+ (await sandbox.poll()) !== null
2293
+ ) {
2294
+ emitModalStage(input.context, 'early:adopt_miss', {
2295
+ key,
2296
+ reason: 'mismatch_or_exited',
2297
+ sandboxId: sandbox.sandboxId,
2298
+ elapsedMs: nowMs() - startedAt,
2299
+ });
2300
+ return null;
400
2301
  }
2302
+ // Re-tag first: from here the sandbox is an ordinary launch sandbox for
2303
+ // every cleanup and reconciliation path, and the reaper skips it.
2304
+ await sandbox.setTags({ ...input.createTags, earlyKey: key });
2305
+ emitModalStage(input.context, 'early:adopted', {
2306
+ key,
2307
+ how,
2308
+ sandboxId: sandbox.sandboxId,
2309
+ elapsedMs: nowMs() - startedAt,
2310
+ });
2311
+ return sandbox;
2312
+ } catch (error) {
2313
+ emitModalStage(input.context, 'early:adopt_miss', {
2314
+ key,
2315
+ reason: 'error',
2316
+ error: error instanceof Error ? error.message : String(error),
2317
+ elapsedMs: nowMs() - startedAt,
2318
+ });
2319
+ return null;
401
2320
  }
402
- throw new AggregateError(
403
- [lastError],
404
- 'RUNTIME_MODAL_LATE_CREATE_PERSIST_FAILED: Modal created a sandbox after the caller deadline, but its durable cleanup obligation could not be recorded.',
405
- );
406
2321
  }
407
2322
 
408
2323
  export const modalPlayRunnerBackend: PlayRunnerBackend = {
@@ -428,6 +2343,29 @@ export const modalPlayRunnerBackend: PlayRunnerBackend = {
428
2343
  const startedAt = Date.now();
429
2344
  const runtimeTiming: PlayRunnerRuntimeTiming = { backend: 'modal' };
430
2345
  emitModalStage(config.context, 'create:start');
2346
+ if (
2347
+ DURABLE_RUNS_ROLLOUT.modalSupervisorSidecar &&
2348
+ modalSupervisorLaunch().prewarmAppExecuteRoute === true &&
2349
+ // B: the run route already sent this run's prewarm at admission.
2350
+ !executePrewarmSentAtAdmission(config.context.experimentSwitchOverrides)
2351
+ ) {
2352
+ prewarmAppExecuteRoute({
2353
+ context: config.context,
2354
+ ...(modalSupervisorLaunch().authenticatedAppPrewarm === true
2355
+ ? {
2356
+ authenticated: {
2357
+ serviceToken: process.env.DEEPLINE_INTERNAL_TOKEN,
2358
+ trustedOrigins: modalSupervisorTrustedAppOrigins(process.env),
2359
+ },
2360
+ }
2361
+ : {}),
2362
+ });
2363
+ }
2364
+ // Independent of the sandbox: start it now so a cold build, or just the
2365
+ // read of the prebuilt file, overlaps provider admission and create. A
2366
+ // build failure still surfaces where the payload is staged.
2367
+ const bundlePromise = buildPlayRunnerBundle();
2368
+ bundlePromise.catch(() => undefined);
431
2369
  const providerCircuitClaim =
432
2370
  await callbacks?.shouldAttemptSandboxProvider?.('modal');
433
2371
  if (providerCircuitClaim && !providerCircuitClaim.allowed) {
@@ -453,36 +2391,105 @@ export const modalPlayRunnerBackend: PlayRunnerBackend = {
453
2391
  timeoutSeconds: modalConfig.limits.timeoutSeconds,
454
2392
  elapsedMs: Date.now() - startedAt,
455
2393
  });
456
- const app = await modalConfig.client.apps.fromName(modalConfig.appName, {
457
- createIfMissing: true,
2394
+ const cacheLookups =
2395
+ DURABLE_RUNS_ROLLOUT.modalSupervisorSidecar &&
2396
+ modalSupervisorLaunch().cacheModalLaunchLookups === true;
2397
+ // With the switch on, the supervisor plan resolves alongside the app and
2398
+ // image; it is still awaited (and fails) at its original point below.
2399
+ const earlySupervisorPlan = cacheLookups
2400
+ ? withModalCallSignal(
2401
+ AbortSignal.timeout(MODAL_SANDBOX_CREATE_TIMEOUT_MS),
2402
+ () =>
2403
+ resolveModalSupervisorPlan({
2404
+ client: modalConfig.client,
2405
+ runtimeSchedulerSchema: config.context.runtimeSchedulerSchema,
2406
+ }),
2407
+ )
2408
+ : null;
2409
+ earlySupervisorPlan?.catch(() => undefined);
2410
+ const app = await modalLaunchLookup({
2411
+ client: modalConfig.client,
2412
+ key: `app:${modalConfig.appName}`,
2413
+ enabled: cacheLookups,
2414
+ load: () =>
2415
+ modalConfig.client.apps.fromName(modalConfig.appName, {
2416
+ createIfMissing: true,
2417
+ }),
458
2418
  });
459
2419
  emitModalStage(config.context, 'app:resolved', {
460
2420
  modalAppId: app.appId,
461
2421
  elapsedMs: Date.now() - startedAt,
462
2422
  });
463
- const baseImage = modalConfig.client.images.fromRegistry(
464
- modalConfig.image,
465
- );
2423
+ // Unchanged (no lookup, no await) unless an operator configured the
2424
+ // baked runner hash; then the published baked image is used only when
2425
+ // Modal resolves it, and its runner file is still verified before use.
2426
+ const runnerImage = await resolveModalRunnerImage({
2427
+ client: modalConfig.client,
2428
+ configuredHash: configuredBakedRunnerHash(),
2429
+ explicitImage: modalConfig.imageExplicit === true,
2430
+ defaultImage: () =>
2431
+ modalConfig.client.images.fromRegistry(modalConfig.image),
2432
+ lookupPublished: (ref) => modalConfig.client.images.fromName(ref),
2433
+ });
2434
+ if (runnerImage.skipped) {
2435
+ emitModalStage(config.context, 'runner:baked_skipped', {
2436
+ reason: runnerImage.skipped,
2437
+ });
2438
+ }
2439
+ if (runnerImage.ref) {
2440
+ emitModalStage(config.context, 'create:image', {
2441
+ baked: runnerImage.baked,
2442
+ bakedImageRef: runnerImage.ref,
2443
+ });
2444
+ }
2445
+ const baseImage = runnerImage.image;
466
2446
  // Modal caches this immutable layer by its build commands. Build before
467
2447
  // sandbox admission so a cold Python image owns no sandbox-capacity lease
468
2448
  // or ambiguous SandboxCreate intent. Production keeps its existing image.
469
2449
  const image = isModalPreviewEvaluation({
470
2450
  runtimeSchedulerSchema: config.context.runtimeSchedulerSchema,
471
2451
  })
472
- ? await withModalCallSignal(
473
- AbortSignal.timeout(MODAL_SANDBOX_CREATE_TIMEOUT_MS),
474
- () =>
475
- baseImage
476
- .dockerfileCommands([
477
- 'RUN apt-get update && apt-get install -y --no-install-recommends python3 python-is-python3 && rm -rf /var/lib/apt/lists/*',
478
- ])
479
- .build(app),
480
- )
2452
+ ? await modalLaunchLookup({
2453
+ client: modalConfig.client,
2454
+ key: `preview-python-image:${app.appId}:${runnerImage.ref ?? modalConfig.image}`,
2455
+ enabled: cacheLookups,
2456
+ load: () =>
2457
+ withModalCallSignal(
2458
+ AbortSignal.timeout(MODAL_SANDBOX_CREATE_TIMEOUT_MS),
2459
+ () =>
2460
+ baseImage
2461
+ .dockerfileCommands([
2462
+ 'RUN apt-get update && apt-get install -y --no-install-recommends python3 python-is-python3 && rm -rf /var/lib/apt/lists/*',
2463
+ ])
2464
+ .build(app),
2465
+ ),
2466
+ })
481
2467
  : baseImage;
482
2468
  emitModalStage(config.context, 'image:resolved', {
483
2469
  built: image !== baseImage,
484
2470
  elapsedMs: Date.now() - startedAt,
485
2471
  });
2472
+ const supervisorPlan = earlySupervisorPlan
2473
+ ? await earlySupervisorPlan
2474
+ : DURABLE_RUNS_ROLLOUT.modalSupervisorSidecar
2475
+ ? await withModalCallSignal(
2476
+ AbortSignal.timeout(MODAL_SANDBOX_CREATE_TIMEOUT_MS),
2477
+ () =>
2478
+ resolveModalSupervisorPlan({
2479
+ client: modalConfig.client,
2480
+ runtimeSchedulerSchema: config.context.runtimeSchedulerSchema,
2481
+ }),
2482
+ )
2483
+ : null;
2484
+ if (supervisorPlan) {
2485
+ emitModalStage(config.context, 'supervisor:resolved', {
2486
+ elapsedMs: Date.now() - startedAt,
2487
+ });
2488
+ }
2489
+ // The runner's gateway origins are the sidecar under the profile.
2490
+ const runnerConfig = supervisorPlan
2491
+ ? { ...config, context: modalSupervisorRunnerContext(config.context) }
2492
+ : config;
486
2493
  const capacityReservation =
487
2494
  await callbacks?.reserveSandboxCapacity?.('modal');
488
2495
  emitModalStage(config.context, 'capacity:reserved', {
@@ -496,6 +2503,16 @@ export const modalPlayRunnerBackend: PlayRunnerBackend = {
496
2503
  runId: config.context.runId ?? 'unknown',
497
2504
  attempt: String(config.context.runAttempt ?? 0),
498
2505
  };
2506
+ // PB: the run's own limits, which a pre-booted runner must match.
2507
+ const runMemoryLimitMiB =
2508
+ memoryPolicy.memoryLimitMiB > memoryPolicy.reservationMemoryMiB
2509
+ ? memoryPolicy.memoryLimitMiB
2510
+ : undefined;
2511
+ const prebootWanted = resolveExperimentSwitch(
2512
+ 'PB',
2513
+ config.context.experimentSwitchOverrides,
2514
+ PREBOOT_RUNNER_IN_EARLY_SANDBOX,
2515
+ );
499
2516
  let sandbox: ModalSandbox;
500
2517
  let createSent = false;
501
2518
  try {
@@ -541,20 +2558,63 @@ export const modalPlayRunnerBackend: PlayRunnerBackend = {
541
2558
  elapsedMs: Date.now() - startedAt,
542
2559
  });
543
2560
  createSent = true;
544
- sandbox = await awaitModalSandboxCreate({
545
- create: modalConfig.client.sandboxes.create(app, image, {
546
- cpu: resources.physicalCpuCores,
547
- cpuLimit: resources.physicalCpuCores,
548
- memoryMiB: memoryPolicy.reservationMemoryMiB,
549
- memoryLimitMiB: memoryPolicy.memoryLimitMiB,
550
- timeoutMs: modalSandboxLifetimeMs(modalConfig.limits),
551
- idleTimeoutMs: modalSandboxLifetimeMs(modalConfig.limits),
552
- workdir: modalConfig.workdir,
553
- tags: createTags,
554
- ...(modalConfig.outboundCidrAllowlist
2561
+ const createParams = {
2562
+ cpu:
2563
+ (supervisorPlan && modalSupervisorLaunch().cpu) ||
2564
+ resources.physicalCpuCores,
2565
+ cpuLimit:
2566
+ (supervisorPlan && modalSupervisorLaunch().cpu) ||
2567
+ resources.physicalCpuCores,
2568
+ timeoutMs: modalSandboxLifetimeMs(modalConfig.limits),
2569
+ idleTimeoutMs: modalSandboxLifetimeMs(modalConfig.limits),
2570
+ workdir: modalConfig.workdir,
2571
+ tags: createTags,
2572
+ memoryMiB: memoryPolicy.reservationMemoryMiB,
2573
+ memoryLimitMiB: memoryPolicy.memoryLimitMiB,
2574
+ // Under the profile the runner has no outbound network at all:
2575
+ // the supervisor sidecar is its only peer.
2576
+ ...(supervisorPlan
2577
+ ? {
2578
+ outboundCidrAllowlist: [],
2579
+ regions:
2580
+ modalSupervisorLaunch().regions ??
2581
+ MODAL_SUPERVISOR_DEFAULT_REGIONS,
2582
+ }
2583
+ : modalConfig.outboundCidrAllowlist
555
2584
  ? { outboundCidrAllowlist: modalConfig.outboundCidrAllowlist }
556
2585
  : {}),
557
- }),
2586
+ };
2587
+ const createSandbox = () =>
2588
+ modalConfig.client.sandboxes.create(app, image, createParams);
2589
+ sandbox = await awaitModalSandboxCreate({
2590
+ create:
2591
+ resolveExperimentSwitch(
2592
+ 'E2',
2593
+ config.context.experimentSwitchOverrides,
2594
+ EARLY_MODAL_SANDBOX_START,
2595
+ ) &&
2596
+ supervisorPlan &&
2597
+ config.context.workflowId
2598
+ ? adoptEarlyModalSandbox({
2599
+ client: modalConfig.client,
2600
+ modalAppId: app.appId,
2601
+ workflowId: config.context.workflowId,
2602
+ expectedLimitsKey: earlyModalLimitsKey({
2603
+ cpu: createParams.cpu,
2604
+ memoryMiB: createParams.memoryMiB,
2605
+ timeoutMs: createParams.timeoutMs,
2606
+ }),
2607
+ createTags,
2608
+ context: config.context,
2609
+ preboot: {
2610
+ wanted: prebootWanted,
2611
+ sandboxRuntimeLimits: modalConfig.limits,
2612
+ ...(runMemoryLimitMiB === undefined
2613
+ ? {}
2614
+ : { memoryLimitMiB: runMemoryLimitMiB }),
2615
+ },
2616
+ }).then((adopted) => adopted ?? createSandbox())
2617
+ : createSandbox(),
558
2618
  onLateSuccess: async (lateSandbox) => {
559
2619
  logSandboxCreateOutcome({
560
2620
  provider: 'modal',
@@ -695,6 +2755,24 @@ export const modalPlayRunnerBackend: PlayRunnerBackend = {
695
2755
  sandboxId: sandbox.sandboxId,
696
2756
  elapsedMs: runtimeTiming.modalCreateMs,
697
2757
  });
2758
+ // PB: only an in-process adoption carries a pre-boot, and adoption has
2759
+ // already refused every running pre-boot this launch must not use.
2760
+ const prebootPending = earlyModalPreboots.get(sandbox);
2761
+ const prebootState = prebootPending ? await prebootPending : undefined;
2762
+ const preboot =
2763
+ prebootWanted && prebootState?.status === 'running'
2764
+ ? prebootState
2765
+ : null;
2766
+ if (prebootState) {
2767
+ emitModalStage(config.context, 'runner:preboot', {
2768
+ sandboxId: sandbox.sandboxId,
2769
+ status: prebootState.status,
2770
+ used: preboot !== null,
2771
+ ...(prebootState.status === 'running'
2772
+ ? {}
2773
+ : { reason: prebootState.reason }),
2774
+ });
2775
+ }
698
2776
  let detached = false;
699
2777
  let setupError: unknown;
700
2778
  let cancelExecution!: (error: Error) => void;
@@ -706,9 +2784,60 @@ export const modalPlayRunnerBackend: PlayRunnerBackend = {
706
2784
  callbacks?.cancellationSignal?.addEventListener('abort', onCancel, {
707
2785
  once: true,
708
2786
  });
2787
+ // Start the supervisor as soon as the sandbox exists: it overlaps
2788
+ // resource recording and payload staging; only its create is awaited
2789
+ // before the runner starts.
2790
+ const earlySupervisor = supervisorPlan
2791
+ ? earlyModalSupervisors.get(sandbox)
2792
+ : undefined;
2793
+ const supervisorReady = earlySupervisor
2794
+ ? Promise.race([earlySupervisor, cancellationPromise])
2795
+ .then(() =>
2796
+ emitModalStage(config.context, 'supervisor:created', {
2797
+ sandboxId: sandbox.sandboxId,
2798
+ early: true,
2799
+ }),
2800
+ )
2801
+ // Started before its run was known: pin it to this run now,
2802
+ // overlapping resource recording and payload staging.
2803
+ .then(async () => {
2804
+ const pinStartedAtMs = Date.now();
2805
+ await pinModalSupervisorSidecar({
2806
+ sandbox,
2807
+ pin: modalSupervisorRunPin(config.context),
2808
+ cancellation: cancellationPromise,
2809
+ });
2810
+ emitModalStage(config.context, 'supervisor:pinned', {
2811
+ sandboxId: sandbox.sandboxId,
2812
+ elapsedMs: Date.now() - pinStartedAtMs,
2813
+ });
2814
+ })
2815
+ : supervisorPlan
2816
+ ? startModalSupervisorSidecar({
2817
+ sandbox,
2818
+ plan: supervisorPlan,
2819
+ context: config.context,
2820
+ cancellation: cancellationPromise,
2821
+ })
2822
+ : null;
2823
+ supervisorReady?.catch(() => undefined);
709
2824
 
710
2825
  try {
711
2826
  if (callbacks?.cancellationSignal?.aborted) onCancel();
2827
+ // Only when an operator enabled the baked image. The probe is a
2828
+ // read-only Node check, not customer code, and it overlaps durable
2829
+ // resource registration and the first filesystem call's connection
2830
+ // setup. Its verdict is consumed only at payload staging.
2831
+ const bakedRunnerExpectation = modalBakedRunnerExpectation({
2832
+ imageBaked: runnerImage.baked,
2833
+ bundlePromise,
2834
+ onStale: (stale) =>
2835
+ emitModalStage(config.context, 'runner:baked_config_stale', {
2836
+ configuredHashPrefix: stale.configuredHash.slice(0, 12),
2837
+ bundleHashPrefix: stale.bundleHash.slice(0, 12),
2838
+ }),
2839
+ });
2840
+ bakedRunnerExpectation.catch(() => undefined);
712
2841
  try {
713
2842
  await callbacks?.onRuntimeResourceAcquired?.({
714
2843
  kind: 'modal_sandbox',
@@ -802,6 +2931,10 @@ export const modalPlayRunnerBackend: PlayRunnerBackend = {
802
2931
  // Awaited (and its failure surfaced) below; this only keeps an upload
803
2932
  // failure from orphaning the read.
804
2933
  baselineHeartbeatRead.catch(() => undefined);
2934
+ // PB: the pre-booted runner is the verified baked runner already.
2935
+ const bakedRunner = preboot
2936
+ ? undefined
2937
+ : await Promise.race([bakedRunnerExpectation, cancellationPromise]);
805
2938
  const uploadStartedAt = Date.now();
806
2939
  const payload = await Promise.race([
807
2940
  stageRunnerPayload({
@@ -815,8 +2948,22 @@ export const modalPlayRunnerBackend: PlayRunnerBackend = {
815
2948
  cancellation: cancellationPromise,
816
2949
  }),
817
2950
  },
818
- bundlePromise: buildPlayRunnerBundle(),
819
- config: withRunnerSandboxProvider(config, 'modal'),
2951
+ bundlePromise,
2952
+ // Opt-in with the baked image: the small per-run envelope rides on
2953
+ // the launch exec's stdin instead of a separate filesystem write.
2954
+ ...(preboot
2955
+ ? {
2956
+ preboot: preboot.runner,
2957
+ envelopeDelivery: 'stdin' as const,
2958
+ }
2959
+ : {}),
2960
+ ...(bakedRunner
2961
+ ? {
2962
+ bakedRunner,
2963
+ envelopeDelivery: 'stdin' as const,
2964
+ }
2965
+ : {}),
2966
+ config: withRunnerSandboxProvider(runnerConfig, 'modal'),
820
2967
  ...(memoryPolicy.memoryLimitMiB > memoryPolicy.reservationMemoryMiB
821
2968
  ? { memoryLimitMiB: memoryPolicy.memoryLimitMiB }
822
2969
  : {}),
@@ -831,7 +2978,8 @@ export const modalPlayRunnerBackend: PlayRunnerBackend = {
831
2978
  // and the defer starts a new attempt on a new sandbox.
832
2979
  if (
833
2980
  !callbacks?.cancellationSignal?.aborted &&
834
- isUndeliveredModalRunnerFailure(error)
2981
+ (isUndeliveredModalRunnerFailure(error) ||
2982
+ error instanceof PrebootedRunnerLimitsMismatchError)
835
2983
  ) {
836
2984
  throw recoveryForRunnerStartupNotLive(error);
837
2985
  }
@@ -843,6 +2991,17 @@ export const modalPlayRunnerBackend: PlayRunnerBackend = {
843
2991
  cancellationPromise,
844
2992
  ]);
845
2993
 
2994
+ if (supervisorReady) {
2995
+ // No runner command ran yet: a supervisor failure defers to a new
2996
+ // attempt on a new sandbox, like an undelivered payload.
2997
+ await supervisorReady.catch((error: unknown) => {
2998
+ if (callbacks?.cancellationSignal?.aborted) throw error;
2999
+ throw recoveryForRunnerStartupNotLive(error);
3000
+ });
3001
+ emitModalStage(config.context, 'supervisor:sidecar_ready', {
3002
+ elapsedMs: Date.now() - startedAt,
3003
+ });
3004
+ }
846
3005
  emitModalStage(config.context, 'execute:start', {
847
3006
  sandboxId: sandbox.sandboxId,
848
3007
  timeoutSeconds: modalConfig.limits.timeoutSeconds,
@@ -850,10 +3009,105 @@ export const modalPlayRunnerBackend: PlayRunnerBackend = {
850
3009
  elapsedMs: Date.now() - startedAt,
851
3010
  });
852
3011
  const executeStartedAt = Date.now();
853
- await Promise.race([
854
- sandbox.exec(['bash', '-lc', payload.command]),
855
- cancellationPromise,
856
- ]);
3012
+ // PB: deliver the envelope to the waiting runner. Any failure here is
3013
+ // before the runner could have reported live: defer to a new attempt.
3014
+ const prebootDelivery = preboot
3015
+ ? await Promise.race([
3016
+ deliverPrebootedRunnerEnvelope({
3017
+ sandbox,
3018
+ payload,
3019
+ cancellation: cancellationPromise,
3020
+ emitStage: (stage, extra) =>
3021
+ emitModalStage(config.context, stage, extra),
3022
+ }),
3023
+ cancellationPromise,
3024
+ ]).catch((error: unknown) => {
3025
+ if (callbacks?.cancellationSignal?.aborted) throw error;
3026
+ throw recoveryForRunnerStartupNotLive(error);
3027
+ })
3028
+ : null;
3029
+ prebootDelivery?.materialized.catch(() => undefined);
3030
+ const launch: ModalRunnerLaunch = prebootDelivery
3031
+ ? {}
3032
+ : await Promise.race([
3033
+ launchModalRunnerCommand({
3034
+ sandbox,
3035
+ payload,
3036
+ cancellation: cancellationPromise,
3037
+ emitStage: (stage, extra) =>
3038
+ emitModalStage(config.context, stage, extra),
3039
+ // Today's full upload (runner included), only if the baked file
3040
+ // does not verify inside the launch command.
3041
+ stageFullUpload: () =>
3042
+ stageRunnerPayload({
3043
+ sandbox: {
3044
+ id: sandbox.sandboxId,
3045
+ uploadFile: (content, path) =>
3046
+ writeModalFileWithDeadline({
3047
+ sandbox,
3048
+ content,
3049
+ path,
3050
+ cancellation: cancellationPromise,
3051
+ }),
3052
+ },
3053
+ bundlePromise,
3054
+ config: withRunnerSandboxProvider(runnerConfig, 'modal'),
3055
+ ...(memoryPolicy.memoryLimitMiB >
3056
+ memoryPolicy.reservationMemoryMiB
3057
+ ? { memoryLimitMiB: memoryPolicy.memoryLimitMiB }
3058
+ : {}),
3059
+ workDir: modalConfig.workdir,
3060
+ startedAt,
3061
+ emitStage: (stage, extra) =>
3062
+ emitModalStage(config.context, stage, extra),
3063
+ }),
3064
+ }),
3065
+ cancellationPromise,
3066
+ ]).catch((error: unknown) => {
3067
+ // Same classification as a failed staging upload: an inline
3068
+ // fallback upload that never landed means no runner started here.
3069
+ if (
3070
+ payload.inlineEnvelope &&
3071
+ !callbacks?.cancellationSignal?.aborted &&
3072
+ isUndeliveredModalRunnerFailure(error)
3073
+ ) {
3074
+ throw recoveryForRunnerStartupNotLive(error);
3075
+ }
3076
+ throw error;
3077
+ });
3078
+ // A fallback re-staged the runner at new paths; the suspension (and
3079
+ // with it every later recovery read) names the runner that started.
3080
+ let restaged = launch.restaged ?? null;
3081
+ // The runner is already booting on the delivered envelope; the
3082
+ // verdict (bounded, 30 s) is awaited before the command counts as
3083
+ // accepted, so a non-`ok` verdict still runs today's full upload
3084
+ // first, exactly in the order it always did.
3085
+ if (launch.bakedVerdict && launch.runBakedFallback) {
3086
+ const verdict = await Promise.race([
3087
+ launch.bakedVerdict,
3088
+ cancellationPromise,
3089
+ ]);
3090
+ emitModalStage(config.context, 'runtime:baked_verified_in_command', {
3091
+ sandboxId: sandbox.sandboxId,
3092
+ bakedRunnerVerdict: verdict,
3093
+ elapsedMs: Date.now() - (launch.startedAt ?? startedAt),
3094
+ });
3095
+ if (bakedVerdictRequiresFallback(verdict)) {
3096
+ restaged = await launch
3097
+ .runBakedFallback(verdict)
3098
+ .catch((error: unknown) => {
3099
+ // Same classification as a failed staging upload.
3100
+ if (
3101
+ !callbacks?.cancellationSignal?.aborted &&
3102
+ isUndeliveredModalRunnerFailure(error)
3103
+ ) {
3104
+ throw recoveryForRunnerStartupNotLive(error);
3105
+ }
3106
+ throw error;
3107
+ });
3108
+ }
3109
+ }
3110
+ const runnerPaths = modalDetachedRunnerPaths(payload, restaged);
857
3111
  runtimeTiming.modalExecuteMs = Date.now() - executeStartedAt;
858
3112
  const commandAcceptedAtMs = Date.now();
859
3113
  emitModalStage(config.context, 'execute:accepted', {
@@ -869,11 +3123,37 @@ export const modalPlayRunnerBackend: PlayRunnerBackend = {
869
3123
  // and that park comes after this check. A runner that never reports
870
3124
  // live therefore never released anything, and the scheduler's defer
871
3125
  // starts a new attempt whose fence rejects it.
872
- await confirmDetachedModalRunnerReady({
873
- readiness: readRunnerReadiness,
874
- baselineHeartbeatAt,
875
- cancellation: cancellationPromise,
876
- });
3126
+ // PB: also stop waiting as soon as the pre-booted runner provably
3127
+ // cannot report live (failed delivery, or its chain exited).
3128
+ let readinessSettled = false;
3129
+ const prebootNotLive =
3130
+ preboot && prebootDelivery
3131
+ ? prebootedRunnerNotLive({
3132
+ materialized: prebootDelivery.materialized,
3133
+ exited: preboot.exited,
3134
+ readiness: readRunnerReadiness,
3135
+ baselineHeartbeatAt,
3136
+ isSettled: () => readinessSettled,
3137
+ })
3138
+ : null;
3139
+ const readinessCancellation = prebootNotLive
3140
+ ? Promise.race([cancellationPromise, prebootNotLive])
3141
+ : cancellationPromise;
3142
+ readinessCancellation.catch(() => undefined);
3143
+ try {
3144
+ await confirmDetachedModalRunnerReady({
3145
+ readiness: readRunnerReadiness,
3146
+ baselineHeartbeatAt,
3147
+ cancellation: readinessCancellation,
3148
+ extendedFastWindow: resolveExperimentSwitch(
3149
+ 'H1',
3150
+ config.context.experimentSwitchOverrides,
3151
+ EXTENDED_FAST_READINESS_WINDOW,
3152
+ ),
3153
+ });
3154
+ } finally {
3155
+ readinessSettled = true;
3156
+ }
877
3157
  const heartbeatReadyAtMs = Date.now();
878
3158
  emitModalStage(config.context, 'execute:heartbeat_ready', {
879
3159
  sandboxId: sandbox.sandboxId,
@@ -918,9 +3198,9 @@ export const modalPlayRunnerBackend: PlayRunnerBackend = {
918
3198
  sandboxId: sandbox.sandboxId,
919
3199
  sessionId: 'modal',
920
3200
  cmdId: sandbox.sandboxId,
921
- outputPath: payload.outputPath,
922
- exitCodePath: payload.exitCodePath,
923
- runtimeCompletedPath: payload.runtimeCompletedPath,
3201
+ outputPath: runnerPaths.outputPath,
3202
+ exitCodePath: runnerPaths.exitCodePath,
3203
+ runtimeCompletedPath: runnerPaths.runtimeCompletedPath,
924
3204
  startedAtMs: Date.now(),
925
3205
  heartbeatTimeoutMs: push.leaseSeconds * 1_000,
926
3206
  runtimeLimitSeconds: modalConfig.limits.timeoutSeconds,