deepline 0.3.484 → 0.3.485

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 (209) hide show
  1. package/dist/bundling-sources/sdk/src/client-core.ts +91 -30
  2. package/dist/bundling-sources/sdk/src/compat.ts +13 -0
  3. package/dist/bundling-sources/sdk/src/plays/client-core.ts +4 -1
  4. package/dist/bundling-sources/sdk/src/plays/run-request.ts +143 -9
  5. package/dist/bundling-sources/sdk/src/release.ts +1 -1
  6. package/dist/bundling-sources/sdk/src/runs/watch-polling.ts +31 -4
  7. package/dist/bundling-sources/sdk/src/tool-calls.ts +1 -1
  8. package/dist/bundling-sources/sdk/src/types.ts +7 -1
  9. package/dist/bundling-sources/shared_libs/play-data-plane/sheet-column-storage.ts +32 -3
  10. package/dist/bundling-sources/shared_libs/play-runtime/app-runtime-api.ts +126 -41
  11. package/dist/bundling-sources/shared_libs/play-runtime/context.ts +231 -25
  12. package/dist/bundling-sources/shared_libs/play-runtime/daytona-runtime-config.ts +9 -0
  13. package/dist/bundling-sources/shared_libs/play-runtime/deployment/fly-machines.ts +130 -19
  14. package/dist/bundling-sources/shared_libs/play-runtime/deployment/fly-registry.ts +105 -0
  15. package/dist/bundling-sources/shared_libs/play-runtime/execute-server-timing.ts +4 -2
  16. package/dist/bundling-sources/shared_libs/play-runtime/governor/app-runtime-rate-state-backend.ts +194 -56
  17. package/dist/bundling-sources/shared_libs/play-runtime/log-provenance.ts +11 -6
  18. package/dist/bundling-sources/shared_libs/play-runtime/play-runs/sandbox-cleanup/job.ts +3 -0
  19. package/dist/bundling-sources/shared_libs/play-runtime/play-runs/sandbox-cleanup/ports.ts +2 -0
  20. package/dist/bundling-sources/shared_libs/play-runtime/play-runs/sandbox-cleanup/postgres-adapter.ts +2 -1
  21. package/dist/bundling-sources/shared_libs/play-runtime/protocol.ts +30 -0
  22. package/dist/bundling-sources/shared_libs/play-runtime/resource-governor.ts +195 -2
  23. package/dist/bundling-sources/shared_libs/play-runtime/run-failure.ts +20 -1
  24. package/dist/bundling-sources/shared_libs/play-runtime/run-ledger-projection-contract.ts +15 -0
  25. package/dist/bundling-sources/shared_libs/play-runtime/run-snapshot-stream.ts +2 -2
  26. package/dist/bundling-sources/shared_libs/play-runtime/runner-app/index.ts +102 -23
  27. package/dist/bundling-sources/shared_libs/play-runtime/runner-app/progress-sidecar.ts +9 -1
  28. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona-control-transport.ts +25 -5
  29. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona-launch-transport.ts +133 -82
  30. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona-lifecycle.ts +58 -16
  31. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona-sandbox-absence.ts +171 -0
  32. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona-session-execution.ts +69 -0
  33. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona.ts +100 -40
  34. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/types.ts +8 -0
  35. package/dist/bundling-sources/shared_libs/play-runtime/runtime-api.ts +67 -9
  36. package/dist/bundling-sources/shared_libs/play-runtime/runtime-incident-drills.ts +5 -5
  37. package/dist/bundling-sources/shared_libs/play-runtime/runtime-receipt-store-adapter.ts +6 -3
  38. package/dist/bundling-sources/shared_libs/play-runtime/runtime-sheet-errors.ts +14 -0
  39. package/dist/bundling-sources/shared_libs/play-runtime/runtime-sheet-row-writer.ts +87 -31
  40. package/dist/bundling-sources/shared_libs/play-runtime/sandbox-runs/contract.ts +18 -0
  41. package/dist/bundling-sources/shared_libs/play-runtime/sandbox-runs/index.ts +19 -0
  42. package/dist/bundling-sources/shared_libs/play-runtime/sandbox-runs/runner-backend-adapter.ts +14 -0
  43. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-runtime-worker.ts +204 -6
  44. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd.ts +39 -0
  45. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/play-run-recovery.ts +12 -1
  46. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres-progress.ts +26 -0
  47. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres-rate-scope.ts +44 -15
  48. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres-rate-state.ts +60 -11
  49. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres.ts +649 -38
  50. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/run-ledger-outbox-recovery.ts +6 -1
  51. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-event-search.ts +17 -0
  52. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-sandbox-capacity.ts +25 -33
  53. package/dist/bundling-sources/shared_libs/play-runtime/suspension.ts +12 -0
  54. package/dist/bundling-sources/shared_libs/play-runtime/test-runtime-seams.ts +21 -0
  55. package/dist/bundling-sources/shared_libs/plays/authoring-contract.ts +1 -1
  56. package/dist/bundling-sources/shared_libs/plays/source-authoring-edition.ts +1 -1
  57. package/dist/cli/auth-ABZBH55L.js +43 -0
  58. package/dist/cli/{auth-EBFOTF7X.mjs → auth-OWMUENCU.mjs} +5 -5
  59. package/dist/cli/{billing-G2G3EF3I.js → billing-2FMNQGOX.js} +80 -80
  60. package/dist/cli/{billing-2ZOIMW5V.mjs → billing-JX4H3VFF.mjs} +7 -7
  61. package/dist/cli/{chunk-M4PG7FGC.js → chunk-2ILND7XX.js} +2 -2
  62. package/dist/cli/{chunk-WXRM3UC6.mjs → chunk-2ZEQ43B7.mjs} +3 -3
  63. package/dist/cli/{chunk-PU52JXKA.mjs → chunk-3DBW6C7M.mjs} +13 -4
  64. package/dist/cli/{chunk-4OVHIWE7.mjs → chunk-3DYU3JQN.mjs} +2 -2
  65. package/dist/cli/{chunk-QIDDTIVZ.js → chunk-3OF7NSGR.js} +322 -294
  66. package/dist/cli/{chunk-YWC5AN26.mjs → chunk-3Z24NKW7.mjs} +62 -34
  67. package/dist/cli/{chunk-RLLEH2SP.js → chunk-5DCQWQCP.js} +26 -26
  68. package/dist/cli/{chunk-DEXSQGXB.mjs → chunk-62PJ6PK7.mjs} +5 -5
  69. package/dist/cli/{chunk-6NPWXE32.mjs → chunk-676NZ7K4.mjs} +1 -1
  70. package/dist/cli/{chunk-FRD5WFT4.js → chunk-775AZTO7.js} +323 -247
  71. package/dist/cli/{chunk-4OEOM6GP.mjs → chunk-ACTUAZYP.mjs} +5 -5
  72. package/dist/cli/{chunk-ZOKM7DVA.js → chunk-AFADYKFE.js} +8 -8
  73. package/dist/cli/{chunk-GVAENVIG.js → chunk-AUQQVDAB.js} +110 -21
  74. package/dist/cli/{chunk-U7IJAGWB.js → chunk-BSKPQB2P.js} +7 -7
  75. package/dist/cli/chunk-C6QWRSMQ.js +42 -0
  76. package/dist/cli/{chunk-AK7UKQ5R.js → chunk-CSBMKHTV.js} +5 -5
  77. package/dist/cli/{chunk-YHA3EV3I.mjs → chunk-CW6TAQBF.mjs} +15 -4
  78. package/dist/cli/{chunk-UT4YMA2N.js → chunk-DMNVM34J.js} +5 -4
  79. package/dist/cli/{chunk-XZXIWPT3.mjs → chunk-E73JXJA3.mjs} +1 -1
  80. package/dist/cli/{chunk-5KNRQWHE.js → chunk-EC2CVPN5.js} +3 -3
  81. package/dist/cli/{chunk-IXWQOVNW.js → chunk-ECIXZNSW.js} +87 -76
  82. package/dist/cli/{chunk-LTZXLYKE.mjs → chunk-FJY6K3BG.mjs} +93 -17
  83. package/dist/cli/{chunk-TRLDJNVE.mjs → chunk-G5PI3RNT.mjs} +1 -1
  84. package/dist/cli/{chunk-WYUCDLVR.mjs → chunk-GHHJWCMD.mjs} +2 -1
  85. package/dist/cli/{chunk-FQK7BULS.js → chunk-HKGXGGIV.js} +1 -1
  86. package/dist/cli/{chunk-2AWYJXBX.js → chunk-IHMYIHF4.js} +5 -5
  87. package/dist/cli/{chunk-SD7QWZTV.mjs → chunk-INW22YP7.mjs} +1 -1
  88. package/dist/cli/{chunk-OWUZKXE7.mjs → chunk-J7EENGKJ.mjs} +1 -1
  89. package/dist/cli/{chunk-TIRSKEZH.mjs → chunk-JD6HKNKD.mjs} +1 -1
  90. package/dist/cli/{chunk-OHKKDPA5.js → chunk-JQXUWYWX.js} +13 -13
  91. package/dist/cli/{chunk-EACX7QXO.mjs → chunk-KZTNNLIL.mjs} +2 -2
  92. package/dist/cli/{chunk-7K5CWKKZ.mjs → chunk-L352NOE3.mjs} +2 -2
  93. package/dist/cli/{chunk-KGOC6HGI.js → chunk-L7IQ3DFH.js} +53 -53
  94. package/dist/cli/{chunk-4IOY2SCQ.js → chunk-LOX3BISD.js} +4 -4
  95. package/dist/cli/{chunk-6GRZEYSG.js → chunk-NKPTM7SK.js} +7 -7
  96. package/dist/cli/{chunk-VEVGM6B5.js → chunk-NLRTFJGH.js} +14 -14
  97. package/dist/cli/{chunk-UKM74PAA.js → chunk-NRNWPWBW.js} +37 -37
  98. package/dist/cli/{chunk-HNRELVCS.mjs → chunk-ONONSV2Q.mjs} +96 -7
  99. package/dist/cli/{chunk-CYWBAV5H.js → chunk-OW4OTEFF.js} +16 -16
  100. package/dist/cli/{chunk-5K5CAND4.mjs → chunk-RZE5I2XJ.mjs} +4 -4
  101. package/dist/cli/{chunk-3XQIVEAT.js → chunk-S3WQJ5VG.js} +3 -3
  102. package/dist/cli/{chunk-4SFC2XUF.mjs → chunk-SR6S4EYG.mjs} +5 -5
  103. package/dist/cli/{chunk-UWOY74RU.js → chunk-T4G2T5DS.js} +21 -21
  104. package/dist/cli/{chunk-TN2GW57M.mjs → chunk-TMCC7ORQ.mjs} +1 -1
  105. package/dist/cli/{chunk-HEI3BWIV.mjs → chunk-TSCUWWTM.mjs} +1 -1
  106. package/dist/cli/{chunk-DBJ62RAO.js → chunk-TVW6USSG.js} +3 -3
  107. package/dist/cli/{chunk-NW4QJE54.js → chunk-U6WEGDD3.js} +2 -2
  108. package/dist/cli/{chunk-V7JCMBLU.mjs → chunk-UPHXGZCE.mjs} +4 -4
  109. package/dist/cli/{chunk-C62NI2X6.js → chunk-UQ3LQ6IF.js} +5 -5
  110. package/dist/cli/{chunk-5GOG5ZGC.mjs → chunk-VZYTLWOM.mjs} +2 -2
  111. package/dist/cli/{chunk-AF7MOUZP.mjs → chunk-W33OL4F2.mjs} +2 -2
  112. package/dist/cli/{chunk-ZM2YPJQJ.js → chunk-XK5DMLZE.js} +5 -1
  113. package/dist/cli/{chunk-LJ5747UC.mjs → chunk-XRDXNAAY.mjs} +5 -1
  114. package/dist/cli/{chunk-YGN77QA5.mjs → chunk-YDA3PMKK.mjs} +3 -3
  115. package/dist/cli/{csv-S3CHUKI6.js → csv-HFEQPGNY.js} +13 -13
  116. package/dist/cli/{csv-NLWVWD3H.mjs → csv-OHF3Y5KB.mjs} +4 -4
  117. package/dist/cli/{db-OGRPAEEM.mjs → db-M456OUXD.mjs} +7 -7
  118. package/dist/cli/{db-WBSKMMOH.js → db-VLQKCYQS.js} +28 -28
  119. package/dist/cli/describe-CP35DZ5Z.js +49 -0
  120. package/dist/cli/{describe-FAD3Z7LN.mjs → describe-M6VXFYVL.mjs} +21 -21
  121. package/dist/cli/describe-core.d.mts +3 -3
  122. package/dist/cli/describe-core.d.ts +3 -3
  123. package/dist/cli/describe-core.js +4 -4
  124. package/dist/cli/describe-core.mjs +3 -3
  125. package/dist/cli/{executions-LYCL344R.mjs → executions-4FGRBPJF.mjs} +7 -7
  126. package/dist/cli/{executions-SOAZHCY4.js → executions-GKINJZI6.js} +9 -9
  127. package/dist/cli/{feedback-AVF6V7SV.mjs → feedback-D2WMGK3V.mjs} +4 -4
  128. package/dist/cli/{feedback-OROUPUNJ.js → feedback-ZH5K7WV7.js} +8 -8
  129. package/dist/cli/git-IDALMZDN.js +25 -0
  130. package/dist/cli/{git-J5N5M57H.mjs → git-OCIJ5ME4.mjs} +5 -5
  131. package/dist/cli/index.js +142 -139
  132. package/dist/cli/index.mjs +45 -42
  133. package/dist/cli/{legacy-noops-QAQMZMEG.js → legacy-noops-QNIVP7LO.js} +8 -8
  134. package/dist/cli/{legacy-noops-ENRRM7BL.mjs → legacy-noops-V6Q2X34P.mjs} +5 -5
  135. package/dist/cli/{monitors-CKQ65WRL.mjs → monitors-2USHTG5G.mjs} +8 -8
  136. package/dist/cli/{monitors-SFMQ5LFR.js → monitors-5DNK7W2K.js} +92 -92
  137. package/dist/cli/{org-3UNTDLT2.js → org-RPGM5AN4.js} +73 -73
  138. package/dist/cli/{org-K4UIEU5P.mjs → org-TL2YPYSE.mjs} +7 -7
  139. package/dist/cli/{pages-NKZTGB4C.js → pages-PNUKPFWV.js} +18 -18
  140. package/dist/cli/{pages-6GPGBIAH.mjs → pages-XDEW6EE3.mjs} +7 -7
  141. package/dist/cli/{play-BDEADESI.js → play-F5LHRKV5.js} +858 -632
  142. package/dist/cli/{play-62BEE7IX.mjs → play-WINNQ4HZ.mjs} +372 -146
  143. package/dist/cli/{providers-SXGP44GH.js → providers-BD4IS5U5.js} +10 -10
  144. package/dist/cli/{providers-X3CUWMFP.mjs → providers-PXGL3FRE.mjs} +7 -7
  145. package/dist/cli/{quickstart-XQ4426M4.js → quickstart-7LVF6HZF.js} +6 -6
  146. package/dist/cli/{quickstart-7LN22BKX.mjs → quickstart-XTH3UQWZ.mjs} +4 -4
  147. package/dist/cli/{run-XXSN3B5A.mjs → run-MBMUENR7.mjs} +26 -26
  148. package/dist/cli/{run-PBJ4ZJ4W.js → run-NH2BAWPA.js} +41 -41
  149. package/dist/cli/{search-M75VMADD.mjs → search-BMRWBV66.mjs} +8 -8
  150. package/dist/cli/search-R3MQJQMT.js +32 -0
  151. package/dist/cli/{search-output-F6HCFYEI.js → search-output-5NNT337U.js} +22 -16
  152. package/dist/cli/{search-output-NUQAKWDM.mjs → search-output-QKKRD4MF.mjs} +14 -8
  153. package/dist/cli/{secrets-J2H6V33R.mjs → secrets-AWEXBTJV.mjs} +7 -7
  154. package/dist/cli/{secrets-LRYY4QPE.js → secrets-KQSTOREN.js} +16 -16
  155. package/dist/cli/{sessions-YPF62CZE.js → sessions-DSPLZYCJ.js} +6 -6
  156. package/dist/cli/{sessions-IMT336UV.mjs → sessions-RO25Q67X.mjs} +5 -5
  157. package/dist/cli/{settings-35YYC5WA.js → settings-7JXIKNKI.js} +79 -79
  158. package/dist/cli/{settings-PDWVQIGH.mjs → settings-JMGXGK4Z.mjs} +12 -12
  159. package/dist/cli/{setup-UR7GOR7H.js → setup-5QFAQQRW.js} +47 -47
  160. package/dist/cli/{setup-DG5DISSE.mjs → setup-ZQZ47FHB.mjs} +9 -9
  161. package/dist/cli/skills-EDZXY7DV.js +33 -0
  162. package/dist/cli/{skills-U6NJD5J7.mjs → skills-W3H2DL56.mjs} +7 -7
  163. package/dist/cli/{tools-2HGEOELR.mjs → tools-2BZCVNBS.mjs} +19 -19
  164. package/dist/cli/tools-2EY2ETCZ.js +56 -0
  165. package/dist/cli/{update-FRAYBAHK.mjs → update-GAWYMGAW.mjs} +9 -9
  166. package/dist/cli/update-UKDQKNBY.js +33 -0
  167. package/dist/cli/{workflow-DDKVTF36.mjs → workflow-M6LLHQ2I.mjs} +8 -8
  168. package/dist/cli/{workflow-JKKLOMBX.js → workflow-ZPTDFPKW.js} +18 -18
  169. package/dist/{client-DJ3r8VQJ.d.mts → client-BkbDHRIg.d.mts} +1 -1
  170. package/dist/{client-JPSNljtj.d.ts → client-D3hVHXjK.d.ts} +1 -1
  171. package/dist/{client-core-3SJlNsKU.d.mts → client-core-BZoSMKcY.d.mts} +30 -15
  172. package/dist/{client-core-rCoQ5Xz3.d.ts → client-core-DUdVqO_m.d.ts} +30 -15
  173. package/dist/{compiler-manifest-gkO9ZkVg.d.mts → compiler-manifest-BFTwq1HI.d.mts} +1 -1
  174. package/dist/{compiler-manifest-gkO9ZkVg.d.ts → compiler-manifest-BFTwq1HI.d.ts} +1 -1
  175. package/dist/{errors-Cc92LKH-.d.ts → errors-c3pMsylw.d.ts} +1 -1
  176. package/dist/{errors-CeCCOKSA.d.mts → errors-w31ybrQM.d.mts} +1 -1
  177. package/dist/{index-DJQKdV76.d.ts → index-CQ-15-QL.d.ts} +1 -1
  178. package/dist/{index-DsqWJL3Q.d.mts → index-DvNtxucX.d.mts} +1 -1
  179. package/dist/index.d.mts +7 -7
  180. package/dist/index.d.ts +7 -7
  181. package/dist/index.js +10 -10
  182. package/dist/index.mjs +7 -7
  183. package/dist/install-integrity.json +117 -116
  184. package/dist/plays/bundle-play-file.d.mts +3 -3
  185. package/dist/plays/bundle-play-file.d.ts +3 -3
  186. package/dist/plays/bundle-play-file.mjs +2 -2
  187. package/dist/plays/play-description.d.mts +2 -2
  188. package/dist/plays/play-description.d.ts +2 -2
  189. package/dist/plays/run-request.d.mts +2 -2
  190. package/dist/plays/run-request.d.ts +2 -2
  191. package/dist/plays/run-request.js +12 -2
  192. package/dist/plays/run-request.mjs +11 -1
  193. package/dist/release.d.mts +1 -1
  194. package/dist/release.d.ts +1 -1
  195. package/dist/release.js +2 -2
  196. package/dist/release.mjs +1 -1
  197. package/dist/server.d.mts +4 -4
  198. package/dist/server.d.ts +4 -4
  199. package/dist/server.js +6 -6
  200. package/dist/server.mjs +4 -4
  201. package/package.json +1 -1
  202. package/dist/cli/auth-L5CSV3UO.js +0 -43
  203. package/dist/cli/chunk-KA2LNIUP.js +0 -33
  204. package/dist/cli/describe-UIAYCHWW.js +0 -49
  205. package/dist/cli/git-ATMWC27D.js +0 -25
  206. package/dist/cli/search-IGHLRLBD.js +0 -32
  207. package/dist/cli/skills-4U5WC4MJ.js +0 -33
  208. package/dist/cli/tools-PYJTQVVS.js +0 -56
  209. package/dist/cli/update-344OTRFM.js +0 -33
