deepline 0.3.502 → 0.3.504

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 (211) hide show
  1. package/dist/bundling-sources/sdk/src/client-core.ts +26 -0
  2. package/dist/bundling-sources/sdk/src/index.ts +1 -0
  3. package/dist/bundling-sources/sdk/src/release.ts +1 -1
  4. package/dist/bundling-sources/sdk/src/types.ts +9 -0
  5. package/dist/bundling-sources/shared_libs/monitors/http-error-response.ts +35 -0
  6. package/dist/bundling-sources/shared_libs/monitors/provider-monitor-batch-operation.ts +1 -1
  7. package/dist/bundling-sources/shared_libs/monitors/provider-monitor-public-aliases.ts +13 -0
  8. package/dist/bundling-sources/shared_libs/monitors/starter-templates.ts +0 -8
  9. package/dist/bundling-sources/shared_libs/observability/dlq.ts +174 -0
  10. package/dist/bundling-sources/shared_libs/observability/queue-health.ts +9 -0
  11. package/dist/bundling-sources/shared_libs/observability/queue-item-connectors.ts +1 -0
  12. package/dist/bundling-sources/shared_libs/observability/scheduled-jobs.json +18 -0
  13. package/dist/bundling-sources/shared_libs/play-runtime/activity-observation.ts +20 -0
  14. package/dist/bundling-sources/shared_libs/play-runtime/app-runtime-api.ts +62 -2
  15. package/dist/bundling-sources/shared_libs/play-runtime/context.ts +667 -62
  16. package/dist/bundling-sources/shared_libs/play-runtime/ctx-types.ts +55 -0
  17. package/dist/bundling-sources/shared_libs/play-runtime/durable-receipt-execution.ts +20 -2
  18. package/dist/bundling-sources/shared_libs/play-runtime/durable-runs-rollout.ts +46 -0
  19. package/dist/bundling-sources/shared_libs/play-runtime/execution-gateway-invocation-fence.ts +80 -4
  20. package/dist/bundling-sources/shared_libs/play-runtime/fixture-egress-fetch.ts +95 -0
  21. package/dist/bundling-sources/shared_libs/play-runtime/freshness-receipt-execution.ts +292 -45
  22. package/dist/bundling-sources/shared_libs/play-runtime/internal-bootstrap-token.ts +15 -0
  23. package/dist/bundling-sources/shared_libs/play-runtime/launch-identity.ts +3 -0
  24. package/dist/bundling-sources/shared_libs/play-runtime/play-http-request.ts +7 -3
  25. package/dist/bundling-sources/shared_libs/play-runtime/play-runtime-semantics.ts +31 -1
  26. package/dist/bundling-sources/shared_libs/play-runtime/post-code-recovery-policy.ts +231 -0
  27. package/dist/bundling-sources/shared_libs/play-runtime/protocol.ts +4 -0
  28. package/dist/bundling-sources/shared_libs/play-runtime/run-ending-event.ts +55 -0
  29. package/dist/bundling-sources/shared_libs/play-runtime/run-ledger.ts +126 -0
  30. package/dist/bundling-sources/shared_libs/play-runtime/runner-app/index.ts +38 -1
  31. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona-launch-transport.ts +2 -9
  32. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona-lifecycle.ts +51 -19
  33. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/local-process.ts +9 -4
  34. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/modal.ts +2 -0
  35. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/runtime-sandbox-reconciliation.ts +2 -0
  36. package/dist/bundling-sources/shared_libs/play-runtime/runtime-actions.ts +12 -1
  37. package/dist/bundling-sources/shared_libs/play-runtime/runtime-authority.ts +3 -0
  38. package/dist/bundling-sources/shared_libs/play-runtime/runtime-incident-drills.ts +42 -0
  39. package/dist/bundling-sources/shared_libs/play-runtime/runtime-operation-contract.ts +7 -0
  40. package/dist/bundling-sources/shared_libs/play-runtime/runtime-receipt-store-adapter.ts +26 -1
  41. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backend.ts +13 -0
  42. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-deadline-reconciliation.ts +53 -0
  43. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-runtime-worker.ts +631 -19
  44. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/durable-run-inventory.ts +719 -0
  45. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/durable-run-sql.ts +206 -0
  46. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/latest-cache-result.ts +83 -0
  47. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres.ts +1432 -157
  48. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/receipt-gateway.ts +61 -0
  49. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-event-search.ts +29 -8
  50. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-queue-health.ts +27 -2
  51. package/dist/bundling-sources/shared_libs/play-runtime/test-runtime-seams.ts +45 -0
  52. package/dist/bundling-sources/shared_libs/play-runtime/tool-cache-policy.ts +18 -0
  53. package/dist/bundling-sources/shared_libs/play-runtime/tool-execute-retry-policy.ts +129 -14
  54. package/dist/bundling-sources/shared_libs/play-runtime/workflow-executor-auth.ts +2 -0
  55. package/dist/bundling-sources/shared_libs/plays/authoring-contract.ts +10 -1
  56. package/dist/cli/{auth-EFHLOVG4.mjs → auth-3L5AA5AX.mjs} +5 -5
  57. package/dist/cli/auth-UPK4IIIN.js +43 -0
  58. package/dist/cli/{billing-Q5XKEYPP.mjs → billing-E7EASVPO.mjs} +19 -12
  59. package/dist/cli/{billing-SKT2VE34.js → billing-HOGXVE2V.js} +92 -85
  60. package/dist/cli/{chunk-L5CTJY74.mjs → chunk-22OCKCYS.mjs} +2 -2
  61. package/dist/cli/{chunk-YWOQYYYS.mjs → chunk-2ABRDH3B.mjs} +2 -2
  62. package/dist/cli/{chunk-IL666WJE.js → chunk-2W77YCKH.js} +5 -5
  63. package/dist/cli/{chunk-2MVIS2UI.mjs → chunk-3MLFFWDM.mjs} +2 -2
  64. package/dist/cli/{chunk-HMZF2CSP.mjs → chunk-4CC67XH5.mjs} +2 -2
  65. package/dist/cli/{chunk-NXVYLX3F.mjs → chunk-5CHBIJIM.mjs} +10 -6
  66. package/dist/cli/chunk-5LUF4LAR.mjs +209 -0
  67. package/dist/cli/{chunk-JL6H4H3G.js → chunk-5Z6EULD5.js} +6 -6
  68. package/dist/cli/{chunk-32YQBJON.js → chunk-67OI26OE.js} +7 -7
  69. package/dist/cli/{chunk-LA3UYRVZ.js → chunk-6JNBMTCZ.js} +1 -1
  70. package/dist/cli/{chunk-DYHTXGLX.js → chunk-6SMR7LU7.js} +2 -2
  71. package/dist/cli/{chunk-OFBLT2LQ.mjs → chunk-7F4OEHQK.mjs} +1 -1
  72. package/dist/cli/{chunk-DRBD4IYQ.mjs → chunk-7MJYZ33I.mjs} +2 -6
  73. package/dist/cli/{chunk-UOANF3DR.js → chunk-7P2QVMBP.js} +26 -7
  74. package/dist/cli/{chunk-GINKIZ7S.js → chunk-A6LA42JY.js} +16 -16
  75. package/dist/cli/{chunk-FVM4PS5Q.js → chunk-BN5VKY4X.js} +25 -12
  76. package/dist/cli/{chunk-Z2H7OQ6E.mjs → chunk-BTWUNKKX.mjs} +2 -2
  77. package/dist/cli/{chunk-R5F7JXT4.mjs → chunk-BX45XMXZ.mjs} +2 -2
  78. package/dist/cli/{chunk-NKLM4J4X.mjs → chunk-DEAJVQEG.mjs} +1 -1
  79. package/dist/cli/{chunk-JFBJLNBI.js → chunk-FISP4LCK.js} +53 -53
  80. package/dist/cli/{chunk-OEUMXKR5.js → chunk-FTRVCIGC.js} +26 -26
  81. package/dist/cli/{chunk-YL2CCF6T.mjs → chunk-GGBXNQCR.mjs} +4 -4
  82. package/dist/cli/{chunk-YPTZJ7LO.js → chunk-GJ2DA35C.js} +100 -17
  83. package/dist/cli/{chunk-2S2F6YSI.js → chunk-GRAGUYIE.js} +41 -41
  84. package/dist/cli/{chunk-2JS3H6H6.mjs → chunk-HUX5DZO6.mjs} +3 -3
  85. package/dist/cli/{chunk-4CCMD7QM.mjs → chunk-IGNQKOWT.mjs} +32 -15
  86. package/dist/cli/{chunk-WKFAX2K7.js → chunk-IPAMOMGP.js} +21 -21
  87. package/dist/cli/{chunk-SAW3FBCA.mjs → chunk-ITJ7NB2D.mjs} +6 -0
  88. package/dist/cli/{chunk-Q3NM6ZL3.js → chunk-JPR2546F.js} +23 -21
  89. package/dist/cli/{chunk-X5MGQ7UT.js → chunk-KCKAFTPY.js} +10 -10
  90. package/dist/cli/{chunk-TAK3MVXY.js → chunk-KGUGNEKL.js} +284 -267
  91. package/dist/cli/{chunk-OVZOMSH2.js → chunk-LHXYCZYO.js} +8 -8
  92. package/dist/cli/{chunk-QOJBRCAS.js → chunk-MJTK6Q3G.js} +3 -3
  93. package/dist/cli/{chunk-MYUISF3P.mjs → chunk-MLMWM5DV.mjs} +5 -5
  94. package/dist/cli/{chunk-JO5FFSR7.js → chunk-NTLBZUHD.js} +6 -0
  95. package/dist/cli/{chunk-MP5QY4A2.mjs → chunk-NZ7Z7WNM.mjs} +2 -2
  96. package/dist/cli/{chunk-HIVRCTDR.mjs → chunk-OX2D6BG4.mjs} +20 -1
  97. package/dist/cli/{chunk-YDXEXVBV.js → chunk-QKKU2FH4.js} +7 -7
  98. package/dist/cli/{chunk-3KEZVGGV.mjs → chunk-QOLX2O2S.mjs} +4 -4
  99. package/dist/cli/{chunk-JFUXUSKB.mjs → chunk-R2VZVHJP.mjs} +15 -2
  100. package/dist/cli/chunk-R7J7CJPZ.js +209 -0
  101. package/dist/cli/{chunk-XMKUJ44Z.js → chunk-SMSQVRHE.js} +5 -5
  102. package/dist/cli/{chunk-54QXWK3C.mjs → chunk-SVFTZTCI.mjs} +1 -1
  103. package/dist/cli/{chunk-FWDAEWCD.js → chunk-TMQUMILM.js} +19 -23
  104. package/dist/cli/{chunk-TFFJ2PRN.mjs → chunk-UFYJTRSF.mjs} +98 -15
  105. package/dist/cli/{chunk-EUWRKWT4.js → chunk-UJMBG5JU.js} +5 -4
  106. package/dist/cli/{chunk-DKAMCJIT.js → chunk-USTJEEND.js} +17 -13
  107. package/dist/cli/{chunk-AJL2Q6IQ.js → chunk-UXQQPMYO.js} +2 -2
  108. package/dist/cli/{chunk-7ZYSXSJJ.mjs → chunk-VJVJWZ6I.mjs} +5 -5
  109. package/dist/cli/{chunk-JLYDLK6X.js → chunk-WBIDPDKJ.js} +3 -3
  110. package/dist/cli/{chunk-QNELA7SX.js → chunk-WZSFIJMG.js} +53 -53
  111. package/dist/cli/{chunk-NZXB27TP.mjs → chunk-XHZSPMNC.mjs} +4 -4
  112. package/dist/cli/{chunk-W5CHE5Q2.mjs → chunk-Y6XKCEPK.mjs} +1 -1
  113. package/dist/cli/{chunk-4WTC5SSN.mjs → chunk-Y7VEHKID.mjs} +10 -8
  114. package/dist/cli/{chunk-3MJSWVQ2.mjs → chunk-YOQ2NNDO.mjs} +2 -1
  115. package/dist/cli/{chunk-ZNB6GR3P.mjs → chunk-Z6FXUDIL.mjs} +1 -1
  116. package/dist/cli/command-docs.d.mts +2 -1
  117. package/dist/cli/command-docs.d.ts +2 -1
  118. package/dist/cli/command-docs.js +6 -2
  119. package/dist/cli/command-docs.mjs +5 -1
  120. package/dist/cli/{csv-OXGSCV75.js → csv-2XWGPITO.js} +13 -13
  121. package/dist/cli/{csv-6AEPKKCO.mjs → csv-433JEHLQ.mjs} +4 -4
  122. package/dist/cli/{db-K3KRK4CZ.mjs → db-K747DH43.mjs} +6 -6
  123. package/dist/cli/{db-6NVHDUZY.js → db-PJJMD4VH.js} +27 -27
  124. package/dist/cli/describe-OYS7LZJD.js +49 -0
  125. package/dist/cli/{describe-P3ZJS7TQ.mjs → describe-VEDDYW4P.mjs} +20 -20
  126. package/dist/cli/describe-core.d.mts +8 -4
  127. package/dist/cli/describe-core.d.ts +8 -4
  128. package/dist/cli/describe-core.js +4 -4
  129. package/dist/cli/describe-core.mjs +3 -3
  130. package/dist/cli/{executions-2C2FFG52.js → executions-HM5T72H6.js} +8 -8
  131. package/dist/cli/{executions-I7XW6WWK.mjs → executions-JWRX3XCT.mjs} +6 -6
  132. package/dist/cli/{feedback-47B57A5Y.js → feedback-34UG4BO3.js} +8 -8
  133. package/dist/cli/{feedback-RSTNBJAI.mjs → feedback-MNSIA63Y.mjs} +4 -4
  134. package/dist/cli/git-5YQJSJFR.js +25 -0
  135. package/dist/cli/{git-3G5AFKBT.mjs → git-ZKEOXV3A.mjs} +5 -5
  136. package/dist/cli/index.js +144 -142
  137. package/dist/cli/index.mjs +44 -42
  138. package/dist/cli/{legacy-noops-NQ262TKL.mjs → legacy-noops-5M4T4ZVT.mjs} +5 -5
  139. package/dist/cli/{legacy-noops-P665PBG4.js → legacy-noops-YXSI4FVU.js} +8 -8
  140. package/dist/cli/{monitors-KUPZODZS.mjs → monitors-C65OC4AW.mjs} +7 -7
  141. package/dist/cli/{monitors-IPWAD7LS.js → monitors-O25GDOYE.js} +95 -95
  142. package/dist/cli/{org-WFC3N672.js → org-2GSPLY2A.js} +72 -72
  143. package/dist/cli/{org-ZCQGEM3L.mjs → org-ZRMG5NS2.mjs} +6 -6
  144. package/dist/cli/{pages-N5BNC67L.js → pages-45DPADK6.js} +18 -18
  145. package/dist/cli/{pages-VE66IU7B.mjs → pages-TZZUFBRO.mjs} +6 -6
  146. package/dist/cli/{play-EIMDIAJB.mjs → play-3D7HH273.mjs} +138 -226
  147. package/dist/cli/{play-NKIRJSKX.js → play-RCGMND6X.js} +454 -542
  148. package/dist/cli/{providers-XU3AGY2F.js → providers-3N3ECMTY.js} +9 -9
  149. package/dist/cli/{providers-KDTJ63ED.mjs → providers-PSAKV6CJ.mjs} +6 -6
  150. package/dist/cli/{quickstart-TXFXUODF.mjs → quickstart-2A35SMGC.mjs} +4 -4
  151. package/dist/cli/{quickstart-OSCHOSXU.js → quickstart-6R6AIXM6.js} +6 -6
  152. package/dist/cli/{run-ODGML35U.mjs → run-F3TLDGUO.mjs} +25 -25
  153. package/dist/cli/{run-ET2KVTPK.js → run-F6ZXTASZ.js} +44 -44
  154. package/dist/cli/{search-DK67K6PR.mjs → search-CZLCY3D2.mjs} +7 -7
  155. package/dist/cli/search-R5VEWJO2.js +32 -0
  156. package/dist/cli/{search-output-6SOKQTCW.mjs → search-output-MQTSTLN5.mjs} +5 -5
  157. package/dist/cli/{search-output-KXP4FA62.js → search-output-R5XDNILW.js} +7 -7
  158. package/dist/cli/{secrets-C6SYTMU7.mjs → secrets-D3GF4B2Z.mjs} +6 -6
  159. package/dist/cli/{secrets-WPS6NMNK.js → secrets-DCJYHDSY.js} +15 -15
  160. package/dist/cli/{sessions-PXVOH34X.mjs → sessions-QGEQ2UYZ.mjs} +5 -5
  161. package/dist/cli/{sessions-IP562J5Z.js → sessions-Z4JYJSDP.js} +6 -6
  162. package/dist/cli/{settings-FBUQGYVJ.mjs → settings-G7QEXA4N.mjs} +11 -11
  163. package/dist/cli/{settings-SUDUIVMY.js → settings-UVXXAT4A.js} +78 -78
  164. package/dist/cli/{setup-I5H6IOEY.js → setup-5I42W7D4.js} +49 -49
  165. package/dist/cli/{setup-JSIMTR73.mjs → setup-QHJU3DUI.mjs} +9 -9
  166. package/dist/cli/{skills-FJQ3LX6N.mjs → skills-5LRF4UKX.mjs} +7 -7
  167. package/dist/cli/skills-FB6TV52O.js +36 -0
  168. package/dist/cli/tools-L2364RPA.js +56 -0
  169. package/dist/cli/{tools-IGBK4BVE.mjs → tools-PUT6STVG.mjs} +18 -18
  170. package/dist/cli/{update-7MTT6F5K.mjs → update-CJ2GA64X.mjs} +9 -9
  171. package/dist/cli/update-ESYJGYVZ.js +34 -0
  172. package/dist/cli/{workflow-PM2J2OU3.mjs → workflow-HVEWRTXD.mjs} +7 -7
  173. package/dist/cli/{workflow-UX3ZX6BQ.js → workflow-O67MEBCP.js} +17 -17
  174. package/dist/{client-Bn8FwKGO.d.ts → client-CIwenMFS.d.ts} +1 -1
  175. package/dist/{client-CfNRmjLK.d.mts → client-DYAfJpaN.d.mts} +1 -1
  176. package/dist/{client-core-B91EV0WS.d.ts → client-core-CRjtyMAI.d.ts} +25 -2
  177. package/dist/{client-core-BG8Cgrmk.d.mts → client-core-DlzP8vEs.d.mts} +25 -2
  178. package/dist/{compiler-manifest-DlXDyndN.d.mts → compiler-manifest-DaJrA2KV.d.mts} +1 -1
  179. package/dist/{compiler-manifest-DlXDyndN.d.ts → compiler-manifest-DaJrA2KV.d.ts} +1 -1
  180. package/dist/{errors-BtriA2ld.d.mts → errors-BKnSYueU.d.mts} +1 -1
  181. package/dist/{errors-DmcLykM7.d.ts → errors-KLga4bLr.d.ts} +1 -1
  182. package/dist/{index-DI0sR_fX.d.mts → index-C-8AFpWy.d.mts} +1 -1
  183. package/dist/{index--Jw-slHY.d.ts → index-C5nAZ-VS.d.ts} +1 -1
  184. package/dist/index.d.mts +7 -7
  185. package/dist/index.d.ts +7 -7
  186. package/dist/index.js +9 -9
  187. package/dist/index.mjs +6 -6
  188. package/dist/install-integrity.json +125 -116
  189. package/dist/plays/bundle-play-file.d.mts +3 -3
  190. package/dist/plays/bundle-play-file.d.ts +3 -3
  191. package/dist/plays/bundle-play-file.mjs +12 -5
  192. package/dist/plays/play-description.d.mts +2 -2
  193. package/dist/plays/play-description.d.ts +2 -2
  194. package/dist/plays/run-request.d.mts +2 -2
  195. package/dist/plays/run-request.d.ts +2 -2
  196. package/dist/release.d.mts +1 -1
  197. package/dist/release.d.ts +1 -1
  198. package/dist/release.js +2 -2
  199. package/dist/release.mjs +1 -1
  200. package/dist/server.d.mts +4 -4
  201. package/dist/server.d.ts +4 -4
  202. package/dist/server.js +5 -5
  203. package/dist/server.mjs +3 -3
  204. package/package.json +1 -1
  205. package/dist/cli/auth-VM3IKP5F.js +0 -43
  206. package/dist/cli/describe-JOUAXXPE.js +0 -49
  207. package/dist/cli/git-OPKIC6JQ.js +0 -25
  208. package/dist/cli/search-6U54Y3OK.js +0 -32
  209. package/dist/cli/skills-VHININXC.js +0 -36
  210. package/dist/cli/tools-XMBMHVKF.js +0 -56
  211. package/dist/cli/update-H7JVW43I.js +0 -34
