deepline 0.3.483 → 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 (217) 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/monitors/signal-radars/inbound-dead-letter.ts +100 -9
  10. package/dist/bundling-sources/shared_libs/play-data-plane/sheet-column-storage.ts +32 -3
  11. package/dist/bundling-sources/shared_libs/play-runtime/app-runtime-api.ts +126 -41
  12. package/dist/bundling-sources/shared_libs/play-runtime/context.ts +231 -25
  13. package/dist/bundling-sources/shared_libs/play-runtime/daytona-runtime-config.ts +9 -0
  14. package/dist/bundling-sources/shared_libs/play-runtime/deployment/fly-machines.ts +130 -19
  15. package/dist/bundling-sources/shared_libs/play-runtime/deployment/fly-registry.ts +105 -0
  16. package/dist/bundling-sources/shared_libs/play-runtime/execute-server-timing.ts +4 -2
  17. package/dist/bundling-sources/shared_libs/play-runtime/governor/app-runtime-rate-state-backend.ts +194 -56
  18. package/dist/bundling-sources/shared_libs/play-runtime/log-provenance.ts +11 -6
  19. package/dist/bundling-sources/shared_libs/play-runtime/play-runs/sandbox-cleanup/job.ts +3 -0
  20. package/dist/bundling-sources/shared_libs/play-runtime/play-runs/sandbox-cleanup/ports.ts +2 -0
  21. package/dist/bundling-sources/shared_libs/play-runtime/play-runs/sandbox-cleanup/postgres-adapter.ts +2 -1
  22. package/dist/bundling-sources/shared_libs/play-runtime/protocol.ts +30 -0
  23. package/dist/bundling-sources/shared_libs/play-runtime/resource-governor.ts +195 -2
  24. package/dist/bundling-sources/shared_libs/play-runtime/run-failure.ts +20 -1
  25. package/dist/bundling-sources/shared_libs/play-runtime/run-ledger-projection-contract.ts +15 -0
  26. package/dist/bundling-sources/shared_libs/play-runtime/run-snapshot-stream.ts +2 -2
  27. package/dist/bundling-sources/shared_libs/play-runtime/runner-app/index.ts +102 -23
  28. package/dist/bundling-sources/shared_libs/play-runtime/runner-app/progress-sidecar.ts +9 -1
  29. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona-control-transport.ts +25 -5
  30. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona-launch-transport.ts +133 -82
  31. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona-lifecycle.ts +58 -16
  32. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona-sandbox-absence.ts +171 -0
  33. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona-session-execution.ts +69 -0
  34. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona.ts +100 -40
  35. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/types.ts +8 -0
  36. package/dist/bundling-sources/shared_libs/play-runtime/runtime-api.ts +67 -9
  37. package/dist/bundling-sources/shared_libs/play-runtime/runtime-incident-drills.ts +5 -5
  38. package/dist/bundling-sources/shared_libs/play-runtime/runtime-receipt-store-adapter.ts +6 -3
  39. package/dist/bundling-sources/shared_libs/play-runtime/runtime-sheet-errors.ts +14 -0
  40. package/dist/bundling-sources/shared_libs/play-runtime/runtime-sheet-row-writer.ts +87 -31
  41. package/dist/bundling-sources/shared_libs/play-runtime/sandbox-runs/contract.ts +18 -0
  42. package/dist/bundling-sources/shared_libs/play-runtime/sandbox-runs/index.ts +19 -0
  43. package/dist/bundling-sources/shared_libs/play-runtime/sandbox-runs/runner-backend-adapter.ts +14 -0
  44. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-runtime-worker.ts +204 -6
  45. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd.ts +39 -0
  46. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/ambiguous-modal-create-state.ts +21 -0
  47. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/compute-billing-job-state.ts +23 -0
  48. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/integration-operation-value-retirement-state.ts +25 -0
  49. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/integration-operation-value-retirement.ts +15 -1
  50. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/outbox-repair-operation-state.ts +30 -0
  51. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/play-run-recovery.ts +12 -1
  52. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres-progress.ts +26 -0
  53. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres-rate-scope.ts +44 -15
  54. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres-rate-state.ts +60 -11
  55. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres.ts +743 -70
  56. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/run-ledger-outbox-recovery.ts +6 -1
  57. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-event-search.ts +17 -0
  58. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-sandbox-capacity.ts +34 -34
  59. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/sandbox-cleanup-job-state.ts +23 -0
  60. package/dist/bundling-sources/shared_libs/play-runtime/suspension.ts +12 -0
  61. package/dist/bundling-sources/shared_libs/play-runtime/test-runtime-seams.ts +21 -0
  62. package/dist/bundling-sources/shared_libs/plays/authoring-contract.ts +1 -1
  63. package/dist/bundling-sources/shared_libs/plays/source-authoring-edition.ts +1 -1
  64. package/dist/bundling-sources/shared_libs/product-notifications/destination-state.ts +93 -0
  65. package/dist/cli/auth-ABZBH55L.js +43 -0
  66. package/dist/cli/{auth-2NXF6Q3Q.mjs → auth-OWMUENCU.mjs} +5 -5
  67. package/dist/cli/{billing-5PW4L5WD.js → billing-2FMNQGOX.js} +80 -80
  68. package/dist/cli/{billing-W2Y4EOZP.mjs → billing-JX4H3VFF.mjs} +7 -7
  69. package/dist/cli/{chunk-UGBZ6MCR.js → chunk-2ILND7XX.js} +2 -2
  70. package/dist/cli/{chunk-25IGCYJP.mjs → chunk-2ZEQ43B7.mjs} +3 -3
  71. package/dist/cli/{chunk-J7S3DJB4.mjs → chunk-3DBW6C7M.mjs} +13 -4
  72. package/dist/cli/{chunk-7APXZ3CX.mjs → chunk-3DYU3JQN.mjs} +2 -2
  73. package/dist/cli/{chunk-VFEW53L5.js → chunk-3OF7NSGR.js} +322 -294
  74. package/dist/cli/{chunk-UDF2CY4D.mjs → chunk-3Z24NKW7.mjs} +62 -34
  75. package/dist/cli/{chunk-62XGOB2D.js → chunk-5DCQWQCP.js} +26 -26
  76. package/dist/cli/{chunk-4X23YY2E.mjs → chunk-62PJ6PK7.mjs} +5 -5
  77. package/dist/cli/{chunk-YL64JIQ7.mjs → chunk-676NZ7K4.mjs} +1 -1
  78. package/dist/cli/{chunk-T5GZZJ7O.js → chunk-775AZTO7.js} +323 -247
  79. package/dist/cli/{chunk-C3LJSOQ6.mjs → chunk-ACTUAZYP.mjs} +5 -5
  80. package/dist/cli/{chunk-R2OR4RHV.js → chunk-AFADYKFE.js} +8 -8
  81. package/dist/cli/{chunk-GVAENVIG.js → chunk-AUQQVDAB.js} +110 -21
  82. package/dist/cli/{chunk-GONUMUBM.js → chunk-BSKPQB2P.js} +7 -7
  83. package/dist/cli/chunk-C6QWRSMQ.js +42 -0
  84. package/dist/cli/{chunk-AK7UKQ5R.js → chunk-CSBMKHTV.js} +5 -5
  85. package/dist/cli/{chunk-PRL7EKJZ.mjs → chunk-CW6TAQBF.mjs} +15 -4
  86. package/dist/cli/{chunk-75IIHFN6.js → chunk-DMNVM34J.js} +5 -4
  87. package/dist/cli/{chunk-IEV5UWPN.mjs → chunk-E73JXJA3.mjs} +1 -1
  88. package/dist/cli/{chunk-DS455RPF.js → chunk-EC2CVPN5.js} +3 -3
  89. package/dist/cli/{chunk-B7HQL77V.js → chunk-ECIXZNSW.js} +87 -76
  90. package/dist/cli/{chunk-JJSLEMQQ.mjs → chunk-FJY6K3BG.mjs} +93 -17
  91. package/dist/cli/{chunk-FK47YUPC.mjs → chunk-G5PI3RNT.mjs} +1 -1
  92. package/dist/cli/{chunk-GRE3ID5E.mjs → chunk-GHHJWCMD.mjs} +2 -1
  93. package/dist/cli/{chunk-2JWG2H2N.js → chunk-HKGXGGIV.js} +1 -1
  94. package/dist/cli/{chunk-2MKX3HV3.js → chunk-IHMYIHF4.js} +5 -5
  95. package/dist/cli/{chunk-SD7QWZTV.mjs → chunk-INW22YP7.mjs} +1 -1
  96. package/dist/cli/{chunk-OWUZKXE7.mjs → chunk-J7EENGKJ.mjs} +1 -1
  97. package/dist/cli/{chunk-AWAFYRFV.mjs → chunk-JD6HKNKD.mjs} +1 -1
  98. package/dist/cli/{chunk-UY7OXFVU.js → chunk-JQXUWYWX.js} +13 -13
  99. package/dist/cli/{chunk-GGJQ4HJW.mjs → chunk-KZTNNLIL.mjs} +2 -2
  100. package/dist/cli/{chunk-NREZRYPU.mjs → chunk-L352NOE3.mjs} +2 -2
  101. package/dist/cli/{chunk-WI2HNYQX.js → chunk-L7IQ3DFH.js} +53 -53
  102. package/dist/cli/{chunk-4IOY2SCQ.js → chunk-LOX3BISD.js} +4 -4
  103. package/dist/cli/{chunk-XRIQN6EP.js → chunk-NKPTM7SK.js} +7 -7
  104. package/dist/cli/{chunk-5ICAG4RE.js → chunk-NLRTFJGH.js} +14 -14
  105. package/dist/cli/{chunk-WKB6Y43W.js → chunk-NRNWPWBW.js} +37 -37
  106. package/dist/cli/{chunk-HNRELVCS.mjs → chunk-ONONSV2Q.mjs} +96 -7
  107. package/dist/cli/{chunk-MYB6JVSD.js → chunk-OW4OTEFF.js} +16 -16
  108. package/dist/cli/{chunk-ISP7ZENV.mjs → chunk-RZE5I2XJ.mjs} +4 -4
  109. package/dist/cli/{chunk-5LHU7NUS.js → chunk-S3WQJ5VG.js} +3 -3
  110. package/dist/cli/{chunk-EDMCD7MX.mjs → chunk-SR6S4EYG.mjs} +5 -5
  111. package/dist/cli/{chunk-2T4OSJEH.js → chunk-T4G2T5DS.js} +21 -21
  112. package/dist/cli/{chunk-EGHYGTJM.mjs → chunk-TMCC7ORQ.mjs} +1 -1
  113. package/dist/cli/{chunk-SCPFOH5Z.mjs → chunk-TSCUWWTM.mjs} +1 -1
  114. package/dist/cli/{chunk-7TKLISLM.js → chunk-TVW6USSG.js} +3 -3
  115. package/dist/cli/{chunk-QSYA6VE4.js → chunk-U6WEGDD3.js} +2 -2
  116. package/dist/cli/{chunk-FGEC5SWP.mjs → chunk-UPHXGZCE.mjs} +4 -4
  117. package/dist/cli/{chunk-5JCXS4MP.js → chunk-UQ3LQ6IF.js} +5 -5
  118. package/dist/cli/{chunk-JYEZ6BWX.mjs → chunk-VZYTLWOM.mjs} +2 -2
  119. package/dist/cli/{chunk-FAZTLYJO.mjs → chunk-W33OL4F2.mjs} +2 -2
  120. package/dist/cli/{chunk-ZM2YPJQJ.js → chunk-XK5DMLZE.js} +5 -1
  121. package/dist/cli/{chunk-LJ5747UC.mjs → chunk-XRDXNAAY.mjs} +5 -1
  122. package/dist/cli/{chunk-S24CK3CJ.mjs → chunk-YDA3PMKK.mjs} +3 -3
  123. package/dist/cli/{csv-EKEFLUIW.js → csv-HFEQPGNY.js} +13 -13
  124. package/dist/cli/{csv-DIFVIR23.mjs → csv-OHF3Y5KB.mjs} +4 -4
  125. package/dist/cli/{db-DOW4EVEU.mjs → db-M456OUXD.mjs} +7 -7
  126. package/dist/cli/{db-S7DDRUHX.js → db-VLQKCYQS.js} +28 -28
  127. package/dist/cli/describe-CP35DZ5Z.js +49 -0
  128. package/dist/cli/{describe-KSZFOWKV.mjs → describe-M6VXFYVL.mjs} +21 -21
  129. package/dist/cli/describe-core.d.mts +3 -3
  130. package/dist/cli/describe-core.d.ts +3 -3
  131. package/dist/cli/describe-core.js +4 -4
  132. package/dist/cli/describe-core.mjs +3 -3
  133. package/dist/cli/{executions-CAG7YC5K.mjs → executions-4FGRBPJF.mjs} +7 -7
  134. package/dist/cli/{executions-3DU5IXB6.js → executions-GKINJZI6.js} +9 -9
  135. package/dist/cli/{feedback-BQMPTE47.mjs → feedback-D2WMGK3V.mjs} +4 -4
  136. package/dist/cli/{feedback-I65JMCP2.js → feedback-ZH5K7WV7.js} +8 -8
  137. package/dist/cli/git-IDALMZDN.js +25 -0
  138. package/dist/cli/{git-UQUCD7XZ.mjs → git-OCIJ5ME4.mjs} +5 -5
  139. package/dist/cli/index.js +142 -139
  140. package/dist/cli/index.mjs +45 -42
  141. package/dist/cli/{legacy-noops-OLNT2BG5.js → legacy-noops-QNIVP7LO.js} +8 -8
  142. package/dist/cli/{legacy-noops-JXKLHUI3.mjs → legacy-noops-V6Q2X34P.mjs} +5 -5
  143. package/dist/cli/{monitors-DLTHHAFQ.mjs → monitors-2USHTG5G.mjs} +8 -8
  144. package/dist/cli/{monitors-Z5X56AZN.js → monitors-5DNK7W2K.js} +92 -92
  145. package/dist/cli/{org-XBHJLKUG.js → org-RPGM5AN4.js} +73 -73
  146. package/dist/cli/{org-6EZZHD3M.mjs → org-TL2YPYSE.mjs} +7 -7
  147. package/dist/cli/{pages-XVJ34SCN.js → pages-PNUKPFWV.js} +18 -18
  148. package/dist/cli/{pages-MYXROSVK.mjs → pages-XDEW6EE3.mjs} +7 -7
  149. package/dist/cli/{play-ACC4T2XQ.js → play-F5LHRKV5.js} +858 -632
  150. package/dist/cli/{play-5PV4LAHE.mjs → play-WINNQ4HZ.mjs} +372 -146
  151. package/dist/cli/{providers-JCI3KNE4.js → providers-BD4IS5U5.js} +10 -10
  152. package/dist/cli/{providers-2DLUGIFF.mjs → providers-PXGL3FRE.mjs} +7 -7
  153. package/dist/cli/{quickstart-PDSQEDLD.js → quickstart-7LVF6HZF.js} +6 -6
  154. package/dist/cli/{quickstart-NSL3C76K.mjs → quickstart-XTH3UQWZ.mjs} +4 -4
  155. package/dist/cli/{run-X5MXCM4P.mjs → run-MBMUENR7.mjs} +26 -26
  156. package/dist/cli/{run-UCFMHOQC.js → run-NH2BAWPA.js} +41 -41
  157. package/dist/cli/{search-RPEMXV6N.mjs → search-BMRWBV66.mjs} +8 -8
  158. package/dist/cli/search-R3MQJQMT.js +32 -0
  159. package/dist/cli/{search-output-MZH3HLVE.js → search-output-5NNT337U.js} +22 -16
  160. package/dist/cli/{search-output-6UO47B7G.mjs → search-output-QKKRD4MF.mjs} +14 -8
  161. package/dist/cli/{secrets-NLEQURD3.mjs → secrets-AWEXBTJV.mjs} +7 -7
  162. package/dist/cli/{secrets-UFBASYGY.js → secrets-KQSTOREN.js} +16 -16
  163. package/dist/cli/{sessions-JYH4DBEE.js → sessions-DSPLZYCJ.js} +6 -6
  164. package/dist/cli/{sessions-3ALFLWVU.mjs → sessions-RO25Q67X.mjs} +5 -5
  165. package/dist/cli/{settings-MQYKNAMB.js → settings-7JXIKNKI.js} +79 -79
  166. package/dist/cli/{settings-YPRILREA.mjs → settings-JMGXGK4Z.mjs} +12 -12
  167. package/dist/cli/{setup-5IGSHH4E.js → setup-5QFAQQRW.js} +47 -47
  168. package/dist/cli/{setup-DK4GM227.mjs → setup-ZQZ47FHB.mjs} +9 -9
  169. package/dist/cli/skills-EDZXY7DV.js +33 -0
  170. package/dist/cli/{skills-KYBZH3IT.mjs → skills-W3H2DL56.mjs} +7 -7
  171. package/dist/cli/{tools-4B2MHNBN.mjs → tools-2BZCVNBS.mjs} +19 -19
  172. package/dist/cli/tools-2EY2ETCZ.js +56 -0
  173. package/dist/cli/{update-S6VEO7NB.mjs → update-GAWYMGAW.mjs} +9 -9
  174. package/dist/cli/update-UKDQKNBY.js +33 -0
  175. package/dist/cli/{workflow-KXZZYFEF.mjs → workflow-M6LLHQ2I.mjs} +8 -8
  176. package/dist/cli/{workflow-FU2XVPUK.js → workflow-ZPTDFPKW.js} +18 -18
  177. package/dist/{client-DJ3r8VQJ.d.mts → client-BkbDHRIg.d.mts} +1 -1
  178. package/dist/{client-JPSNljtj.d.ts → client-D3hVHXjK.d.ts} +1 -1
  179. package/dist/{client-core-3SJlNsKU.d.mts → client-core-BZoSMKcY.d.mts} +30 -15
  180. package/dist/{client-core-rCoQ5Xz3.d.ts → client-core-DUdVqO_m.d.ts} +30 -15
  181. package/dist/{compiler-manifest-gkO9ZkVg.d.mts → compiler-manifest-BFTwq1HI.d.mts} +1 -1
  182. package/dist/{compiler-manifest-gkO9ZkVg.d.ts → compiler-manifest-BFTwq1HI.d.ts} +1 -1
  183. package/dist/{errors-Cc92LKH-.d.ts → errors-c3pMsylw.d.ts} +1 -1
  184. package/dist/{errors-CeCCOKSA.d.mts → errors-w31ybrQM.d.mts} +1 -1
  185. package/dist/{index-DJQKdV76.d.ts → index-CQ-15-QL.d.ts} +1 -1
  186. package/dist/{index-DsqWJL3Q.d.mts → index-DvNtxucX.d.mts} +1 -1
  187. package/dist/index.d.mts +7 -7
  188. package/dist/index.d.ts +7 -7
  189. package/dist/index.js +10 -10
  190. package/dist/index.mjs +7 -7
  191. package/dist/install-integrity.json +123 -116
  192. package/dist/plays/bundle-play-file.d.mts +3 -3
  193. package/dist/plays/bundle-play-file.d.ts +3 -3
  194. package/dist/plays/bundle-play-file.mjs +2 -2
  195. package/dist/plays/play-description.d.mts +2 -2
  196. package/dist/plays/play-description.d.ts +2 -2
  197. package/dist/plays/run-request.d.mts +2 -2
  198. package/dist/plays/run-request.d.ts +2 -2
  199. package/dist/plays/run-request.js +12 -2
  200. package/dist/plays/run-request.mjs +11 -1
  201. package/dist/release.d.mts +1 -1
  202. package/dist/release.d.ts +1 -1
  203. package/dist/release.js +2 -2
  204. package/dist/release.mjs +1 -1
  205. package/dist/server.d.mts +4 -4
  206. package/dist/server.d.ts +4 -4
  207. package/dist/server.js +6 -6
  208. package/dist/server.mjs +4 -4
  209. package/package.json +1 -1
  210. package/dist/cli/auth-JHQKM6QY.js +0 -43
  211. package/dist/cli/chunk-PHDEQ6W3.js +0 -33
  212. package/dist/cli/describe-RXYQCJRR.js +0 -49
  213. package/dist/cli/git-ADIABNMQ.js +0 -25
  214. package/dist/cli/search-YILJZD36.js +0 -32
  215. package/dist/cli/skills-I4IUZN3U.js +0 -33
  216. package/dist/cli/tools-NLZR7ABS.js +0 -56
  217. package/dist/cli/update-RVDEUJTE.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';