@@ -18,6 +18,7 @@ import { normalizeRunLogIds } from '../run-log-buffer';
18
18
  import { sanitizeLedgerLogLine } from '../ledger-safe-payload';
19
19
  import {
20
20
  retainedPlayPipelineFields,
21
+ encodeRetainedPlayPipelines,
21
22
  hydrateRetainedPlayPipelines,
22
23
  prepareRetainedPlayPipelinesForTransport,
23
24
  } from '../../plays/execution-pipeline';
@@ -166,6 +167,7 @@ import {
166
167
  } from '../log-provenance';
167
168
  import {
168
169
  buildRunLedgerEventsIdempotencyKey,
170
+ RunLedgerProgressAttemptSupersededError,
169
171
  RunLedgerProjectionLeaseLostError,
170
172
  type RunLedgerProjectionChunk,
171
173
  type RunLedgerProjectionLeaseLostReason,
@@ -183,6 +185,7 @@ import {
183
185
  terminalRunResultForLedger,
184
186
  } from '../output-size-limits';
185
187
  import {
188
+ APP_RUNTIME_REQUEST_BODY_MAX_BYTES,
186
189
  AppRuntimeApiResponseError,
187
190
  AppRuntimeApiTransportError,
188
191
  projectRunEventsViaAppRuntime,
@@ -1304,6 +1307,8 @@ export type PostgresSchedulerSchemaShapeRequirements = Readonly<{
1304
1307
  runtimeLogStorage?: boolean;
1305
1308
  /** v64 records whether terminal projection owns array-input retirement. */
1306
1309
  arrayInputIntent?: boolean;
1310
+ /** Sandbox admission routines are installed by additive repair, not table DDL. */
1311
+ sandboxCapacityAdmissionFunctions?: boolean;
1307
1312
  }>;
1308
1313
 
1309
1314
  export async function hasCurrentPostgresSchedulerSchemaShape(
@@ -1954,6 +1959,13 @@ export async function hasCurrentPostgresSchedulerSchemaShape(
1954
1959
  AND column_default IS NOT NULL
1955
1960
  )
1956
1961
  )
1962
+ AND (
1963
+ $41::boolean = false
1964
+ OR (
1965
+ to_regprocedure($42) IS NOT NULL
1966
+ AND to_regprocedure($43) IS NOT NULL
1967
+ )
1968
+ )
1957
1969
  AS ready
1958
1970
  `,
1959
1971
  [
@@ -1997,6 +2009,9 @@ export async function hasCurrentPostgresSchedulerSchemaShape(
1997
2009
  requirements.runtimeLogStorage !== false,
1998
2010
  requirements.gatewayReaderFence !== false,
1999
2011
  requirements.arrayInputIntent !== false,
2012
+ requirements.sandboxCapacityAdmissionFunctions !== false,
2013
+ `${quotedSchema}.runtime_sandbox_capacity_lock(text)`,
2014
+ `${quotedSchema}.runtime_sandbox_capacity_observation(text, integer)`,
2000
2015
  ],
2001
2016
  );
2002
2017
  if (currentShape.rows[0]?.ready !== true) return false;
@@ -2250,6 +2265,76 @@ async function ensurePostgresSchedulerGatewayReaderFenceSchema(
2250
2265
  `);
2251
2266
  }
