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
@@ -0,0 +1,719 @@
1
+ /**
2
+ * Read-only operator inventory of durable Play runs in Runtime Postgres:
3
+ * which runs are in flight, which are waiting out an automatic recovery
4
+ * delay, and which stopped runs could continue in place.
5
+ *
6
+ * Every read is bounded and walks an existing index of `runs`:
7
+ * - in-flight statuses and `cancelled`: `runtime_scheduler_runs_status_created_idx`
8
+ * (status, created_at DESC, run_id);
9
+ * - `failed`: `runtime_scheduler_runs_failed_recent_idx` (finished_at DESC, run_id);
10
+ * - the latest attempt: the `attempts` primary key (run_id, attempt).
11
+ * Filtered views (recovering, cancelled within the resume window, failed by
12
+ * cause) examine at most `DURABLE_RUN_INVENTORY_SCAN_LIMIT` index rows per page
13
+ * and return a cursor to continue, so a page can hold fewer matches than its
14
+ * limit.
15
+ *
16
+ * Nothing here writes. Resume eligibility is not decided here: callers pass
17
+ * stopped runs to `readPostgresSchedulerRunResumeEligibility`, the same
18
+ * predicate resume evaluates under its lock.
19
+ */
20
+ import {
21
+ RUN_RESUME_WINDOW_MS,
22
+ type PostgresSchedulerQueryClient,
23
+ } from './postgres';
24
+ import {
25
+ DURABLE_RUN_FAILURE_CAUSES,
26
+ durableRunFailureLateralSql,
27
+ durableRunRecoveringSql,
28
+ durableRunTable as table,
29
+ isDurableRunFailureCause,
30
+ type DurableRunFailureCause,
31
+ type DurableRunFailureClass,
32
+ type DurableRunSqlOptions as Options,
33
+ } from './durable-run-sql';
34
+
35
+ export {
36
+ DURABLE_RUN_FAILURE_CAUSES,
37
+ DURABLE_RUN_FAILURE_CLASSES,
38
+ isDurableRunFailureCause,
39
+ type DurableRunFailureCause,
40
+ type DurableRunFailureClass,
41
+ } from './durable-run-sql';
42
+
43
+ /** Maximum runs one page returns. */
44
+ export const DURABLE_RUN_INVENTORY_MAX_LIMIT = 100;
45
+ /** Maximum index rows a filtered page examines before returning a cursor. */
46
+ export const DURABLE_RUN_INVENTORY_SCAN_LIMIT = 500;
47
+
48
+ /** Native run statuses an operator lists. */
49
+ export const DURABLE_RUN_LIST_STATES = [
50
+ /** queued, running and waiting together, newest first. */
51
+ 'in_flight',
52
+ 'queued',
53
+ 'running',
54
+ 'waiting',
55
+ /** Queued runs waiting out an automatic recovery delay. */
56
+ 'recovering',
57
+ /** Failed inside the resume window. */
58
+ 'failed',
59
+ /** Cancelled inside the resume window. */
60
+ 'cancelled',
61
+ ] as const;
62
+ export type DurableRunListState = (typeof DURABLE_RUN_LIST_STATES)[number];
63
+
64
+ export function isDurableRunListState(
65
+ value: unknown,
66
+ ): value is DurableRunListState {
67
+ return (
68
+ typeof value === 'string' &&
69
+ (DURABLE_RUN_LIST_STATES as readonly string[]).includes(value)
70
+ );
71
+ }
72
+
73
+ /**
74
+ * What the run is doing now. `recovering` is a queued run whose last attempt
75
+ * was retired by automatic platform recovery and whose next attempt has not
76
+ * been created yet.
77
+ */
78
+ export type DurableRunPhase =
79
+ | 'queued'
80
+ | 'running'
81
+ | 'waiting'
82
+ | 'recovering'
83
+ | 'failed'
84
+ | 'cancelled'
85
+ | 'completed';
86
+
87
+ /** One recovery namespace of `runs.recovery_json`, fixed size. */
88
+ export type DurableRunRecovery = {
89
+ /** `post_code`: after customer code started; `pre_code`: before it. */
90
+ readonly kind: 'post_code' | 'pre_code';
91
+ /** True while the run is waiting out this recovery's delay. */
92
+ readonly active: boolean;
93
+ readonly reason: string | null;
94
+ /** Pre-code only: the dependency whose failure was recovered. */
95
+ readonly dependency: string | null;
96
+ readonly deferCount: number | null;
97
+ /** Post-code only: attempts in a row that recorded no new history. */
98
+ readonly unproductiveAttempts: number | null;
99
+ readonly nextRetryAt: string | null;
100
+ /** The recovery horizon: no retry is scheduled after this. */
101
+ readonly deadlineAt: string | null;
102
+ readonly exhaustedAt: string | null;
103
+ readonly updatedAt: string | null;
104
+ };
105
+
106
+ export type DurableRunLatestAttempt = {
107
+ readonly attempt: number;
108
+ readonly status: string;
109
+ readonly heartbeatAt: string | null;
110
+ readonly leaseExpiresAt: string | null;
111
+ /** `error_json.kind`, e.g. `platform_post_code_recovery`. */
112
+ readonly errorKind: string | null;
113
+ };
114
+
115
+ /**
116
+ * Why a stopped run stopped. Fixed size: `code` is a short machine token and
117
+ * `message` is only Deepline's fixed exhausted-recovery text; the Play's own
118
+ * error text is never carried.
119
+ */
120
+ export type DurableRunFailure = {
121
+ readonly class: DurableRunFailureClass;
122
+ readonly code: string | null;
123
+ readonly message: string | null;
124
+ /** When recovery was exhausted, else when the run stopped. */
125
+ readonly at: string | null;
126
+ };
127
+
128
+ /** Fixed-size summary of one run; never carries input, output or logs. */
129
+ export type DurableRunRow = {
130
+ readonly runId: string;
131
+ readonly orgId: string;
132
+ readonly playName: string;
133
+ readonly status: string;
134
+ readonly phase: DurableRunPhase;
135
+ readonly createdAt: string | null;
136
+ readonly startedAt: string | null;
137
+ readonly finishedAt: string | null;
138
+ readonly updatedAt: string | null;
139
+ /** 0 until the run is resumed. */
140
+ readonly resumeEpoch: number;
141
+ /** Attempts in the current epoch (0 before the first claim). */
142
+ readonly attemptsThisEpoch: number;
143
+ readonly latestAttempt: DurableRunLatestAttempt | null;
144
+ /** Admin-only: the Absurd release lane the run is pinned to. */
145
+ readonly releaseId: string | null;
146
+ readonly revisionId: string | null;
147
+ readonly parentRunId: string | null;
148
+ /** The active recovery, else the most recently updated one. */
149
+ readonly recovery: DurableRunRecovery | null;
150
+ /** Failed and cancelled runs only; null while in flight or completed. */
151
+ readonly failure: DurableRunFailure | null;
152
+ };
153
+
154
+ export type DurableRunPage = {
155
+ readonly state: DurableRunListState;
156
+ readonly rows: readonly DurableRunRow[];
157
+ readonly nextCursor: string | null;
158
+ /** Index rows examined for this page. */
159
+ readonly examined: number;
160
+ /** The index that bounded this page. */
161
+ readonly index: string;
162
+ };
163
+
164
+ function rowColumnsSql(options?: Options): string {
165
+ return `runs.run_id,
166
+ runs.org_id,
167
+ runs.play_name,
168
+ runs.status,
169
+ runs.created_at,
170
+ runs.started_at,
171
+ runs.finished_at,
172
+ runs.updated_at,
173
+ coalesce(runs.admission_json, runs.launch_json) AS launch,
174
+ runs.recovery_json,
175
+ ${durableRunRecoveringSql(options)} AS recovering,
176
+ last_attempt.attempt AS latest_attempt,
177
+ last_attempt.status AS latest_attempt_status,
178
+ last_attempt.heartbeat_at AS latest_heartbeat_at,
179
+ last_attempt.lease_expires_at AS latest_lease_expires_at,
180
+ last_attempt.error_json ->> 'kind' AS latest_error_kind,
181
+ failure.failure_class,
182
+ failure.failure_code,
183
+ failure.failure_message,
184
+ failure.failure_at_ms`;
185
+ }
186
+
187
+ function attemptJoinSql(options?: Options): string {
188
+ return `LEFT JOIN LATERAL (
189
+ SELECT attempts.attempt, attempts.status, attempts.heartbeat_at,
190
+ attempts.lease_expires_at, attempts.error_json
191
+ FROM ${table('attempts', options)} AS attempts
192
+ WHERE attempts.run_id = runs.run_id
193
+ ORDER BY attempts.attempt DESC
194
+ LIMIT 1
195
+ ) AS last_attempt ON true`;
196
+ }
197
+
198
+ type RawRow = {
199
+ run_id: string;
200
+ org_id: string;
201
+ play_name: string;
202
+ status: string;
203
+ created_at: Date | string | null;
204
+ started_at: Date | string | null;
205
+ finished_at: Date | string | null;
206
+ updated_at: Date | string | null;
207
+ launch: Record<string, unknown> | string | null;
208
+ recovery_json: Record<string, unknown> | string | null;
209
+ recovering: boolean;
210
+ latest_attempt: number | string | null;
211
+ latest_attempt_status: string | null;
212
+ latest_heartbeat_at: Date | string | null;
213
+ latest_lease_expires_at: Date | string | null;
214
+ latest_error_kind: string | null;
215
+ failure_class: DurableRunFailureClass | null;
216
+ failure_code: string | null;
217
+ failure_message: string | null;
218
+ failure_at_ms: string | number | null;
219
+ };
220
+
221
+ function iso(value: unknown): string | null {
222
+ if (value === null || value === undefined) return null;
223
+ const date = value instanceof Date ? value : new Date(String(value));
224
+ return Number.isFinite(date.getTime()) ? date.toISOString() : null;
225
+ }
226
+
227
+ function msIso(value: unknown): string | null {
228
+ const ms = typeof value === 'string' ? Number(value) : value;
229
+ return typeof ms === 'number' && Number.isFinite(ms)
230
+ ? new Date(ms).toISOString()
231
+ : null;
232
+ }
233
+
234
+ function num(value: unknown): number | null {
235
+ const parsed = typeof value === 'string' ? Number(value) : value;
236
+ return typeof parsed === 'number' && Number.isFinite(parsed) ? parsed : null;
237
+ }
238
+
239
+ function str(value: unknown): string | null {
240
+ return typeof value === 'string' && value.trim() ? value.trim() : null;
241
+ }
242
+
243
+ function object(value: unknown): Record<string, unknown> {
244
+ if (typeof value === 'string') {
245
+ try {
246
+ return object(JSON.parse(value));
247
+ } catch {
248
+ return {};
249
+ }
250
+ }
251
+ return value && typeof value === 'object' && !Array.isArray(value)
252
+ ? (value as Record<string, unknown>)
253
+ : {};
254
+ }
255
+
256
+ function recoveryFrom(
257
+ recoveryJson: Record<string, unknown>,
258
+ recovering: boolean,
259
+ latestErrorKind: string | null,
260
+ ): DurableRunRecovery | null {
261
+ const post = object(recoveryJson.postCode);
262
+ const candidates: DurableRunRecovery[] = [];
263
+ if (Object.keys(post).length > 0) {
264
+ candidates.push({
265
+ kind: 'post_code',
266
+ active: recovering && latestErrorKind === 'platform_post_code_recovery',
267
+ reason: str(post.reason),
268
+ dependency: null,
269
+ deferCount: num(post.deferCount),
270
+ unproductiveAttempts: num(post.unproductiveAttempts),
271
+ nextRetryAt: msIso(post.nextRetryAtMs),
272
+ deadlineAt: msIso(post.deadlineAtMs),
273
+ exhaustedAt: msIso(post.exhaustedAtMs),
274
+ updatedAt: msIso(post.updatedAtMs),
275
+ });
276
+ }
277
+ if (recoveryJson.kind === 'platform_pre_code') {
278
+ candidates.push({
279
+ kind: 'pre_code',
280
+ active: recovering && latestErrorKind === 'platform_pre_code_recovery',
281
+ reason: str(recoveryJson.reason),
282
+ dependency: str(recoveryJson.dependency),
283
+ deferCount: num(recoveryJson.deferCount),
284
+ unproductiveAttempts: null,
285
+ nextRetryAt: msIso(recoveryJson.nextRetryAtMs),
286
+ deadlineAt: msIso(recoveryJson.deadlineAtMs),
287
+ exhaustedAt: msIso(recoveryJson.exhaustedAtMs),
288
+ updatedAt: msIso(recoveryJson.updatedAtMs),
289
+ });
290
+ }
291
+ const active = candidates.find((candidate) => candidate.active);
292
+ if (active) return active;
293
+ return (
294
+ [...candidates].sort((left, right) =>
295
+ (right.updatedAt ?? '').localeCompare(left.updatedAt ?? ''),
296
+ )[0] ?? null
297
+ );
298
+ }
299
+
300
+ function phaseFor(status: string, recovering: boolean): DurableRunPhase {
301
+ if (recovering) return 'recovering';
302
+ if (
303
+ status === 'queued' ||
304
+ status === 'running' ||
305
+ status === 'waiting' ||
306
+ status === 'failed' ||
307
+ status === 'cancelled' ||
308
+ status === 'completed'
309
+ ) {
310
+ return status;
311
+ }
312
+ throw new Error(`Runtime run has an unknown status: ${status}`);
313
+ }
314
+
315
+ export function durableRunRowFromRaw(raw: RawRow): DurableRunRow {
316
+ const launch = object(raw.launch);
317
+ const epoch = num(launch.resumeEpoch) ?? 0;
318
+ const firstAttempt = num(launch.resumeEpochFirstAttempt) ?? 1;
319
+ const latestAttempt = num(raw.latest_attempt);
320
+ const recovering = raw.recovering === true;
321
+ const parentRunId = str(launch.parentRunId);
322
+ return {
323
+ runId: raw.run_id,
324
+ orgId: raw.org_id,
325
+ playName: raw.play_name,
326
+ status: raw.status,
327
+ phase: phaseFor(raw.status, recovering),
328
+ createdAt: iso(raw.created_at),
329
+ startedAt: iso(raw.started_at),
330
+ finishedAt: iso(raw.finished_at),
331
+ updatedAt: iso(raw.updated_at),
332
+ resumeEpoch: epoch,
333
+ attemptsThisEpoch:
334
+ latestAttempt === null
335
+ ? 0
336
+ : Math.max(0, latestAttempt - (epoch > 0 ? firstAttempt : 1) + 1),
337
+ latestAttempt:
338
+ latestAttempt === null
339
+ ? null
340
+ : {
341
+ attempt: latestAttempt,
342
+ status: raw.latest_attempt_status ?? 'unknown',
343
+ heartbeatAt: iso(raw.latest_heartbeat_at),
344
+ leaseExpiresAt: iso(raw.latest_lease_expires_at),
345
+ errorKind: raw.latest_error_kind,
346
+ },
347
+ releaseId: str(launch.absurdReleaseId),
348
+ revisionId: str(launch.revisionId),
349
+ parentRunId: parentRunId && parentRunId !== raw.run_id ? parentRunId : null,
350
+ recovery: recoveryFrom(
351
+ object(raw.recovery_json),
352
+ recovering,
353
+ raw.latest_error_kind,
354
+ ),
355
+ failure: raw.failure_class
356
+ ? {
357
+ class: raw.failure_class,
358
+ code: raw.failure_code,
359
+ message: raw.failure_message,
360
+ at: msIso(raw.failure_at_ms) ?? iso(raw.finished_at),
361
+ }
362
+ : null,
363
+ };
364
+ }
365
+
366
+ type Cursor = {
367
+ readonly v: 1;
368
+ readonly state: DurableRunListState;
369
+ /** Sort timestamp of the last examined row (ISO). */
370
+ readonly at: string;
371
+ readonly runId: string;
372
+ };
373
+
374
+ export function encodeDurableRunCursor(cursor: Cursor): string {
375
+ return Buffer.from(JSON.stringify(cursor)).toString('base64url');
376
+ }
377
+
378
+ export function decodeDurableRunCursor(
379
+ value: string,
380
+ state: DurableRunListState,
381
+ ): Cursor {
382
+ let parsed: Partial<Cursor>;
383
+ try {
384
+ parsed = JSON.parse(Buffer.from(value, 'base64url').toString('utf8'));
385
+ } catch {
386
+ throw new DurableRunInventoryInputError('The cursor is not valid.');
387
+ }
388
+ if (
389
+ parsed.v !== 1 ||
390
+ parsed.state !== state ||
391
+ typeof parsed.at !== 'string' ||
392
+ !Number.isFinite(Date.parse(parsed.at)) ||
393
+ typeof parsed.runId !== 'string' ||
394
+ !parsed.runId
395
+ ) {
396
+ throw new DurableRunInventoryInputError(
397
+ `The cursor does not belong to a ${state} listing. Restart without --cursor.`,
398
+ );
399
+ }
400
+ return parsed as Cursor;
401
+ }
402
+
403
+ /** A caller error (bad state, limit or cursor); never a source failure. */
404
+ export class DurableRunInventoryInputError extends Error {
405
+ constructor(message: string) {
406
+ super(message);
407
+ this.name = 'DurableRunInventoryInputError';
408
+ }
409
+ }
410
+
411
+ const STATUS_CREATED_INDEX = 'runtime_scheduler_runs_status_created_idx';
412
+ const FAILED_RECENT_INDEX = 'runtime_scheduler_runs_failed_recent_idx';
413
+
414
+ /** Ordered keyset slice of one status, newest first. */
415
+ function statusSliceSql(input: {
416
+ statusParam: string;
417
+ cursorAtParam: string;
418
+ cursorIdParam: string;
419
+ limitParam: string;
420
+ options?: Options;
421
+ }): string {
422
+ return `(
423
+ SELECT runs.run_id, runs.created_at AS sort_at
424
+ FROM ${table('runs', input.options)} AS runs
425
+ WHERE runs.status = ${input.statusParam}
426
+ AND (
427
+ ${input.cursorAtParam}::timestamptz IS NULL
428
+ OR runs.created_at < ${input.cursorAtParam}::timestamptz
429
+ OR (
430
+ runs.created_at = ${input.cursorAtParam}::timestamptz
431
+ AND runs.run_id > ${input.cursorIdParam}::text
432
+ )
433
+ )
434
+ ORDER BY runs.created_at DESC, runs.run_id ASC
435
+ LIMIT ${input.limitParam}
436
+ )`;
437
+ }
438
+
439
+ async function hydrate(
440
+ client: PostgresSchedulerQueryClient,
441
+ keys: readonly { run_id: string }[],
442
+ options?: Options,
443
+ ): Promise<Map<string, DurableRunRow>> {
444
+ if (keys.length === 0) return new Map();
445
+ const result = await client.query<RawRow>(
446
+ `SELECT ${rowColumnsSql(options)}
447
+ FROM ${table('runs', options)} AS runs
448
+ ${attemptJoinSql(options)}
449
+ ${durableRunFailureLateralSql()}
450
+ WHERE runs.run_id = ANY($1::text[])`,
451
+ [keys.map((key) => key.run_id)],
452
+ );
453
+ return new Map(
454
+ result.rows.map((row) => [row.run_id, durableRunRowFromRaw(row)]),
455
+ );
456
+ }
457
+
458
+ function ordered(
459
+ keys: readonly { run_id: string }[],
460
+ rows: Map<string, DurableRunRow>,
461
+ ): DurableRunRow[] {
462
+ return keys.flatMap((key) => {
463
+ const row = rows.get(key.run_id);
464
+ return row ? [row] : [];
465
+ });
466
+ }
467
+
468
+ function sortAtIso(value: unknown): string {
469
+ const at = iso(value);
470
+ if (!at) throw new Error('Runtime run row has no sort timestamp.');
471
+ return at;
472
+ }
473
+
474
+ /** One bounded page of runs in one listing state. */
475
+ export async function listDurableRuns(
476
+ client: PostgresSchedulerQueryClient,
477
+ input: {
478
+ state: DurableRunListState;
479
+ limit: number;
480
+ cursor?: string | null;
481
+ /**
482
+ * `failed` only: keep platform (exhausted recovery or platform failure)
483
+ * or Play failures. Filters a bounded index slice like `recovering`.
484
+ */
485
+ cause?: DurableRunFailureCause | null;
486
+ },
487
+ options?: Options,
488
+ ): Promise<DurableRunPage> {
489
+ const { state } = input;
490
+ const cause = input.cause ?? null;
491
+ if (cause !== null && !isDurableRunFailureCause(cause)) {
492
+ throw new DurableRunInventoryInputError(
493
+ `cause must be one of ${Object.keys(DURABLE_RUN_FAILURE_CAUSES).join(', ')}.`,
494
+ );
495
+ }
496
+ if (cause !== null && state !== 'failed') {
497
+ throw new DurableRunInventoryInputError(
498
+ 'cause filters only the failed listing.',
499
+ );
500
+ }
501
+ if (!isDurableRunListState(state)) {
502
+ throw new DurableRunInventoryInputError(
503
+ `state must be one of ${DURABLE_RUN_LIST_STATES.join(', ')}.`,
504
+ );
505
+ }
506
+ if (
507
+ !Number.isInteger(input.limit) ||
508
+ input.limit < 1 ||
509
+ input.limit > DURABLE_RUN_INVENTORY_MAX_LIMIT
510
+ ) {
511
+ throw new DurableRunInventoryInputError(
512
+ `limit must be an integer from 1 through ${DURABLE_RUN_INVENTORY_MAX_LIMIT}.`,
513
+ );
514
+ }
515
+ const cursor = input.cursor
516
+ ? decodeDurableRunCursor(input.cursor, state)
517
+ : null;
518
+ const cursorAt = cursor?.at ?? null;
519
+ const cursorId = cursor?.runId ?? '';
520
+ const page = (
521
+ keys: readonly { run_id: string; sort_at: unknown }[],
522
+ rows: DurableRunRow[],
523
+ nextFrom: { run_id: string; sort_at: unknown } | null,
524
+ examined: number,
525
+ index: string,
526
+ ): DurableRunPage => ({
527
+ state,
528
+ rows,
529
+ nextCursor: nextFrom
530
+ ? encodeDurableRunCursor({
531
+ v: 1,
532
+ state,
533
+ at: sortAtIso(nextFrom.sort_at),
534
+ runId: nextFrom.run_id,
535
+ })
536
+ : null,
537
+ examined,
538
+ index,
539
+ });
540
+
541
+ // Filtered views: examine a bounded index slice, keep the matches.
542
+ const filteredPage = async (
543
+ scanned: readonly { run_id: string; sort_at: unknown; matched: boolean }[],
544
+ index: string,
545
+ ): Promise<DurableRunPage> => {
546
+ const matched: { run_id: string; sort_at: unknown }[] = [];
547
+ let nextFrom: { run_id: string; sort_at: unknown } | null = null;
548
+ let examined = 0;
549
+ for (const row of scanned) {
550
+ examined += 1;
551
+ if (row.matched === true) matched.push(row);
552
+ if (matched.length === input.limit) {
553
+ nextFrom = row;
554
+ break;
555
+ }
556
+ }
557
+ if (!nextFrom && scanned.length === DURABLE_RUN_INVENTORY_SCAN_LIMIT) {
558
+ nextFrom = scanned.at(-1)!;
559
+ }
560
+ const rows = ordered(matched, await hydrate(client, matched, options));
561
+ return page(matched, rows, nextFrom, examined, index);
562
+ };
563
+
564
+ if (state === 'failed' && cause !== null) {
565
+ // No index covers the failure class, so this examines at most
566
+ // DURABLE_RUN_INVENTORY_SCAN_LIMIT rows of the failed index per page.
567
+ const scanned = await client.query<{
568
+ run_id: string;
569
+ sort_at: unknown;
570
+ matched: boolean;
571
+ }>(
572
+ `WITH slice AS (
573
+ SELECT runs.run_id, runs.finished_at AS sort_at
574
+ FROM ${table('runs', options)} AS runs
575
+ WHERE runs.status = 'failed'
576
+ AND runs.finished_at >= now() - ($1::bigint * interval '1 millisecond')
577
+ AND (
578
+ $2::timestamptz IS NULL
579
+ OR runs.finished_at < $2::timestamptz
580
+ OR (runs.finished_at = $2::timestamptz AND runs.run_id > $3::text)
581
+ )
582
+ ORDER BY runs.finished_at DESC, runs.run_id ASC
583
+ LIMIT $4::int
584
+ )
585
+ SELECT slice.run_id, slice.sort_at,
586
+ coalesce(failure.failure_class = ANY($5::text[]), false) AS matched
587
+ FROM slice
588
+ JOIN ${table('runs', options)} AS runs ON runs.run_id = slice.run_id
589
+ ${durableRunFailureLateralSql()}
590
+ ORDER BY slice.sort_at DESC, slice.run_id ASC`,
591
+ [
592
+ RUN_RESUME_WINDOW_MS,
593
+ cursorAt,
594
+ cursorId,
595
+ DURABLE_RUN_INVENTORY_SCAN_LIMIT,
596
+ [...DURABLE_RUN_FAILURE_CAUSES[cause]],
597
+ ],
598
+ );
599
+ return filteredPage(scanned.rows, FAILED_RECENT_INDEX);
600
+ }
601
+
602
+ if (state === 'failed') {
603
+ const keys = await client.query<{ run_id: string; sort_at: unknown }>(
604
+ `SELECT runs.run_id, runs.finished_at AS sort_at
605
+ FROM ${table('runs', options)} AS runs
606
+ WHERE runs.status = 'failed'
607
+ AND runs.finished_at >= now() - ($1::bigint * interval '1 millisecond')
608
+ AND (
609
+ $2::timestamptz IS NULL
610
+ OR runs.finished_at < $2::timestamptz
611
+ OR (runs.finished_at = $2::timestamptz AND runs.run_id > $3::text)
612
+ )
613
+ ORDER BY runs.finished_at DESC, runs.run_id ASC
614
+ LIMIT $4::int`,
615
+ [RUN_RESUME_WINDOW_MS, cursorAt, cursorId, input.limit],
616
+ );
617
+ const rows = ordered(keys.rows, await hydrate(client, keys.rows, options));
618
+ return page(
619
+ keys.rows,
620
+ rows,
621
+ keys.rows.length === input.limit ? keys.rows.at(-1)! : null,
622
+ keys.rows.length,
623
+ FAILED_RECENT_INDEX,
624
+ );
625
+ }
626
+
627
+ if (state === 'queued' || state === 'running' || state === 'waiting') {
628
+ const keys = await client.query<{ run_id: string; sort_at: unknown }>(
629
+ statusSliceSql({
630
+ statusParam: '$1::text',
631
+ cursorAtParam: '$2',
632
+ cursorIdParam: '$3',
633
+ limitParam: '$4::int',
634
+ options,
635
+ }),
636
+ [state, cursorAt, cursorId, input.limit],
637
+ );
638
+ const rows = ordered(keys.rows, await hydrate(client, keys.rows, options));
639
+ return page(
640
+ keys.rows,
641
+ rows,
642
+ keys.rows.length === input.limit ? keys.rows.at(-1)! : null,
643
+ keys.rows.length,
644
+ STATUS_CREATED_INDEX,
645
+ );
646
+ }
647
+
648
+ if (state === 'in_flight') {
649
+ // One ordered index slice per status, merged; each slice is bounded.
650
+ const keys = await client.query<{ run_id: string; sort_at: unknown }>(
651
+ `SELECT run_id, sort_at FROM (
652
+ ${['queued', 'running', 'waiting']
653
+ .map((status) =>
654
+ statusSliceSql({
655
+ statusParam: `'${status}'`,
656
+ cursorAtParam: '$1',
657
+ cursorIdParam: '$2',
658
+ limitParam: '$3::int',
659
+ options,
660
+ }),
661
+ )
662
+ .join(' UNION ALL ')}
663
+ ) AS merged
664
+ ORDER BY sort_at DESC, run_id ASC
665
+ LIMIT $3::int`,
666
+ [cursorAt, cursorId, input.limit],
667
+ );
668
+ const rows = ordered(keys.rows, await hydrate(client, keys.rows, options));
669
+ return page(
670
+ keys.rows,
671
+ rows,
672
+ keys.rows.length === input.limit ? keys.rows.at(-1)! : null,
673
+ keys.rows.length,
674
+ STATUS_CREATED_INDEX,
675
+ );
676
+ }
677
+
678
+ const scanStatus = state === 'recovering' ? 'queued' : 'cancelled';
679
+ const matchSql =
680
+ state === 'recovering'
681
+ ? durableRunRecoveringSql(options)
682
+ : `runs.finished_at >= now() - ($5::bigint * interval '1 millisecond')`;
683
+ const scanned = await client.query<{
684
+ run_id: string;
685
+ sort_at: unknown;
686
+ matched: boolean;
687
+ }>(
688
+ `SELECT slice.run_id, slice.sort_at, ${matchSql} AS matched
689
+ FROM ${statusSliceSql({
690
+ statusParam: '$1::text',
691
+ cursorAtParam: '$2',
692
+ cursorIdParam: '$3',
693
+ limitParam: '$4::int',
694
+ options,
695
+ })} AS slice
696
+ JOIN ${table('runs', options)} AS runs ON runs.run_id = slice.run_id
697
+ ORDER BY slice.sort_at DESC, slice.run_id ASC`,
698
+ state === 'recovering'
699
+ ? [scanStatus, cursorAt, cursorId, DURABLE_RUN_INVENTORY_SCAN_LIMIT]
700
+ : [
701
+ scanStatus,
702
+ cursorAt,
703
+ cursorId,
704
+ DURABLE_RUN_INVENTORY_SCAN_LIMIT,
705
+ RUN_RESUME_WINDOW_MS,
706
+ ],
707
+ );
708
+ return filteredPage(scanned.rows, STATUS_CREATED_INDEX);
709
+ }
710
+
711
+ /** One run by id, or null when this scheduler schema has no such run. */
712
+ export async function readDurableRun(
713
+ client: PostgresSchedulerQueryClient,
714
+ input: { runId: string },
715
+ options?: Options,
716
+ ): Promise<DurableRunRow | null> {
717
+ const rows = await hydrate(client, [{ run_id: input.runId }], options);
718
+ return rows.get(input.runId) ?? null;
719
+ }