@@ -59,6 +60,24 @@ import {
59
60
  type RuntimeSandboxProvider,
60
61
  runtimeSandboxProviderForResourceKind,
61
62
  } from './runtime-sandbox-operation';
63
+ import {
64
+ AmbiguousModalCreateStatus,
65
+ readAmbiguousModalCreateStatus,
66
+ } from './ambiguous-modal-create-state';
67
+ import {
68
+ ComputeBillingJobStatus,
69
+ readComputeBillingJobStatus,
70
+ } from './compute-billing-job-state';
71
+ import {
72
+ SandboxCleanupJobStatus,
73
+ readSandboxCleanupJobStatus,
74
+ } from './sandbox-cleanup-job-state';
75
+ export {
76
+ OutboxRepairOperationState,
77
+ canTransitionOutboxRepairOperation,
78
+ readOutboxRepairOperationState,
79
+ } from './outbox-repair-operation-state';
80
+ export type { OutboxRepairOperationState as OutboxRepairOperationStateType } from './outbox-repair-operation-state';
62
81
  import {
63
82
  TOOL_EXECUTION_ERROR_SCHEMA_VERSION,
64
83
  type ToolExecutionErrorSchemaVersion,
@@ -148,6 +167,7 @@ import {
148
167
  } from '../log-provenance';
149
168
  import {
150
169
  buildRunLedgerEventsIdempotencyKey,
170
+ RunLedgerProgressAttemptSupersededError,
151
171
  RunLedgerProjectionLeaseLostError,
152
172
  type RunLedgerProjectionChunk,
153
173
  type RunLedgerProjectionLeaseLostReason,
@@ -165,6 +185,7 @@ import {
165
185
  terminalRunResultForLedger,
166
186
  } from '../output-size-limits';
167
187
  import {
188
+ APP_RUNTIME_REQUEST_BODY_MAX_BYTES,
168
189
  AppRuntimeApiResponseError,
169
190
  AppRuntimeApiTransportError,
170
191
  projectRunEventsViaAppRuntime,
@@ -1286,6 +1307,8 @@ export type PostgresSchedulerSchemaShapeRequirements = Readonly<{
1286
1307
  runtimeLogStorage?: boolean;
1287
1308
  /** v64 records whether terminal projection owns array-input retirement. */
1288
1309
  arrayInputIntent?: boolean;
1310
+ /** Sandbox admission routines are installed by additive repair, not table DDL. */
1311
+ sandboxCapacityAdmissionFunctions?: boolean;
1289
1312
  }>;
1290
1313
 
1291
1314
  export async function hasCurrentPostgresSchedulerSchemaShape(
@@ -1936,6 +1959,13 @@ export async function hasCurrentPostgresSchedulerSchemaShape(
1936
1959
  AND column_default IS NOT NULL
1937
1960
  )
1938
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
+ )
1939
1969
  AS ready
1940
1970
  `,
1941
1971
  [
@@ -1979,6 +2009,9 @@ export async function hasCurrentPostgresSchedulerSchemaShape(
1979
2009
  requirements.runtimeLogStorage !== false,
1980
2010
  requirements.gatewayReaderFence !== false,
1981
2011
  requirements.arrayInputIntent !== false,
2012
+ requirements.sandboxCapacityAdmissionFunctions !== false,
2013
+ `${quotedSchema}.runtime_sandbox_capacity_lock(text)`,
2014
+ `${quotedSchema}.runtime_sandbox_capacity_observation(text, integer)`,
1982
2015
  ],
1983
2016
  );
1984
2017
  if (currentShape.rows[0]?.ready !== true) return false;
@@ -2232,6 +2265,76 @@ async function ensurePostgresSchedulerGatewayReaderFenceSchema(
2232
2265
  `);
2233
2266
  }
2234
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
+
2235
2338
  /**
2236
2339
  * Expand the shared scheduler schema without retaining locks across tables.
2237
2340
  *
@@ -2288,6 +2391,10 @@ export async function ensurePostgresSchedulerOnlineAdditiveExpansion(
2288
2391
  await ensurePostgresSchedulerRunLogStorageExpansion(client, options);
2289
2392
  await ensurePostgresSchedulerArrayInputIntentExpansion(client, options);
2290
2393
  await ensurePostgresSchedulerGatewayReaderFenceSchema(client, options);
2394
+ await ensurePostgresSchedulerSandboxCapacityAdmissionFunctions(
2395
+ client,
2396
+ options,
2397
+ );
2291
2398
  }
2292
2399
 
2293
2400
  /** Deployment-owned v64 expansion; absent values retain legacy behavior. */
@@ -2771,6 +2878,7 @@ export async function ensurePostgresSchedulerSchema(
2771
2878
  outboxWakeTrigger: false,
2772
2879
  cronScheduleSchema: false,
2773
2880
  arrayInputIntent: false,
2881
+ sandboxCapacityAdmissionFunctions: false,
2774
2882
  }));