2252
2267
 
2268
+ /**
2269
+ * Install the runtime sandbox capacity helper functions. Reservation
2270
+ * observations use two transaction-scoped lanes: this keeps the per-org limit
2271
+ * soft while bounding a simultaneous reservation race to one extra lease. The
2272
+ * separate lock serializes limit-cache writes. Existing schemas take additive
2273
+ * fast paths, so repair these independently from the numbered schema bootstrap.
2274
+ */
2275
+ export async function ensurePostgresSchedulerSandboxCapacityAdmissionFunctions(
2276
+ client: PostgresSchedulerQueryClient,
2277
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
2278
+ ): Promise<void> {
2279
+ const quotedSchema = quoteIdent(schemaName(options));
2280
+ await client.query(`
2281
+ CREATE OR REPLACE FUNCTION ${quotedSchema}.runtime_sandbox_capacity_lock(
2282
+ requested_org_id text
2283
+ ) RETURNS void
2284
+ LANGUAGE plpgsql VOLATILE
2285
+ AS $runtime_sandbox_capacity_lock$
2286
+ BEGIN
2287
+ PERFORM pg_advisory_xact_lock(
2288
+ hashtextextended(
2289
+ 'deepline:runtime-sandbox-capacity:' || requested_org_id,
2290
+ 270985
2291
+ )
2292
+ );
2293
+ END;
2294
+ $runtime_sandbox_capacity_lock$
2295
+ `);
2296
+ await client.query(`
2297
+ CREATE OR REPLACE FUNCTION ${quotedSchema}.runtime_sandbox_capacity_observation(
2298
+ requested_org_id text,
2299
+ default_limit integer
2300
+ ) RETURNS TABLE (configured_limit integer, active_leases integer)
2301
+ LANGUAGE plpgsql VOLATILE
2302
+ AS $runtime_sandbox_capacity_observation$
2303
+ BEGIN
2304
+ -- Two lanes allow one racing reservation past the soft limit, while
2305
+ -- preventing an unbounded burst from all observing the same free slot.
2306
+ PERFORM pg_advisory_xact_lock(
2307
+ hashtext(
2308
+ 'deepline:runtime-sandbox-capacity-observation:' || requested_org_id
2309
+ ),
2310
+ mod(txid_current(), 2)::integer
2311
+ );
2312
+ RETURN QUERY
2313
+ SELECT
2314
+ coalesce(
2315
+ (
2316
+ SELECT CASE
2317
+ WHEN expires_at IS NOT NULL AND expires_at <= clock_timestamp()
2318
+ THEN default_limit
2319
+ ELSE "limit"
2320
+ END
2321
+ FROM ${tableName('runtime_org_sandbox_limit_cache', options)}
2322
+ WHERE org_id = requested_org_id
2323
+ ),
2324
+ default_limit
2325
+ ),
2326
+ (
2327
+ SELECT count(*)::integer
2328
+ FROM ${tableName('runtime_sandbox_capacity_leases', options)}
2329
+ WHERE org_id = requested_org_id
2330
+ AND released_at IS NULL
2331
+ AND (sandbox_id IS NOT NULL OR expires_at > clock_timestamp())
2332
+ );
2333
+ END;
2334
+ $runtime_sandbox_capacity_observation$
2335
+ `);
2336
+ }
2337
+
2253
2338
  /**
2254
2339
  * Expand the shared scheduler schema without retaining locks across tables.
2255
2340
  *
@@ -2306,6 +2391,10 @@ export async function ensurePostgresSchedulerOnlineAdditiveExpansion(
2306
2391
  await ensurePostgresSchedulerRunLogStorageExpansion(client, options);
2307
2392
  await ensurePostgresSchedulerArrayInputIntentExpansion(client, options);
2308
2393
  await ensurePostgresSchedulerGatewayReaderFenceSchema(client, options);
2394
+ await ensurePostgresSchedulerSandboxCapacityAdmissionFunctions(
2395
+ client,
2396
+ options,
2397
+ );
2309
2398
  }
2310
2399
 
2311
2400
  /** Deployment-owned v64 expansion; absent values retain legacy behavior. */
@@ -2789,6 +2878,7 @@ export async function ensurePostgresSchedulerSchema(
2789
2878
  outboxWakeTrigger: false,
2790
2879
  cronScheduleSchema: false,
2791
2880
  arrayInputIntent: false,
2881
+ sandboxCapacityAdmissionFunctions: false,
2792
2882
  }));
2793
2883
  const schemaCoreIsCurrent =
2794
2884
  schemaIsCurrent || schemaIsCurrentWithoutAdditiveFastPathObjects;
@@ -2818,6 +2908,10 @@ export async function ensurePostgresSchedulerSchema(
2818
2908
  concurrently: false,
2819
2909
  });
2820
2910
  }
2911
+ await ensurePostgresSchedulerSandboxCapacityAdmissionFunctions(
2912
+ client,
2913
+ options,
2914
+ );
2821
2915
  await ensurePostgresSchedulerLaunchAdmissionFunctions(client, options);
