deepline 0.3.537 → 0.3.539

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