2775
2883
  const schemaCoreIsCurrent =
2776
2884
  schemaIsCurrent || schemaIsCurrentWithoutAdditiveFastPathObjects;
@@ -2800,6 +2908,10 @@ export async function ensurePostgresSchedulerSchema(
2800
2908
  concurrently: false,
2801
2909
  });
2802
2910
  }
2911
+ await ensurePostgresSchedulerSandboxCapacityAdmissionFunctions(
2912
+ client,
2913
+ options,
2914
+ );
2803
2915
  await ensurePostgresSchedulerLaunchAdmissionFunctions(client, options);
2804
2916
  if (!schemaIsCurrent) {
2805
2917
  await ensurePostgresSchedulerTerminalComputeBillingOutboxTrigger(
@@ -3146,10 +3258,10 @@ export async function ensurePostgresSchedulerSchema(
3146
3258
  event_id
3147
3259
  )
3148
3260
  `);
3149
- // Per-organization sandbox admission is intentionally a lightweight
3150
- // capacity hint, not a strict distributed lock. Convex owns desired
3151
- // limits; the runtime consumes only this local mirror so worker launches
3152
- // 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.
3153
3265
  await client.query(`
3154
3266
  CREATE TABLE IF NOT EXISTS ${tableName('runtime_org_sandbox_limit_cache', options)} (
3155
3267
  org_id text PRIMARY KEY,
@@ -3178,6 +3290,10 @@ export async function ensurePostgresSchedulerSchema(
3178
3290
  ALTER TABLE ${tableName('runtime_sandbox_capacity_leases', options)}
3179
3291
  ADD COLUMN IF NOT EXISTS routing_domain text
3180
3292
  `);
3293
+ await ensurePostgresSchedulerSandboxCapacityAdmissionFunctions(
3294
+ client,
3295
+ options,
3296
+ );
3181
3297
  // The operation ledger is authoritative for a physical sandbox lifecycle.
3182
3298
  // `resource_json` stays a compatibility/audit projection, never a source
3183
3299
  // for capacity admission or reconciliation.
@@ -9161,9 +9277,34 @@ export async function deferPostgresSchedulerAttemptForRecovery(
9161
9277
  options?: Pick<PostgresSchedulerOptions, 'schema'>,
9162
9278
  ): Promise<PostgresSchedulerRecoveryDeferral> {
9163
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}`;
9164
9304
  const result = await client.query<{
9165
9305
  candidate: boolean;
9166
9306
  deferred: boolean;
9307
+ work_counters_recorded: boolean;
9167
9308
  defer_count: string | null;
9168
9309
  deadline_at_ms: string | null;
9169
9310
  }>(
@@ -9243,6 +9384,19 @@ export async function deferPostgresSchedulerAttemptForRecovery(
9243
9384
  JOIN deferred_attempt ON deferred_attempt.run_id = computed.run_id
9244
9385
  WHERE runs.run_id = computed.run_id
9245
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
9246
9400
  ), exhausted_run AS (
9247
9401
  UPDATE ${tableName('runs', options)} AS runs
9248
9402
  SET recovery_json = jsonb_build_object(
@@ -9264,6 +9418,15 @@ export async function deferPostgresSchedulerAttemptForRecovery(
9264
9418
  )
9265
9419
  SELECT EXISTS (SELECT 1 FROM candidate) AS candidate,
9266
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,
9267
9430
  EXISTS (SELECT 1 FROM open_circuit) AS circuit_opened,
9268
9431
  (SELECT defer_count::text FROM computed LIMIT 1) AS defer_count,
9269
9432
  (SELECT deadline_at_ms::text FROM computed LIMIT 1) AS deadline_at_ms
@@ -9286,6 +9449,8 @@ export async function deferPostgresSchedulerAttemptForRecovery(
9286
9449
  input.openCircuit ?? true,
9287
9450
  input.deferBaseMs ?? 15_000,
9288
9451
  input.deferMaxMs ?? 300_000,
9452
+ noCodeWorkCounterEventId,
9453
+ stableStringify({ events: [noCodeWorkCounterEvent] }),
9289
9454
  ],
9290
9455
  );
9291
9456
  const row = result.rows[0];
@@ -9297,6 +9462,11 @@ export async function deferPostgresSchedulerAttemptForRecovery(
9297
9462
  deadlineAtMs: null,
9298
9463
  };
9299
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
+ }
9300
9470
  const deferCount = row.defer_count ? Number(row.defer_count) : null;
9301
9471
  const deadlineAtMs = row.deadline_at_ms ? Number(row.deadline_at_ms) : null;
9302
9472
  return {
@@ -10099,6 +10269,8 @@ export async function recordPostgresSchedulerManagedSandboxOperationLive(
10099
10269
  JOIN custody_leases AS lease ON lease.lease_id = operation.operation_key
10100
10270
  WHERE attempt.run_id = $1 AND attempt.attempt = $2 AND attempt.lease_token = $3
10101
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)
10102
10274
  AND NOT EXISTS (SELECT 1 FROM custody_attempts AS newer WHERE newer.attempt > $2)
10103
10275
  AND EXISTS (SELECT 1 FROM custody_runs WHERE status IN ('queued', 'running', 'waiting'))
10104
10276
  AND operation.operation_key = $5 AND operation.sandbox_id = $6
@@ -10245,7 +10417,7 @@ export async function recordPostgresSchedulerAmbiguousModalCreateIntent(
10245
10417
  },
10246
10418
  options?: Pick<PostgresSchedulerOptions, 'schema'>,
10247
10419
  ): Promise<boolean> {
10248
- const recorded = await client.query<{ run_id: string }>(
10420
+ const recorded = await client.query<{ run_id: string; status: unknown }>(
10249
10421
  `
10250
10422
  INSERT INTO ${tableName('ambiguous_modal_creates', options)} (
10251
10423
  run_id, attempt, modal_app_id, environment, tags_json, sandbox_capacity_lease_id
@@ -10263,7 +10435,7 @@ export async function recordPostgresSchedulerAmbiguousModalCreateIntent(
10263
10435
  sandbox_capacity_lease_id = EXCLUDED.sandbox_capacity_lease_id,
10264
10436
  status = 'pending',
10265
10437
  resolved_at = NULL
10266
- RETURNING run_id
10438
+ RETURNING run_id, status
10267
10439
  `,
10268
10440
  [
10269
10441
  input.runId,
@@ -10275,6 +10447,16 @@ export async function recordPostgresSchedulerAmbiguousModalCreateIntent(
10275
10447
  input.sandboxCapacityLeaseId?.trim() || null,
10276
10448
  ],
10277
10449
  );
10450
+ for (const row of recorded.rows) {
10451
+ if (
10452
+ readAmbiguousModalCreateStatus(row.status) !==
10453
+ AmbiguousModalCreateStatus.Pending
10454
+ ) {
10455
+ throw new Error(
10456
+ 'Recorded ambiguous Modal create intent was not pending.',
10457
+ );
10458
+ }
10459
+ }
10278
10460
  return recorded.rows.length > 0;
10279
10461
  }
10280
10462
 
@@ -10302,6 +10484,7 @@ export async function resolvePostgresSchedulerAmbiguousModalCreateIntent(
10302
10484
  }
10303
10485
 
10304
10486
  export type PostgresSchedulerAmbiguousModalCreateIntent = {
10487
+ status: typeof AmbiguousModalCreateStatus.Pending;
10305
10488
  runId: string;
10306
10489
  attempt: number;
10307
10490
  modalAppId: string;
@@ -10329,6 +10512,7 @@ export async function listPostgresSchedulerAmbiguousModalCreateIntents(
10329
10512
  const minimumAgeMs = Math.max(0, Math.floor(input.minimumAgeMs));
10330
10513
  const rows = await client.query<{
10331
10514
  run_id: string;
10515
+ status: unknown;
10332
10516
  attempt: number;
10333
10517
  modal_app_id: string;
10334
10518
  environment: 'preview' | 'production';
@@ -10337,7 +10521,7 @@ export async function listPostgresSchedulerAmbiguousModalCreateIntents(
10337
10521
  created_at_ms: number;
10338
10522
  }>(
10339
10523
  `
10340
- SELECT run_id, attempt, modal_app_id, environment, tags_json, sandbox_capacity_lease_id,
10524
+ SELECT run_id, status, attempt, modal_app_id, environment, tags_json, sandbox_capacity_lease_id,
10341
10525
  floor(extract(epoch FROM created_at) * 1000)::bigint AS created_at_ms
10342
10526
  FROM ${tableName('ambiguous_modal_creates', options)}
10343
10527
  WHERE status = 'pending'
@@ -10348,15 +10532,24 @@ export async function listPostgresSchedulerAmbiguousModalCreateIntents(
10348
10532
  `,
10349
10533
  [input.environment, minimumAgeMs, limit],
10350
10534
  );
10351
- return rows.rows.map((row) => ({
10352
- runId: row.run_id,
10353
- attempt: Number(row.attempt),
10354
- modalAppId: row.modal_app_id,
10355
- environment: row.environment,
10356
- tags: row.tags_json,
10357
- sandboxCapacityLeaseId: row.sandbox_capacity_lease_id,
10358
- createdAtMs: Number(row.created_at_ms),
10359
- }));
10535
+ return rows.rows.map((row) => {
10536
+ const status = readAmbiguousModalCreateStatus(row.status);
10537
+ if (status !== AmbiguousModalCreateStatus.Pending) {
10538
+ throw new Error(
10539
+ `Ambiguous Modal create intent ${row.run_id} was listed in ${status} state.`,
10540
+ );
10541
+ }
10542
+ return {
10543
+ status,
10544
+ runId: row.run_id,
10545
+ attempt: Number(row.attempt),
10546
+ modalAppId: row.modal_app_id,
10547
+ environment: row.environment,
10548
+ tags: row.tags_json,
10549
+ sandboxCapacityLeaseId: row.sandbox_capacity_lease_id,
10550
+ createdAtMs: Number(row.created_at_ms),
10551
+ };
10552
+ });
10360
10553
  }
10361
10554
 
10362
10555
  /** Provider-confirmed absence is terminal for one pre-create selector. */
@@ -11743,6 +11936,7 @@ export async function directCompletePostgresSchedulerRunnerTerminal(
11743
11936
  }
11744
11937
 
11745
11938
  export type PostgresSchedulerComputeBillingJob = {
11939
+ status: typeof ComputeBillingJobStatus.Settling;
11746
11940
  runId: string;
11747
11941
  attemptCount: number;
11748
11942
  failureCount: number;
@@ -11994,6 +12188,7 @@ export async function claimPostgresSchedulerComputeBillingJobs(
11994
12188
  );
11995
12189
  const claimed = await client.query<{
11996
12190
  run_id: string;
12191
+ status: unknown;
11997
12192
  attempt_count: number;
11998
12193
  failure_count: number;
11999
12194
  run_status: string;
@@ -12045,6 +12240,7 @@ export async function claimPostgresSchedulerComputeBillingJobs(
12045
12240
  WHERE job.run_id = candidates.run_id
12046
12241
  RETURNING
12047
12242
  job.run_id,
12243
+ job.status,
12048
12244
  job.attempt_count,
12049
12245
  job.failure_count,
12050
12246
  job.session_bootstrap_approved_at,
@@ -12052,6 +12248,7 @@ export async function claimPostgresSchedulerComputeBillingJobs(
12052
12248
  )
12053
12249
  SELECT
12054
12250
  claimed.run_id,
12251
+ claimed.status,
12055
12252
  claimed.attempt_count,
12056
12253
  claimed.failure_count,
12057
12254
  claimed.session_bootstrap_approved_at,
@@ -12063,15 +12260,24 @@ export async function claimPostgresSchedulerComputeBillingJobs(
12063
12260
  `,
12064
12261
  [input.leaseOwner, limit, leaseSeconds],
12065
12262
  );
12066
- return claimed.rows.map((row) => ({
12067
- runId: row.run_id,
12068
- attemptCount: row.attempt_count,
12069
- failureCount: row.failure_count,
12070
- success: row.run_status === 'completed',
12071
- bootstrapSessionPending:
12072
- row.session_bootstrap_approved_at !== null &&
12073
- row.session_bootstrap_completed_at === null,
12074
- }));
12263
+ return claimed.rows.map((row) => {
12264
+ const status = readComputeBillingJobStatus(row.status);
12265
+ if (status !== ComputeBillingJobStatus.Settling) {
12266
+ throw new Error(
12267
+ `Compute billing job ${row.run_id} was claimed in ${status} state.`,
12268
+ );
12269
+ }
12270
+ return {
12271
+ status,
12272
+ runId: row.run_id,
12273
+ attemptCount: row.attempt_count,
12274
+ failureCount: row.failure_count,
12275
+ success: row.run_status === 'completed',
12276
+ bootstrapSessionPending:
12277
+ row.session_bootstrap_approved_at !== null &&
12278
+ row.session_bootstrap_completed_at === null,
12279
+ };
12280
+ });
12075
12281
  }
12076
12282
 
12077
12283
  /**
@@ -12476,6 +12682,7 @@ function protectedDetachedResourceSql(
12476
12682
  }
12477
12683
 
12478
12684
  export type PostgresSchedulerSandboxCleanupJob = {
12685
+ status: typeof SandboxCleanupJobStatus.Deleting;
12479
12686
  provider: 'daytona' | 'modal';
12480
12687
  sandboxId: string;
12481
12688
  runId: string;
@@ -12683,10 +12890,125 @@ export async function hasPendingPostgresSchedulerSandboxCleanupForRun(
12683
12890
  return pending.rows[0]?.pending ?? true;
12684
12891
  }
12685
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
+
12686
13002
  export async function claimPostgresSchedulerSandboxCleanupJobs(
12687
13003
  client: PostgresSchedulerQueryClient,
12688
13004
  input: {
12689
13005
  leaseOwner: string;
13006
+ exactResource?: {
13007
+ provider: 'daytona' | 'modal';
13008
+ sandboxId: string;
13009
+ routingDomain: string | null;
13010
+ attempt: number;
13011
+ };
12690
13012
  runId?: string;
12691
13013
  throughAttempt?: number;
12692
13014
  limit?: number;
@@ -12696,6 +13018,8 @@ export async function claimPostgresSchedulerSandboxCleanupJobs(
12696
13018
  },
12697
13019
  options?: Pick<PostgresSchedulerOptions, 'schema'>,
12698
13020
  ): Promise<PostgresSchedulerSandboxCleanupJob[]> {
13021
+ if (input.exactResource && !input.runId)
13022
+ throw new Error('Exact sandbox cleanup requires its run identity.');
12699
13023
  const limit = Math.min(100, Math.max(1, Math.floor(input.limit ?? 20)));
12700
13024
  const leaseSeconds = Math.min(
12701
13025
  300,
@@ -12708,6 +13032,22 @@ export async function claimPostgresSchedulerSandboxCleanupJobs(
12708
13032
  (provider) => provider === 'daytona' || provider === 'modal',
12709
13033
  );
12710
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
+ ];
12711
13051
  // The v12 table retains deleted history. Avoid planning the lineage repair
12712
13052
  // when neither a legacy row nor a v2 NULL-domain duplicate needs adoption.
12713
13053
  // The same read proves whether any v2 row could be claimed: the claim below
@@ -12729,23 +13069,9 @@ export async function claimPostgresSchedulerSandboxCleanupJobs(
12729
13069
  SELECT 1 FROM ${tableName('sandbox_cleanup_jobs', options)}
12730
13070
  WHERE status <> 'deleted'
12731
13071
  ) AS pending,
12732
- EXISTS (
12733
- SELECT 1 FROM ${tableName('sandbox_cleanup_jobs_v2', options)} AS cleanup
12734
- WHERE cleanup.status <> 'deleted' AND cleanup.blocked_at IS NULL
12735
- AND (cleanup.available_at <= now() OR cleanup.diagnostic_json IS NOT NULL)
12736
- AND (cleanup.lease_expires_at IS NULL OR cleanup.lease_expires_at <= now())
12737
- AND ($1::text IS NULL OR cleanup.environment = $1)
12738
- AND ($2::text[] IS NULL OR cleanup.provider = ANY($2::text[]))
12739
- AND ($3::text IS NULL OR cleanup.run_id = $3)
12740
- AND ($4::integer IS NULL OR cleanup.attempt <= $4)
12741
- ) AS claimable
13072
+ ${claimablePredicate} AS claimable
12742
13073
  `,
12743
- [
12744
- input.environment?.trim() || null,
12745
- providers,
12746
- input.runId ?? null,
12747
- input.throughAttempt ?? null,
12748
- ],
13074
+ claimableParams,
12749
13075
  );
12750
13076
  if (
12751
13077
  typeof adoptionWork.rows[0]?.pending !== 'boolean' ||
@@ -12760,7 +13086,8 @@ export async function claimPostgresSchedulerSandboxCleanupJobs(
12760
13086
  // otherwise make every later adoption recreate a pending NULL-domain row.
12761
13087
  // Reconcile only the exact original identity proved by the immutable
12762
13088
  // provider confirmation and the matching deleted v2 tombstone.
12763
- if (adoptionWork.rows[0].pending)
13089
+ let claimable = adoptionWork.rows[0].claimable;
13090
+ if (adoptionWork.rows[0].pending) {
12764
13091
  await client.query(
12765
13092
  `
12766
13093
  WITH pending_legacy AS MATERIALIZED (
@@ -12946,11 +13273,27 @@ export async function claimPostgresSchedulerSandboxCleanupJobs(
12946
13273
  ON CONFLICT (provider, sandbox_id, routing_domain_key) DO NOTHING
12947
13274
  `,
12948
13275
  );
12949
- // Adoption may have just created claimable v2 rows, so only an idle read
12950
- // that proved neither kind of work skips the claim.
12951
- if (!adoptionWork.rows[0].pending && !adoptionWork.rows[0].claimable)
12952
- 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 [];
12953
13295
  const claimed = await client.query<{
13296
+ status: unknown;
12954
13297
  provider: 'daytona' | 'modal';
12955
13298
  sandbox_id: string;
12956
13299
  run_id: string;
@@ -12973,6 +13316,11 @@ export async function claimPostgresSchedulerSandboxCleanupJobs(
12973
13316
  AND ($5::text[] IS NULL OR cleanup.provider = ANY($5::text[]))
12974
13317
  AND ($8::text IS NULL OR cleanup.run_id = $8)
12975
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
+ ))
12976
13324
  AND NOT ${protectedDetachedSandboxSql({ runId: 'cleanup.run_id', provider: 'cleanup.provider', sandboxId: 'cleanup.sandbox_id', routingDomain: 'cleanup.routing_domain' }, options)}
12977
13325
  ORDER BY CASE WHEN cleanup.diagnostic_json IS NOT NULL THEN 0 ELSE 1 END,
12978
13326
  cleanup.available_at, cleanup.created_at, cleanup.provider, cleanup.sandbox_id, cleanup.routing_domain_key
@@ -13003,6 +13351,11 @@ export async function claimPostgresSchedulerSandboxCleanupJobs(
13003
13351
  AND ($5::text[] IS NULL OR cleanup.provider = ANY($5::text[]))
13004
13352
  AND ($8::text IS NULL OR cleanup.run_id = $8)
13005
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
+ ))
13006
13359
  AND NOT ${protectedDetachedSandboxSql({ runId: 'cleanup.run_id', provider: 'cleanup.provider', sandboxId: 'cleanup.sandbox_id', routingDomain: 'cleanup.routing_domain' }, options, true)}
13007
13360
  ORDER BY
13008
13361
  CASE WHEN cleanup.diagnostic_json IS NOT NULL THEN 0 ELSE 1 END ASC,
@@ -13031,6 +13384,7 @@ export async function claimPostgresSchedulerSandboxCleanupJobs(
13031
13384
  target.run_id,
13032
13385
  target.attempt,
13033
13386
  target.environment,
13387
+ target.status,
13034
13388
  target.routing_domain,
13035
13389
  target.attempt_count,
13036
13390
  target.failure_count,
@@ -13106,20 +13460,33 @@ export async function claimPostgresSchedulerSandboxCleanupJobs(
13106
13460
  RuntimeSandboxOperationState.Live,
13107
13461
  input.runId ?? null,
13108
13462
  input.throughAttempt ?? null,
13463
+ input.exactResource?.provider ?? null,
13464
+ input.exactResource?.sandboxId ?? null,
13465
+ input.exactResource?.routingDomain ?? null,
13466
+ input.exactResource?.attempt ?? null,
13109
13467
  ],
13110
13468
  );
13111
- return claimed.rows.map((row) => ({
13112
- provider: row.provider,
13113
- sandboxId: row.sandbox_id,
13114
- runId: row.run_id,
13115
- attempt: row.attempt,
13116
- environment: row.environment,
13117
- routingDomain: row.routing_domain,
13118
- attemptCount: row.attempt_count,
13119
- failureCount: row.failure_count,
13120
- runStatusAtClaim: row.terminal_status,
13121
- diagnostic: row.diagnostic_json,
13122
- }));
13469
+ return claimed.rows.map((row) => {
13470
+ const status = readSandboxCleanupJobStatus(row.status);
13471
+ if (status !== SandboxCleanupJobStatus.Deleting) {
13472
+ throw new Error(
13473
+ `Sandbox cleanup job ${row.sandbox_id} was claimed in ${status} state.`,
13474
+ );
13475
+ }
13476
+ return {
13477
+ status,
13478
+ provider: row.provider,
13479
+ sandboxId: row.sandbox_id,
13480
+ runId: row.run_id,
13481
+ attempt: row.attempt,
13482
+ environment: row.environment,
13483
+ routingDomain: row.routing_domain,
13484
+ attemptCount: row.attempt_count,
13485
+ failureCount: row.failure_count,
13486
+ runStatusAtClaim: row.terminal_status,
13487
+ diagnostic: row.diagnostic_json,
13488
+ };
13489
+ });
13123
13490
  }
13124
13491
 
13125
13492
  /**
@@ -13662,6 +14029,7 @@ export async function retryPostgresSchedulerSandboxCleanupJob(
13662
14029
  claimGeneration: number;
13663
14030
  error: string;
13664
14031
  retryAfterMs: number;
14032
+ confirmationPending?: { code: string };
13665
14033
  },
13666
14034
  options?: Pick<PostgresSchedulerOptions, 'schema'>,
13667
14035
  ): Promise<
@@ -13686,7 +14054,7 @@ export async function retryPostgresSchedulerSandboxCleanupJob(
13686
14054
  available_at = now() + ($4::double precision * interval '1 millisecond'),
13687
14055
  lease_owner = NULL,
13688
14056
  lease_expires_at = NULL,
13689
- last_error = left($5, 2000),
14057
+ last_error = CASE WHEN $8::text IS NULL THEN left($5, 2000) ELSE NULL END,
13690
14058
  updated_at = now()
13691
14059
  WHERE provider = $6
13692
14060
  AND sandbox_id = $1
@@ -13694,7 +14062,23 @@ export async function retryPostgresSchedulerSandboxCleanupJob(
13694
14062
  AND status = 'deleting'
13695
14063
  AND lease_owner = $2
13696
14064
  AND attempt_count = $3
13697
- 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
13698
14082
  )
13699
14083
  SELECT CASE
13700
14084
  WHEN EXISTS (SELECT 1 FROM retried) THEN 'retry_scheduled'
@@ -13711,6 +14095,7 @@ export async function retryPostgresSchedulerSandboxCleanupJob(
13711
14095
  input.error,
13712
14096
  input.provider ?? 'daytona',
13713
14097
  input.routingDomain?.trim() || null,
14098
+ input.confirmationPending?.code ?? null,
13714
14099
  ],
13715
14100
  );
13716
14101
  const outcome = retried.rows[0]?.outcome;
@@ -15354,6 +15739,12 @@ export async function cancelPostgresSchedulerRun(
15354
15739
  absurdTaskId: string;
15355
15740
  engineTaskTable: string | null;
15356
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 };
15357
15748
  /**
15358
15749
  * Optional control-plane ownership for the oldest pending causal fact.
15359
15750
  * Cancellation makes the remaining prefix due without sharing this lease
@@ -15370,6 +15761,24 @@ export async function cancelPostgresSchedulerRun(
15370
15761
  Math.min(300, Math.floor(input.outboxLease?.leaseSeconds ?? 15)),
15371
15762
  );
15372
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
+ : '';
15373
15782
  const strandedEligibility = strandedFence
15374
15783
  ? `AND target.status = 'queued'
15375
15784
  AND target.launch_json->>'absurdReleaseId' = $8
@@ -15405,6 +15814,7 @@ export async function cancelPostgresSchedulerRun(
15405
15814
  WHERE target.run_id = $1
15406
15815
  AND target.status IN ('queued', 'running', 'waiting')
15407
15816
  ${strandedEligibility}
15817
+ ${createdEligibility}
15408
15818
  RETURNING target.run_id, target.launch_json
15409
15819
  ),
15410
15820
  cancelled_attempts AS (
@@ -15580,6 +15990,7 @@ export async function cancelPostgresSchedulerRun(
15580
15990
  ...(strandedFence
15581
15991
  ? [strandedFence.releaseId, strandedFence.absurdTaskId]
15582
15992
  : []),
15993
+ ...(createdFence ? [createdFence.absurdTaskId] : []),
15583
15994
  ],
15584
15995
  );
15585
15996
  if (cancelled.rows.length === 0 && outboxLeaseOwner) {
@@ -19251,6 +19662,13 @@ export async function appendPostgresRunLedgerEvents(
19251
19662
  orgId: string;
19252
19663
  runId: string;
19253
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;
19254
19672
  },
19255
19673
  options?: Pick<PostgresSchedulerOptions, 'schema'>,
19256
19674
  ): Promise<PostgresSchedulerLifecycleOutboxEvent> {
@@ -19269,10 +19687,24 @@ export async function appendPostgresRunLedgerEvents(
19269
19687
  // Stable across a lost response. The complete event identity (including log
19270
19688
  // channel offsets and original timestamps) participates in the digest.
19271
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
+ }
19272
19703
  return appendRunLedgerOutboxFact(
19273
19704
  client,
19274
19705
  {
19275
- ...input,
19706
+ orgId: input.orgId,
19707
+ runId: input.runId,
19276
19708
  eventId,
19277
19709
  eventType: RUN_SCHEDULER_OUTBOX_EVENT_TYPE.runEvents,
19278
19710
  payload,
@@ -19354,7 +19786,117 @@ async function appendRunLedgerOutboxFact(
19354
19786
  return { runId: input.runId, eventId: input.eventId };
19355
19787
  }
19356
19788
 
19357
- 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';
19358
19900
 
19359
19901
  /** Extend only our still-live lease before another bounded transport piece. */
19360
19902
  export async function renewPostgresRunLedgerDelivery(
@@ -22403,6 +22945,8 @@ export function postgresSchedulerInlineCreatedProjectionLease(runId: string): {
22403
22945
  export type RunLedgerOutboxDispatchInput = {
22404
22946
  /** App-owned transport; launch authority and routing still come from the lease. */
22405
22947
  appRuntimeFetch?: typeof fetch;
22948
+ /** The receiver origin `appRuntimeFetch` serves in-process, without ingress. */
22949
+ appRuntimeInProcessOrigin?: string | null;
22406
22950
  /** Dedicated bounded checkout for indexing; claims/ACKs use withClient. */
22407
22951
  withObservabilityClient?: RunLedgerOutboxWithClient;
22408
22952
 
@@ -22585,6 +23129,7 @@ type RunLedgerOutboxAuthorityScope = {
22585
23129
  runtimeApi: WorkerRuntimeApiContext & {
22586
23130
  refreshExecutorToken?: () => Promise<string>;
22587
23131
  invalidateExecutorToken?: () => void;
23132
+ resolveRetainedPipelineGraphs?: () => Promise<true | undefined>;
22588
23133
  };
22589
23134
  expiresAtMs: number | null;
22590
23135
  } | null;
@@ -23743,7 +24288,14 @@ async function dispatchRunLedgerOutboxBatchWithScope(
23743
24288
  runtimeApi = {
23744
24289
  ...resolvedRuntimeApi,
23745
24290
  ...(tokenAuthority === 'local_mint' && input.appRuntimeFetch
23746
- ? { 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
+ }
23747
24299
  : {}),
23748
24300
  ...(gatewayRuntimeApi && input.runtimeApi
23749
24301
  ? {
@@ -23994,7 +24546,11 @@ async function dispatchRunLedgerOutboxBatchWithScope(
23994
24546
  // its snapshot. Retain that mutation as its own exact delivery.
23995
24547
  if (first.eventType === RUN_SCHEDULER_OUTBOX_EVENT_TYPE.runCreated) {
23996
24548
  await renewDelivery();
23997
- await projectPostgresSchedulerCreatedEvent(runtimeApi, first);
24549
+ await projectPostgresSchedulerCreatedEvent(
24550
+ runtimeApi,
24551
+ first,
24552
+ gatewayRuntimeApi?.resolveRetainedPipelineGraphs,
24553
+ );
23998
24554
  } else if (
23999
24555
  first.eventType === RUN_SCHEDULER_OUTBOX_EVENT_TYPE.runStarted
24000
24556
  ) {
@@ -24640,9 +25196,85 @@ async function acknowledgeRunLedgerPrefixWithContinuation(
24640
25196
  });
24641
25197
  }
24642
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
+
24643
25274
  async function projectPostgresSchedulerCreatedEvent(
24644
25275
  runtimeApi: WorkerRuntimeApiContext,
24645
25276
  event: PostgresSchedulerOutboxEvent,
25277
+ resolveRetainedPipelineGraphs?: () => Promise<true | undefined>,
24646
25278
  ): Promise<void> {
24647
25279
  event = { ...event, payload: hydrateRetainedPlayPipelines(event.payload) };
24648
25280
  const value = (key: string) => stringPayloadField(event.payload, key);
@@ -24658,7 +25290,10 @@ async function projectPostgresSchedulerCreatedEvent(
24658
25290
  const inputSha256 = value('inputSha256');
24659
25291
  const replayedFromRunId = value('replayedFromRunId');
24660
25292
  const asyncAncestryPlayIds = raw('asyncAncestryPlayIds');
24661
- await projectRunCreatedViaAppRuntime(runtimeApi, {
25293
+ const staticPipeline = raw('staticPipeline');
25294
+ const request = (pipelineSource: {
25295
+ retainedPipelineGraph?: unknown;
25296
+ }): Parameters<typeof projectRunCreatedViaAppRuntime>[1] => ({
24662
25297
  deliveryLeaseOwner: event.leaseOwner ?? undefined,
24663
25298
  idempotencyKey: buildRunLedgerStartIdempotencyKey({
24664
25299
  runId: event.runId,
@@ -24715,10 +25350,7 @@ async function projectPostgresSchedulerCreatedEvent(
24715
25350
  runtimeWorkflowName: value('runtimeWorkflowName'),
24716
25351
  runtimeHarnessWorkerName: value('runtimeHarnessWorkerName'),
24717
25352
  maxCreditsPerRun: number('maxCreditsPerRun'),
24718
- ...retainedPlayPipelineFields(
24719
- raw('staticPipeline'),
24720
- event.payload as { retainedPipelineGraph?: unknown },
24721
- ),
25353
+ ...retainedPlayPipelineFields(staticPipeline, pipelineSource),
24722
25354
  source: sourcePayloadField(event.payload, 'source'),
24723
25355
  ...(triggerSource === 'api' ||
24724
25356
  triggerSource === 'webhook' ||
@@ -24738,6 +25370,16 @@ async function projectPostgresSchedulerCreatedEvent(
24738
25370
  ? { inputSummary: inputSummary as Record<string, unknown> }
24739
25371
  : {}),
24740
25372
  });
25373
+ await projectRunCreatedViaAppRuntime(
25374
+ runtimeApi,
25375
+ await fitRunCreatedRequest({
25376
+ runtimeApi,
25377
+ resolveRetainedPipelineGraphs,
25378
+ payload: event.payload,
25379
+ staticPipeline,
25380
+ request,
25381
+ }),
25382
+ );
24741
25383
  }
24742
25384
 
24743
25385
  async function projectPostgresSchedulerStartEvent(
@@ -24868,6 +25510,7 @@ async function resolvePostgresSchedulerRuntimeApiForRun(
24868
25510
  WorkerRuntimeApiContext & {
24869
25511
  refreshExecutorToken?: () => Promise<string>;
24870
25512
  invalidateExecutorToken?: () => void;
25513
+ resolveRetainedPipelineGraphs?: () => Promise<true | undefined>;
24871
25514
  }
24872
25515
  > {
24873
25516
  const launch = parseRunLedgerDispatchLaunch(launchJson);
@@ -24890,6 +25533,12 @@ async function resolvePostgresSchedulerRuntimeApiForRun(
24890
25533
  }
24891
25534
  let executorToken: string;
24892
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;
24893
25542
  let refreshExecutorToken: (() => Promise<string>) | undefined;
24894
25543
  let invalidateExecutorToken: (() => void) | undefined;
24895
25544
  if (tokenAuthority === 'local_mint') {
@@ -24934,6 +25583,11 @@ async function resolvePostgresSchedulerRuntimeApiForRun(
24934
25583
  refreshExecutorToken = async () =>
24935
25584
  (await requestRunLedgerDispatchToken(dispatchRequest, true))
24936
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;
24937
25591
  } else {
24938
25592
  const dispatchAuthority =
24939
25593
  await requestRunLedgerDispatchToken(dispatchRequest);
@@ -24955,6 +25609,7 @@ async function resolvePostgresSchedulerRuntimeApiForRun(
24955
25609
  executorToken = dispatchAuthority.executorToken;
24956
25610
  runLedgerIngressPrefixBatching =
24957
25611
  dispatchAuthority.runLedgerIngressPrefixBatching;
25612
+ retainedPipelineGraphs = dispatchAuthority.retainedPipelineGraphs;
24958
25613
  }
24959
25614
  }
24960
25615
  // A mutable source can seal array pages after this prefix was claimed.
@@ -24973,6 +25628,8 @@ async function resolvePostgresSchedulerRuntimeApiForRun(
24973
25628
  ...(runLedgerIngressPrefixBatching
24974
25629
  ? { runLedgerIngressPrefixBatching }
24975
25630
  : {}),
25631
+ ...(retainedPipelineGraphs ? { retainedPipelineGraphs } : {}),
25632
+ ...(resolveRetainedPipelineGraphs ? { resolveRetainedPipelineGraphs } : {}),
24976
25633
  vercelProtectionBypassToken: launch.vercelProtectionBypassToken ?? null,
24977
25634
  ...(refreshExecutorToken ? { refreshExecutorToken } : {}),
24978
25635
  ...(invalidateExecutorToken ? { invalidateExecutorToken } : {}),
@@ -25188,7 +25845,12 @@ const RUN_LEDGER_DISPATCH_TOKEN_CACHE_MS = 30_000;
25188
25845
  const RUN_LEDGER_DISPATCH_TOKEN_CACHE_ENTRIES = 256;
25189
25846
  const runLedgerDispatchTokens = new Map<
25190
25847
  string,
25191
- { token: string; expiresAt: number; runLedgerIngressPrefixBatching?: true }
25848
+ {
25849
+ token: string;
25850
+ expiresAt: number;
25851
+ runLedgerIngressPrefixBatching?: true;
25852
+ retainedPipelineGraphs?: true;
25853
+ }
25192
25854
  >();
25193
25855
 
25194
25856
  async function requestRunLedgerDispatchToken(
@@ -25206,6 +25868,7 @@ async function requestRunLedgerDispatchToken(
25206
25868
  reused: boolean;
25207
25869
  cacheKey: string;
25208
25870
  runLedgerIngressPrefixBatching?: true;
25871
+ retainedPipelineGraphs?: true;
25209
25872
  /** Present only when this call made the request (never for a reused token). */
25210
25873
  responseTrace?: RunLedgerDispatchResponseTrace;
25211
25874
  }> {
@@ -25240,6 +25903,9 @@ async function requestRunLedgerDispatchToken(
25240
25903
  ...(cached.runLedgerIngressPrefixBatching
25241
25904
  ? { runLedgerIngressPrefixBatching: true as const }
25242
25905
  : {}),
25906
+ ...(cached.retainedPipelineGraphs
25907
+ ? { retainedPipelineGraphs: true as const }
25908
+ : {}),
25243
25909
  };
25244
25910
  runLedgerDispatchTokens.delete(cacheKey);
25245
25911
  const url = `${input.receiverBaseUrl.replace(/\/$/, '')}/api/v2/internal/play-runtime/run-ledger-dispatch-token`;
@@ -25279,6 +25945,7 @@ async function requestRunLedgerDispatchToken(
25279
25945
  return JSON.parse(responseText) as {
25280
25946
  executorToken?: unknown;
25281
25947
  runLedgerIngressPrefixBatching?: unknown;
25948
+ retainedPipelineGraphs?: unknown;
25282
25949
  error?: unknown;
25283
25950
  code?: unknown;
25284
25951
  retryable?: unknown;
@@ -25340,6 +26007,9 @@ async function requestRunLedgerDispatchToken(
25340
26007
  ...(reusablePrefix
25341
26008
  ? { runLedgerIngressPrefixBatching: true as const }
25342
26009
  : {}),
26010
+ ...(body.retainedPipelineGraphs === true
26011
+ ? { retainedPipelineGraphs: true as const }
26012
+ : {}),
25343
26013
  });
25344
26014
  while (
25345
26015
  runLedgerDispatchTokens.size > RUN_LEDGER_DISPATCH_TOKEN_CACHE_ENTRIES
@@ -25363,6 +26033,9 @@ async function requestRunLedgerDispatchToken(
25363
26033
  ...(body.runLedgerIngressPrefixBatching === true
25364
26034
  ? { runLedgerIngressPrefixBatching: true as const }
25365
26035
  : {}),
26036
+ ...(body.retainedPipelineGraphs === true
26037
+ ? { retainedPipelineGraphs: true as const }
26038
+ : {}),
25366
26039
  responseTrace: {
25367
26040
  platformRequestId: readRuntimeApiDiagnosticHeader(
25368
26041
  response.headers,