deepline 0.3.484 → 0.3.486

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 (210) 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/ledger-safe-payload.ts +8 -4
  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 +139 -67
  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 +206 -7
  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/play-run-recovery.ts +12 -1
  47. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres-progress.ts +28 -9
  48. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres-rate-scope.ts +44 -15
  49. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres-rate-state.ts +60 -11
  50. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres.ts +656 -64
  51. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/run-ledger-outbox-recovery.ts +6 -1
  52. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-event-search.ts +17 -0
  53. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-sandbox-capacity.ts +25 -33
  54. package/dist/bundling-sources/shared_libs/play-runtime/suspension.ts +12 -0
  55. package/dist/bundling-sources/shared_libs/play-runtime/test-runtime-seams.ts +21 -0
  56. package/dist/bundling-sources/shared_libs/plays/authoring-contract.ts +1 -1
  57. package/dist/bundling-sources/shared_libs/plays/source-authoring-edition.ts +1 -1
  58. package/dist/cli/auth-ARKH3OAU.js +43 -0
  59. package/dist/cli/{auth-EBFOTF7X.mjs → auth-B4DJO4FB.mjs} +5 -5
  60. package/dist/cli/{billing-G2G3EF3I.js → billing-GDWAMARK.js} +80 -80
  61. package/dist/cli/{billing-2ZOIMW5V.mjs → billing-IIQ3VNXU.mjs} +7 -7
  62. package/dist/cli/{chunk-YWC5AN26.mjs → chunk-2DVFQYPG.mjs} +62 -34
  63. package/dist/cli/{chunk-UWOY74RU.js → chunk-5DUP4ZUE.js} +21 -21
  64. package/dist/cli/{chunk-EACX7QXO.mjs → chunk-5QYZ4MEW.mjs} +2 -2
  65. package/dist/cli/{chunk-HEI3BWIV.mjs → chunk-5RLVCOKH.mjs} +1 -1
  66. package/dist/cli/{chunk-TIRSKEZH.mjs → chunk-5Y7LLRWO.mjs} +1 -1
  67. package/dist/cli/{chunk-IXWQOVNW.js → chunk-5YILTBF7.js} +87 -76
  68. package/dist/cli/{chunk-OHKKDPA5.js → chunk-7FTQKEZ6.js} +13 -13
  69. package/dist/cli/{chunk-TN2GW57M.mjs → chunk-A456YVDE.mjs} +1 -1
  70. package/dist/cli/{chunk-GVAENVIG.js → chunk-AUQQVDAB.js} +110 -21
  71. package/dist/cli/{chunk-3XQIVEAT.js → chunk-BJL7RYQN.js} +3 -3
  72. package/dist/cli/{chunk-2AWYJXBX.js → chunk-BNB2RK4L.js} +5 -5
  73. package/dist/cli/{chunk-U7IJAGWB.js → chunk-BYEDI5PM.js} +7 -7
  74. package/dist/cli/{chunk-RLLEH2SP.js → chunk-C4GFBB52.js} +26 -26
  75. package/dist/cli/{chunk-AK7UKQ5R.js → chunk-CSBMKHTV.js} +5 -5
  76. package/dist/cli/{chunk-UT4YMA2N.js → chunk-DFHS5XVZ.js} +5 -4
  77. package/dist/cli/{chunk-XZXIWPT3.mjs → chunk-F3G2HAUQ.mjs} +1 -1
  78. package/dist/cli/{chunk-C62NI2X6.js → chunk-FCAKAW6S.js} +5 -5
  79. package/dist/cli/{chunk-AF7MOUZP.mjs → chunk-FGPJXQEJ.mjs} +2 -2
  80. package/dist/cli/chunk-FSCOYTRV.js +42 -0
  81. package/dist/cli/{chunk-6GRZEYSG.js → chunk-GCEUOHJW.js} +7 -7
  82. package/dist/cli/{chunk-SD7QWZTV.mjs → chunk-INW22YP7.mjs} +1 -1
  83. package/dist/cli/{chunk-OWUZKXE7.mjs → chunk-J7EENGKJ.mjs} +1 -1
  84. package/dist/cli/{chunk-QIDDTIVZ.js → chunk-KPIVQFXZ.js} +322 -294
  85. package/dist/cli/{chunk-4IOY2SCQ.js → chunk-LOX3BISD.js} +4 -4
  86. package/dist/cli/{chunk-WYUCDLVR.mjs → chunk-MJ56FCYU.mjs} +2 -1
  87. package/dist/cli/{chunk-DBJ62RAO.js → chunk-NSPMJLYA.js} +3 -3
  88. package/dist/cli/{chunk-HNRELVCS.mjs → chunk-ONONSV2Q.mjs} +96 -7
  89. package/dist/cli/{chunk-PU52JXKA.mjs → chunk-P6KGYOCM.mjs} +13 -4
  90. package/dist/cli/{chunk-VEVGM6B5.js → chunk-PCYZDTDC.js} +14 -14
  91. package/dist/cli/{chunk-NW4QJE54.js → chunk-PHWFY26F.js} +2 -2
  92. package/dist/cli/{chunk-LTZXLYKE.mjs → chunk-PKOFEHZL.mjs} +93 -17
  93. package/dist/cli/{chunk-7K5CWKKZ.mjs → chunk-PQHDZHZG.mjs} +2 -2
  94. package/dist/cli/{chunk-UKM74PAA.js → chunk-PTM3QRAT.js} +37 -37
  95. package/dist/cli/{chunk-YGN77QA5.mjs → chunk-PV7AYBKQ.mjs} +3 -3
  96. package/dist/cli/{chunk-4OEOM6GP.mjs → chunk-PYDHVRAF.mjs} +5 -5
  97. package/dist/cli/{chunk-FRD5WFT4.js → chunk-QD22TY33.js} +323 -247
  98. package/dist/cli/{chunk-5KNRQWHE.js → chunk-QEQ3KHVY.js} +3 -3
  99. package/dist/cli/{chunk-KGOC6HGI.js → chunk-S5EYODEG.js} +53 -53
  100. package/dist/cli/{chunk-FQK7BULS.js → chunk-S7OILDJH.js} +1 -1
  101. package/dist/cli/{chunk-TRLDJNVE.mjs → chunk-T3Q6BMVH.mjs} +1 -1
  102. package/dist/cli/{chunk-5K5CAND4.mjs → chunk-TBE2K5W4.mjs} +4 -4
  103. package/dist/cli/{chunk-YHA3EV3I.mjs → chunk-TE2QT2MX.mjs} +15 -4
  104. package/dist/cli/{chunk-ZOKM7DVA.js → chunk-TNHY3ATN.js} +8 -8
  105. package/dist/cli/{chunk-4OVHIWE7.mjs → chunk-U23L57VU.mjs} +2 -2
  106. package/dist/cli/{chunk-5GOG5ZGC.mjs → chunk-UEJLWUJ3.mjs} +2 -2
  107. package/dist/cli/{chunk-6NPWXE32.mjs → chunk-VJLL5XIP.mjs} +1 -1
  108. package/dist/cli/{chunk-WXRM3UC6.mjs → chunk-WCOJH4W4.mjs} +3 -3
  109. package/dist/cli/{chunk-4SFC2XUF.mjs → chunk-XAZWUW6I.mjs} +5 -5
  110. package/dist/cli/{chunk-ZM2YPJQJ.js → chunk-XK5DMLZE.js} +5 -1
  111. package/dist/cli/{chunk-LJ5747UC.mjs → chunk-XRDXNAAY.mjs} +5 -1
  112. package/dist/cli/{chunk-V7JCMBLU.mjs → chunk-YIKHNZ6B.mjs} +4 -4
  113. package/dist/cli/{chunk-M4PG7FGC.js → chunk-YS6JOYYS.js} +2 -2
  114. package/dist/cli/{chunk-DEXSQGXB.mjs → chunk-ZMRZ3BXG.mjs} +5 -5
  115. package/dist/cli/{chunk-CYWBAV5H.js → chunk-ZQI26KE4.js} +16 -16
  116. package/dist/cli/{csv-S3CHUKI6.js → csv-3PSMPZM5.js} +13 -13
  117. package/dist/cli/{csv-NLWVWD3H.mjs → csv-LFCT3WQ4.mjs} +4 -4
  118. package/dist/cli/{db-OGRPAEEM.mjs → db-HULKVAMU.mjs} +7 -7
  119. package/dist/cli/{db-WBSKMMOH.js → db-R7I2PPTV.js} +28 -28
  120. package/dist/cli/{describe-FAD3Z7LN.mjs → describe-D55V42LH.mjs} +21 -21
  121. package/dist/cli/describe-H47BLOEP.js +49 -0
  122. package/dist/cli/describe-core.d.mts +3 -3
  123. package/dist/cli/describe-core.d.ts +3 -3
  124. package/dist/cli/describe-core.js +4 -4
  125. package/dist/cli/describe-core.mjs +3 -3
  126. package/dist/cli/{executions-LYCL344R.mjs → executions-ICVVOYVG.mjs} +7 -7
  127. package/dist/cli/{executions-SOAZHCY4.js → executions-O37FN2SK.js} +9 -9
  128. package/dist/cli/{feedback-AVF6V7SV.mjs → feedback-3K3QPGCQ.mjs} +4 -4
  129. package/dist/cli/{feedback-OROUPUNJ.js → feedback-MAZQ7C6S.js} +8 -8
  130. package/dist/cli/{git-J5N5M57H.mjs → git-2MMD5KJS.mjs} +5 -5
  131. package/dist/cli/git-RQ2XLFYZ.js +25 -0
  132. package/dist/cli/index.js +142 -139
  133. package/dist/cli/index.mjs +45 -42
  134. package/dist/cli/{legacy-noops-QAQMZMEG.js → legacy-noops-2OX2Y3Y2.js} +8 -8
  135. package/dist/cli/{legacy-noops-ENRRM7BL.mjs → legacy-noops-VLSWJ6VE.mjs} +5 -5
  136. package/dist/cli/{monitors-CKQ65WRL.mjs → monitors-2NODQQWG.mjs} +8 -8
  137. package/dist/cli/{monitors-SFMQ5LFR.js → monitors-UCSV5FOR.js} +92 -92
  138. package/dist/cli/{org-3UNTDLT2.js → org-4YY73VTW.js} +73 -73
  139. package/dist/cli/{org-K4UIEU5P.mjs → org-W7AUQCDE.mjs} +7 -7
  140. package/dist/cli/{pages-NKZTGB4C.js → pages-FBZEUMXK.js} +18 -18
  141. package/dist/cli/{pages-6GPGBIAH.mjs → pages-ZRP7U5PO.mjs} +7 -7
  142. package/dist/cli/{play-BDEADESI.js → play-LFCTQJXA.js} +858 -632
  143. package/dist/cli/{play-62BEE7IX.mjs → play-XF2BSGTP.mjs} +372 -146
  144. package/dist/cli/{providers-SXGP44GH.js → providers-5456JNHP.js} +10 -10
  145. package/dist/cli/{providers-X3CUWMFP.mjs → providers-SICAPKGI.mjs} +7 -7
  146. package/dist/cli/{quickstart-XQ4426M4.js → quickstart-2KLLIPIU.js} +6 -6
  147. package/dist/cli/{quickstart-7LN22BKX.mjs → quickstart-IBVG6GX6.mjs} +4 -4
  148. package/dist/cli/{run-PBJ4ZJ4W.js → run-DNLDGJRC.js} +41 -41
  149. package/dist/cli/{run-XXSN3B5A.mjs → run-XPIZIQ7H.mjs} +26 -26
  150. package/dist/cli/search-2KQA65LH.js +32 -0
  151. package/dist/cli/{search-M75VMADD.mjs → search-PW22AEAL.mjs} +8 -8
  152. package/dist/cli/{search-output-F6HCFYEI.js → search-output-H6F6QMRF.js} +22 -16
  153. package/dist/cli/{search-output-NUQAKWDM.mjs → search-output-JFD53H2N.mjs} +14 -8
  154. package/dist/cli/{secrets-J2H6V33R.mjs → secrets-542CTZRZ.mjs} +7 -7
  155. package/dist/cli/{secrets-LRYY4QPE.js → secrets-LCCRRAN7.js} +16 -16
  156. package/dist/cli/{sessions-YPF62CZE.js → sessions-5FYDQE3N.js} +6 -6
  157. package/dist/cli/{sessions-IMT336UV.mjs → sessions-CALLS2XD.mjs} +5 -5
  158. package/dist/cli/{settings-PDWVQIGH.mjs → settings-GSKPHUEC.mjs} +12 -12
  159. package/dist/cli/{settings-35YYC5WA.js → settings-ORGKOBP6.js} +79 -79
  160. package/dist/cli/{setup-UR7GOR7H.js → setup-4BUWJKB6.js} +47 -47
  161. package/dist/cli/{setup-DG5DISSE.mjs → setup-V57GHVAF.mjs} +9 -9
  162. package/dist/cli/skills-KYZPPGSN.js +33 -0
  163. package/dist/cli/{skills-U6NJD5J7.mjs → skills-NGLCFQFT.mjs} +7 -7
  164. package/dist/cli/tools-AFYXUEMD.js +56 -0
  165. package/dist/cli/{tools-2HGEOELR.mjs → tools-G2YNCFNX.mjs} +19 -19
  166. package/dist/cli/{update-FRAYBAHK.mjs → update-IZ3Z5T5C.mjs} +9 -9
  167. package/dist/cli/update-T6JJ7A3K.js +33 -0
  168. package/dist/cli/{workflow-JKKLOMBX.js → workflow-7AHST2XV.js} +18 -18
  169. package/dist/cli/{workflow-DDKVTF36.mjs → workflow-L7ROQIM7.mjs} +8 -8
  170. package/dist/{client-DJ3r8VQJ.d.mts → client-BkbDHRIg.d.mts} +1 -1
  171. package/dist/{client-JPSNljtj.d.ts → client-D3hVHXjK.d.ts} +1 -1
  172. package/dist/{client-core-3SJlNsKU.d.mts → client-core-BZoSMKcY.d.mts} +30 -15
  173. package/dist/{client-core-rCoQ5Xz3.d.ts → client-core-DUdVqO_m.d.ts} +30 -15
  174. package/dist/{compiler-manifest-gkO9ZkVg.d.mts → compiler-manifest-BFTwq1HI.d.mts} +1 -1
  175. package/dist/{compiler-manifest-gkO9ZkVg.d.ts → compiler-manifest-BFTwq1HI.d.ts} +1 -1
  176. package/dist/{errors-Cc92LKH-.d.ts → errors-c3pMsylw.d.ts} +1 -1
  177. package/dist/{errors-CeCCOKSA.d.mts → errors-w31ybrQM.d.mts} +1 -1
  178. package/dist/{index-DJQKdV76.d.ts → index-CQ-15-QL.d.ts} +1 -1
  179. package/dist/{index-DsqWJL3Q.d.mts → index-DvNtxucX.d.mts} +1 -1
  180. package/dist/index.d.mts +7 -7
  181. package/dist/index.d.ts +7 -7
  182. package/dist/index.js +10 -10
  183. package/dist/index.mjs +7 -7
  184. package/dist/install-integrity.json +117 -116
  185. package/dist/plays/bundle-play-file.d.mts +3 -3
  186. package/dist/plays/bundle-play-file.d.ts +3 -3
  187. package/dist/plays/bundle-play-file.mjs +2 -2
  188. package/dist/plays/play-description.d.mts +2 -2
  189. package/dist/plays/play-description.d.ts +2 -2
  190. package/dist/plays/run-request.d.mts +2 -2
  191. package/dist/plays/run-request.d.ts +2 -2
  192. package/dist/plays/run-request.js +12 -2
  193. package/dist/plays/run-request.mjs +11 -1
  194. package/dist/release.d.mts +1 -1
  195. package/dist/release.d.ts +1 -1
  196. package/dist/release.js +2 -2
  197. package/dist/release.mjs +1 -1
  198. package/dist/server.d.mts +4 -4
  199. package/dist/server.d.ts +4 -4
  200. package/dist/server.js +6 -6
  201. package/dist/server.mjs +4 -4
  202. package/package.json +1 -1
  203. package/dist/cli/auth-L5CSV3UO.js +0 -43
  204. package/dist/cli/chunk-KA2LNIUP.js +0 -33
  205. package/dist/cli/describe-UIAYCHWW.js +0 -49
  206. package/dist/cli/git-ATMWC27D.js +0 -25
  207. package/dist/cli/search-IGHLRLBD.js +0 -32
  208. package/dist/cli/skills-4U5WC4MJ.js +0 -33
  209. package/dist/cli/tools-PYJTQVVS.js +0 -56
  210. 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;