2822
2916
  if (!schemaIsCurrent) {
2823
2917
  await ensurePostgresSchedulerTerminalComputeBillingOutboxTrigger(
@@ -3164,10 +3258,10 @@ export async function ensurePostgresSchedulerSchema(
3164
3258
  event_id
3165
3259
  )
3166
3260
  `);
3167
- // Per-organization sandbox admission is intentionally a lightweight
3168
- // capacity hint, not a strict distributed lock. Convex owns desired
3169
- // limits; the runtime consumes only this local mirror so worker launches
3170
- // stay independent of the control plane during an incident.
3261
+ // Convex owns desired limits; the runtime consumes this local mirror so
3262
+ // worker launches stay independent of the control plane during an
3263
+ // incident. Admission serializes only its short DB observation/write
3264
+ // statement, never the external provider create.
3171
3265
  await client.query(`
3172
3266
  CREATE TABLE IF NOT EXISTS ${tableName('runtime_org_sandbox_limit_cache', options)} (
3173
3267
  org_id text PRIMARY KEY,
@@ -3196,6 +3290,10 @@ export async function ensurePostgresSchedulerSchema(
3196
3290
  ALTER TABLE ${tableName('runtime_sandbox_capacity_leases', options)}
3197
3291
  ADD COLUMN IF NOT EXISTS routing_domain text
3198
3292
  `);
3293
+ await ensurePostgresSchedulerSandboxCapacityAdmissionFunctions(
3294
+ client,
3295
+ options,
3296
+ );
3199
3297
  // The operation ledger is authoritative for a physical sandbox lifecycle.
3200
3298
  // `resource_json` stays a compatibility/audit projection, never a source
3201
3299
  // for capacity admission or reconciliation.
@@ -9179,9 +9277,34 @@ export async function deferPostgresSchedulerAttemptForRecovery(
9179
9277
  options?: Pick<PostgresSchedulerOptions, 'schema'>,
9180
9278
  ): Promise<PostgresSchedulerRecoveryDeferral> {
9181
9279
  const initialDeadlineAtMs = input.nowMs + input.horizonMs;
9280
+ const noCodeWorkCounterDigest = createHash('sha256')
9281
+ .update(`${input.runId}\u0000${input.attempt}\u0000pre-code`)
9282
+ .digest('hex');
9283
+ const noCodeWorkCounterSegmentId = [
9284
+ noCodeWorkCounterDigest.slice(0, 8),
9285
+ noCodeWorkCounterDigest.slice(8, 12),
9286
+ noCodeWorkCounterDigest.slice(12, 16),
9287
+ noCodeWorkCounterDigest.slice(16, 20),
9288
+ noCodeWorkCounterDigest.slice(20, 32),
9289
+ ].join('-');
9290
+ const noCodeWorkCounterEvent = {
9291
+ type: RUN_EVENT_KIND.workCounters,
9292
+ runId: input.runId,
9293
+ source: 'worker',
9294
+ occurredAt: input.nowMs,
9295
+ attempt: input.attempt,
9296
+ invocationSeq: 1,
9297
+ segmentId: noCodeWorkCounterSegmentId,
9298
+ logicalCalls: 0,
9299
+ providerRequests: 0,
9300
+ provider429s: 0,
9301
+ final: true,
9302
+ };
9303
+ const noCodeWorkCounterEventId = `run-pre-code-work-counters:${input.runId}:${input.attempt}`;
9182
9304
  const result = await client.query<{
9183
9305
  candidate: boolean;
9184
9306
  deferred: boolean;
9307
+ work_counters_recorded: boolean;
9185
9308
  defer_count: string | null;
9186
9309
  deadline_at_ms: string | null;
9187
9310
  }>(
@@ -9261,6 +9384,19 @@ export async function deferPostgresSchedulerAttemptForRecovery(
9261
9384
  JOIN deferred_attempt ON deferred_attempt.run_id = computed.run_id
9262
9385
  WHERE runs.run_id = computed.run_id
9263
9386
  RETURNING runs.run_id
9387
+ ), no_code_work_counters AS (
9388
+ INSERT INTO ${tableName('outbox', options)} (
9389
+ event_id, run_id, event_type, payload_json, created_at
9390
+ )
9391
+ SELECT
9392
+ $14::text,
9393
+ requeued_run.run_id,
9394
+ ${RUN_SCHEDULER_OUTBOX_EVENT_TYPE_SQL_LITERAL.runEvents},
9395
+ $15::jsonb,
9396
+ ${causalOutboxCreatedAt('requeued_run.run_id', options)}
9397
+ FROM requeued_run
9398
+ ON CONFLICT (event_id) DO NOTHING
9399
+ RETURNING event_id
9264
9400
  ), exhausted_run AS (
9265
9401
  UPDATE ${tableName('runs', options)} AS runs
9266
9402
  SET recovery_json = jsonb_build_object(
@@ -9282,6 +9418,15 @@ export async function deferPostgresSchedulerAttemptForRecovery(
9282
9418
  )
9283
9419
  SELECT EXISTS (SELECT 1 FROM candidate) AS candidate,
9284
9420
  EXISTS (SELECT 1 FROM requeued_run) AS deferred,
9421
+ (
9422
+ EXISTS (SELECT 1 FROM no_code_work_counters)
9423
+ OR EXISTS (
9424
+ SELECT 1 FROM ${tableName('outbox', options)}
9425
+ WHERE event_id = $14::text
9426
+ AND run_id = $1::text
9427
+ AND event_type = ${RUN_SCHEDULER_OUTBOX_EVENT_TYPE_SQL_LITERAL.runEvents}
9428
+ )
9429
+ ) AS work_counters_recorded,
9285
9430
  EXISTS (SELECT 1 FROM open_circuit) AS circuit_opened,
9286
9431
  (SELECT defer_count::text FROM computed LIMIT 1) AS defer_count,
9287
9432
  (SELECT deadline_at_ms::text FROM computed LIMIT 1) AS deadline_at_ms
@@ -9304,6 +9449,8 @@ export async function deferPostgresSchedulerAttemptForRecovery(
9304
9449
  input.openCircuit ?? true,
9305
9450
  input.deferBaseMs ?? 15_000,
9306
9451
  input.deferMaxMs ?? 300_000,
9452
+ noCodeWorkCounterEventId,
9453
+ stableStringify({ events: [noCodeWorkCounterEvent] }),
9307
9454
  ],
9308
9455
  );
9309
9456
  const row = result.rows[0];
@@ -9315,6 +9462,11 @@ export async function deferPostgresSchedulerAttemptForRecovery(
9315
9462
  deadlineAtMs: null,
9316
9463
  };
9317
9464
  }
9465
+ if (row.deferred && !row.work_counters_recorded) {
9466
+ throw new Error(
9467
+ `Pre-code recovery for ${input.runId}/${input.attempt} was deferred without its final zero-work ledger fact.`,
9468
+ );
9469
+ }
9318
9470
  const deferCount = row.defer_count ? Number(row.defer_count) : null;
9319
9471
  const deadlineAtMs = row.deadline_at_ms ? Number(row.deadline_at_ms) : null;
9320
9472
  return {
@@ -10117,6 +10269,8 @@ export async function recordPostgresSchedulerManagedSandboxOperationLive(
10117
10269
  JOIN custody_leases AS lease ON lease.lease_id = operation.operation_key
10118
10270
  WHERE attempt.run_id = $1 AND attempt.attempt = $2 AND attempt.lease_token = $3
10119
10271
  AND attempt.status IN ('claimed', 'running', 'waiting')
10272
+ AND (attempt.lease_expires_at IS NULL OR attempt.lease_expires_at > clock_timestamp())
10273
+ AND NOT EXISTS (SELECT 1 FROM ${tableName('control', options)} AS cancel WHERE cancel.key = 'runtime_cancel:' || $1)
10120
10274
  AND NOT EXISTS (SELECT 1 FROM custody_attempts AS newer WHERE newer.attempt > $2)
10121
10275
  AND EXISTS (SELECT 1 FROM custody_runs WHERE status IN ('queued', 'running', 'waiting'))
10122
10276
  AND operation.operation_key = $5 AND operation.sandbox_id = $6
@@ -10298,7 +10452,9 @@ export async function recordPostgresSchedulerAmbiguousModalCreateIntent(
10298
10452
  readAmbiguousModalCreateStatus(row.status) !==
10299
10453
  AmbiguousModalCreateStatus.Pending
10300
10454
  ) {
10301
- throw new Error('Recorded ambiguous Modal create intent was not pending.');
10455
+ throw new Error(
10456
+ 'Recorded ambiguous Modal create intent was not pending.',
10457
+ );
10302
10458
  }
10303
10459
  }
10304
10460
  return recorded.rows.length > 0;
@@ -12734,10 +12890,125 @@ export async function hasPendingPostgresSchedulerSandboxCleanupForRun(
12734
12890
  return pending.rows[0]?.pending ?? true;
12735
12891
  }
12736
12892
 
12893
+ /** Exact-resource join; completion never substitutes for the initiating attempt fence. */
12894
+ export async function readPostgresSchedulerSandboxRetirement(
12895
+ client: PostgresSchedulerQueryClient,
12896
+ input: {
12897
+ runId: string;
12898
+ attempt: number;
12899
+ leaseToken: string;
12900
+ provider: 'daytona' | 'modal';
12901
+ sandboxId: string;
12902
+ routingDomain: string | null;
12903
+ },
12904
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
12905
+ ): Promise<{
12906
+ fenced: boolean;
12907
+ status: string | null;
12908
+ blocked: boolean;
12909
+ error: string | null;
12910
+ }> {
12911
+ const result = await client.query<{
12912
+ fenced: boolean;
12913
+ status: string | null;
12914
+ blocked: boolean;
12915
+ error: string | null;
12916
+ }>(
12917
+ `
12918
+ SELECT EXISTS (
12919
+ SELECT 1 FROM ${tableName('attempts', options)} AS attempt
12920
+ JOIN ${tableName('runs', options)} AS run ON run.run_id = attempt.run_id
12921
+ WHERE attempt.run_id = $1 AND attempt.attempt = $2 AND attempt.lease_token = $3
12922
+ AND attempt.status IN ('claimed', 'running', 'waiting')
12923
+ AND run.status IN ('queued', 'running', 'waiting')
12924
+ AND (attempt.lease_expires_at IS NULL OR attempt.lease_expires_at > clock_timestamp())
12925
+ AND NOT EXISTS (SELECT 1 FROM ${tableName('attempts', options)} AS newer WHERE newer.run_id = $1 AND newer.attempt > $2)
12926
+ AND NOT EXISTS (SELECT 1 FROM ${tableName('control', options)} AS cancel WHERE cancel.key = 'runtime_cancel:' || $1)
12927
+ ) AS fenced,
12928
+ cleanup.status, COALESCE(cleanup.blocked_at IS NOT NULL, false) AS blocked, cleanup.last_error AS error
12929
+ FROM (SELECT 1) AS requested
12930
+ LEFT JOIN ${tableName('sandbox_cleanup_jobs_v2', options)} AS cleanup
12931
+ ON cleanup.run_id = $1 AND cleanup.attempt = $2
12932
+ AND cleanup.provider = $4 AND cleanup.sandbox_id = $5
12933
+ AND cleanup.routing_domain IS NOT DISTINCT FROM $6::text
12934
+ `,
12935
+ [
12936
+ input.runId,
12937
+ input.attempt,
12938
+ input.leaseToken,
12939
+ input.provider,
12940
+ input.sandboxId,
12941
+ input.routingDomain,
12942
+ ],
12943
+ );
12944
+ return (
12945
+ result.rows[0] ?? {
12946
+ fenced: false,
12947
+ status: null,
12948
+ blocked: false,
12949
+ error: null,
12950
+ }
12951
+ );
12952
+ }
12953
+
12954
+ /** Read-only authorization for another DELETE by the same live cleanup claim. */
12955
+ export async function readPostgresSchedulerSandboxCleanupClaim(
12956
+ client: PostgresSchedulerQueryClient,
12957
+ input: {
12958
+ provider: 'daytona' | 'modal';
12959
+ sandboxId: string;
12960
+ routingDomain: string | null;
12961
+ runId: string;
12962
+ attempt: number;
12963
+ cleanupAttempt: number;
12964
+ leaseOwner: string;
12965
+ leaseToken: string;
12966
+ },
12967
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
12968
+ ): Promise<boolean> {
12969
+ const result = await client.query<{ authorized: boolean }>(
12970
+ `SELECT EXISTS (
12971
+ SELECT 1 FROM ${tableName('sandbox_cleanup_jobs_v2', options)}
12972
+ WHERE provider = $1 AND sandbox_id = $2
12973
+ AND routing_domain IS NOT DISTINCT FROM $3::text
12974
+ AND run_id = $4 AND attempt = $5 AND attempt_count = $6
12975
+ AND lease_owner = $7 AND status = 'deleting'
12976
+ AND blocked_at IS NULL AND lease_expires_at > clock_timestamp()
12977
+ AND EXISTS (
12978
+ SELECT 1 FROM ${tableName('attempts', options)} AS initiating
12979
+ JOIN ${tableName('runs', options)} AS run ON run.run_id = initiating.run_id
12980
+ WHERE initiating.run_id = $4 AND initiating.attempt = $5 AND initiating.lease_token = $8
12981
+ AND initiating.status IN ('claimed', 'running', 'waiting')
12982
+ AND run.status IN ('queued', 'running', 'waiting')
12983
+ AND (initiating.lease_expires_at IS NULL OR initiating.lease_expires_at > clock_timestamp())
12984
+ AND NOT EXISTS (SELECT 1 FROM ${tableName('attempts', options)} AS newer WHERE newer.run_id = $4 AND newer.attempt > $5)
12985
+ AND NOT EXISTS (SELECT 1 FROM ${tableName('control', options)} AS cancel WHERE cancel.key = 'runtime_cancel:' || $4)
12986
+ )
12987
+ ) AS authorized`,
12988
+ [
12989
+ input.provider,
12990
+ input.sandboxId,
12991
+ input.routingDomain,
12992
+ input.runId,
12993
+ input.attempt,
12994
+ input.cleanupAttempt,
12995
+ input.leaseOwner,
12996
+ input.leaseToken,
12997
+ ],
12998
+ );
12999
+ return result.rows[0]?.authorized === true;
13000
+ }
13001
+
12737
13002
  export async function claimPostgresSchedulerSandboxCleanupJobs(
12738
13003
  client: PostgresSchedulerQueryClient,
12739
13004
  input: {
12740
13005
  leaseOwner: string;
13006
+ exactResource?: {
13007
+ provider: 'daytona' | 'modal';
13008
+ sandboxId: string;
13009
+ routingDomain: string | null;
13010
+ attempt: number;
13011
+ };
12741
13012
  runId?: string;
12742
13013
  throughAttempt?: number;
12743
13014
  limit?: number;
@@ -12747,6 +13018,8 @@ export async function claimPostgresSchedulerSandboxCleanupJobs(
12747
13018
  },
12748
13019
  options?: Pick<PostgresSchedulerOptions, 'schema'>,
12749
13020
  ): Promise<PostgresSchedulerSandboxCleanupJob[]> {
13021
+ if (input.exactResource && !input.runId)
13022
+ throw new Error('Exact sandbox cleanup requires its run identity.');
12750
13023
  const limit = Math.min(100, Math.max(1, Math.floor(input.limit ?? 20)));
12751
13024
  const leaseSeconds = Math.min(
12752
13025
  300,
@@ -12759,6 +13032,22 @@ export async function claimPostgresSchedulerSandboxCleanupJobs(
12759
13032
  (provider) => provider === 'daytona' || provider === 'modal',
12760
13033
  );
12761
13034
  if (providers?.length === 0) return [];
13035
+ const claimablePredicate = `EXISTS (
13036
+ SELECT 1 FROM ${tableName('sandbox_cleanup_jobs_v2', options)} AS cleanup
13037
+ WHERE cleanup.status <> 'deleted' AND cleanup.blocked_at IS NULL
13038
+ AND (cleanup.available_at <= now() OR cleanup.diagnostic_json IS NOT NULL)
13039
+ AND (cleanup.lease_expires_at IS NULL OR cleanup.lease_expires_at <= now())
13040
+ AND ($1::text IS NULL OR cleanup.environment = $1)
13041
+ AND ($2::text[] IS NULL OR cleanup.provider = ANY($2::text[]))
13042
+ AND ($3::text IS NULL OR cleanup.run_id = $3)
13043
+ AND ($4::integer IS NULL OR cleanup.attempt <= $4)
13044
+ )`;
13045
+ const claimableParams = [
13046
+ input.environment?.trim() || null,
13047
+ providers,
13048
+ input.runId ?? null,
13049
+ input.throughAttempt ?? null,
13050
+ ];
12762
13051
  // The v12 table retains deleted history. Avoid planning the lineage repair
12763
13052
  // when neither a legacy row nor a v2 NULL-domain duplicate needs adoption.
12764
13053
  // The same read proves whether any v2 row could be claimed: the claim below
@@ -12780,23 +13069,9 @@ export async function claimPostgresSchedulerSandboxCleanupJobs(
12780
13069
  SELECT 1 FROM ${tableName('sandbox_cleanup_jobs', options)}
12781
13070
  WHERE status <> 'deleted'
12782
13071
  ) AS pending,
12783
- EXISTS (
12784
- SELECT 1 FROM ${tableName('sandbox_cleanup_jobs_v2', options)} AS cleanup
12785
- WHERE cleanup.status <> 'deleted' AND cleanup.blocked_at IS NULL
12786
- AND (cleanup.available_at <= now() OR cleanup.diagnostic_json IS NOT NULL)
12787
- AND (cleanup.lease_expires_at IS NULL OR cleanup.lease_expires_at <= now())
12788
- AND ($1::text IS NULL OR cleanup.environment = $1)
12789
- AND ($2::text[] IS NULL OR cleanup.provider = ANY($2::text[]))
12790
- AND ($3::text IS NULL OR cleanup.run_id = $3)
12791
- AND ($4::integer IS NULL OR cleanup.attempt <= $4)
12792
- ) AS claimable
13072
+ ${claimablePredicate} AS claimable
12793
13073
  `,
12794
- [
12795
- input.environment?.trim() || null,
12796
- providers,
12797
- input.runId ?? null,
12798
- input.throughAttempt ?? null,
12799
- ],
13074
+ claimableParams,
12800
13075
  );
12801
13076
  if (
12802
13077
  typeof adoptionWork.rows[0]?.pending !== 'boolean' ||
@@ -12811,7 +13086,8 @@ export async function claimPostgresSchedulerSandboxCleanupJobs(
12811
13086
  // otherwise make every later adoption recreate a pending NULL-domain row.
12812
13087
  // Reconcile only the exact original identity proved by the immutable
12813
13088
  // provider confirmation and the matching deleted v2 tombstone.
12814
- if (adoptionWork.rows[0].pending)
13089
+ let claimable = adoptionWork.rows[0].claimable;
13090
+ if (adoptionWork.rows[0].pending) {
12815
13091
  await client.query(
12816
13092
  `
12817
13093
  WITH pending_legacy AS MATERIALIZED (
@@ -12997,10 +13273,25 @@ export async function claimPostgresSchedulerSandboxCleanupJobs(
12997
13273
  ON CONFLICT (provider, sandbox_id, routing_domain_key) DO NOTHING
12998
13274
  `,
12999
13275
  );
13000
- // Adoption may have just created claimable v2 rows, so only an idle read
13001
- // that proved neither kind of work skips the claim.
13002
- if (!adoptionWork.rows[0].pending && !adoptionWork.rows[0].claimable)
13003
- return [];
13276
+ // Legacy rows retain their old state during adoption. Recheck the exact
13277
+ // claim predicate after copying them so blocked, leased, and future work
13278
+ // does not force planning the large claim on every poll.
13279
+ if (!claimable) {
13280
+ const adoptedWork = await client.query<{ claimable: boolean }>(
13281
+ `SELECT ${claimablePredicate} AS claimable`,
13282
+ claimableParams,
13283
+ );
13284
+ if (typeof adoptedWork.rows[0]?.claimable !== 'boolean') {
13285
+ throw new Error(
13286
+ 'Sandbox cleanup adoption claimability check returned no proof.',
13287
+ );
13288
+ }
13289
+ claimable = adoptedWork.rows[0].claimable;
13290
+ }
13291
+ }
13292
+ // A claimable row can arrive after the proof; it is picked up by the next
13293
+ // poll. Never plan the large claim when this snapshot is empty.
13294
+ if (!claimable) return [];
13004
13295
  const claimed = await client.query<{
13005
13296
  status: unknown;
13006
13297
  provider: 'daytona' | 'modal';
@@ -13025,6 +13316,11 @@ export async function claimPostgresSchedulerSandboxCleanupJobs(
13025
13316
  AND ($5::text[] IS NULL OR cleanup.provider = ANY($5::text[]))
13026
13317
  AND ($8::text IS NULL OR cleanup.run_id = $8)
13027
13318
  AND ($9::integer IS NULL OR cleanup.attempt <= $9)
13319
+ AND ($10::text IS NULL OR (
13320
+ cleanup.provider = $10 AND cleanup.sandbox_id = $11
13321
+ AND cleanup.routing_domain IS NOT DISTINCT FROM $12::text
13322
+ AND cleanup.attempt = $13::integer
13323
+ ))
13028
13324
  AND NOT ${protectedDetachedSandboxSql({ runId: 'cleanup.run_id', provider: 'cleanup.provider', sandboxId: 'cleanup.sandbox_id', routingDomain: 'cleanup.routing_domain' }, options)}
13029
13325
  ORDER BY CASE WHEN cleanup.diagnostic_json IS NOT NULL THEN 0 ELSE 1 END,
13030
13326
  cleanup.available_at, cleanup.created_at, cleanup.provider, cleanup.sandbox_id, cleanup.routing_domain_key
@@ -13055,6 +13351,11 @@ export async function claimPostgresSchedulerSandboxCleanupJobs(
13055
13351
  AND ($5::text[] IS NULL OR cleanup.provider = ANY($5::text[]))
13056
13352
  AND ($8::text IS NULL OR cleanup.run_id = $8)
13057
13353
  AND ($9::integer IS NULL OR cleanup.attempt <= $9)
13354
+ AND ($10::text IS NULL OR (
13355
+ cleanup.provider = $10 AND cleanup.sandbox_id = $11
13356
+ AND cleanup.routing_domain IS NOT DISTINCT FROM $12::text
13357
+ AND cleanup.attempt = $13::integer
13358
+ ))
13058
13359
  AND NOT ${protectedDetachedSandboxSql({ runId: 'cleanup.run_id', provider: 'cleanup.provider', sandboxId: 'cleanup.sandbox_id', routingDomain: 'cleanup.routing_domain' }, options, true)}
13059
13360
  ORDER BY
13060
13361
  CASE WHEN cleanup.diagnostic_json IS NOT NULL THEN 0 ELSE 1 END ASC,
@@ -13159,6 +13460,10 @@ export async function claimPostgresSchedulerSandboxCleanupJobs(
13159
13460
  RuntimeSandboxOperationState.Live,
13160
13461
  input.runId ?? null,
13161
13462
  input.throughAttempt ?? null,
13463
+ input.exactResource?.provider ?? null,
13464
+ input.exactResource?.sandboxId ?? null,
13465
+ input.exactResource?.routingDomain ?? null,
13466
+ input.exactResource?.attempt ?? null,
13162
13467
  ],
13163
13468
  );
13164
13469
  return claimed.rows.map((row) => {
@@ -13724,6 +14029,7 @@ export async function retryPostgresSchedulerSandboxCleanupJob(
13724
14029
  claimGeneration: number;
13725
14030
  error: string;
13726
14031
  retryAfterMs: number;
14032
+ confirmationPending?: { code: string };
13727
14033
  },
13728
14034
  options?: Pick<PostgresSchedulerOptions, 'schema'>,
13729
14035
  ): Promise<
@@ -13748,7 +14054,7 @@ export async function retryPostgresSchedulerSandboxCleanupJob(
13748
14054
  available_at = now() + ($4::double precision * interval '1 millisecond'),
13749
14055
  lease_owner = NULL,
13750
14056
  lease_expires_at = NULL,
13751
- last_error = left($5, 2000),
14057
+ last_error = CASE WHEN $8::text IS NULL THEN left($5, 2000) ELSE NULL END,
13752
14058
  updated_at = now()
13753
14059
  WHERE provider = $6
13754
14060
  AND sandbox_id = $1
@@ -13756,7 +14062,23 @@ export async function retryPostgresSchedulerSandboxCleanupJob(
13756
14062
  AND status = 'deleting'
13757
14063
  AND lease_owner = $2
13758
14064
  AND attempt_count = $3
13759
- RETURNING sandbox_id
14065
+ RETURNING provider, sandbox_id, routing_domain, run_id, attempt, attempt_count
14066
+ ),
14067
+ pending_confirmation AS (
14068
+ INSERT INTO ${tableName('sandbox_cleanup_events_v2', options)} (
14069
+ provider, sandbox_id, routing_domain, run_id, attempt,
14070
+ cleanup_attempt, lease_owner, event_type, details_json
14071
+ )
14072
+ SELECT provider, sandbox_id, routing_domain, run_id, attempt,
14073
+ attempt_count, $2, 'provider_delete_pending',
14074
+ jsonb_build_object(
14075
+ 'code', $8::text,
14076
+ 'detail', left($5::text, 2000),
14077
+ 'retryAfterMs', $4::double precision
14078
+ )
14079
+ FROM retried
14080
+ WHERE $8::text IS NOT NULL
14081
+ RETURNING event_id
13760
14082
  )
13761
14083
  SELECT CASE
13762
14084
  WHEN EXISTS (SELECT 1 FROM retried) THEN 'retry_scheduled'
@@ -13773,6 +14095,7 @@ export async function retryPostgresSchedulerSandboxCleanupJob(
13773
14095
  input.error,
13774
14096
  input.provider ?? 'daytona',
13775
14097
  input.routingDomain?.trim() || null,
14098
+ input.confirmationPending?.code ?? null,
13776
14099
  ],
13777
14100
  );
13778
14101
  const outcome = retried.rows[0]?.outcome;
@@ -15416,6 +15739,12 @@ export async function cancelPostgresSchedulerRun(
15416
15739
  absurdTaskId: string;
15417
15740
  engineTaskTable: string | null;
15418
15741
  };
15742
+ /**
15743
+ * Narrow operator-only fence for a queued run that never reached Convex:
15744
+ * its run.created projection failed permanently, so no control-plane row
15745
+ * exists to cancel through. Zero attempts proves execution never began.
15746
+ */
15747
+ onlyIfCreatedProjectionFailed?: { absurdTaskId: string };
15419
15748
  /**
15420
15749
  * Optional control-plane ownership for the oldest pending causal fact.
15421
15750
  * Cancellation makes the remaining prefix due without sharing this lease
@@ -15432,6 +15761,24 @@ export async function cancelPostgresSchedulerRun(
15432
15761
  Math.min(300, Math.floor(input.outboxLease?.leaseSeconds ?? 15)),
15433
15762
  );
15434
15763
  const strandedFence = input.onlyIfStrandedPreExecution;
15764
+ const createdFence = input.onlyIfCreatedProjectionFailed;
15765
+ if (strandedFence && createdFence) {
15766
+ throw new Error('A scheduler cancellation accepts one operator fence.');
15767
+ }
15768
+ const createdEligibility = createdFence
15769
+ ? `AND target.status = 'queued'
15770
+ AND target.absurd_task_id = $8
15771
+ AND NOT EXISTS (
15772
+ SELECT 1 FROM ${tableName('attempts', options)} AS attempt
15773
+ WHERE attempt.run_id = target.run_id
15774
+ )
15775
+ AND EXISTS (
15776
+ SELECT 1 FROM ${tableName('outbox', options)} AS created
15777
+ WHERE created.event_id = 'run-created:' || target.run_id
15778
+ AND created.delivered_at IS NULL
15779
+ AND created.failed_at IS NOT NULL
15780
+ )`
15781
+ : '';
15435
15782
  const strandedEligibility = strandedFence
15436
15783
  ? `AND target.status = 'queued'
15437
15784
  AND target.launch_json->>'absurdReleaseId' = $8
@@ -15467,6 +15814,7 @@ export async function cancelPostgresSchedulerRun(
15467
15814
  WHERE target.run_id = $1
15468
15815
  AND target.status IN ('queued', 'running', 'waiting')
15469
15816
  ${strandedEligibility}
15817
+ ${createdEligibility}
15470
15818
  RETURNING target.run_id, target.launch_json
15471
15819
  ),
15472
15820
  cancelled_attempts AS (
@@ -15642,6 +15990,7 @@ export async function cancelPostgresSchedulerRun(
15642
15990
  ...(strandedFence
15643
15991
  ? [strandedFence.releaseId, strandedFence.absurdTaskId]
15644
15992
  : []),
15993
+ ...(createdFence ? [createdFence.absurdTaskId] : []),
15645
15994
  ],
15646
15995
  );
15647
15996
  if (cancelled.rows.length === 0 && outboxLeaseOwner) {
@@ -19313,6 +19662,13 @@ export async function appendPostgresRunLedgerEvents(
19313
19662
  orgId: string;
19314
19663
  runId: string;
19315
19664
  events: readonly AcceptedPlayRunLedgerEvent[];
19665
+ /**
19666
+ * The attempt whose live progress this batch is. When set, the insert
19667
+ * commits only while that attempt is current and the run is not terminal,
19668
+ * and otherwise throws RunLedgerProgressAttemptSupersededError. Terminal
19669
+ * finalizes and replays omit it: they are designed to land after the end.
19670
+ */
19671
+ progressAttempt?: number;
19316
19672
  },
19317
19673
  options?: Pick<PostgresSchedulerOptions, 'schema'>,
19318
19674
  ): Promise<PostgresSchedulerLifecycleOutboxEvent> {
@@ -19331,10 +19687,24 @@ export async function appendPostgresRunLedgerEvents(
19331
19687
  // Stable across a lost response. The complete event identity (including log
19332
19688
  // channel offsets and original timestamps) participates in the digest.
19333
19689
  const eventId = `run-events:${input.runId}:${createHash('sha256').update(payload).digest('hex')}`;
19690
+ if (input.progressAttempt !== undefined) {
19691
+ return appendRunLedgerLiveProgressFact(
19692
+ client,
19693
+ {
19694
+ orgId: input.orgId,
19695
+ runId: input.runId,
19696
+ attempt: input.progressAttempt,
19697
+ eventId,
19698
+ payload,
19699
+ },
19700
+ options,
19701
+ );
19702
+ }
19334
19703
  return appendRunLedgerOutboxFact(
19335
19704
  client,
19336
19705
  {
19337
- ...input,
19706
+ orgId: input.orgId,
19707
+ runId: input.runId,
19338
19708
  eventId,
19339
19709
  eventType: RUN_SCHEDULER_OUTBOX_EVENT_TYPE.runEvents,
19340
19710
  payload,
@@ -19416,7 +19786,117 @@ async function appendRunLedgerOutboxFact(
19416
19786
  return { runId: input.runId, eventId: input.eventId };
19417
19787
  }
19418
19788
 
19419
- export { RunLedgerProjectionLeaseLostError } from '../run-ledger-projection-contract';
19789
+ /**
19790
+ * Live progress intake, fenced at commit time.
19791
+ *
19792
+ * The gateway checks the attempt before publishing, but the publish crosses a
19793
+ * network hop and the terminal path deliberately does not wait for it. A batch
19794
+ * built before a cancel, or delayed past the terminal, used to be stored after
19795
+ * the run closed, where the event-search projection quarantined its lane
19796
+ * (KAR-160 group B). This mirrors acceptRunnerTerminal's commit-time fence.
19797
+ *
19798
+ * The first statement takes the run row lock that attempt assignment,
19799
+ * cancellation and terminal settlement all take before changing the run or
19800
+ * its attempts. The second statement starts after that lock, so its snapshot
19801
+ * sees everything they committed while it waited, and decides:
19802
+ *
19803
+ * - the run is not terminal;
19804
+ * - the attempt is active, no newer attempt exists, and it has not recorded
19805
+ * its runner result (its sealed tail carries any in-flight batch).
19806
+ *
19807
+ * The runner-result writer locks only the attempt row. A result committing
19808
+ * after the decision is concurrent with this insert; the run cannot close
19809
+ * until this transaction releases the run lock, so nothing lands after it.
19810
+ * A retried batch whose first insert already committed is still accepted.
19811
+ */
19812
+ async function appendRunLedgerLiveProgressFact(
19813
+ client: PostgresSchedulerQueryClient,
19814
+ input: {
19815
+ orgId: string;
19816
+ runId: string;
19817
+ attempt: number;
19818
+ eventId: string;
19819
+ payload: string;
19820
+ },
19821
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
19822
+ ): Promise<PostgresSchedulerLifecycleOutboxEvent> {
19823
+ if (!Number.isSafeInteger(input.attempt) || input.attempt < 0) {
19824
+ throw new Error(
19825
+ 'Run Ledger progress attempt must be a nonnegative integer.',
19826
+ );
19827
+ }
19828
+ await client.query('BEGIN');
19829
+ let accepted: boolean;
19830
+ try {
19831
+ const run = await client.query<{ run_id: string }>(
19832
+ `
19833
+ SELECT run_id FROM ${tableName('runs', options)}
19834
+ WHERE run_id = $1 AND org_id = $2
19835
+ FOR NO KEY UPDATE
19836
+ `,
19837
+ [input.runId, input.orgId],
19838
+ );
19839
+ if (run.rows.length !== 1) {
19840
+ throw new Error(
19841
+ 'Run Ledger ingress run is missing or outside the organization scope.',
19842
+ );
19843
+ }
19844
+ const result = await client.query<{ accepted: boolean }>(
19845
+ `
19846
+ WITH fenced AS MATERIALIZED (
19847
+ SELECT run.run_id FROM ${tableName('runs', options)} AS run
19848
+ WHERE run.run_id = $1
19849
+ AND run.status IN ('queued', 'running', 'waiting')
19850
+ AND EXISTS (
19851
+ SELECT 1 FROM ${tableName('attempts', options)} AS current_attempt
19852
+ WHERE current_attempt.run_id = $1
19853
+ AND current_attempt.attempt = $5
19854
+ AND current_attempt.status IN ('claimed', 'running', 'waiting')
19855
+ AND (
19856
+ current_attempt.runner_result_json IS NULL
19857
+ OR current_attempt.runner_result_json = 'null'::jsonb
19858
+ )
19859
+ )
19860
+ AND NOT EXISTS (
19861
+ SELECT 1 FROM ${tableName('attempts', options)} AS newer_attempt
19862
+ WHERE newer_attempt.run_id = $1 AND newer_attempt.attempt > $5
19863
+ )
19864
+ ), recorded AS (
19865
+ INSERT INTO ${tableName('outbox', options)}
19866
+ (event_id, run_id, event_type, payload_json, created_at)
19867
+ SELECT $2, run_id, $4, $3::jsonb,
19868
+ ${causalOutboxCreatedAt('fenced.run_id', options)}
19869
+ FROM fenced
19870
+ ON CONFLICT (event_id) DO NOTHING
19871
+ )
19872
+ SELECT EXISTS (SELECT 1 FROM fenced)
19873
+ OR EXISTS (
19874
+ SELECT 1 FROM ${tableName('outbox', options)}
19875
+ WHERE event_id = $2
19876
+ ) AS accepted
19877
+ `,
19878
+ [
19879
+ input.runId,
19880
+ input.eventId,
19881
+ input.payload,
19882
+ RUN_SCHEDULER_OUTBOX_EVENT_TYPE.runEvents,
19883
+ input.attempt,
19884
+ ],
19885
+ );
19886
+ accepted = result.rows[0]?.accepted === true;
19887
+ await client.query('COMMIT');
19888
+ } catch (error) {
19889
+ await client.query('ROLLBACK');
19890
+ throw error;
19891
+ }
19892
+ if (!accepted) throw new RunLedgerProgressAttemptSupersededError();
19893
+ return { runId: input.runId, eventId: input.eventId };
19894
+ }
19895
+
19896
+ export {
19897
+ RunLedgerProgressAttemptSupersededError,
19898
+ RunLedgerProjectionLeaseLostError,
19899
+ } from '../run-ledger-projection-contract';
19420
19900
 
19421
19901
  /** Extend only our still-live lease before another bounded transport piece. */
19422
19902
  export async function renewPostgresRunLedgerDelivery(
@@ -22465,6 +22945,8 @@ export function postgresSchedulerInlineCreatedProjectionLease(runId: string): {
22465
22945
  export type RunLedgerOutboxDispatchInput = {
22466
22946
  /** App-owned transport; launch authority and routing still come from the lease. */
22467
22947
  appRuntimeFetch?: typeof fetch;
22948
+ /** The receiver origin `appRuntimeFetch` serves in-process, without ingress. */
22949
+ appRuntimeInProcessOrigin?: string | null;
22468
22950
  /** Dedicated bounded checkout for indexing; claims/ACKs use withClient. */
22469
22951
  withObservabilityClient?: RunLedgerOutboxWithClient;
22470
22952
 
@@ -22647,6 +23129,7 @@ type RunLedgerOutboxAuthorityScope = {
22647
23129
  runtimeApi: WorkerRuntimeApiContext & {
22648
23130
  refreshExecutorToken?: () => Promise<string>;
22649
23131
  invalidateExecutorToken?: () => void;
23132
+ resolveRetainedPipelineGraphs?: () => Promise<true | undefined>;
22650
23133
  };
22651
23134
  expiresAtMs: number | null;
22652
23135
  } | null;
@@ -23805,7 +24288,14 @@ async function dispatchRunLedgerOutboxBatchWithScope(
23805
24288
  runtimeApi = {
23806
24289
  ...resolvedRuntimeApi,
23807
24290
  ...(tokenAuthority === 'local_mint' && input.appRuntimeFetch
23808
- ? { fetch: input.appRuntimeFetch }
24291
+ ? {
24292
+ fetch: input.appRuntimeFetch,
24293
+ ...(input.appRuntimeInProcessOrigin &&
24294
+ resolvedRuntimeApi.baseUrl.replace(/\/$/, '') ===
24295
+ input.appRuntimeInProcessOrigin
24296
+ ? { bypassesIngressLimit: true as const }
24297
+ : {}),
24298
+ }
23809
24299
  : {}),
23810
24300
  ...(gatewayRuntimeApi && input.runtimeApi
23811
24301
  ? {
@@ -24056,7 +24546,11 @@ async function dispatchRunLedgerOutboxBatchWithScope(
24056
24546
  // its snapshot. Retain that mutation as its own exact delivery.
24057
24547
  if (first.eventType === RUN_SCHEDULER_OUTBOX_EVENT_TYPE.runCreated) {
24058
24548
  await renewDelivery();
24059
- await projectPostgresSchedulerCreatedEvent(runtimeApi, first);
24549
+ await projectPostgresSchedulerCreatedEvent(
24550
+ runtimeApi,
24551
+ first,
24552
+ gatewayRuntimeApi?.resolveRetainedPipelineGraphs,
24553
+ );
24060
24554
  } else if (
24061
24555
  first.eventType === RUN_SCHEDULER_OUTBOX_EVENT_TYPE.runStarted
24062
24556
  ) {
@@ -24702,9 +25196,85 @@ async function acknowledgeRunLedgerPrefixWithContinuation(
24702
25196
  });
24703
25197
  }
24704
25198
 
25199
+ /** A run.created body the receiver's ingress would refuse. Never resent as-is. */
25200
+ class RunCreatedProjectionTooLargeError extends AppRuntimeApiResponseError {
25201
+ constructor(detail: string) {
25202
+ super({
25203
+ action: 'project_run_created',
25204
+ status: 413,
25205
+ code: 'run_created_too_large',
25206
+ retryable: false,
25207
+ detail,
25208
+ });
25209
+ }
25210
+ }
25211
+
25212
+ /**
25213
+ * Keep run.created within the receiver's request limit, measured over the
25214
+ * whole request body. A request within the limit keeps the pipeline
25215
+ * representation its admission owner selected. An oversized inline pipeline
25216
+ * is sent as the lossless retained graph only when the receiver advertised
25217
+ * graph storage, either on the dispatch-token response that authorized this
25218
+ * delivery or, for a token minted at admission, on one fetched now under the
25219
+ * same outbox lease. Otherwise the projection fails before sending with a
25220
+ * typed code instead of an opaque ingress 413.
25221
+ */
25222
+ async function fitRunCreatedRequest<T extends object>(input: {
25223
+ runtimeApi: WorkerRuntimeApiContext;
25224
+ resolveRetainedPipelineGraphs?: () => Promise<true | undefined>;
25225
+ payload: PostgresSchedulerOutboxEvent['payload'];
25226
+ staticPipeline: unknown;
25227
+ request: (source: { retainedPipelineGraph?: unknown }) => T;
25228
+ }): Promise<T> {
25229
+ // Measure the body the transport sends, which re-encodes a retained graph.
25230
+ const exceedsLimit = (request: T) =>
25231
+ jsonByteLengthUpTo(
25232
+ prepareRetainedPlayPipelinesForTransport({
25233
+ action: 'project_run_created',
25234
+ ...request,
25235
+ }),
25236
+ APP_RUNTIME_REQUEST_BODY_MAX_BYTES,
25237
+ ).exceeded;
25238
+ const source = input.payload as { retainedPipelineGraph?: unknown };
25239
+ const selected = input.request(source);
25240
+ // An in-process receiver has no ingress limit: keep the selected format.
25241
+ if (input.runtimeApi.bypassesIngressLimit === true) return selected;
25242
+ if (!exceedsLimit(selected)) return selected;
25243
+ if (
25244
+ source.retainedPipelineGraph !== undefined ||
25245
+ input.staticPipeline === undefined ||
25246
+ input.staticPipeline === null
25247
+ ) {
25248
+ throw new RunCreatedProjectionTooLargeError(
25249
+ `run.created request exceeds ${APP_RUNTIME_REQUEST_BODY_MAX_BYTES} bytes without an inline pipeline to compact.`,
25250
+ );
25251
+ }
25252
+ const storesGraphs =
25253
+ input.runtimeApi.retainedPipelineGraphs === true ||
25254
+ (await input.resolveRetainedPipelineGraphs?.()) === true;
25255
+ if (!storesGraphs) {
25256
+ throw new RunCreatedProjectionTooLargeError(
25257
+ `run.created request exceeds ${APP_RUNTIME_REQUEST_BODY_MAX_BYTES} bytes and the receiver did not advertise retained pipeline graphs.`,
25258
+ );
25259
+ }
25260
+ const compact = input.request(
25261
+ encodeRetainedPlayPipelines<{
25262
+ staticPipeline: unknown;
25263
+ retainedPipelineGraph?: unknown;
25264
+ }>({ staticPipeline: input.staticPipeline }),
25265
+ );
25266
+ if (exceedsLimit(compact)) {
25267
+ throw new RunCreatedProjectionTooLargeError(
25268
+ `run.created request exceeds ${APP_RUNTIME_REQUEST_BODY_MAX_BYTES} bytes with a retained pipeline graph.`,
25269
+ );
25270
+ }
25271
+ return compact;
25272
+ }
25273
+
24705
25274
  async function projectPostgresSchedulerCreatedEvent(
24706
25275
  runtimeApi: WorkerRuntimeApiContext,
24707
25276
  event: PostgresSchedulerOutboxEvent,
25277
+ resolveRetainedPipelineGraphs?: () => Promise<true | undefined>,
24708
25278
  ): Promise<void> {
24709
25279
  event = { ...event, payload: hydrateRetainedPlayPipelines(event.payload) };
24710
25280
  const value = (key: string) => stringPayloadField(event.payload, key);
@@ -24720,7 +25290,10 @@ async function projectPostgresSchedulerCreatedEvent(
24720
25290
  const inputSha256 = value('inputSha256');
24721
25291
  const replayedFromRunId = value('replayedFromRunId');
24722
25292
  const asyncAncestryPlayIds = raw('asyncAncestryPlayIds');
24723
- await projectRunCreatedViaAppRuntime(runtimeApi, {
25293
+ const staticPipeline = raw('staticPipeline');
25294
+ const request = (pipelineSource: {
25295
+ retainedPipelineGraph?: unknown;
25296
+ }): Parameters<typeof projectRunCreatedViaAppRuntime>[1] => ({
24724
25297
  deliveryLeaseOwner: event.leaseOwner ?? undefined,
24725
25298
  idempotencyKey: buildRunLedgerStartIdempotencyKey({
24726
25299
  runId: event.runId,
@@ -24777,10 +25350,7 @@ async function projectPostgresSchedulerCreatedEvent(
24777
25350
  runtimeWorkflowName: value('runtimeWorkflowName'),
24778
25351
  runtimeHarnessWorkerName: value('runtimeHarnessWorkerName'),
24779
25352
  maxCreditsPerRun: number('maxCreditsPerRun'),
24780
- ...retainedPlayPipelineFields(
24781
- raw('staticPipeline'),
24782
- event.payload as { retainedPipelineGraph?: unknown },
24783
- ),
25353
+ ...retainedPlayPipelineFields(staticPipeline, pipelineSource),
24784
25354
  source: sourcePayloadField(event.payload, 'source'),
24785
25355
  ...(triggerSource === 'api' ||
24786
25356
  triggerSource === 'webhook' ||
@@ -24800,6 +25370,16 @@ async function projectPostgresSchedulerCreatedEvent(
24800
25370
  ? { inputSummary: inputSummary as Record<string, unknown> }
24801
25371
  : {}),
24802
25372
  });
25373
+ await projectRunCreatedViaAppRuntime(
25374
+ runtimeApi,
25375
+ await fitRunCreatedRequest({
25376
+ runtimeApi,
25377
+ resolveRetainedPipelineGraphs,
25378
+ payload: event.payload,
25379
+ staticPipeline,
25380
+ request,
25381
+ }),
25382
+ );
24803
25383
  }
24804
25384
 
24805
25385
  async function projectPostgresSchedulerStartEvent(
@@ -24930,6 +25510,7 @@ async function resolvePostgresSchedulerRuntimeApiForRun(
24930
25510
  WorkerRuntimeApiContext & {
24931
25511
  refreshExecutorToken?: () => Promise<string>;
24932
25512
  invalidateExecutorToken?: () => void;
25513
+ resolveRetainedPipelineGraphs?: () => Promise<true | undefined>;
24933
25514
  }
24934
25515
  > {
24935
25516
  const launch = parseRunLedgerDispatchLaunch(launchJson);
@@ -24952,6 +25533,12 @@ async function resolvePostgresSchedulerRuntimeApiForRun(
24952
25533
  }
24953
25534
  let executorToken: string;
24954
25535
  let runLedgerIngressPrefixBatching: true | undefined;
25536
+ // Only the receiver's own dispatch response proves graph storage. A token
25537
+ // minted locally or at admission says nothing about the receiving build.
25538
+ let retainedPipelineGraphs: true | undefined;
25539
+ let resolveRetainedPipelineGraphs:
25540
+ | (() => Promise<true | undefined>)
25541
+ | undefined;
24955
25542
  let refreshExecutorToken: (() => Promise<string>) | undefined;
24956
25543
  let invalidateExecutorToken: (() => void) | undefined;
24957
25544
  if (tokenAuthority === 'local_mint') {
@@ -24996,6 +25583,11 @@ async function resolvePostgresSchedulerRuntimeApiForRun(
24996
25583
  refreshExecutorToken = async () =>
24997
25584
  (await requestRunLedgerDispatchToken(dispatchRequest, true))
24998
25585
  .executorToken;
25586
+ // The admission token carries no receiver capability. Ask the receiver
25587
+ // through this lease only when a projection needs it.
25588
+ resolveRetainedPipelineGraphs = async () =>
25589
+ (await requestRunLedgerDispatchToken(dispatchRequest))
25590
+ .retainedPipelineGraphs;
24999
25591
  } else {
25000
25592
  const dispatchAuthority =
25001
25593
  await requestRunLedgerDispatchToken(dispatchRequest);
@@ -25017,6 +25609,7 @@ async function resolvePostgresSchedulerRuntimeApiForRun(
25017
25609
  executorToken = dispatchAuthority.executorToken;
25018
25610
  runLedgerIngressPrefixBatching =
25019
25611
  dispatchAuthority.runLedgerIngressPrefixBatching;
25612
+ retainedPipelineGraphs = dispatchAuthority.retainedPipelineGraphs;
25020
25613
  }
25021
25614
  }
25022
25615
  // A mutable source can seal array pages after this prefix was claimed.
@@ -25035,6 +25628,8 @@ async function resolvePostgresSchedulerRuntimeApiForRun(
25035
25628
  ...(runLedgerIngressPrefixBatching
25036
25629
  ? { runLedgerIngressPrefixBatching }
25037
25630
  : {}),
25631
+ ...(retainedPipelineGraphs ? { retainedPipelineGraphs } : {}),
25632
+ ...(resolveRetainedPipelineGraphs ? { resolveRetainedPipelineGraphs } : {}),
25038
25633
  vercelProtectionBypassToken: launch.vercelProtectionBypassToken ?? null,
25039
25634
  ...(refreshExecutorToken ? { refreshExecutorToken } : {}),
25040
25635
  ...(invalidateExecutorToken ? { invalidateExecutorToken } : {}),
@@ -25250,7 +25845,12 @@ const RUN_LEDGER_DISPATCH_TOKEN_CACHE_MS = 30_000;
25250
25845
  const RUN_LEDGER_DISPATCH_TOKEN_CACHE_ENTRIES = 256;
25251
25846
  const runLedgerDispatchTokens = new Map<
25252
25847
  string,
25253
- { token: string; expiresAt: number; runLedgerIngressPrefixBatching?: true }
25848
+ {
25849
+ token: string;
25850
+ expiresAt: number;
25851
+ runLedgerIngressPrefixBatching?: true;
25852
+ retainedPipelineGraphs?: true;
25853
+ }
25254
25854
  >();
25255
25855
 
25256
25856
  async function requestRunLedgerDispatchToken(
@@ -25268,6 +25868,7 @@ async function requestRunLedgerDispatchToken(
25268
25868
  reused: boolean;
25269
25869
  cacheKey: string;
25270
25870
  runLedgerIngressPrefixBatching?: true;
25871
+ retainedPipelineGraphs?: true;
25271
25872
  /** Present only when this call made the request (never for a reused token). */
25272
25873
  responseTrace?: RunLedgerDispatchResponseTrace;
25273
25874
  }> {
@@ -25302,6 +25903,9 @@ async function requestRunLedgerDispatchToken(
25302
25903
  ...(cached.runLedgerIngressPrefixBatching
25303
25904
  ? { runLedgerIngressPrefixBatching: true as const }
25304
25905
  : {}),
25906
+ ...(cached.retainedPipelineGraphs
25907
+ ? { retainedPipelineGraphs: true as const }
25908
+ : {}),
25305
25909
  };
25306
25910
  runLedgerDispatchTokens.delete(cacheKey);
25307
25911
  const url = `${input.receiverBaseUrl.replace(/\/$/, '')}/api/v2/internal/play-runtime/run-ledger-dispatch-token`;
@@ -25341,6 +25945,7 @@ async function requestRunLedgerDispatchToken(
25341
25945
  return JSON.parse(responseText) as {
25342
25946
  executorToken?: unknown;
25343
25947
  runLedgerIngressPrefixBatching?: unknown;
25948
+ retainedPipelineGraphs?: unknown;
25344
25949
  error?: unknown;
25345
25950
  code?: unknown;
25346
25951
  retryable?: unknown;
@@ -25402,6 +26007,9 @@ async function requestRunLedgerDispatchToken(
25402
26007
  ...(reusablePrefix
25403
26008
  ? { runLedgerIngressPrefixBatching: true as const }
25404
26009
  : {}),
26010
+ ...(body.retainedPipelineGraphs === true
26011
+ ? { retainedPipelineGraphs: true as const }
26012
+ : {}),
25405
26013
  });
25406
26014
  while (
25407
26015
  runLedgerDispatchTokens.size > RUN_LEDGER_DISPATCH_TOKEN_CACHE_ENTRIES
@@ -25425,6 +26033,9 @@ async function requestRunLedgerDispatchToken(
25425
26033
  ...(body.runLedgerIngressPrefixBatching === true
25426
26034
  ? { runLedgerIngressPrefixBatching: true as const }
25427
26035
  : {}),
26036
+ ...(body.retainedPipelineGraphs === true
26037
+ ? { retainedPipelineGraphs: true as const }
26038
+ : {}),
25428
26039
  responseTrace: {
25429
26040
  platformRequestId: readRuntimeApiDiagnosticHeader(
25430
26041
  response.headers,