@@ -1,3 +1,4 @@
1
+ import { PLATFORM_RECOVERY_ACTIVITY_ID } from '../activity-observation';
1
2
  import { readPrebuiltResultQuality } from '../prebuilt-result-quality';
2
3
  import { resolveRuntimeAppTransport } from '../runtime-app-transport';
3
4
  import {
@@ -5,6 +6,13 @@ import {
5
6
  normalizeTerminalRuntimePerformance,
6
7
  normalizeTerminalRuntimePerformanceUnavailableReason,
7
8
  } from '../terminal-runtime-performance';
9
+ import {
10
+ computeBillingSessionId,
11
+ isRunEndingEventId,
12
+ normalizeResumeEpoch,
13
+ runEndingEventEpoch,
14
+ runEndingEventId,
15
+ } from '../run-ending-event';
8
16
  import { escapeLiteral } from 'pg';
9
17
  import { readRuntimeGatewayLaunchPin } from '../runtime-gateway-profile';
10
18
  import { RUNTIME_GATEWAY_OIDC_MAX_AGE_SECONDS } from '../runtime-gateway-oidc';
@@ -277,6 +285,12 @@ import type {
277
285
  DurableInvocationResponse,
278
286
  DurableInvocationStore,
279
287
  } from '../execution-gateway-invocation-fence';
288
+ import { fenceOwnerAttemptSql } from '../execution-gateway-invocation-fence';
289
+ import { DURABLE_RUNS_ROLLOUT } from '../durable-runs-rollout';
290
+ import {
291
+ replayTrackedMarkerReceiptKey,
292
+ replayUnsafeMarkerReceiptKey,
293
+ } from '../post-code-recovery-policy';
280
294
  import {
281
295
  recordSchedulerLaunchRead,
282
296
  type SchedulerLaunchReadCaller,
@@ -419,8 +433,14 @@ const POSTGRES_SCHEDULER_SCHEMA_INIT_STATEMENT_TIMEOUT_MS = 60_000;
419
433
  // unexpanded acquires retain their existing operation-local measurement.
420
434
  // v64 adds the optional per-run array-input intent used by terminal retirement.
421
435
  // Existing runs default to false and older workers ignore the column.
436
+ // v65 lets the ending of a resumed run (`run-ended:*`) re-open its settled
437
+ // compute billing job, so a resumed epoch's compute is settled too. A
438
+ // never-resumed run's single ending keeps the original insert-once behavior.
439
+ // v66 adds the nullable `array_input_kept_for_resume_at` marker: positive
440
+ // evidence, written where a stopped run's staged input is kept for `runs
441
+ // resume`. Absent on older runs, whose input an older build may have deleted.
422
442
  // This marker records deployment work, never a runtime schema floor.
423
- export const POSTGRES_SCHEDULER_SCHEMA_VERSION = 64;
443
+ export const POSTGRES_SCHEDULER_SCHEMA_VERSION = 66;
424
444
  const POSTGRES_SCHEDULER_SCHEMA_MIGRATIONS_TABLE =
425
445
  'scheduler_schema_migrations';
426
446
  export const POSTGRES_SCHEDULER_OPEN_RECOVERY_INDEX =
@@ -860,27 +880,40 @@ export function createPostgresIntegrationInvocationStore(input: {
860
880
  response_headers = NULL,
861
881
  response_body = NULL,
862
882
  updated_at = now()
863
- WHERE integration_invocation_receipts.parent_run_id
864
- IS DISTINCT FROM EXCLUDED.parent_run_id
865
- AND (
866
- -- An explicit later Play Run is the recovery boundary for an
867
- -- indeterminate provider outcome. Transport metadata such as
868
- -- parent_run_id is part of the wire fingerprint, so the same
869
- -- semantic invocation necessarily has a different fingerprint
870
- -- in that later run. The stable invocation_key remains the
871
- -- semantic identity and same-run callers can never enter here.
872
- integration_invocation_receipts.state = 'indeterminate'
873
- OR (
874
- integration_invocation_receipts.request_fingerprint =
875
- ANY($6::text[])
876
- AND
877
- integration_invocation_receipts.state IN ('completed', 'compacted')
878
- AND NOT (
879
- integration_invocation_receipts.response_status
880
- BETWEEN 200 AND 299
883
+ WHERE (
884
+ integration_invocation_receipts.parent_run_id
885
+ IS DISTINCT FROM EXCLUDED.parent_run_id
886
+ AND (
887
+ -- An explicit later Play Run is the recovery boundary for an
888
+ -- indeterminate provider outcome. Transport metadata such as
889
+ -- parent_run_id is part of the wire fingerprint, so the same
890
+ -- semantic invocation necessarily has a different fingerprint
891
+ -- in that later run. The stable invocation_key remains the
892
+ -- semantic identity and same-run callers can never enter here.
893
+ integration_invocation_receipts.state = 'indeterminate'
894
+ OR (
895
+ integration_invocation_receipts.request_fingerprint =
896
+ ANY($6::text[])
897
+ AND
898
+ integration_invocation_receipts.state IN ('completed', 'compacted')
899
+ AND NOT (
900
+ integration_invocation_receipts.response_status
901
+ BETWEEN 200 AND 299
902
+ )
881
903
  )
882
904
  )
883
905
  )
906
+ -- A newer attempt of the same run sends a call an older attempt
907
+ -- abandoned (unknown outcome) again, with the same key and the
908
+ -- same request. A legacy owner ID carries no attempt and is never
909
+ -- taken over.
910
+ OR (
911
+ integration_invocation_receipts.state = 'indeterminate'
912
+ AND integration_invocation_receipts.request_fingerprint =
913
+ ANY($6::text[])
914
+ AND ${fenceOwnerAttemptSql('integration_invocation_receipts.owner_id')}
915
+ < ${fenceOwnerAttemptSql('EXCLUDED.owner_id')}
916
+ )
884
917
  RETURNING ${returning}`,
885
918
  [
886
919
  input.orgId,
@@ -990,9 +1023,30 @@ export async function compactPostgresIntegrationInvocationResponses(input: {
990
1023
  SELECT ctid, COALESCE(octet_length(response_body), 0) AS response_bytes
991
1024
  FROM ${tableName('integration_invocation_receipts', {
992
1025
  schema: input.schema,
993
- })}
1026
+ })} AS invocation
994
1027
  WHERE state = 'completed'
995
1028
  AND updated_at < now() - ($1::bigint * interval '1 millisecond')
1029
+ -- A run that is still active or recovering, or that can still be
1030
+ -- resumed, replays these answers; keep them. The fence parent is
1031
+ -- the run id, with a ':resume:N' suffix after a resume.
1032
+ AND NOT EXISTS (
1033
+ SELECT 1
1034
+ FROM ${tableName('runs', { schema: input.schema })} AS runs
1035
+ WHERE runs.run_id = regexp_replace(
1036
+ invocation.parent_run_id,
1037
+ ':resume:[0-9]+$',
1038
+ ''
1039
+ )
1040
+ AND (
1041
+ runs.status IN ('queued', 'running', 'waiting')
1042
+ OR (
1043
+ $4::boolean
1044
+ AND runs.status IN ('failed', 'cancelled')
1045
+ AND runs.finished_at
1046
+ >= now() - ($3::bigint * interval '1 millisecond')
1047
+ )
1048
+ )
1049
+ )
996
1050
  ORDER BY updated_at ASC
997
1051
  LIMIT $2
998
1052
  FOR UPDATE SKIP LOCKED
@@ -1008,7 +1062,8 @@ export async function compactPostgresIntegrationInvocationResponses(input: {
1008
1062
  FROM candidates
1009
1063
  WHERE receipts.ctid = candidates.ctid
1010
1064
  RETURNING candidates.response_bytes`,
1011
- [olderThanMs, limit],
1065
+ // A stopped run's answers matter only while it can still be resumed.
1066
+ [olderThanMs, limit, RUN_RESUME_WINDOW_MS, DURABLE_RUNS_ROLLOUT.runsResume],
1012
1067
  );
1013
1068
  return {
1014
1069
  rows: result.rows.length,
@@ -2429,6 +2484,133 @@ async function ensurePostgresSchedulerArrayInputIntentExpansion(
2429
2484
  ): Promise<void> {
2430
2485
  await client.query(`ALTER TABLE ${tableName('runs', options)}
2431
2486
  ADD COLUMN IF NOT EXISTS array_input_started boolean NOT NULL DEFAULT false`);
2487
+ // When the run's staged array input was deleted. Absent means it is still
2488
+ // there (or the run never staged any), so `runs resume` can read it.
2489
+ await client.query(`ALTER TABLE ${tableName('runs', options)}
2490
+ ADD COLUMN IF NOT EXISTS array_input_retired_at timestamptz`);
2491
+ // The last failed expiry-sweep attempt, so a run that cannot be retired
2492
+ // moves behind the others instead of holding the head of every pass.
2493
+ await client.query(`ALTER TABLE ${tableName('runs', options)}
2494
+ ADD COLUMN IF NOT EXISTS array_input_retire_attempted_at timestamptz,
2495
+ -- Positive evidence that the staged input was deliberately kept for
2496
+ -- resume. A build that predates the keep decision deletes the input at
2497
+ -- terminal and never writes this, so its absence must not be read as
2498
+ -- "input still there".
2499
+ ADD COLUMN IF NOT EXISTS array_input_kept_for_resume_at timestamptz`);
2500
+ }
2501
+
2502
+ /**
2503
+ * Record, at the point the terminal delivery decides to keep a stopped run's
2504
+ * staged array input, that it was kept for `runs resume`. A scheduler schema
2505
+ * older than the column keeps its previous behavior (resume is refused there).
2506
+ */
2507
+ export async function markPostgresSchedulerArrayInputKeptForResume(
2508
+ client: PostgresSchedulerQueryClient,
2509
+ input: { orgId: string; runId: string },
2510
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
2511
+ ): Promise<void> {
2512
+ const column = await client.query<{ present: boolean }>(
2513
+ `SELECT EXISTS (
2514
+ SELECT 1 FROM pg_attribute
2515
+ WHERE attrelid = to_regclass($1)
2516
+ AND attname = 'array_input_kept_for_resume_at'
2517
+ AND NOT attisdropped
2518
+ ) AS present`,
2519
+ [tableName('runs', options)],
2520
+ );
2521
+ if (column.rows[0]?.present !== true) return;
2522
+ await client.query(
2523
+ `UPDATE ${tableName('runs', options)}
2524
+ SET array_input_kept_for_resume_at =
2525
+ coalesce(array_input_kept_for_resume_at, now())
2526
+ WHERE run_id = $1 AND org_id = $2
2527
+ AND status IN ('failed', 'cancelled')
2528
+ AND array_input_started
2529
+ AND array_input_retired_at IS NULL`,
2530
+ [input.runId, input.orgId],
2531
+ );
2532
+ }
2533
+
2534
+ async function runsArrayInputRetiredColumnPresent(
2535
+ client: PostgresSchedulerQueryClient,
2536
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
2537
+ ): Promise<boolean> {
2538
+ const column = await client.query<{ present: boolean }>(
2539
+ `SELECT (
2540
+ SELECT count(*) FROM pg_attribute
2541
+ WHERE attrelid = to_regclass($1)
2542
+ AND attname IN ('array_input_retired_at', 'array_input_retire_attempted_at')
2543
+ AND NOT attisdropped
2544
+ ) = 2 AS present`,
2545
+ [tableName('runs', options)],
2546
+ );
2547
+ return column.rows[0]?.present === true;
2548
+ }
2549
+
2550
+ /**
2551
+ * Record that a stopped run's staged array input was deleted. A scheduler
2552
+ * schema older than the column keeps its previous behavior.
2553
+ */
2554
+ export async function markPostgresSchedulerArrayInputRetired(
2555
+ client: PostgresSchedulerQueryClient,
2556
+ input: { orgId: string; runId: string },
2557
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
2558
+ ): Promise<void> {
2559
+ if (!(await runsArrayInputRetiredColumnPresent(client, options))) return;
2560
+ await client.query(
2561
+ `UPDATE ${tableName('runs', options)}
2562
+ SET array_input_retired_at = coalesce(array_input_retired_at, now())
2563
+ WHERE run_id = $1 AND org_id = $2
2564
+ AND status IN ('completed', 'failed', 'cancelled')`,
2565
+ [input.runId, input.orgId],
2566
+ );
2567
+ }
2568
+
2569
+ /** Record a failed expiry-sweep attempt for a run's staged input. */
2570
+ export async function recordPostgresSchedulerArrayInputRetireAttempt(
2571
+ client: PostgresSchedulerQueryClient,
2572
+ input: { orgId: string; runId: string },
2573
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
2574
+ ): Promise<void> {
2575
+ if (!(await runsArrayInputRetiredColumnPresent(client, options))) return;
2576
+ await client.query(
2577
+ `UPDATE ${tableName('runs', options)}
2578
+ SET array_input_retire_attempted_at = now()
2579
+ WHERE run_id = $1 AND org_id = $2`,
2580
+ [input.runId, input.orgId],
2581
+ );
2582
+ }
2583
+
2584
+ /**
2585
+ * Stopped runs whose staged array input outlived the resume window, oldest
2586
+ * first. Each is retired and then marked, so a pass never selects it again.
2587
+ */
2588
+ export async function listPostgresSchedulerExpiredStagedInputRuns(
2589
+ client: PostgresSchedulerQueryClient,
2590
+ input: { limit: number },
2591
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
2592
+ ): Promise<Array<{ runId: string; orgId: string; playName: string }>> {
2593
+ if (!(await runsArrayInputRetiredColumnPresent(client, options))) return [];
2594
+ const result = await client.query<{
2595
+ run_id: string;
2596
+ org_id: string;
2597
+ play_name: string;
2598
+ }>(
2599
+ `SELECT run_id, org_id, play_name
2600
+ FROM ${tableName('runs', options)}
2601
+ WHERE status IN ('failed', 'cancelled')
2602
+ AND array_input_started
2603
+ AND array_input_retired_at IS NULL
2604
+ AND finished_at < now() - ($1::bigint * interval '1 millisecond')
2605
+ ORDER BY coalesce(array_input_retire_attempted_at, finished_at) ASC
2606
+ LIMIT $2`,
2607
+ [RUN_RESUME_WINDOW_MS, Math.max(1, Math.min(500, input.limit))],
2608
+ );
2609
+ return result.rows.map((row) => ({
2610
+ runId: row.run_id,
2611
+ orgId: row.org_id,
2612
+ playName: row.play_name,
2613
+ }));
2432
2614
  }
2433
2615
 
2434
2616
  /** Deployment-only expansion; absent values keep legacy storage authoritative. */
@@ -2548,7 +2730,21 @@ async function ensurePostgresSchedulerTerminalComputeBillingOutboxTrigger(
2548
2730
  )
2549
2731
  )
2550
2732
  )
2551
- ON CONFLICT (run_id) DO NOTHING;
2733
+ -- A resumed run's ending re-opens its billing, so the resumed epoch's
2734
+ -- compute is settled too. A settlement still in flight loses its lease:
2735
+ -- its completion write is fenced on that lease and matches nothing,
2736
+ -- and the job settles again. Settlement is idempotent per compute
2737
+ -- session, so nothing is billed twice.
2738
+ ON CONFLICT (run_id) DO UPDATE
2739
+ SET status = 'pending',
2740
+ available_at = now(),
2741
+ lease_owner = NULL,
2742
+ lease_expires_at = NULL,
2743
+ settled_at = NULL,
2744
+ updated_at = now()
2745
+ WHERE ${tableName('compute_billing_jobs_v2', options)}.status
2746
+ IN ('settled', 'settling')
2747
+ AND NEW.event_id LIKE 'run-ended:%';
2552
2748
 
2553
2749
  RETURN NEW;
2554
2750
  END
@@ -2732,6 +2928,9 @@ export async function ensurePostgresSchedulerLaunchAdmissionFunctions(
2732
2928
  'runtimeApiBaseUrl',
2733
2929
  'arrayInputTerminalRetirementSupported',
2734
2930
  'arrayInputTerminalProjectionOrigin',
2931
+ 'runScopedKeys',
2932
+ 'resumeEpoch',
2933
+ 'resumeEpochFirstAttempt',
2735
2934
  'vercelProtectionBypassToken'
2736
2935
  ]::text[],
2737
2936
  '{maxConcurrentExternalCalls}',
@@ -3931,6 +4130,9 @@ export async function ensurePostgresSchedulerSchema(
3931
4130
  'runtimeApiBaseUrl',
3932
4131
  'arrayInputTerminalRetirementSupported',
3933
4132
  'arrayInputTerminalProjectionOrigin',
4133
+ 'runScopedKeys',
4134
+ 'resumeEpoch',
4135
+ 'resumeEpochFirstAttempt',
3934
4136
  'vercelProtectionBypassToken'
3935
4137
  ]::text[],
3936
4138
  '{maxConcurrentExternalCalls}',
@@ -7673,10 +7875,26 @@ export async function countPostgresSchedulerAdoptableParkedRuns(
7673
7875
  `
7674
7876
  SELECT count(*)::text AS n
7675
7877
  FROM ${tableName('runs', options)} AS runs
7676
- WHERE runs.status = 'waiting'
7677
- AND runs.suspension_json ->> 'kind'
7678
- IN ('sleep', 'integration_event', 'integration_event_batch')
7679
- AND runs.launch_json ->> 'absurdReleaseId' = $1
7878
+ WHERE runs.launch_json ->> 'absurdReleaseId' = $1
7879
+ AND (
7880
+ (
7881
+ runs.status = 'waiting'
7882
+ AND runs.suspension_json ->> 'kind'
7883
+ IN ('sleep', 'integration_event', 'integration_event_batch')
7884
+ )
7885
+ -- A run waiting out a post-code recovery delay holds no compute;
7886
+ -- a newer lane adopts its wake, so it must not pin this lane for
7887
+ -- the recovery horizon.
7888
+ OR (
7889
+ runs.status = 'queued'
7890
+ AND runs.recovery_json #>> '{postCode,nextRetryAtMs}' IS NOT NULL
7891
+ AND NOT EXISTS (
7892
+ SELECT 1 FROM ${tableName('attempts', options)} AS attempts
7893
+ WHERE attempts.run_id = runs.run_id
7894
+ AND attempts.status IN ('claimed', 'running', 'waiting')
7895
+ )
7896
+ )
7897
+ )
7680
7898
  `,
7681
7899
  [input.releaseId],
7682
7900
  );
@@ -7846,6 +8064,7 @@ export async function assignPostgresSchedulerRunAttempt(
7846
8064
  'run-started:' || run_started.run_id,
7847
8065
  run_started.run_id,
7848
8066
  ${RUN_EVENT_KIND_SQL_LITERAL.runStarted},
8067
+ ${runResumeEpochPayloadSql('run_started.run_id', options)} ||
7849
8068
  jsonb_build_object(
7850
8069
  'playName', run_started.launch_json ->> 'playName',
7851
8070
  'runtimeBackend', run_started.launch_json ->> 'runtimeBackend',
@@ -7980,7 +8199,7 @@ export async function resumePostgresSchedulerDetachedRunnerAttempt(
7980
8199
  INSERT INTO ${tableName('outbox', options)} (
7981
8200
  event_id, run_id, event_type, payload_json, created_at
7982
8201
  )
7983
- SELECT $4, run_id, ${RUN_EVENT_KIND_SQL_LITERAL.runWaiting}, jsonb_build_object('kind', 'detached_runner'),
8202
+ SELECT $4, run_id, ${RUN_EVENT_KIND_SQL_LITERAL.runWaiting}, ${runResumeEpochPayloadSql('restored_run.run_id', options)} || jsonb_build_object('kind', 'detached_runner'),
7984
8203
  ${causalOutboxCreatedAt('restored_run.run_id', options)}
7985
8204
  FROM restored_run
7986
8205
  RETURNING run_id
@@ -8121,6 +8340,7 @@ export async function markPostgresSchedulerAttemptWaiting(
8121
8340
  $6,
8122
8341
  waiting_run.run_id,
8123
8342
  ${RUN_EVENT_KIND_SQL_LITERAL.runWaiting},
8343
+ ${runResumeEpochPayloadSql('waiting_run.run_id', options)} ||
8124
8344
  jsonb_strip_nulls(jsonb_build_object(
8125
8345
  'kind', NULLIF(btrim($4::jsonb ->> 'kind'), ''),
8126
8346
  'eventKey', NULLIF($7::text, ''),
@@ -8267,6 +8487,7 @@ export async function markPostgresSchedulerAttemptRunning(
8267
8487
  $4,
8268
8488
  running_run.run_id,
8269
8489
  ${RUN_EVENT_KIND_SQL_LITERAL.runResumed},
8490
+ ${runResumeEpochPayloadSql('running_run.run_id', options)} ||
8270
8491
  jsonb_strip_nulls(jsonb_build_object(
8271
8492
  'kind', NULLIF(btrim(running_run.suspension_json ->> 'kind'), ''),
8272
8493
  'eventKey',
@@ -8365,6 +8586,7 @@ export async function claimPostgresSchedulerCompletedDetachedRunnerTerminal(
8365
8586
  $3,
8366
8587
  run_id,
8367
8588
  ${RUN_EVENT_KIND_SQL_LITERAL.runResumed},
8589
+ ${runResumeEpochPayloadSql('running_run.run_id', options)} ||
8368
8590
  jsonb_build_object(
8369
8591
  'kind', 'detached_runner',
8370
8592
  'eventKey', 'detached_runner_terminal'
@@ -8511,6 +8733,7 @@ export async function claimPostgresSchedulerOverdueDetachedRunnerCeilings(
8511
8733
  $3 || ':' || running_runs.run_id,
8512
8734
  running_runs.run_id,
8513
8735
  ${RUN_EVENT_KIND_SQL_LITERAL.runResumed},
8736
+ ${runResumeEpochPayloadSql('running_runs.run_id', options)} ||
8514
8737
  jsonb_build_object(
8515
8738
  'kind', 'detached_runner',
8516
8739
  'eventKey', 'detached_runner_hard_ceiling'
@@ -8769,7 +8992,7 @@ export async function failPostgresSchedulerScheduledChildWaits(
8769
8992
  event_id, run_id, event_type, payload_json, created_at
8770
8993
  )
8771
8994
  SELECT
8772
- 'run-terminal:' || run_id,
8995
+ ${runEndingEventIdSql('terminal_runs.run_id', options)},
8773
8996
  terminal_runs.run_id,
8774
8997
  ${RUN_EVENT_KIND_SQL_LITERAL.runFailed},
8775
8998
  jsonb_build_object('error', $2::text),
@@ -9039,6 +9262,7 @@ export async function claimPostgresSchedulerWaitingDetachedAttemptForTerminal(
9039
9262
  $4,
9040
9263
  running_run.run_id,
9041
9264
  ${RUN_EVENT_KIND_SQL_LITERAL.runResumed},
9265
+ ${runResumeEpochPayloadSql('running_run.run_id', options)} ||
9042
9266
  jsonb_build_object(
9043
9267
  'kind', 'detached_runner',
9044
9268
  'eventKey', 'detached_runner_terminal_salvage'
@@ -9178,113 +9402,923 @@ export async function claimPostgresSchedulerRecoveryCircuit(
9178
9402
  (state = 'open' AND open_until_ms <= $2::bigint)
9179
9403
  OR (state = 'half_open' AND probe_until_ms <= $2::bigint)
9180
9404
  )
9181
- RETURNING dependency, probe_token
9405
+ RETURNING dependency, probe_token
9406
+ `,
9407
+ [
9408
+ input.dependency,
9409
+ input.nowMs,
9410
+ RECOVERY_CIRCUIT_PROBE_LEASE_MS,
9411
+ probeToken,
9412
+ ],
9413
+ );
9414
+ if (probe.rows.length > 0) {
9415
+ return { allowed: true, probeToken: probe.rows[0]?.probe_token ?? null };
9416
+ }
9417
+ const current = await client.query<{ state: string }>(
9418
+ `SELECT state
9419
+ FROM ${tableName(POSTGRES_SCHEDULER_DEPENDENCY_CIRCUITS_TABLE, options)}
9420
+ WHERE dependency = $1`,
9421
+ [input.dependency],
9422
+ );
9423
+ return { allowed: current.rows[0]?.state === 'closed', probeToken: null };
9424
+ }
9425
+
9426
+ /** Mark a half-open probe healthy only after its provider resource is durable. */
9427
+ export async function closePostgresSchedulerRecoveryCircuit(
9428
+ client: PostgresSchedulerQueryClient,
9429
+ input: { dependency: string; probeToken: string },
9430
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
9431
+ ): Promise<boolean> {
9432
+ const result = await client.query<{ dependency: string }>(
9433
+ `
9434
+ UPDATE ${tableName(POSTGRES_SCHEDULER_DEPENDENCY_CIRCUITS_TABLE, options)}
9435
+ SET state = 'closed',
9436
+ open_until_ms = 0,
9437
+ probe_until_ms = 0,
9438
+ probe_token = NULL,
9439
+ updated_at = now()
9440
+ WHERE dependency = $1
9441
+ AND state = 'half_open'
9442
+ AND probe_token = $2
9443
+ RETURNING dependency
9444
+ `,
9445
+ [input.dependency, input.probeToken],
9446
+ );
9447
+ return result.rows.length > 0;
9448
+ }
9449
+
9450
+ /** Operator-only recovery after a verified incident; keep an auditable reason. */
9451
+ export async function resetPostgresSchedulerRecoveryCircuit(
9452
+ client: PostgresSchedulerQueryClient,
9453
+ input: { dependency: string; reason: string },
9454
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
9455
+ ): Promise<boolean> {
9456
+ const result = await client.query<{ dependency: string }>(
9457
+ `
9458
+ UPDATE ${tableName(POSTGRES_SCHEDULER_DEPENDENCY_CIRCUITS_TABLE, options)}
9459
+ SET state = 'closed',
9460
+ open_until_ms = 0,
9461
+ probe_until_ms = 0,
9462
+ probe_token = NULL,
9463
+ last_reason = $2,
9464
+ updated_at = now()
9465
+ WHERE dependency = $1
9466
+ RETURNING dependency
9467
+ `,
9468
+ [input.dependency, input.reason],
9469
+ );
9470
+ return result.rows.length > 0;
9471
+ }
9472
+
9473
+ export async function readPostgresSchedulerRecoveryCircuits(
9474
+ client: PostgresSchedulerQueryClient,
9475
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
9476
+ ): Promise<PostgresSchedulerRecoveryCircuit[]> {
9477
+ const result = await client.query<{
9478
+ dependency: string;
9479
+ state: PostgresSchedulerRecoveryCircuit['state'];
9480
+ open_until_ms: string;
9481
+ probe_until_ms: string;
9482
+ last_reason: string | null;
9483
+ updated_at: Date;
9484
+ }>(
9485
+ `SELECT dependency, state, open_until_ms, probe_until_ms, last_reason, updated_at
9486
+ FROM ${tableName(POSTGRES_SCHEDULER_DEPENDENCY_CIRCUITS_TABLE, options)}
9487
+ ORDER BY dependency`,
9488
+ );
9489
+ return result.rows.map((row) => ({
9490
+ dependency: row.dependency,
9491
+ state: row.state,
9492
+ openUntilMs: Number(row.open_until_ms),
9493
+ probeUntilMs: Number(row.probe_until_ms),
9494
+ lastReason: row.last_reason,
9495
+ updatedAt: row.updated_at,
9496
+ }));
9497
+ }
9498
+
9499
+ export type PostgresSchedulerRecoveryDeferral = {
9500
+ deferred: boolean;
9501
+ exhausted: boolean;
9502
+ deferCount: number | null;
9503
+ deadlineAtMs: number | null;
9504
+ };
9505
+
9506
+ /**
9507
+ * Park a proven pre-code platform failure without spending an Absurd engine
9508
+ * attempt. Unlike ordinary capacity parking, this records a finite recovery
9509
+ * horizon on the canonical run row. The task engine owns the wake; this store
9510
+ * owns the fact that another wake is still allowed.
9511
+ */
9512
+ /**
9513
+ * The outbox event ID of a run's ending. A run that was never resumed keeps
9514
+ * `run-terminal:{runId}`, so its consumers see no change; each ending after
9515
+ * a resume gets `run-ended:{runId}:{epoch}`, so it is a new event instead of
9516
+ * a conflict with the earlier ending. Mirror of `runEndingEventId`.
9517
+ */
9518
+ function runEndingEventIdSql(
9519
+ runIdExpression: string,
9520
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
9521
+ ): string {
9522
+ return `(
9523
+ SELECT CASE
9524
+ WHEN coalesce(
9525
+ (coalesce(ending_run.admission_json, ending_run.launch_json) ->> 'resumeEpoch')::integer,
9526
+ 0
9527
+ ) = 0
9528
+ THEN 'run-terminal:' || ending_run.run_id
9529
+ ELSE 'run-ended:' || ending_run.run_id || ':' ||
9530
+ (coalesce(ending_run.admission_json, ending_run.launch_json) ->> 'resumeEpoch')
9531
+ END
9532
+ FROM ${tableName('runs', options)} AS ending_run
9533
+ WHERE ending_run.run_id = ${runIdExpression}
9534
+ )`;
9535
+ }
9536
+
9537
+ /** Freeze the epoch when a lifecycle fact is written, never at delivery. */
9538
+ function runResumeEpochPayloadSql(
9539
+ runIdExpression: string,
9540
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
9541
+ ): string {
9542
+ return `(SELECT CASE WHEN coalesce((coalesce(epoch_run.admission_json, epoch_run.launch_json) ->> 'resumeEpoch')::integer, 0) > 0
9543
+ THEN jsonb_build_object('epoch', (coalesce(epoch_run.admission_json, epoch_run.launch_json) ->> 'resumeEpoch')::integer)
9544
+ ELSE '{}'::jsonb END
9545
+ FROM ${tableName('runs', options)} AS epoch_run
9546
+ WHERE epoch_run.run_id = ${runIdExpression})`;
9547
+ }
9548
+
9549
+ /** The ending event ID for a run at its current resume epoch. */
9550
+ export async function readPostgresSchedulerRunEndingEventId(
9551
+ client: PostgresSchedulerQueryClient,
9552
+ runId: string,
9553
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
9554
+ ): Promise<string> {
9555
+ const result = await client.query<{ event_id: string | null }>(
9556
+ `SELECT ${runEndingEventIdSql('$1::text', options)} AS event_id`,
9557
+ [runId],
9558
+ );
9559
+ return result.rows[0]?.event_id ?? runEndingEventId(runId);
9560
+ }
9561
+
9562
+ /** How long after it ended a failed or cancelled run can be resumed. */
9563
+ export const RUN_RESUME_WINDOW_MS = 14 * 24 * 60 * 60_000;
9564
+
9565
+ export type PostgresSchedulerRunResume =
9566
+ | { resumed: true; epoch: number; taskId: string }
9567
+ | {
9568
+ resumed: false;
9569
+ reason:
9570
+ | 'run_not_found'
9571
+ | 'run_not_stopped'
9572
+ | 'attempt_not_settled'
9573
+ | 'sandbox_cleanup_pending'
9574
+ | 'resume_window_expired'
9575
+ /**
9576
+ * The run made a call with no recorded result (a pre-edition-11
9577
+ * inline child) or predates replay tracking, so continuing it could
9578
+ * repeat work.
9579
+ */
9580
+ | 'not_replay_safe'
9581
+ /** The Play changed since this run; start over on the new code. */
9582
+ | 'play_revision_changed'
9583
+ /**
9584
+ * The run's staged array input was deleted at its ending, so a
9585
+ * resumed attempt could not read its rows. Start over with
9586
+ * `plays run --from-run`.
9587
+ */
9588
+ | 'staged_input_retired';
9589
+ };
9590
+
9591
+ /** Scheduler-owned reasons a stopped run cannot continue in place. */
9592
+ export type PostgresSchedulerRunResumeRefusal = Exclude<
9593
+ Extract<PostgresSchedulerRunResume, { resumed: false }>['reason'],
9594
+ 'run_not_found'
9595
+ >;
9596
+
9597
+ /** The facts the resume gate reads, one boolean per gate. */
9598
+ export type PostgresSchedulerRunResumeChecks = {
9599
+ stopped: boolean;
9600
+ attempts_settled: boolean;
9601
+ cleanup_settled: boolean;
9602
+ within_window: boolean;
9603
+ input_kept: boolean;
9604
+ replay_safe: boolean;
9605
+ revision_unchanged: boolean;
9606
+ };
9607
+
9608
+ /**
9609
+ * The one resume predicate: the refusal a run's checks produce, in the order
9610
+ * `resumePostgresSchedulerRun` reports it, or null when every gate passes.
9611
+ * Resume and every read-only eligibility reader share this and
9612
+ * `postgresSchedulerRunResumeChecksSql`, so an operator view can never
9613
+ * disagree with what resume would do.
9614
+ */
9615
+ export function postgresSchedulerRunResumeRefusal(
9616
+ checks: PostgresSchedulerRunResumeChecks,
9617
+ ): PostgresSchedulerRunResumeRefusal | null {
9618
+ if (!checks.stopped) return 'run_not_stopped';
9619
+ if (!checks.attempts_settled) return 'attempt_not_settled';
9620
+ if (!checks.cleanup_settled) return 'sandbox_cleanup_pending';
9621
+ if (!checks.replay_safe) return 'not_replay_safe';
9622
+ if (!checks.revision_unchanged) return 'play_revision_changed';
9623
+ if (!checks.input_kept) return 'staged_input_retired';
9624
+ if (!checks.within_window) return 'resume_window_expired';
9625
+ return null;
9626
+ }
9627
+
9628
+ /** Columns of the `target` row the resume checks read, from `runs AS runs`. */
9629
+ function postgresSchedulerRunResumeTargetColumnsSql(): string {
9630
+ return `runs.run_id,
9631
+ runs.status,
9632
+ runs.finished_at,
9633
+ -- Row JSON keeps this optional on historical scheduler schemas.
9634
+ to_jsonb(runs) ->> 'array_input_retired_at'
9635
+ AS array_input_retired_at,
9636
+ to_jsonb(runs) ->> 'array_input_kept_for_resume_at'
9637
+ AS array_input_kept_for_resume_at,
9638
+ runs.array_input_started,
9639
+ runs.launch_json ->> 'revisionId' AS revision_id,
9640
+ coalesce(
9641
+ (coalesce(runs.admission_json, runs.launch_json) ->> 'resumeEpoch')::integer,
9642
+ 0
9643
+ ) AS epoch`;
9644
+ }
9645
+
9646
+ /**
9647
+ * The resume checks over a `target` row, as SQL select-list columns. Each
9648
+ * input is a SQL expression, so the locking resume statement and the
9649
+ * read-only batch reader evaluate the identical predicate.
9650
+ */
9651
+ function postgresSchedulerRunResumeChecksSql(
9652
+ input: {
9653
+ orgIdSql: string;
9654
+ windowMsSql: string;
9655
+ revisionIdsSql: string;
9656
+ trackedMarkerKeySql: string;
9657
+ unsafeMarkerKeySql: string;
9658
+ },
9659
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
9660
+ ): string {
9661
+ return `target.status IN ('failed', 'cancelled') AS stopped,
9662
+ NOT EXISTS (
9663
+ SELECT 1 FROM ${tableName('attempts', options)} AS attempts
9664
+ WHERE attempts.run_id = target.run_id
9665
+ AND attempts.status IN ('queued', 'claimed', 'running', 'waiting')
9666
+ )
9667
+ -- The stopped epoch's compute bills against the current
9668
+ -- launch; it must settle before the launch moves to a new one.
9669
+ AND NOT EXISTS (
9670
+ SELECT 1
9671
+ FROM ${tableName('compute_billing_jobs_v2', options)} AS billing
9672
+ WHERE billing.run_id = target.run_id
9673
+ AND billing.status <> 'settled'
9674
+ ) AS attempts_settled,
9675
+ NOT EXISTS (
9676
+ SELECT 1
9677
+ FROM ${tableName('sandbox_cleanup_jobs_v2', options)} AS cleanup
9678
+ WHERE cleanup.run_id = target.run_id
9679
+ AND cleanup.status <> 'deleted'
9680
+ ) AS cleanup_settled,
9681
+ coalesce(
9682
+ target.finished_at >= now() - (${input.windowMsSql} * interval '1 millisecond'),
9683
+ false
9684
+ ) AS within_window,
9685
+ -- Positive evidence only: the run never staged input, or its
9686
+ -- terminal delivery recorded keeping it. A NULL retired marker
9687
+ -- alone is not proof; an older build deletes input unmarked.
9688
+ (
9689
+ target.array_input_retired_at IS NULL
9690
+ AND (
9691
+ NOT coalesce(target.array_input_started, false)
9692
+ OR target.array_input_kept_for_resume_at IS NOT NULL
9693
+ )
9694
+ ) AS input_kept,
9695
+ (
9696
+ EXISTS (
9697
+ SELECT 1 FROM ${tableName('receipts', options)} AS marker
9698
+ WHERE marker.org_id = ${input.orgIdSql} AND marker.k = ${input.trackedMarkerKeySql}
9699
+ AND marker.status = 'completed'
9700
+ )
9701
+ AND NOT EXISTS (
9702
+ SELECT 1 FROM ${tableName('receipts', options)} AS marker
9703
+ WHERE marker.org_id = ${input.orgIdSql} AND marker.k = ${input.unsafeMarkerKeySql}
9704
+ )
9705
+ ) AS replay_safe,
9706
+ (
9707
+ target.revision_id IS NULL
9708
+ OR target.revision_id = ANY(${input.revisionIdsSql})
9709
+ ) AS revision_unchanged`;
9710
+ }
9711
+
9712
+ /** At most this many runs are evaluated by one read-only eligibility read. */
9713
+ export const POSTGRES_SCHEDULER_RESUME_ELIGIBILITY_MAX_RUNS = 100;
9714
+
9715
+ export type PostgresSchedulerRunResumeEligibility = {
9716
+ runId: string;
9717
+ /** False when the run is absent from this org (resume: `run_not_found`). */
9718
+ found: boolean;
9719
+ checks: PostgresSchedulerRunResumeChecks | null;
9720
+ /** Null when resume would continue the run now. */
9721
+ refusal: PostgresSchedulerRunResumeRefusal | 'run_not_found' | null;
9722
+ /** The epoch resume would continue from. */
9723
+ epoch: number | null;
9724
+ };
9725
+
9726
+ /**
9727
+ * Read-only resume eligibility for a bounded batch of runs: the exact
9728
+ * predicate resume evaluates, without its row lock, task spawn or write. A
9729
+ * concurrent writer can still change the answer before a resume runs; the
9730
+ * resume statement re-evaluates the same predicate under its lock.
9731
+ */
9732
+ export async function readPostgresSchedulerRunResumeEligibility(
9733
+ client: PostgresSchedulerQueryClient,
9734
+ input: {
9735
+ runs: readonly {
9736
+ runId: string;
9737
+ orgId: string;
9738
+ /** The Play's current revisions, as resume passes them. */
9739
+ currentRevisionIds: readonly string[];
9740
+ }[];
9741
+ },
9742
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
9743
+ ): Promise<PostgresSchedulerRunResumeEligibility[]> {
9744
+ if (input.runs.length === 0) return [];
9745
+ if (input.runs.length > POSTGRES_SCHEDULER_RESUME_ELIGIBILITY_MAX_RUNS) {
9746
+ throw new Error(
9747
+ `Resume eligibility reads at most ${POSTGRES_SCHEDULER_RESUME_ELIGIBILITY_MAX_RUNS} runs; received ${input.runs.length}.`,
9748
+ );
9749
+ }
9750
+ const requested = input.runs.map((run) => ({
9751
+ run_id: run.runId,
9752
+ org_id: run.orgId,
9753
+ revision_ids: [...run.currentRevisionIds],
9754
+ tracked_key: replayTrackedMarkerReceiptKey(run.orgId, run.runId),
9755
+ unsafe_key: replayUnsafeMarkerReceiptKey(run.orgId, run.runId),
9756
+ }));
9757
+ const result = await client.query<
9758
+ {
9759
+ run_id: string;
9760
+ epoch: number | string;
9761
+ } & PostgresSchedulerRunResumeChecks
9762
+ >(
9763
+ `
9764
+ WITH requested AS (
9765
+ SELECT *
9766
+ FROM jsonb_to_recordset($1::jsonb) AS requested(
9767
+ run_id text, org_id text, revision_ids jsonb,
9768
+ tracked_key text, unsafe_key text
9769
+ )
9770
+ ), target AS (
9771
+ SELECT ${postgresSchedulerRunResumeTargetColumnsSql()},
9772
+ requested.org_id AS requested_org_id,
9773
+ ARRAY(
9774
+ SELECT jsonb_array_elements_text(requested.revision_ids)
9775
+ )::text[] AS requested_revision_ids,
9776
+ requested.tracked_key,
9777
+ requested.unsafe_key
9778
+ FROM requested
9779
+ JOIN ${tableName('runs', options)} AS runs
9780
+ ON runs.run_id = requested.run_id
9781
+ AND runs.org_id = requested.org_id
9782
+ )
9783
+ SELECT target.run_id,
9784
+ target.epoch,
9785
+ ${postgresSchedulerRunResumeChecksSql(
9786
+ {
9787
+ orgIdSql: 'target.requested_org_id',
9788
+ windowMsSql: '$2::bigint',
9789
+ revisionIdsSql: 'target.requested_revision_ids',
9790
+ trackedMarkerKeySql: 'target.tracked_key',
9791
+ unsafeMarkerKeySql: 'target.unsafe_key',
9792
+ },
9793
+ options,
9794
+ )}
9795
+ FROM target
9796
+ `,
9797
+ [stringifyPostgresJson(requested), RUN_RESUME_WINDOW_MS],
9798
+ );
9799
+ const byRunId = new Map(result.rows.map((row) => [row.run_id, row]));
9800
+ return input.runs.map((run) => {
9801
+ const row = byRunId.get(run.runId);
9802
+ if (!row) {
9803
+ return {
9804
+ runId: run.runId,
9805
+ found: false,
9806
+ checks: null,
9807
+ refusal: 'run_not_found',
9808
+ epoch: null,
9809
+ };
9810
+ }
9811
+ const checks: PostgresSchedulerRunResumeChecks = {
9812
+ stopped: row.stopped === true,
9813
+ attempts_settled: row.attempts_settled === true,
9814
+ cleanup_settled: row.cleanup_settled === true,
9815
+ within_window: row.within_window === true,
9816
+ input_kept: row.input_kept === true,
9817
+ replay_safe: row.replay_safe === true,
9818
+ revision_unchanged: row.revision_unchanged === true,
9819
+ };
9820
+ return {
9821
+ runId: run.runId,
9822
+ found: true,
9823
+ checks,
9824
+ refusal: postgresSchedulerRunResumeRefusal(checks),
9825
+ epoch: Number(row.epoch),
9826
+ };
9827
+ });
9828
+ }
9829
+
9830
+ /**
9831
+ * Continue a failed or cancelled run as the same run.
9832
+ *
9833
+ * One statement: compare-and-set the run from its ending back to queued,
9834
+ * bump its resume epoch, clear the ending, stamp the caller's current release
9835
+ * lane (a run is pinned to the lane that admitted it, which is usually retired
9836
+ * within a day), spawn a new scheduler task (the finished one cannot restart)
9837
+ * keyed by run and epoch, record it as the run's task, reset the post-code
9838
+ * recovery budget, and append the `run.resumed` event. Its next attempt
9839
+ * replays the Play from its checkpoint and recovers every recorded call.
9840
+ *
9841
+ * The epoch lives in `launch_json.resumeEpoch` (absent means 0) and is not
9842
+ * part of launch identity. Readers order a run's endings by it, so a later
9843
+ * ending supersedes an earlier one instead of being dropped as a duplicate.
9844
+ */
9845
+ export async function resumePostgresSchedulerRun(
9846
+ client: PostgresSchedulerQueryClient,
9847
+ input: {
9848
+ runId: string;
9849
+ orgId: string;
9850
+ requestedBy: string | null;
9851
+ releaseId: string;
9852
+ releaseEnvironment: string;
9853
+ /**
9854
+ * The Play's current revisions (working and live). A run pinned to a
9855
+ * revision that is neither is refused. A run with no revision (started
9856
+ * from a local file) skips the check. A missing Play cannot establish that
9857
+ * its pinned revision is unchanged.
9858
+ */
9859
+ currentRevisionIds: readonly string[];
9860
+ task: {
9861
+ queueName: string;
9862
+ taskName: string;
9863
+ params: Record<string, unknown>;
9864
+ options: Record<string, unknown>;
9865
+ };
9866
+ },
9867
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
9868
+ ): Promise<PostgresSchedulerRunResume> {
9869
+ const result = await client.query<
9870
+ {
9871
+ found: boolean;
9872
+ task_id: string | null;
9873
+ epoch: number | null;
9874
+ } & PostgresSchedulerRunResumeChecks
9875
+ >(
9876
+ `
9877
+ WITH target AS (
9878
+ SELECT ${postgresSchedulerRunResumeTargetColumnsSql()}
9879
+ FROM ${tableName('runs', options)} AS runs
9880
+ WHERE runs.run_id = $1
9881
+ AND runs.org_id = $2
9882
+ FOR UPDATE
9883
+ ), checks AS (
9884
+ SELECT target.*,
9885
+ ${postgresSchedulerRunResumeChecksSql(
9886
+ {
9887
+ orgIdSql: '$2',
9888
+ windowMsSql: '$3::bigint',
9889
+ revisionIdsSql: '$11::text[]',
9890
+ trackedMarkerKeySql: '$12',
9891
+ unsafeMarkerKeySql: '$13',
9892
+ },
9893
+ options,
9894
+ )}
9895
+ FROM target
9896
+ ), eligible AS (
9897
+ SELECT * FROM checks
9898
+ WHERE stopped AND attempts_settled AND cleanup_settled AND within_window
9899
+ AND input_kept AND replay_safe AND revision_unchanged
9900
+ ), task_spawn AS MATERIALIZED (
9901
+ SELECT spawned.task_id::text AS task_id, eligible.epoch + 1 AS epoch,
9902
+ -- The resumed epoch's attempts start after every earlier one;
9903
+ -- its compute is billed from these alone.
9904
+ (
9905
+ SELECT coalesce(max(attempts.attempt), 0) + 1
9906
+ FROM ${tableName('attempts', options)} AS attempts
9907
+ WHERE attempts.run_id = eligible.run_id
9908
+ ) AS first_attempt
9909
+ FROM eligible
9910
+ CROSS JOIN LATERAL absurd.spawn_task(
9911
+ $4::text,
9912
+ $5::text,
9913
+ $6::jsonb,
9914
+ $7::jsonb || jsonb_build_object(
9915
+ 'idempotency_key',
9916
+ eligible.run_id || ':resume:' || (eligible.epoch + 1)::text
9917
+ )
9918
+ ) AS spawned
9919
+ ), resumed AS (
9920
+ UPDATE ${tableName('runs', options)} AS runs
9921
+ SET status = 'queued',
9922
+ terminal_result_json = NULL,
9923
+ terminal_error_json = NULL,
9924
+ finished_at = NULL,
9925
+ suspension_json = NULL,
9926
+ wait_deadline = NULL,
9927
+ absurd_task_id = task_spawn.task_id,
9928
+ recovery_json = coalesce(runs.recovery_json, '{}'::jsonb) - ARRAY[
9929
+ 'postCode', 'version', 'kind', 'dependency', 'reason', 'deferCount',
9930
+ 'deadlineAtMs', 'nextRetryAtMs', 'updatedAtMs', 'exhaustedAtMs'
9931
+ ]::text[],
9932
+ launch_json = runs.launch_json || jsonb_build_object(
9933
+ 'resumeEpoch', task_spawn.epoch,
9934
+ 'resumeEpochFirstAttempt', task_spawn.first_attempt,
9935
+ 'absurdReleaseId', $8::text,
9936
+ 'absurdReleaseEnvironment', $9::text
9937
+ ),
9938
+ -- Readers use admission_json in place of launch_json when it is
9939
+ -- present, so the epoch and lane must land in both.
9940
+ admission_json = CASE
9941
+ WHEN runs.admission_json IS NULL THEN NULL
9942
+ ELSE runs.admission_json || jsonb_build_object(
9943
+ 'resumeEpoch', task_spawn.epoch,
9944
+ 'resumeEpochFirstAttempt', task_spawn.first_attempt,
9945
+ 'absurdReleaseId', $8::text,
9946
+ 'absurdReleaseEnvironment', $9::text
9947
+ )
9948
+ END,
9949
+ updated_at = now()
9950
+ FROM task_spawn
9951
+ WHERE runs.run_id = $1
9952
+ RETURNING runs.run_id, task_spawn.epoch, task_spawn.task_id
9953
+ ), resumed_event AS (
9954
+ INSERT INTO ${tableName('outbox', options)} (
9955
+ event_id, run_id, event_type, payload_json
9956
+ )
9957
+ SELECT 'run-resumed:' || resumed.run_id || ':' || resumed.epoch::text,
9958
+ resumed.run_id,
9959
+ 'run.resumed',
9960
+ jsonb_build_object(
9961
+ 'runId', resumed.run_id,
9962
+ 'epoch', resumed.epoch,
9963
+ 'requestedBy', $10::text,
9964
+ 'resumedAtMs', (extract(epoch from clock_timestamp()) * 1000)::bigint
9965
+ )
9966
+ FROM resumed
9967
+ ON CONFLICT (event_id) DO NOTHING
9968
+ RETURNING event_id
9969
+ )
9970
+ SELECT EXISTS (SELECT 1 FROM checks) AS found,
9971
+ coalesce((SELECT stopped FROM checks), false) AS stopped,
9972
+ coalesce((SELECT attempts_settled FROM checks), false) AS attempts_settled,
9973
+ coalesce((SELECT cleanup_settled FROM checks), false) AS cleanup_settled,
9974
+ coalesce((SELECT within_window FROM checks), false) AS within_window,
9975
+ coalesce((SELECT input_kept FROM checks), false) AS input_kept,
9976
+ coalesce((SELECT replay_safe FROM checks), false) AS replay_safe,
9977
+ coalesce((SELECT revision_unchanged FROM checks), false)
9978
+ AS revision_unchanged,
9979
+ (SELECT task_id FROM resumed) AS task_id,
9980
+ (SELECT epoch FROM resumed) AS epoch
9981
+ `,
9982
+ [
9983
+ input.runId,
9984
+ input.orgId,
9985
+ RUN_RESUME_WINDOW_MS,
9986
+ input.task.queueName,
9987
+ input.task.taskName,
9988
+ stringifyPostgresJson(input.task.params),
9989
+ stringifyPostgresJson(input.task.options),
9990
+ input.releaseId,
9991
+ input.releaseEnvironment,
9992
+ input.requestedBy,
9993
+ [...input.currentRevisionIds],
9994
+ replayTrackedMarkerReceiptKey(input.orgId, input.runId),
9995
+ replayUnsafeMarkerReceiptKey(input.orgId, input.runId),
9996
+ ],
9997
+ );
9998
+ const row = result.rows[0];
9999
+ if (!row?.found) return { resumed: false, reason: 'run_not_found' };
10000
+ if (row.task_id && row.epoch !== null) {
10001
+ return { resumed: true, epoch: Number(row.epoch), taskId: row.task_id };
10002
+ }
10003
+ // Every check passed but no task was spawned: report the last gate, as
10004
+ // before this predicate was shared.
10005
+ return {
10006
+ resumed: false,
10007
+ reason: postgresSchedulerRunResumeRefusal(row) ?? 'resume_window_expired',
10008
+ };
10009
+ }
10010
+
10011
+ /** Whether any attempt of the run was retired for post-code recovery. */
10012
+ export async function hasPostgresSchedulerPostCodeRecoveryDeferral(
10013
+ client: PostgresSchedulerQueryClient,
10014
+ input: { runId: string },
10015
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
10016
+ ): Promise<boolean> {
10017
+ const result = await client.query<{ deferred: boolean }>(
10018
+ `SELECT EXISTS (
10019
+ SELECT 1 FROM ${tableName('attempts', options)} AS attempts
10020
+ WHERE attempts.run_id = $1
10021
+ AND attempts.error_json ->> 'kind' = 'platform_post_code_recovery'
10022
+ ) AS deferred`,
10023
+ [input.runId],
10024
+ );
10025
+ return result.rows[0]?.deferred === true;
10026
+ }
10027
+
10028
+ export type PostgresSchedulerPostCodeRecoveryDeferral = {
10029
+ /** The attempt was retired and the run requeued for `delayMs`. */
10030
+ deferred: boolean;
10031
+ /** The budget is spent (count, horizon or no progress); fail the run. */
10032
+ exhausted: boolean;
10033
+ deferCount: number | null;
10034
+ delayMs: number | null;
10035
+ deadlineAtMs: number | null;
10036
+ historyRows: number | null;
10037
+ /**
10038
+ * False when the run lacks the runner's replay-tracked marker or carries
10039
+ * the replay-unsafe marker; such a run is never deferred.
10040
+ */
10041
+ replaySafe: boolean;
10042
+ };
10043
+
10044
+ /** Public progress is committed with the fenced recovery decision, never
10045
+ * inferred from an error string or appended after the attempt becomes stale.
10046
+ * Both callers expose the same bounded activity and existing wire vocabulary.
10047
+ */
10048
+ function platformRecoveryActivityEventSql(stateSql: string): string {
10049
+ return `jsonb_build_object(
10050
+ 'type', ${RUN_EVENT_KIND_SQL_LITERAL.activityObserved},
10051
+ 'runId', requeued_run.run_id,
10052
+ 'source', 'worker',
10053
+ 'occurredAt', $7::bigint,
10054
+ 'resumeEpoch', coalesce(requeued_run.launch_json->'resumeEpoch', '0'::jsonb),
10055
+ 'observation', jsonb_build_object(
10056
+ 'activityId', ${escapeLiteral(PLATFORM_RECOVERY_ACTIVITY_ID)},
10057
+ 'target', jsonb_build_object(
10058
+ 'kind', 'capacity', 'pool', 'runner', 'label', 'Play execution'
10059
+ ),
10060
+ 'state', jsonb_build_object(
10061
+ 'kind', 'retrying', 'reason', 'transport_error',
10062
+ 'retryAt', (${stateSql})->'nextRetryAtMs',
10063
+ 'attempt', $2::integer
10064
+ ),
10065
+ 'observedAt', $7::bigint
10066
+ )
10067
+ )`;
10068
+ }
10069
+
10070
+ /**
10071
+ * Defer a run whose attempt ended in a post-code platform failure.
10072
+ *
10073
+ * Its counters live under `recovery_json.postCode`, beside the pre-code
10074
+ * fields, and are merged rather than rebuilt. The progress rule counts the
10075
+ * run's completed history rows: an attempt that records nothing new raises
10076
+ * the unproductive streak, and reaching `maxUnproductiveAttempts` exhausts
10077
+ * the budget, so a Play that crashes the same way every time stops instead
10078
+ * of looping until the horizon. The caller computes the jittered delay so
10079
+ * the scheduler's actual DeferTask delay and the stored next-retry time are
10080
+ * the same number.
10081
+ */
10082
+ export async function deferPostgresSchedulerAttemptForPostCodeRecovery(
10083
+ client: PostgresSchedulerQueryClient,
10084
+ input: {
10085
+ runId: string;
10086
+ orgId: string;
10087
+ attempt: number;
10088
+ leaseToken: string;
10089
+ reason: string;
10090
+ nowMs: number;
10091
+ maxDefers: number;
10092
+ horizonMs: number;
10093
+ maxUnproductiveAttempts: number;
10094
+ /**
10095
+ * Whether an attempt that recorded nothing counts toward the no-progress
10096
+ * rule. An outage stops progress through no fault of the Play.
10097
+ */
10098
+ countsTowardProgress?: boolean;
10099
+ /** Delay for the defer that this call would record, by its defer count. */
10100
+ delayMsForDeferCount: (deferCount: number) => number;
10101
+ replayTrackedMarkerKey: string;
10102
+ replayUnsafeMarkerKey: string;
10103
+ },
10104
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
10105
+ ): Promise<PostgresSchedulerPostCodeRecoveryDeferral> {
10106
+ const probe = await client.query<{
10107
+ defer_count: string | null;
10108
+ history_rows: string;
10109
+ replay_safe: boolean;
10110
+ }>(
10111
+ `
10112
+ SELECT coalesce((runs.recovery_json #>> '{postCode,deferCount}')::integer, 0) + 1
10113
+ AS defer_count,
10114
+ (
10115
+ EXISTS (
10116
+ SELECT 1 FROM ${tableName('receipts', options)} AS marker
10117
+ WHERE marker.org_id = $2 AND marker.k = $3
10118
+ AND marker.status = 'completed'
10119
+ )
10120
+ AND NOT EXISTS (
10121
+ SELECT 1 FROM ${tableName('receipts', options)} AS marker
10122
+ WHERE marker.org_id = $2 AND marker.k = $4
10123
+ )
10124
+ ) AS replay_safe,
10125
+ (
10126
+ SELECT count(*)
10127
+ FROM ${tableName('receipts', options)} AS receipts
10128
+ WHERE receipts.org_id = $2
10129
+ AND receipts.run_id = $1
10130
+ AND receipts.status = 'completed'
10131
+ AND receipts.k LIKE 'ctx:' || $2 || ':freshness:operation:%'
10132
+ )::text AS history_rows
10133
+ FROM ${tableName('runs', options)} AS runs
10134
+ WHERE runs.run_id = $1
10135
+ `,
10136
+ [
10137
+ input.runId,
10138
+ input.orgId,
10139
+ input.replayTrackedMarkerKey,
10140
+ input.replayUnsafeMarkerKey,
10141
+ ],
10142
+ );
10143
+ const probed = probe.rows[0];
10144
+ if (!probed || probed.replay_safe !== true) {
10145
+ return {
10146
+ deferred: false,
10147
+ exhausted: false,
10148
+ deferCount: null,
10149
+ delayMs: null,
10150
+ deadlineAtMs: null,
10151
+ historyRows: null,
10152
+ replaySafe: false,
10153
+ };
10154
+ }
10155
+ const nextDeferCount = Number(probed.defer_count ?? '1');
10156
+ const delayMs = input.delayMsForDeferCount(nextDeferCount);
10157
+ const historyRows = Number(probed.history_rows);
10158
+ const result = await client.query<{
10159
+ candidate: boolean;
10160
+ deferred: boolean;
10161
+ defer_count: string | null;
10162
+ deadline_at_ms: string | null;
10163
+ }>(
10164
+ `
10165
+ WITH ${runtimeSandboxCustodyLocksSql('run.run_id = $1', options)}, candidate AS (
10166
+ SELECT runs.run_id,
10167
+ coalesce(runs.recovery_json, '{}'::jsonb) AS recovery_json
10168
+ FROM custody_runs AS runs
10169
+ JOIN custody_attempts AS attempts
10170
+ ON attempts.run_id = runs.run_id
10171
+ WHERE attempts.run_id = $1
10172
+ AND attempts.attempt = $2
10173
+ AND attempts.lease_token = $3
10174
+ AND attempts.status IN ('claimed', 'running', 'waiting')
10175
+ AND runs.status IN ('queued', 'running', 'waiting')
10176
+ ), computed AS (
10177
+ SELECT run_id,
10178
+ recovery_json,
10179
+ coalesce((recovery_json #>> '{postCode,deferCount}')::integer, 0) + 1
10180
+ AS defer_count,
10181
+ coalesce(
10182
+ (recovery_json #>> '{postCode,deadlineAtMs}')::bigint,
10183
+ $4::bigint
10184
+ ) AS deadline_at_ms,
10185
+ CASE
10186
+ WHEN NOT $12::boolean
10187
+ THEN coalesce(
10188
+ (recovery_json #>> '{postCode,unproductiveAttempts}')::integer,
10189
+ 0
10190
+ )
10191
+ WHEN coalesce((recovery_json #>> '{postCode,historyRowsAtLastDefer}')::bigint, 0)
10192
+ IS NOT DISTINCT FROM $10::bigint
10193
+ THEN coalesce(
10194
+ (recovery_json #>> '{postCode,unproductiveAttempts}')::integer,
10195
+ 0
10196
+ ) + 1
10197
+ ELSE 0
10198
+ END AS unproductive_attempts
10199
+ FROM candidate
10200
+ ), deferred_attempt AS (
10201
+ UPDATE ${tableName('attempts', options)} AS attempts
10202
+ SET status = 'stale',
10203
+ lease_expires_at = NULL,
10204
+ heartbeat_at = now(),
10205
+ error_json = $5::jsonb,
10206
+ updated_at = now()
10207
+ FROM computed
10208
+ WHERE attempts.run_id = computed.run_id
10209
+ AND attempts.attempt = $2
10210
+ AND attempts.lease_token = $3
10211
+ AND computed.defer_count <= $6
10212
+ AND $7::bigint < computed.deadline_at_ms
10213
+ AND computed.unproductive_attempts < $11
10214
+ RETURNING attempts.run_id
10215
+ ), post_code_state AS (
10216
+ SELECT run_id,
10217
+ jsonb_build_object(
10218
+ 'kind', 'platform_post_code',
10219
+ 'reason', $8::text,
10220
+ 'deferCount', defer_count,
10221
+ 'deadlineAtMs', deadline_at_ms,
10222
+ 'historyRowsAtLastDefer', $10::bigint,
10223
+ 'unproductiveAttempts', unproductive_attempts,
10224
+ 'updatedAtMs', $7::bigint
10225
+ ) AS state
10226
+ FROM computed
10227
+ ), requeued_run AS (
10228
+ UPDATE ${tableName('runs', options)} AS runs
10229
+ SET status = 'queued',
10230
+ suspension_json = NULL,
10231
+ wait_deadline = NULL,
10232
+ recovery_json = computed.recovery_json || jsonb_build_object(
10233
+ 'postCode',
10234
+ post_code_state.state || jsonb_build_object(
10235
+ 'nextRetryAtMs', $7::bigint + $9::bigint
10236
+ )
10237
+ ),
10238
+ updated_at = now()
10239
+ FROM computed
10240
+ JOIN post_code_state ON post_code_state.run_id = computed.run_id
10241
+ JOIN deferred_attempt ON deferred_attempt.run_id = computed.run_id
10242
+ WHERE runs.run_id = computed.run_id
10243
+ RETURNING runs.run_id, runs.launch_json, runs.recovery_json
10244
+ ), recovery_activity AS (
10245
+ INSERT INTO ${tableName('outbox', options)} (
10246
+ event_id, run_id, event_type, payload_json, created_at
10247
+ )
10248
+ SELECT 'run-platform-recovery:' || requeued_run.run_id || ':' || $2::text,
10249
+ requeued_run.run_id,
10250
+ ${RUN_SCHEDULER_OUTBOX_EVENT_TYPE_SQL_LITERAL.runEvents},
10251
+ jsonb_build_object('events', jsonb_build_array(
10252
+ ${platformRecoveryActivityEventSql("requeued_run.recovery_json->'postCode'")}
10253
+ )),
10254
+ ${causalOutboxCreatedAt('requeued_run.run_id', options)}
10255
+ FROM requeued_run
10256
+ ON CONFLICT (event_id) DO NOTHING
10257
+ RETURNING event_id
10258
+ ), exhausted_run AS (
10259
+ UPDATE ${tableName('runs', options)} AS runs
10260
+ SET recovery_json = computed.recovery_json || jsonb_build_object(
10261
+ 'postCode',
10262
+ post_code_state.state || jsonb_build_object(
10263
+ 'nextRetryAtMs', NULL,
10264
+ 'exhaustedAtMs', $7::bigint
10265
+ )
10266
+ ),
10267
+ updated_at = now()
10268
+ FROM computed
10269
+ JOIN post_code_state ON post_code_state.run_id = computed.run_id
10270
+ WHERE runs.run_id = computed.run_id
10271
+ AND NOT EXISTS (SELECT 1 FROM deferred_attempt)
10272
+ RETURNING runs.run_id
10273
+ )
10274
+ SELECT EXISTS (SELECT 1 FROM candidate) AS candidate,
10275
+ EXISTS (SELECT 1 FROM requeued_run) AS deferred,
10276
+ (SELECT defer_count::text FROM computed LIMIT 1) AS defer_count,
10277
+ (SELECT deadline_at_ms::text FROM computed LIMIT 1) AS deadline_at_ms
9182
10278
  `,
9183
10279
  [
9184
- input.dependency,
10280
+ input.runId,
10281
+ input.attempt,
10282
+ input.leaseToken,
10283
+ input.nowMs + input.horizonMs,
10284
+ stringifyPostgresJson({
10285
+ kind: 'platform_post_code_recovery',
10286
+ message: input.reason,
10287
+ }),
10288
+ input.maxDefers,
9185
10289
  input.nowMs,
9186
- RECOVERY_CIRCUIT_PROBE_LEASE_MS,
9187
- probeToken,
10290
+ input.reason,
10291
+ delayMs,
10292
+ historyRows,
10293
+ input.maxUnproductiveAttempts,
10294
+ input.countsTowardProgress !== false,
9188
10295
  ],
9189
10296
  );
9190
- if (probe.rows.length > 0) {
9191
- return { allowed: true, probeToken: probe.rows[0]?.probe_token ?? null };
10297
+ const row = result.rows[0];
10298
+ if (!row?.candidate) {
10299
+ return {
10300
+ deferred: false,
10301
+ exhausted: false,
10302
+ deferCount: null,
10303
+ delayMs: null,
10304
+ deadlineAtMs: null,
10305
+ historyRows,
10306
+ replaySafe: true,
10307
+ };
9192
10308
  }
9193
- const current = await client.query<{ state: string }>(
9194
- `SELECT state
9195
- FROM ${tableName(POSTGRES_SCHEDULER_DEPENDENCY_CIRCUITS_TABLE, options)}
9196
- WHERE dependency = $1`,
9197
- [input.dependency],
9198
- );
9199
- return { allowed: current.rows[0]?.state === 'closed', probeToken: null };
9200
- }
9201
-
9202
- /** Mark a half-open probe healthy only after its provider resource is durable. */
9203
- export async function closePostgresSchedulerRecoveryCircuit(
9204
- client: PostgresSchedulerQueryClient,
9205
- input: { dependency: string; probeToken: string },
9206
- options?: Pick<PostgresSchedulerOptions, 'schema'>,
9207
- ): Promise<boolean> {
9208
- const result = await client.query<{ dependency: string }>(
9209
- `
9210
- UPDATE ${tableName(POSTGRES_SCHEDULER_DEPENDENCY_CIRCUITS_TABLE, options)}
9211
- SET state = 'closed',
9212
- open_until_ms = 0,
9213
- probe_until_ms = 0,
9214
- probe_token = NULL,
9215
- updated_at = now()
9216
- WHERE dependency = $1
9217
- AND state = 'half_open'
9218
- AND probe_token = $2
9219
- RETURNING dependency
9220
- `,
9221
- [input.dependency, input.probeToken],
9222
- );
9223
- return result.rows.length > 0;
9224
- }
9225
-
9226
- /** Operator-only recovery after a verified incident; keep an auditable reason. */
9227
- export async function resetPostgresSchedulerRecoveryCircuit(
9228
- client: PostgresSchedulerQueryClient,
9229
- input: { dependency: string; reason: string },
9230
- options?: Pick<PostgresSchedulerOptions, 'schema'>,
9231
- ): Promise<boolean> {
9232
- const result = await client.query<{ dependency: string }>(
9233
- `
9234
- UPDATE ${tableName(POSTGRES_SCHEDULER_DEPENDENCY_CIRCUITS_TABLE, options)}
9235
- SET state = 'closed',
9236
- open_until_ms = 0,
9237
- probe_until_ms = 0,
9238
- probe_token = NULL,
9239
- last_reason = $2,
9240
- updated_at = now()
9241
- WHERE dependency = $1
9242
- RETURNING dependency
9243
- `,
9244
- [input.dependency, input.reason],
9245
- );
9246
- return result.rows.length > 0;
9247
- }
9248
-
9249
- export async function readPostgresSchedulerRecoveryCircuits(
9250
- client: PostgresSchedulerQueryClient,
9251
- options?: Pick<PostgresSchedulerOptions, 'schema'>,
9252
- ): Promise<PostgresSchedulerRecoveryCircuit[]> {
9253
- const result = await client.query<{
9254
- dependency: string;
9255
- state: PostgresSchedulerRecoveryCircuit['state'];
9256
- open_until_ms: string;
9257
- probe_until_ms: string;
9258
- last_reason: string | null;
9259
- updated_at: Date;
9260
- }>(
9261
- `SELECT dependency, state, open_until_ms, probe_until_ms, last_reason, updated_at
9262
- FROM ${tableName(POSTGRES_SCHEDULER_DEPENDENCY_CIRCUITS_TABLE, options)}
9263
- ORDER BY dependency`,
9264
- );
9265
- return result.rows.map((row) => ({
9266
- dependency: row.dependency,
9267
- state: row.state,
9268
- openUntilMs: Number(row.open_until_ms),
9269
- probeUntilMs: Number(row.probe_until_ms),
9270
- lastReason: row.last_reason,
9271
- updatedAt: row.updated_at,
9272
- }));
10309
+ const deferCount = row.defer_count ? Number(row.defer_count) : null;
10310
+ const deadlineAtMs = row.deadline_at_ms ? Number(row.deadline_at_ms) : null;
10311
+ return {
10312
+ deferred: row.deferred,
10313
+ exhausted: !row.deferred,
10314
+ deferCount: Number.isSafeInteger(deferCount) ? deferCount : null,
10315
+ delayMs: row.deferred ? delayMs : null,
10316
+ deadlineAtMs: Number.isSafeInteger(deadlineAtMs) ? deadlineAtMs : null,
10317
+ historyRows,
10318
+ replaySafe: true,
10319
+ };
9273
10320
  }
9274
10321
 
9275
- export type PostgresSchedulerRecoveryDeferral = {
9276
- deferred: boolean;
9277
- exhausted: boolean;
9278
- deferCount: number | null;
9279
- deadlineAtMs: number | null;
9280
- };
9281
-
9282
- /**
9283
- * Park a proven pre-code platform failure without spending an Absurd engine
9284
- * attempt. Unlike ordinary capacity parking, this records a finite recovery
9285
- * horizon on the canonical run row. The task engine owns the wake; this store
9286
- * owns the fact that another wake is still allowed.
9287
- */
9288
10322
  export async function deferPostgresSchedulerAttemptForRecovery(
9289
10323
  client: PostgresSchedulerQueryClient,
9290
10324
  input: {
@@ -9393,7 +10427,9 @@ export async function deferPostgresSchedulerAttemptForRecovery(
9393
10427
  SET status = 'queued',
9394
10428
  suspension_json = NULL,
9395
10429
  wait_deadline = NULL,
9396
- recovery_json = jsonb_build_object(
10430
+ -- Post-code recovery state is a separate namespace; keep it.
10431
+ recovery_json =
10432
+ coalesce(runs.recovery_json, '{}'::jsonb) || jsonb_build_object(
9397
10433
  'version', 1,
9398
10434
  'kind', 'platform_pre_code',
9399
10435
  'dependency', $8::text,
@@ -9411,7 +10447,7 @@ export async function deferPostgresSchedulerAttemptForRecovery(
9411
10447
  FROM computed
9412
10448
  JOIN deferred_attempt ON deferred_attempt.run_id = computed.run_id
9413
10449
  WHERE runs.run_id = computed.run_id
9414
- RETURNING runs.run_id
10450
+ RETURNING runs.run_id, runs.launch_json, runs.recovery_json
9415
10451
  ), no_code_work_counters AS (
9416
10452
  INSERT INTO ${tableName('outbox', options)} (
9417
10453
  event_id, run_id, event_type, payload_json, created_at
@@ -9420,14 +10456,19 @@ export async function deferPostgresSchedulerAttemptForRecovery(
9420
10456
  $14::text,
9421
10457
  requeued_run.run_id,
9422
10458
  ${RUN_SCHEDULER_OUTBOX_EVENT_TYPE_SQL_LITERAL.runEvents},
9423
- $15::jsonb,
10459
+ jsonb_set($15::jsonb, '{events}',
10460
+ ($15::jsonb->'events') || jsonb_build_array(
10461
+ ${platformRecoveryActivityEventSql('requeued_run.recovery_json')}
10462
+ )
10463
+ ),
9424
10464
  ${causalOutboxCreatedAt('requeued_run.run_id', options)}
9425
10465
  FROM requeued_run
9426
10466
  ON CONFLICT (event_id) DO NOTHING
9427
10467
  RETURNING event_id
9428
10468
  ), exhausted_run AS (
9429
10469
  UPDATE ${tableName('runs', options)} AS runs
9430
- SET recovery_json = jsonb_build_object(
10470
+ SET recovery_json =
10471
+ coalesce(runs.recovery_json, '{}'::jsonb) || jsonb_build_object(
9431
10472
  'version', 1,
9432
10473
  'kind', 'platform_pre_code',
9433
10474
  'dependency', $8::text,
@@ -9567,6 +10608,7 @@ export async function handoffPostgresSchedulerAttemptContinuation(
9567
10608
  $6,
9568
10609
  continuation_run.run_id,
9569
10610
  ${RUN_EVENT_KIND_SQL_LITERAL.runResumed},
10611
+ ${runResumeEpochPayloadSql('continuation_run.run_id', options)} ||
9570
10612
  jsonb_strip_nulls(jsonb_build_object(
9571
10613
  'kind', NULLIF(btrim(continuation_run.suspension_json ->> 'kind'), ''),
9572
10614
  'eventKey',
@@ -9932,6 +10974,8 @@ const POSTGRES_SCHEDULER_ATTEMPT_AUTHORITY_FIELDS = [
9932
10974
  'runtimeTokenOrigin',
9933
10975
  'runtimeBackend',
9934
10976
  'runtimeAuthority',
10977
+ // Minted onto the attempt token so the gateway scopes operation fences.
10978
+ 'resumeEpoch',
9935
10979
  // Optional Runtime gateway pin; null on unpinned launches. The executor-token
9936
10980
  // issuer reads it to require the reader flag and add the pinned claims.
9937
10981
  'runtimeGatewayProfileId',
@@ -11222,6 +12266,8 @@ export async function readPostgresSchedulerRuntimeResourcesForRun(
11222
12266
  runId: string;
11223
12267
  attempt?: number | null;
11224
12268
  throughAttempt?: number;
12269
+ /** The first attempt of the epoch being billed (a resumed run). */
12270
+ fromAttempt?: number | null;
11225
12271
  },
11226
12272
  options?: Pick<PostgresSchedulerOptions, 'schema'>,
11227
12273
  ): Promise<unknown[]> {
@@ -11232,10 +12278,16 @@ export async function readPostgresSchedulerRuntimeResourcesForRun(
11232
12278
  WHERE run_id = $1
11233
12279
  AND ($2::integer IS NULL OR attempt = $2)
11234
12280
  AND ($3::integer IS NULL OR attempt <= $3)
12281
+ AND ($4::integer IS NULL OR attempt >= $4)
11235
12282
  AND resource_json IS NOT NULL
11236
12283
  ORDER BY attempt DESC
11237
12284
  `,
11238
- [input.runId, input.attempt ?? null, input.throughAttempt ?? null],
12285
+ [
12286
+ input.runId,
12287
+ input.attempt ?? null,
12288
+ input.throughAttempt ?? null,
12289
+ input.fromAttempt ?? null,
12290
+ ],
11239
12291
  );
11240
12292
  return resources.rows.flatMap((row) =>
11241
12293
  Array.isArray(row.resource_json) ? row.resource_json : [row.resource_json],
@@ -11846,7 +12898,7 @@ export async function directCompletePostgresSchedulerRunnerTerminal(
11846
12898
  event_id, run_id, event_type, payload_json, created_at
11847
12899
  )
11848
12900
  SELECT
11849
- 'run-terminal:' || run_id,
12901
+ ${runEndingEventIdSql('run_terminal.run_id', options)},
11850
12902
  run_terminal.run_id,
11851
12903
  ${RUN_EVENT_KIND_SQL_LITERAL.runCompleted},
11852
12904
  jsonb_build_object(
@@ -12630,6 +13682,91 @@ export async function blockPostgresSchedulerComputeBillingJob(
12630
13682
  );
12631
13683
  }
12632
13684
 
13685
+ /** Read one obligation under its authenticated workspace, without changing it. */
13686
+ export async function readPostgresSchedulerComputeBillingRecovery(
13687
+ client: PostgresSchedulerQueryClient,
13688
+ input: { runId: string; orgId: string },
13689
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
13690
+ ): Promise<{ status: string; blocked: boolean; runStatus: string } | null> {
13691
+ const result = await client.query<{
13692
+ status: string;
13693
+ blocked: boolean;
13694
+ run_status: string;
13695
+ }>(
13696
+ `SELECT job.status, job.blocked_at IS NOT NULL AS blocked,
13697
+ run.status AS run_status
13698
+ FROM ${tableName('compute_billing_jobs_v2', options)} AS job
13699
+ JOIN ${tableName('runs', options)} AS run ON run.run_id = job.run_id
13700
+ WHERE job.run_id = $1 AND run.org_id = $2`,
13701
+ [input.runId, input.orgId],
13702
+ );
13703
+ const row = result.rows[0];
13704
+ return row
13705
+ ? { status: row.status, blocked: row.blocked, runStatus: row.run_status }
13706
+ : null;
13707
+ }
13708
+
13709
+ /**
13710
+ * Explicit operator reconciliation takes its own settlement lease atomically.
13711
+ * A retained worker must not win a pending-row race and use the old issuer.
13712
+ * No Play is admitted and no financial obligation is deleted or marked settled.
13713
+ */
13714
+ export async function claimPostgresSchedulerComputeBillingReconciliation(
13715
+ client: PostgresSchedulerQueryClient,
13716
+ input: { runId: string; orgId: string; reason: string; leaseOwner: string },
13717
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
13718
+ ): Promise<PostgresSchedulerComputeBillingJob | null> {
13719
+ if (!input.reason.trim() || !input.leaseOwner.trim()) {
13720
+ throw new Error(
13721
+ 'Compute reconciliation requires an operator reason and lease owner.',
13722
+ );
13723
+ }
13724
+ const result = await client.query<{
13725
+ run_id: string;
13726
+ attempt_count: number;
13727
+ failure_count: number;
13728
+ run_status: string;
13729
+ }>(
13730
+ `WITH approved AS (
13731
+ UPDATE ${tableName('compute_billing_jobs_v2', options)} AS job
13732
+ SET status = 'settling',
13733
+ attempt_count = job.attempt_count + 1,
13734
+ blocked_at = NULL, block_reason = NULL,
13735
+ session_bootstrap_approved_at = clock_timestamp(),
13736
+ session_bootstrap_approval_reason = left($3, 4000),
13737
+ session_bootstrap_completed_at = NULL,
13738
+ session_bootstrap_retry_at = NULL,
13739
+ available_at = 'infinity'::timestamptz,
13740
+ lease_owner = $4,
13741
+ lease_expires_at = clock_timestamp() + interval '5 minutes',
13742
+ updated_at = clock_timestamp()
13743
+ WHERE job.run_id = $1 AND job.status = 'pending'
13744
+ AND job.blocked_at IS NOT NULL AND job.lease_owner IS NULL
13745
+ AND EXISTS (
13746
+ SELECT 1 FROM ${tableName('runs', options)} AS run
13747
+ WHERE run.run_id = job.run_id AND run.org_id = $2
13748
+ AND run.status IN ('completed', 'failed', 'cancelled')
13749
+ )
13750
+ RETURNING job.run_id, job.attempt_count, job.failure_count
13751
+ )
13752
+ SELECT approved.*, run.status AS run_status
13753
+ FROM approved JOIN ${tableName('runs', options)} AS run
13754
+ ON run.run_id = approved.run_id`,
13755
+ [input.runId, input.orgId, input.reason, input.leaseOwner],
13756
+ );
13757
+ const row = result.rows[0];
13758
+ return row
13759
+ ? {
13760
+ status: ComputeBillingJobStatus.Settling,
13761
+ runId: row.run_id,
13762
+ attemptCount: row.attempt_count,
13763
+ failureCount: row.failure_count,
13764
+ success: row.run_status === 'completed',
13765
+ bootstrapSessionPending: true,
13766
+ }
13767
+ : null;
13768
+ }
13769
+
12633
13770
  /**
12634
13771
  * Explicit operator reconciliation approves the missing lifecycle bootstrap
12635
13772
  * for one quarantined obligation and re-enables it. The approval is durable
@@ -13055,6 +14192,51 @@ export async function hasPendingPostgresSchedulerSandboxCleanupForRun(
13055
14192
  return pending.rows[0]?.pending ?? true;
13056
14193
  }
13057
14194
 
14195
+ /**
14196
+ * Whether any attempt up to `throughAttempt` still owns an unconfirmed sandbox:
14197
+ * a cleanup job not yet `deleted` (including blocked ones), a reserved create,
14198
+ * or a pending ambiguous Modal create. Post-code recovery starts no new
14199
+ * sandbox, and releases no older attempt's claims, until this is false.
14200
+ */
14201
+ export async function hasPendingPostgresSchedulerSandboxDeletionThroughAttempt(
14202
+ client: PostgresSchedulerQueryClient,
14203
+ input: { runId: string; throughAttempt: number },
14204
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
14205
+ ): Promise<boolean> {
14206
+ const pending = await client.query<{ pending: boolean }>(
14207
+ `
14208
+ SELECT EXISTS (
14209
+ SELECT 1 FROM ${tableName('sandbox_cleanup_jobs_v2', options)}
14210
+ WHERE run_id = $1 AND attempt <= $2 AND status <> 'deleted'
14211
+ ) OR EXISTS (
14212
+ SELECT 1 FROM ${tableName('runtime_sandbox_operations', options)}
14213
+ WHERE run_id = $1 AND attempt <= $2 AND state = 'reserved'
14214
+ ) OR EXISTS (
14215
+ SELECT 1 FROM ${tableName('ambiguous_modal_creates', options)}
14216
+ WHERE run_id = $1 AND attempt <= $2 AND status = 'pending'
14217
+ ) AS pending
14218
+ `,
14219
+ [input.runId, input.throughAttempt],
14220
+ );
14221
+ // A missing answer is not proof of deletion.
14222
+ return pending.rows[0]?.pending ?? true;
14223
+ }
14224
+
14225
+ /** Whether the run is inside an open (not exhausted) post-code recovery. */
14226
+ export async function readPostgresSchedulerPostCodeRecoveryOpen(
14227
+ client: PostgresSchedulerQueryClient,
14228
+ input: { runId: string },
14229
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
14230
+ ): Promise<boolean> {
14231
+ const result = await client.query<{ open: boolean }>(
14232
+ `SELECT coalesce((recovery_json #>> '{postCode,deferCount}')::integer, 0) > 0
14233
+ AND (recovery_json #>> '{postCode,exhaustedAtMs}') IS NULL AS open
14234
+ FROM ${tableName('runs', options)} WHERE run_id = $1`,
14235
+ [input.runId],
14236
+ );
14237
+ return result.rows[0]?.open === true;
14238
+ }
14239
+
13058
14240
  /** Exact-resource join; completion never substitutes for the initiating attempt fence. */
13059
14241
  export async function readPostgresSchedulerSandboxRetirement(
13060
14242
  client: PostgresSchedulerQueryClient,
@@ -15370,7 +16552,7 @@ export async function completePostgresSchedulerAttempt(
15370
16552
  event_id, run_id, event_type, payload_json, created_at
15371
16553
  )
15372
16554
  SELECT
15373
- 'run-terminal:' || run_id,
16555
+ ${runEndingEventIdSql('run_terminal.run_id', options)},
15374
16556
  run_terminal.run_id,
15375
16557
  ${RUN_EVENT_KIND_SQL_LITERAL.runCompleted},
15376
16558
  jsonb_build_object(
@@ -15783,7 +16965,7 @@ export async function failPostgresSchedulerAttempt(
15783
16965
  event_id, run_id, event_type, payload_json, created_at
15784
16966
  )
15785
16967
  SELECT
15786
- 'run-terminal:' || run_id,
16968
+ ${runEndingEventIdSql('run_terminal.run_id', options)},
15787
16969
  run_terminal.run_id,
15788
16970
  ${RUN_EVENT_KIND_SQL_LITERAL.runFailed},
15789
16971
  jsonb_build_object(
@@ -16129,7 +17311,7 @@ export async function cancelPostgresSchedulerRun(
16129
17311
  next_attempt_at, lease_owner, lease_expires_at
16130
17312
  )
16131
17313
  SELECT
16132
- 'run-terminal:' || run_id,
17314
+ ${runEndingEventIdSql('cancelled_run.run_id', options)},
16133
17315
  cancelled_run.run_id,
16134
17316
  ${RUN_EVENT_KIND_SQL_LITERAL.runCancelled},
16135
17317
  jsonb_build_object('error', $5::text),
@@ -16388,7 +17570,7 @@ export async function finalizePostgresSchedulerComputeBilling(
16388
17570
  });
16389
17571
  for (const item of items) {
16390
17572
  await recordComputeBillingItemViaAppRuntime(runtimeApi, {
16391
- sessionId: launch.runId,
17573
+ sessionId: computeBillingSessionId(launch.runId, launch.resumeEpoch),
16392
17574
  orgId: launch.orgId,
16393
17575
  ...(launch.userId ? { userId: launch.userId } : {}),
16394
17576
  operation: 'workflow_run',
@@ -16396,7 +17578,7 @@ export async function finalizePostgresSchedulerComputeBilling(
16396
17578
  });
16397
17579
  }
16398
17580
  await finalizeComputeBillingSessionViaAppRuntime(runtimeApi, {
16399
- sessionId: launch.runId,
17581
+ sessionId: computeBillingSessionId(launch.runId, launch.resumeEpoch),
16400
17582
  orgId: launch.orgId,
16401
17583
  ...(launch.userId ? { userId: launch.userId } : {}),
16402
17584
  operation: 'workflow_run',
@@ -17346,6 +18528,10 @@ export function buildPostgresSchedulerRunnerContext(
17346
18528
  playId: launch.playId,
17347
18529
  runId: launch.runId,
17348
18530
  replayedFromRunId: launch.replayedFromRunId ?? null,
18531
+ ...(launch.runScopedKeys === true ? { runScopedKeys: true } : {}),
18532
+ ...(typeof launch.resumeEpoch === 'number' && launch.resumeEpoch > 0
18533
+ ? { resumeEpoch: launch.resumeEpoch }
18534
+ : {}),
17349
18535
  rootRunId,
17350
18536
  runAttempt,
17351
18537
  playName: launch.playName,
@@ -18999,6 +20185,42 @@ export async function releasePostgresSchedulerReceiptsForAttempt(
18999
20185
  return { released: releasedKeys.length, releasedKeys };
19000
20186
  }
19001
20187
 
20188
+ /**
20189
+ * Release every receipt claim the run's attempts up to `throughAttempt`
20190
+ * still hold. Only for a run whose runner the provider proved gone: its
20191
+ * claims would otherwise block the retry until their leases expire. A fenced
20192
+ * call still in flight on the gateway stays blocked by the gateway's own
20193
+ * fence, never dispatched twice.
20194
+ */
20195
+ export async function releasePostgresSchedulerReceiptsThroughAttempt(
20196
+ client: PostgresSchedulerQueryClient,
20197
+ input: { runId: string; throughAttempt: number },
20198
+ options: PostgresSchedulerReceiptOptions,
20199
+ ): Promise<{ released: number }> {
20200
+ const throughAttempt = normalizePostgresSchedulerReceiptRunAttempt(
20201
+ input.throughAttempt,
20202
+ );
20203
+ const released = await client.query<{ k: string }>(
20204
+ `
20205
+ UPDATE ${tableName('receipts', options)}
20206
+ SET ${RELEASE_RECEIPT_TO_PENDING_SET_CLAUSE}
20207
+ WHERE org_id = $1
20208
+ AND run_id = $2
20209
+ AND status = ANY($4::text[])
20210
+ AND COALESCE(lease_owner_run_id, run_id) = $2
20211
+ AND COALESCE(lease_owner_attempt, 0) <= $3::integer
20212
+ RETURNING k
20213
+ `,
20214
+ [
20215
+ receiptOrgId(options),
20216
+ input.runId,
20217
+ throughAttempt,
20218
+ schedulerWorkReceiptFromStatuses('release_attempt'),
20219
+ ],
20220
+ );
20221
+ return { released: released.rows.length };
20222
+ }
20223
+
19002
20224
  async function markPostgresSchedulerReceiptsStatus(
19003
20225
  client: PostgresSchedulerQueryClient,
19004
20226
  input:
@@ -19989,7 +21211,7 @@ async function appendRunLedgerOutboxFact(
19989
21211
  ), recorded AS (
19990
21212
  INSERT INTO ${tableName('outbox', options)}
19991
21213
  (event_id, run_id, event_type, payload_json, created_at)
19992
- SELECT $3, run_id, $5, $4::jsonb,
21214
+ SELECT $3, run_id, $5, $4::jsonb || ${runResumeEpochPayloadSql('admitted.run_id', options)},
19993
21215
  ${causalOutboxCreatedAt('admitted.run_id', options)}
19994
21216
  FROM admitted
19995
21217
  ON CONFLICT (event_id) DO NOTHING
@@ -20084,7 +21306,7 @@ async function appendRunLedgerLiveProgressFact(
20084
21306
  ), recorded AS (
20085
21307
  INSERT INTO ${tableName('outbox', options)}
20086
21308
  (event_id, run_id, event_type, payload_json, created_at)
20087
- SELECT $2, run_id, $4, $3::jsonb,
21309
+ SELECT $2, run_id, $4, $3::jsonb || ${runResumeEpochPayloadSql('fenced.run_id', options)},
20088
21310
  ${causalOutboxCreatedAt('fenced.run_id', options)}
20089
21311
  FROM fenced
20090
21312
  ON CONFLICT (event_id) DO NOTHING
@@ -20213,7 +21435,7 @@ export async function readPostgresSchedulerTerminalArrayInputIntent(
20213
21435
  client: PostgresSchedulerQueryClient,
20214
21436
  input: { orgId: string; runId: string },
20215
21437
  options?: Pick<PostgresSchedulerOptions, 'schema'>,
20216
- ): Promise<{ playName: string | null; started: boolean }> {
21438
+ ): Promise<{ playName: string | null; started: boolean; status?: string }> {
20217
21439
  return readTerminalArrayInputIntentForScope(client, input, options);
20218
21440
  }
20219
21441
 
@@ -20226,7 +21448,7 @@ export async function assertPostgresRunLedgerDeliveryAndReadTerminalArrayInputIn
20226
21448
  client: PostgresSchedulerQueryClient,
20227
21449
  input: Parameters<typeof assertPostgresRunLedgerDelivery>[1],
20228
21450
  options?: Pick<PostgresSchedulerOptions, 'schema'>,
20229
- ): Promise<{ playName: string | null; started: boolean }> {
21451
+ ): Promise<{ playName: string | null; started: boolean; status?: string }> {
20230
21452
  const markerPresent = await provePostgresRunLedgerDelivery(
20231
21453
  client,
20232
21454
  input,
@@ -20243,7 +21465,7 @@ async function readTerminalArrayInputIntentForScope(
20243
21465
  client: PostgresSchedulerQueryClient,
20244
21466
  input: { orgId?: string; runId: string },
20245
21467
  options?: Pick<PostgresSchedulerOptions, 'schema'>,
20246
- ): Promise<{ playName: string | null; started: boolean }> {
21468
+ ): Promise<{ playName: string | null; started: boolean; status?: string }> {
20247
21469
  // Historical scheduler schemas have no marker. Inspect only a terminal
20248
21470
  // delivery, then read the scalar column directly when it exists. Converting
20249
21471
  // the whole wide run tuple to JSON for every outbox fact would copy launch,
@@ -20267,12 +21489,13 @@ async function readTerminalArrayInputIntentRow(
20267
21489
  client: PostgresSchedulerQueryClient,
20268
21490
  input: { orgId?: string; runId: string },
20269
21491
  options?: Pick<PostgresSchedulerOptions, 'schema'>,
20270
- ): Promise<{ playName: string | null; started: boolean }> {
21492
+ ): Promise<{ playName: string | null; started: boolean; status?: string }> {
20271
21493
  const run = await client.query<{
20272
21494
  array_input_started: boolean;
20273
21495
  play_name: string;
21496
+ status: string;
20274
21497
  }>(
20275
- `SELECT array_input_started, play_name FROM ${tableName('runs', options)}
21498
+ `SELECT array_input_started, play_name, status FROM ${tableName('runs', options)}
20276
21499
  WHERE run_id = $1 ${input.orgId === undefined ? '' : 'AND org_id = $2'}
20277
21500
  AND status IN ('completed', 'failed', 'cancelled')`,
20278
21501
  input.orgId === undefined ? [input.runId] : [input.runId, input.orgId],
@@ -20280,6 +21503,7 @@ async function readTerminalArrayInputIntentRow(
20280
21503
  return {
20281
21504
  playName: run.rows[0]?.play_name ?? null,
20282
21505
  started: run.rows[0]?.array_input_started === true,
21506
+ ...(run.rows[0]?.status ? { status: run.rows[0].status } : {}),
20283
21507
  };
20284
21508
  }
20285
21509
 
@@ -20308,6 +21532,7 @@ async function provePostgresRunLedgerDelivery(
20308
21532
  readArrayInputMarker = false,
20309
21533
  ): Promise<boolean> {
20310
21534
  const result = await client.query<{
21535
+ event_id: string;
20311
21536
  delivery_key: string;
20312
21537
  event_type: string;
20313
21538
  delivery_batch_started_at: string | null;
@@ -20320,7 +21545,8 @@ async function provePostgresRunLedgerDelivery(
20320
21545
  array_input_marker_present?: boolean;
20321
21546
  }>(
20322
21547
  `
20323
- SELECT outbox.delivery_key,
21548
+ SELECT outbox.event_id,
21549
+ outbox.delivery_key,
20324
21550
  outbox.event_type,
20325
21551
  -- Row JSON keeps this optional on historical scheduler schemas.
20326
21552
  to_jsonb(outbox)->>'delivery_batch_started_at' AS delivery_batch_started_at,
@@ -20453,7 +21679,9 @@ async function provePostgresRunLedgerDelivery(
20453
21679
  for (const prefixRow of prefix) {
20454
21680
  prefixEvents.push(
20455
21681
  ...buildRunLedgerEventsFromPostgresSchedulerOutbox({
20456
- eventId: prefixRow.delivery_key,
21682
+ // The event id, not the delivery key, carries a resumed run's
21683
+ // epoch, so the expected projection stamps it as the sender did.
21684
+ eventId: prefixRow.event_id,
20457
21685
  runId: input.runId,
20458
21686
  eventType: prefixRow.event_type,
20459
21687
  payload: prefixRow.payload_json,
@@ -20709,7 +21937,7 @@ function runLedgerTerminalPendingSql(
20709
21937
  ): string {
20710
21938
  return `EXISTS (
20711
21939
  SELECT 1 FROM ${tableName('outbox', options)} AS terminal_event
20712
- WHERE terminal_event.event_id = 'run-terminal:' || ${alias}.run_id
21940
+ WHERE terminal_event.event_id = ${runEndingEventIdSql(`${alias}.run_id`, options)}
20713
21941
  AND terminal_event.run_id = ${alias}.run_id
20714
21942
  AND terminal_event.event_type IN (${RUN_EVENT_KIND_SQL_LITERAL.runCompleted}, ${RUN_EVENT_KIND_SQL_LITERAL.runFailed}, ${RUN_EVENT_KIND_SQL_LITERAL.runCancelled})
20715
21943
  AND terminal_event.delivered_at IS NULL
@@ -22951,8 +24179,31 @@ function normalizeOutboxIngressPreview(
22951
24179
  return { ...event, progress: { ...progress, nodeIo } };
22952
24180
  }
22953
24181
 
24182
+ /**
24183
+ * Ledger events for one outbox row. A resumed run's endings and its
24184
+ * `run.resumed` carry the run's resume epoch, so the ledger orders them after
24185
+ * the earlier epoch instead of treating them as duplicates or stale.
24186
+ */
22954
24187
  export function buildRunLedgerEventsFromPostgresSchedulerOutbox(
22955
24188
  event: PostgresSchedulerOutboxEvent,
24189
+ ): PlayRunLedgerIngressEvent[] {
24190
+ const events =
24191
+ buildUnstampedRunLedgerEventsFromPostgresSchedulerOutbox(event);
24192
+ const epoch =
24193
+ event.eventType === RUN_SCHEDULER_OUTBOX_EVENT_TYPE.runResumed
24194
+ ? normalizeResumeEpoch(numberPayloadField(event.payload, 'epoch'))
24195
+ : (runEndingEventEpoch(event.eventId, event.runId) ??
24196
+ normalizeResumeEpoch(numberPayloadField(event.payload, 'epoch')));
24197
+ return events.map((ledgerEvent) =>
24198
+ ledgerEvent.type !== RUN_EVENT_KIND.logAppended &&
24199
+ ledgerEvent.type !== RUN_EVENT_KIND.workCounters
24200
+ ? { ...ledgerEvent, resumeEpoch: ledgerEvent.resumeEpoch ?? epoch }
24201
+ : ledgerEvent,
24202
+ );
24203
+ }
24204
+
24205
+ function buildUnstampedRunLedgerEventsFromPostgresSchedulerOutbox(
24206
+ event: PostgresSchedulerOutboxEvent,
22956
24207
  ): PlayRunLedgerIngressEvent[] {
22957
24208
  if (
22958
24209
  payloadField(event.payload, RUNTIME_EVENT_DEFERRED_PROJECTION_FIELD) ===
@@ -23833,7 +25084,7 @@ async function dispatchRunLedgerOutboxBatchWithScope(
23833
25084
  // claim's first-HTTP lease proof. Background discovery can still prioritize
23834
25085
  // a terminal after claiming it, but must renew before its first append.
23835
25086
  const targetedTerminalRunId =
23836
- scope && scope.targetEventId === `run-terminal:${scope.runId}`
25087
+ scope && isRunEndingEventId(scope.targetEventId, scope.runId)
23837
25088
  ? scope.runId
23838
25089
  : null;
23839
25090
  let terminalRunId = targetedTerminalRunId;
@@ -25582,7 +26833,20 @@ async function acknowledgeRunLedgerPrefixWithContinuation(
25582
26833
  continuation: RunLedgerOutboxDrainScope | null;
25583
26834
  }> {
25584
26835
  const runId = input.events[0]!.runId;
25585
- const targetEventId = input.scope?.targetEventId ?? `run-terminal:${runId}`;
26836
+ // Without an explicit target, aim for this run's latest ending among the
26837
+ // delivered events; a never-resumed run's ending keeps its original ID.
26838
+ const targetEventId =
26839
+ input.scope?.targetEventId ??
26840
+ input.events
26841
+ .map((event) => event.eventId)
26842
+ .filter((eventId) => isRunEndingEventId(eventId, runId))
26843
+ .sort(
26844
+ (left, right) =>
26845
+ (runEndingEventEpoch(left, runId) ?? 0) -
26846
+ (runEndingEventEpoch(right, runId) ?? 0),
26847
+ )
26848
+ .at(-1) ??
26849
+ runEndingEventId(runId);
25586
26850
  const retainContinuation =
25587
26851
  !!input.scope ||
25588
26852
  (input.input.continueThroughTerminal === true && !input.input.headEventId);
@@ -26586,6 +27850,7 @@ export async function requestComputeBillingDispatchToken(input: {
26586
27850
  leaseOwner: string;
26587
27851
  attemptCount: number;
26588
27852
  schedulerSchema: string | null;
27853
+ tokenIssuerOrigin?: string;
26589
27854
  }): Promise<string> {
26590
27855
  const internalToken = process.env.DEEPLINE_INTERNAL_TOKEN?.trim();
26591
27856
  if (!internalToken || !input.runId || !input.leaseOwner) {
@@ -26593,15 +27858,25 @@ export async function requestComputeBillingDispatchToken(input: {
26593
27858
  'Compute-billing recovery requires a valid dispatch lease and DEEPLINE_INTERNAL_TOKEN.',
26594
27859
  );
26595
27860
  }
27861
+ if (
27862
+ input.tokenIssuerOrigin &&
27863
+ !isImmutableRuntimeExecutionRecoveryOrigin(input.tokenIssuerOrigin)
27864
+ ) {
27865
+ throw new Error(
27866
+ 'Compute billing recovery requires an immutable Deepline token issuer.',
27867
+ );
27868
+ }
26596
27869
  // Signed with the internal token, which is never pinned.
26597
- const appBaseUrl = resolveRuntimeAppTransport({
26598
- caller: 'direct',
26599
- launch: input.launch,
26600
- executorToken: internalToken,
26601
- }).baseUrl;
26602
- const url = `${appBaseUrl.replace(/\/$/, '')}/api/v2/internal/play-runtime/compute-billing-dispatch-token`;
27870
+ const issuerOrigin =
27871
+ input.tokenIssuerOrigin ??
27872
+ resolveRuntimeAppTransport({
27873
+ caller: 'direct',
27874
+ launch: input.launch,
27875
+ executorToken: internalToken,
27876
+ }).baseUrl;
27877
+ const url = `${issuerOrigin.replace(/\/$/, '')}/api/v2/internal/play-runtime/compute-billing-dispatch-token`;
26603
27878
  const vercelProtectionHeaders = await vercelProtectionBypassHeaders({
26604
- baseUrl: appBaseUrl,
27879
+ baseUrl: issuerOrigin,
26605
27880
  token: input.launch.vercelProtectionBypassToken,
26606
27881
  });
26607
27882
  const response = await fetch(url, {