@@ -14686,7 +15009,7 @@ export async function completePostgresSchedulerAttempt(
14686
15009
  );
14687
15010
  const terminalLogEntries = (input.terminalLogLines ?? [])
14688
15011
  .map((line, index) => ({
14689
- line: sanitizeTerminalLogBody(line),
15012
+ line: sanitizeLedgerLogLine(line),
14690
15013
  context: input.terminalLogContexts?.[index] ?? null,
14691
15014
  metadata: input.terminalLogMetadata?.[index] ?? null,
14692
15015
  entryId: terminalLogIds?.[index] ?? null,
@@ -15018,7 +15341,7 @@ export async function failPostgresSchedulerAttempt(
15018
15341
  );
15019
15342
  const terminalLogEntries = (input.terminalLogLines ?? [])
15020
15343
  .map((line, index) => ({
15021
- line: sanitizeTerminalLogBody(line),
15344
+ line: sanitizeLedgerLogLine(line),
15022
15345
  context: input.terminalLogContexts?.[index] ?? null,
15023
15346
  metadata: input.terminalLogMetadata?.[index] ?? null,
15024
15347
  entryId: terminalLogIds?.[index] ?? null,
@@ -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) {
@@ -16152,26 +16501,13 @@ function sanitizeTerminalProgressEvents(
16152
16501
  // Invalid values still reach the existing SQL validation unchanged.
16153
16502
  lines: item.lines.map((line) =>
16154
16503
  typeof line === 'string'
16155
- ? sanitizeTerminalLogBody(line) || '(blank log line)'
16504
+ ? sanitizeLedgerLogLine(line) || '(blank log line)'
16156
16505
  : line,
16157
16506
  ),
16158
16507
  };
16159
16508
  });
16160
16509
  }
16161
16510
 
16162
- function sanitizeTerminalLogBody(line: string): string {
16163
- const body = line.trim();
16164
- const runtimeDiagnostic =
16165
- body.startsWith('[runtime.failure_diagnostic] ') ||
16166
- body.startsWith('[runtime.phase_summary] ') ||
16167
- body.startsWith('[runtime.logs] ') ||
16168
- body.startsWith('[runtime.log_transport] ');
16169
- // These runtime records contain machine-readable JSON, already bounded by
16170
- // the terminal transport. Keep it parseable while applying the same redaction.
16171
- // Authored tagged lines retain the ordinary live-ingress line bound.
16172
- return sanitizeLedgerLogLine(body, !runtimeDiagnostic);
16173
- }
16174
-
16175
16511
  /**
16176
16512
  * One error line stating why a run failed. `message` must be the public failure
16177
16513
  * text. The line ID keeps it out of the envelope's position space, where a
@@ -16252,19 +16588,13 @@ function terminalLogProjectionForOutbox(
16252
16588
  .map((line, index) => {
16253
16589
  if (typeof line !== 'string') return null;
16254
16590
  const normalized = readProvenanceTag(line).line.trim();
16255
- // Retain bounded terminal measurement summaries alongside timestamped
16256
- // customer/recovery lines after a detached runner has exited.
16257
- const retained =
16258
- CTX_LOG_TIMESTAMP_PREFIX_RE.test(normalized) ||
16259
- normalized.startsWith('[runtime.failure_diagnostic] ') ||
16260
- normalized.startsWith('[runtime.phase_summary] ') ||
16261
- normalized.startsWith('[runtime.logs] ') ||
16262
- normalized.startsWith('[runtime.log_transport] ');
16263
- if (!retained) return null;
16591
+ // Retain timestamped customer/recovery lines after a detached runner
16592
+ // has exited. Runtime measurements travel as structured stats.
16593
+ if (!CTX_LOG_TIMESTAMP_PREFIX_RE.test(normalized)) return null;
16264
16594
  return {
16265
16595
  // The live API applies this same canonicalization before indexing.
16266
16596
  // Replaying an origin ID must carry that exact redacted, bounded body.
16267
- line: sanitizeTerminalLogBody(line),
16597
+ line: sanitizeLedgerLogLine(line),
16268
16598
  context: normalizePlayLogContext(logContexts?.[index]),
16269
16599
  metadata: normalizePlayLogMetadata(logMetadata?.[index]),
16270
16600
  entryId: logIds?.[index] ?? null,
@@ -19313,6 +19643,13 @@ export async function appendPostgresRunLedgerEvents(
19313
19643
  orgId: string;
19314
19644
  runId: string;
19315
19645
  events: readonly AcceptedPlayRunLedgerEvent[];
19646
+ /**
19647
+ * The attempt whose live progress this batch is. When set, the insert
19648
+ * commits only while that attempt is current and the run is not terminal,
19649
+ * and otherwise throws RunLedgerProgressAttemptSupersededError. Terminal
19650
+ * finalizes and replays omit it: they are designed to land after the end.
19651
+ */
19652
+ progressAttempt?: number;
19316
19653
  },
19317
19654
  options?: Pick<PostgresSchedulerOptions, 'schema'>,
19318
19655
  ): Promise<PostgresSchedulerLifecycleOutboxEvent> {
@@ -19331,10 +19668,24 @@ export async function appendPostgresRunLedgerEvents(
19331
19668
  // Stable across a lost response. The complete event identity (including log
19332
19669
  // channel offsets and original timestamps) participates in the digest.
19333
19670
  const eventId = `run-events:${input.runId}:${createHash('sha256').update(payload).digest('hex')}`;
19671
+ if (input.progressAttempt !== undefined) {
19672
+ return appendRunLedgerLiveProgressFact(
19673
+ client,
19674
+ {
19675
+ orgId: input.orgId,
19676
+ runId: input.runId,
19677
+ attempt: input.progressAttempt,
19678
+ eventId,
19679
+ payload,
19680
+ },
19681
+ options,
19682
+ );
19683
+ }
19334
19684
  return appendRunLedgerOutboxFact(
19335
19685
  client,
19336
19686
  {
19337
- ...input,
19687
+ orgId: input.orgId,
19688
+ runId: input.runId,
19338
19689
  eventId,
19339
19690
  eventType: RUN_SCHEDULER_OUTBOX_EVENT_TYPE.runEvents,
19340
19691
  payload,
@@ -19416,7 +19767,117 @@ async function appendRunLedgerOutboxFact(
19416
19767
  return { runId: input.runId, eventId: input.eventId };
19417
19768
  }
19418
19769
 
19419
- export { RunLedgerProjectionLeaseLostError } from '../run-ledger-projection-contract';
19770
+ /**
19771
+ * Live progress intake, fenced at commit time.
19772
+ *
19773
+ * The gateway checks the attempt before publishing, but the publish crosses a
19774
+ * network hop and the terminal path deliberately does not wait for it. A batch
19775
+ * built before a cancel, or delayed past the terminal, used to be stored after
19776
+ * the run closed, where the event-search projection quarantined its lane
19777
+ * (KAR-160 group B). This mirrors acceptRunnerTerminal's commit-time fence.
19778
+ *
19779
+ * The first statement takes the run row lock that attempt assignment,
19780
+ * cancellation and terminal settlement all take before changing the run or
19781
+ * its attempts. The second statement starts after that lock, so its snapshot
19782
+ * sees everything they committed while it waited, and decides:
19783
+ *
19784
+ * - the run is not terminal;
19785
+ * - the attempt is active, no newer attempt exists, and it has not recorded
19786
+ * its runner result (its sealed tail carries any in-flight batch).
19787
+ *
19788
+ * The runner-result writer locks only the attempt row. A result committing
19789
+ * after the decision is concurrent with this insert; the run cannot close
19790
+ * until this transaction releases the run lock, so nothing lands after it.
19791
+ * A retried batch whose first insert already committed is still accepted.
19792
+ */
19793
+ async function appendRunLedgerLiveProgressFact(
19794
+ client: PostgresSchedulerQueryClient,
19795
+ input: {
19796
+ orgId: string;
19797
+ runId: string;
19798
+ attempt: number;
19799
+ eventId: string;
19800
+ payload: string;
19801
+ },
19802
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
19803
+ ): Promise<PostgresSchedulerLifecycleOutboxEvent> {
19804
+ if (!Number.isSafeInteger(input.attempt) || input.attempt < 0) {
19805
+ throw new Error(
19806
+ 'Run Ledger progress attempt must be a nonnegative integer.',
19807
+ );
19808
+ }
19809
+ await client.query('BEGIN');
19810
+ let accepted: boolean;
19811
+ try {
19812
+ const run = await client.query<{ run_id: string }>(
19813
+ `
19814
+ SELECT run_id FROM ${tableName('runs', options)}
19815
+ WHERE run_id = $1 AND org_id = $2
19816
+ FOR NO KEY UPDATE
19817
+ `,
19818
+ [input.runId, input.orgId],
19819
+ );
19820
+ if (run.rows.length !== 1) {
19821
+ throw new Error(
19822
+ 'Run Ledger ingress run is missing or outside the organization scope.',
19823
+ );
19824
+ }
19825
+ const result = await client.query<{ accepted: boolean }>(
19826
+ `
19827
+ WITH fenced AS MATERIALIZED (
19828
+ SELECT run.run_id FROM ${tableName('runs', options)} AS run
19829
+ WHERE run.run_id = $1
19830
+ AND run.status IN ('queued', 'running', 'waiting')
19831
+ AND EXISTS (
19832
+ SELECT 1 FROM ${tableName('attempts', options)} AS current_attempt
19833
+ WHERE current_attempt.run_id = $1
19834
+ AND current_attempt.attempt = $5
19835
+ AND current_attempt.status IN ('claimed', 'running', 'waiting')
19836
+ AND (
19837
+ current_attempt.runner_result_json IS NULL
19838
+ OR current_attempt.runner_result_json = 'null'::jsonb
19839
+ )
19840
+ )
19841
+ AND NOT EXISTS (
19842
+ SELECT 1 FROM ${tableName('attempts', options)} AS newer_attempt
19843
+ WHERE newer_attempt.run_id = $1 AND newer_attempt.attempt > $5
19844
+ )
19845
+ ), recorded AS (
19846
+ INSERT INTO ${tableName('outbox', options)}
19847
+ (event_id, run_id, event_type, payload_json, created_at)
19848
+ SELECT $2, run_id, $4, $3::jsonb,
19849
+ ${causalOutboxCreatedAt('fenced.run_id', options)}
19850
+ FROM fenced
19851
+ ON CONFLICT (event_id) DO NOTHING
19852
+ )
19853
+ SELECT EXISTS (SELECT 1 FROM fenced)
19854
+ OR EXISTS (
19855
+ SELECT 1 FROM ${tableName('outbox', options)}
19856
+ WHERE event_id = $2
19857
+ ) AS accepted
19858
+ `,
19859
+ [
19860
+ input.runId,
19861
+ input.eventId,
19862
+ input.payload,
19863
+ RUN_SCHEDULER_OUTBOX_EVENT_TYPE.runEvents,
19864
+ input.attempt,
19865
+ ],
19866
+ );
19867
+ accepted = result.rows[0]?.accepted === true;
19868
+ await client.query('COMMIT');
19869
+ } catch (error) {
19870
+ await client.query('ROLLBACK');
19871
+ throw error;
19872
+ }
19873
+ if (!accepted) throw new RunLedgerProgressAttemptSupersededError();
19874
+ return { runId: input.runId, eventId: input.eventId };
19875
+ }
19876
+
19877
+ export {
19878
+ RunLedgerProgressAttemptSupersededError,
19879
+ RunLedgerProjectionLeaseLostError,
19880
+ } from '../run-ledger-projection-contract';
19420
19881
 
19421
19882
  /** Extend only our still-live lease before another bounded transport piece. */
19422
19883
  export async function renewPostgresRunLedgerDelivery(
@@ -22465,6 +22926,8 @@ export function postgresSchedulerInlineCreatedProjectionLease(runId: string): {
22465
22926
  export type RunLedgerOutboxDispatchInput = {
22466
22927
  /** App-owned transport; launch authority and routing still come from the lease. */
22467
22928
  appRuntimeFetch?: typeof fetch;
22929
+ /** The receiver origin `appRuntimeFetch` serves in-process, without ingress. */
22930
+ appRuntimeInProcessOrigin?: string | null;
22468
22931
  /** Dedicated bounded checkout for indexing; claims/ACKs use withClient. */
22469
22932
  withObservabilityClient?: RunLedgerOutboxWithClient;
22470
22933
 
@@ -22647,6 +23110,7 @@ type RunLedgerOutboxAuthorityScope = {
22647
23110
  runtimeApi: WorkerRuntimeApiContext & {
22648
23111
  refreshExecutorToken?: () => Promise<string>;
22649
23112
  invalidateExecutorToken?: () => void;
23113
+ resolveRetainedPipelineGraphs?: () => Promise<true | undefined>;
22650
23114
  };
22651
23115
  expiresAtMs: number | null;
22652
23116
  } | null;
@@ -23805,7 +24269,14 @@ async function dispatchRunLedgerOutboxBatchWithScope(
23805
24269
  runtimeApi = {
23806
24270
  ...resolvedRuntimeApi,
23807
24271
  ...(tokenAuthority === 'local_mint' && input.appRuntimeFetch
23808
- ? { fetch: input.appRuntimeFetch }
24272
+ ? {
24273
+ fetch: input.appRuntimeFetch,
24274
+ ...(input.appRuntimeInProcessOrigin &&
24275
+ resolvedRuntimeApi.baseUrl.replace(/\/$/, '') ===
24276
+ input.appRuntimeInProcessOrigin
24277
+ ? { bypassesIngressLimit: true as const }
24278
+ : {}),
24279
+ }
23809
24280
  : {}),
23810
24281
  ...(gatewayRuntimeApi && input.runtimeApi
23811
24282
  ? {
@@ -24056,7 +24527,11 @@ async function dispatchRunLedgerOutboxBatchWithScope(
24056
24527
  // its snapshot. Retain that mutation as its own exact delivery.
24057
24528
  if (first.eventType === RUN_SCHEDULER_OUTBOX_EVENT_TYPE.runCreated) {
24058
24529
  await renewDelivery();
24059
- await projectPostgresSchedulerCreatedEvent(runtimeApi, first);
24530
+ await projectPostgresSchedulerCreatedEvent(
24531
+ runtimeApi,
24532
+ first,
24533
+ gatewayRuntimeApi?.resolveRetainedPipelineGraphs,
24534
+ );
24060
24535
  } else if (
24061
24536
  first.eventType === RUN_SCHEDULER_OUTBOX_EVENT_TYPE.runStarted
24062
24537
  ) {
@@ -24702,9 +25177,85 @@ async function acknowledgeRunLedgerPrefixWithContinuation(
24702
25177
  });
24703
25178
  }
24704
25179
 
25180
+ /** A run.created body the receiver's ingress would refuse. Never resent as-is. */
25181
+ class RunCreatedProjectionTooLargeError extends AppRuntimeApiResponseError {
25182
+ constructor(detail: string) {
25183
+ super({
25184
+ action: 'project_run_created',
25185
+ status: 413,
25186
+ code: 'run_created_too_large',
25187
+ retryable: false,
25188
+ detail,
25189
+ });
25190
+ }
25191
+ }
25192
+
25193
+ /**
25194
+ * Keep run.created within the receiver's request limit, measured over the
25195
+ * whole request body. A request within the limit keeps the pipeline
25196
+ * representation its admission owner selected. An oversized inline pipeline
25197
+ * is sent as the lossless retained graph only when the receiver advertised
25198
+ * graph storage, either on the dispatch-token response that authorized this
25199
+ * delivery or, for a token minted at admission, on one fetched now under the
25200
+ * same outbox lease. Otherwise the projection fails before sending with a
25201
+ * typed code instead of an opaque ingress 413.
25202
+ */
25203
+ async function fitRunCreatedRequest<T extends object>(input: {
25204
+ runtimeApi: WorkerRuntimeApiContext;
25205
+ resolveRetainedPipelineGraphs?: () => Promise<true | undefined>;
25206
+ payload: PostgresSchedulerOutboxEvent['payload'];
25207
+ staticPipeline: unknown;
25208
+ request: (source: { retainedPipelineGraph?: unknown }) => T;
25209
+ }): Promise<T> {
25210
+ // Measure the body the transport sends, which re-encodes a retained graph.
25211
+ const exceedsLimit = (request: T) =>
25212
+ jsonByteLengthUpTo(
25213
+ prepareRetainedPlayPipelinesForTransport({
25214
+ action: 'project_run_created',
25215
+ ...request,
25216
+ }),
25217
+ APP_RUNTIME_REQUEST_BODY_MAX_BYTES,
25218
+ ).exceeded;
25219
+ const source = input.payload as { retainedPipelineGraph?: unknown };
25220
+ const selected = input.request(source);
25221
+ // An in-process receiver has no ingress limit: keep the selected format.
25222
+ if (input.runtimeApi.bypassesIngressLimit === true) return selected;
25223
+ if (!exceedsLimit(selected)) return selected;
25224
+ if (
25225
+ source.retainedPipelineGraph !== undefined ||
25226
+ input.staticPipeline === undefined ||
25227
+ input.staticPipeline === null
25228
+ ) {
25229
+ throw new RunCreatedProjectionTooLargeError(
25230
+ `run.created request exceeds ${APP_RUNTIME_REQUEST_BODY_MAX_BYTES} bytes without an inline pipeline to compact.`,
25231
+ );
25232
+ }
25233
+ const storesGraphs =
25234
+ input.runtimeApi.retainedPipelineGraphs === true ||
25235
+ (await input.resolveRetainedPipelineGraphs?.()) === true;
25236
+ if (!storesGraphs) {
25237
+ throw new RunCreatedProjectionTooLargeError(
25238
+ `run.created request exceeds ${APP_RUNTIME_REQUEST_BODY_MAX_BYTES} bytes and the receiver did not advertise retained pipeline graphs.`,
25239
+ );
25240
+ }
25241
+ const compact = input.request(
25242
+ encodeRetainedPlayPipelines<{
25243
+ staticPipeline: unknown;
25244
+ retainedPipelineGraph?: unknown;
25245
+ }>({ staticPipeline: input.staticPipeline }),
25246
+ );
25247
+ if (exceedsLimit(compact)) {
25248
+ throw new RunCreatedProjectionTooLargeError(
25249
+ `run.created request exceeds ${APP_RUNTIME_REQUEST_BODY_MAX_BYTES} bytes with a retained pipeline graph.`,
25250
+ );
25251
+ }
25252
+ return compact;
25253
+ }
25254
+
24705
25255
  async function projectPostgresSchedulerCreatedEvent(
24706
25256
  runtimeApi: WorkerRuntimeApiContext,
24707
25257
  event: PostgresSchedulerOutboxEvent,
25258
+ resolveRetainedPipelineGraphs?: () => Promise<true | undefined>,
24708
25259
  ): Promise<void> {
24709
25260
  event = { ...event, payload: hydrateRetainedPlayPipelines(event.payload) };
24710
25261
  const value = (key: string) => stringPayloadField(event.payload, key);
@@ -24720,7 +25271,10 @@ async function projectPostgresSchedulerCreatedEvent(
24720
25271
  const inputSha256 = value('inputSha256');
24721
25272
  const replayedFromRunId = value('replayedFromRunId');
24722
25273
  const asyncAncestryPlayIds = raw('asyncAncestryPlayIds');
24723
- await projectRunCreatedViaAppRuntime(runtimeApi, {
25274
+ const staticPipeline = raw('staticPipeline');
25275
+ const request = (pipelineSource: {
25276
+ retainedPipelineGraph?: unknown;
25277
+ }): Parameters<typeof projectRunCreatedViaAppRuntime>[1] => ({
24724
25278
  deliveryLeaseOwner: event.leaseOwner ?? undefined,
24725
25279
  idempotencyKey: buildRunLedgerStartIdempotencyKey({
24726
25280
  runId: event.runId,
@@ -24777,10 +25331,7 @@ async function projectPostgresSchedulerCreatedEvent(
24777
25331
  runtimeWorkflowName: value('runtimeWorkflowName'),
24778
25332
  runtimeHarnessWorkerName: value('runtimeHarnessWorkerName'),
24779
25333
  maxCreditsPerRun: number('maxCreditsPerRun'),
24780
- ...retainedPlayPipelineFields(
24781
- raw('staticPipeline'),
24782
- event.payload as { retainedPipelineGraph?: unknown },
24783
- ),
25334
+ ...retainedPlayPipelineFields(staticPipeline, pipelineSource),
24784
25335
  source: sourcePayloadField(event.payload, 'source'),
24785
25336
  ...(triggerSource === 'api' ||
24786
25337
  triggerSource === 'webhook' ||
@@ -24800,6 +25351,16 @@ async function projectPostgresSchedulerCreatedEvent(
24800
25351
  ? { inputSummary: inputSummary as Record<string, unknown> }
24801
25352
  : {}),
24802
25353
  });
25354
+ await projectRunCreatedViaAppRuntime(
25355
+ runtimeApi,
25356
+ await fitRunCreatedRequest({
25357
+ runtimeApi,
25358
+ resolveRetainedPipelineGraphs,
25359
+ payload: event.payload,
25360
+ staticPipeline,
25361
+ request,
25362
+ }),
25363
+ );
24803
25364
  }
24804
25365
 
24805
25366
  async function projectPostgresSchedulerStartEvent(
@@ -24930,6 +25491,7 @@ async function resolvePostgresSchedulerRuntimeApiForRun(
24930
25491
  WorkerRuntimeApiContext & {
24931
25492
  refreshExecutorToken?: () => Promise<string>;
24932
25493
  invalidateExecutorToken?: () => void;
25494
+ resolveRetainedPipelineGraphs?: () => Promise<true | undefined>;
24933
25495
  }
24934
25496
  > {
24935
25497
  const launch = parseRunLedgerDispatchLaunch(launchJson);
@@ -24952,6 +25514,12 @@ async function resolvePostgresSchedulerRuntimeApiForRun(
24952
25514
  }
24953
25515
  let executorToken: string;
24954
25516
  let runLedgerIngressPrefixBatching: true | undefined;
25517
+ // Only the receiver's own dispatch response proves graph storage. A token
25518
+ // minted locally or at admission says nothing about the receiving build.
25519
+ let retainedPipelineGraphs: true | undefined;
25520
+ let resolveRetainedPipelineGraphs:
25521
+ | (() => Promise<true | undefined>)
25522
+ | undefined;
24955
25523
  let refreshExecutorToken: (() => Promise<string>) | undefined;
24956
25524
  let invalidateExecutorToken: (() => void) | undefined;
24957
25525
  if (tokenAuthority === 'local_mint') {
@@ -24996,6 +25564,11 @@ async function resolvePostgresSchedulerRuntimeApiForRun(
24996
25564
  refreshExecutorToken = async () =>
24997
25565
  (await requestRunLedgerDispatchToken(dispatchRequest, true))
24998
25566
  .executorToken;
25567
+ // The admission token carries no receiver capability. Ask the receiver
25568
+ // through this lease only when a projection needs it.
25569
+ resolveRetainedPipelineGraphs = async () =>
25570
+ (await requestRunLedgerDispatchToken(dispatchRequest))
25571
+ .retainedPipelineGraphs;
24999
25572
  } else {
25000
25573
  const dispatchAuthority =
25001
25574
  await requestRunLedgerDispatchToken(dispatchRequest);
@@ -25017,6 +25590,7 @@ async function resolvePostgresSchedulerRuntimeApiForRun(
25017
25590
  executorToken = dispatchAuthority.executorToken;
25018
25591
  runLedgerIngressPrefixBatching =
25019
25592
  dispatchAuthority.runLedgerIngressPrefixBatching;
25593
+ retainedPipelineGraphs = dispatchAuthority.retainedPipelineGraphs;
25020
25594
  }
25021
25595
  }
25022
25596
  // A mutable source can seal array pages after this prefix was claimed.
@@ -25035,6 +25609,8 @@ async function resolvePostgresSchedulerRuntimeApiForRun(
25035
25609
  ...(runLedgerIngressPrefixBatching
25036
25610
  ? { runLedgerIngressPrefixBatching }
25037
25611
  : {}),
25612
+ ...(retainedPipelineGraphs ? { retainedPipelineGraphs } : {}),
25613
+ ...(resolveRetainedPipelineGraphs ? { resolveRetainedPipelineGraphs } : {}),
25038
25614
  vercelProtectionBypassToken: launch.vercelProtectionBypassToken ?? null,
25039
25615
  ...(refreshExecutorToken ? { refreshExecutorToken } : {}),
25040
25616
  ...(invalidateExecutorToken ? { invalidateExecutorToken } : {}),
@@ -25250,7 +25826,12 @@ const RUN_LEDGER_DISPATCH_TOKEN_CACHE_MS = 30_000;
25250
25826
  const RUN_LEDGER_DISPATCH_TOKEN_CACHE_ENTRIES = 256;
25251
25827
  const runLedgerDispatchTokens = new Map<
25252
25828
  string,
25253
- { token: string; expiresAt: number; runLedgerIngressPrefixBatching?: true }
25829
+ {
25830
+ token: string;
25831
+ expiresAt: number;
25832
+ runLedgerIngressPrefixBatching?: true;
25833
+ retainedPipelineGraphs?: true;
25834
+ }
25254
25835
  >();
25255
25836
 
25256
25837
  async function requestRunLedgerDispatchToken(
@@ -25268,6 +25849,7 @@ async function requestRunLedgerDispatchToken(
25268
25849
  reused: boolean;
25269
25850
  cacheKey: string;
25270
25851
  runLedgerIngressPrefixBatching?: true;
25852
+ retainedPipelineGraphs?: true;
25271
25853
  /** Present only when this call made the request (never for a reused token). */
25272
25854
  responseTrace?: RunLedgerDispatchResponseTrace;
25273
25855
  }> {
@@ -25302,6 +25884,9 @@ async function requestRunLedgerDispatchToken(
25302
25884
  ...(cached.runLedgerIngressPrefixBatching
25303
25885
  ? { runLedgerIngressPrefixBatching: true as const }
25304
25886
  : {}),
25887
+ ...(cached.retainedPipelineGraphs
25888
+ ? { retainedPipelineGraphs: true as const }
25889
+ : {}),
25305
25890
  };
25306
25891
  runLedgerDispatchTokens.delete(cacheKey);
25307
25892
  const url = `${input.receiverBaseUrl.replace(/\/$/, '')}/api/v2/internal/play-runtime/run-ledger-dispatch-token`;
@@ -25341,6 +25926,7 @@ async function requestRunLedgerDispatchToken(
25341
25926
  return JSON.parse(responseText) as {
25342
25927
  executorToken?: unknown;
25343
25928
  runLedgerIngressPrefixBatching?: unknown;
25929
+ retainedPipelineGraphs?: unknown;
25344
25930
  error?: unknown;
25345
25931
  code?: unknown;
25346
25932
  retryable?: unknown;
@@ -25402,6 +25988,9 @@ async function requestRunLedgerDispatchToken(
25402
25988
  ...(reusablePrefix
25403
25989
  ? { runLedgerIngressPrefixBatching: true as const }
25404
25990
  : {}),
25991
+ ...(body.retainedPipelineGraphs === true
25992
+ ? { retainedPipelineGraphs: true as const }
25993
+ : {}),
25405
25994
  });
25406
25995
  while (
25407
25996
  runLedgerDispatchTokens.size > RUN_LEDGER_DISPATCH_TOKEN_CACHE_ENTRIES
@@ -25425,6 +26014,9 @@ async function requestRunLedgerDispatchToken(
25425
26014
  ...(body.runLedgerIngressPrefixBatching === true
25426
26015
  ? { runLedgerIngressPrefixBatching: true as const }
25427
26016
  : {}),
26017
+ ...(body.retainedPipelineGraphs === true
26018
+ ? { retainedPipelineGraphs: true as const }
26019
+ : {}),
25428
26020
  responseTrace: {
25429
26021
  platformRequestId: readRuntimeApiDiagnosticHeader(
25430
26022
  response.headers,