deepline 0.3.492 → 0.3.493

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 (173) hide show
  1. package/dist/bundling-sources/sdk/src/client-core.ts +11 -5
  2. package/dist/bundling-sources/sdk/src/plays/run-request.ts +1 -0
  3. package/dist/bundling-sources/sdk/src/release.ts +1 -1
  4. package/dist/bundling-sources/sdk/src/types.ts +6 -0
  5. package/dist/bundling-sources/shared_libs/monitors/fleets/verdict.ts +25 -9
  6. package/dist/bundling-sources/shared_libs/observability/scheduled-jobs.json +36 -0
  7. package/dist/bundling-sources/shared_libs/observability/scheduled-work-manual.ts +5 -4
  8. package/dist/bundling-sources/shared_libs/play-runtime/crustdata-company-identify-batching.ts +162 -0
  9. package/dist/bundling-sources/shared_libs/play-runtime/daytona-sandbox-reaper.ts +19 -3
  10. package/dist/bundling-sources/shared_libs/play-runtime/play-runtime-batching-registry.ts +2 -0
  11. package/dist/bundling-sources/shared_libs/play-runtime/receipt-sql.ts +17 -23
  12. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona-modal-fallback.ts +28 -1
  13. package/dist/bundling-sources/shared_libs/play-runtime/runtime-sandbox-placement-policy.ts +75 -0
  14. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-runtime-worker.ts +20 -0
  15. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres.ts +412 -59
  16. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-sandbox-capacity.ts +38 -10
  17. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-sandbox-ledger-reconciliation.ts +19 -11
  18. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/runtime-sandbox-operation.ts +165 -12
  19. package/dist/bundling-sources/shared_libs/play-runtime/work-receipt-state-machine.ts +358 -0
  20. package/dist/cli/{auth-4I6QY5WX.mjs → auth-3NAY3AST.mjs} +5 -5
  21. package/dist/cli/auth-KYQLDI6V.js +43 -0
  22. package/dist/cli/{billing-2H4GOJZY.js → billing-FSB4BBBO.js} +80 -80
  23. package/dist/cli/{billing-4F6L4JSI.mjs → billing-SBWQCC7B.mjs} +7 -7
  24. package/dist/cli/{chunk-MQ2LQOAM.mjs → chunk-2BRTYIAH.mjs} +23 -9
  25. package/dist/cli/{chunk-E47VAVAR.js → chunk-2H4OFVR5.js} +5 -5
  26. package/dist/cli/{chunk-ZDTPSVGF.js → chunk-2I7VN65H.js} +10 -10
  27. package/dist/cli/{chunk-LCCFGSV7.mjs → chunk-2IHGVAGT.mjs} +2 -2
  28. package/dist/cli/{chunk-BDUFZSUL.js → chunk-2NGIBJM2.js} +8 -8
  29. package/dist/cli/{chunk-OTUT3XTX.mjs → chunk-3QGUWB6E.mjs} +4 -4
  30. package/dist/cli/{chunk-3BRDP4UP.mjs → chunk-4IJFQV3O.mjs} +1 -1
  31. package/dist/cli/{chunk-PIC6M4X3.mjs → chunk-4NIGNT7X.mjs} +1 -1
  32. package/dist/cli/{chunk-YVOYZPMY.mjs → chunk-5DIZ2G74.mjs} +2 -2
  33. package/dist/cli/{chunk-TKLDKIJU.mjs → chunk-5JPKRDFC.mjs} +7 -5
  34. package/dist/cli/{chunk-FTXIJTV2.mjs → chunk-5WOPBX3H.mjs} +1 -1
  35. package/dist/cli/{chunk-R5MP3CIY.mjs → chunk-67ZG7XZV.mjs} +3 -3
  36. package/dist/cli/{chunk-W4FEX5ZF.js → chunk-7HABWOMB.js} +261 -261
  37. package/dist/cli/{chunk-FPLN7PHP.js → chunk-AGTXL6LZ.js} +5 -5
  38. package/dist/cli/{chunk-SE23YSBK.js → chunk-AWMCZAUR.js} +3 -3
  39. package/dist/cli/{chunk-HHTVRICE.js → chunk-C2MRDPA5.js} +17 -17
  40. package/dist/cli/{chunk-ONONSV2Q.mjs → chunk-DVQHG6AM.mjs} +1 -0
  41. package/dist/cli/{chunk-O3K22ZC7.js → chunk-DWJ4RXSA.js} +34 -11
  42. package/dist/cli/{chunk-6YO4OJPM.mjs → chunk-DYP27IWC.mjs} +99 -24
  43. package/dist/cli/{chunk-EANFUHRM.mjs → chunk-E5ILCMKQ.mjs} +1 -1
  44. package/dist/cli/{chunk-Y7QCMOGZ.mjs → chunk-EBAS3UT2.mjs} +6 -6
  45. package/dist/cli/{chunk-DJOLMS2A.js → chunk-EFO5GVYS.js} +1 -1
  46. package/dist/cli/{chunk-NF7NUKWF.js → chunk-EYG336YV.js} +132 -57
  47. package/dist/cli/{chunk-OKHBAAJG.mjs → chunk-GSC35TPZ.mjs} +2 -2
  48. package/dist/cli/{chunk-MPITIXW4.mjs → chunk-HLM2UFQ5.mjs} +13 -5
  49. package/dist/cli/{chunk-TVUE4CPW.js → chunk-HTUSTPP4.js} +32 -32
  50. package/dist/cli/{chunk-GDSZWTJK.mjs → chunk-IJJ6D5WL.mjs} +12 -12
  51. package/dist/cli/{chunk-3TISK5RQ.js → chunk-IJOHWGPF.js} +6 -6
  52. package/dist/cli/{chunk-NBL6JMIY.js → chunk-IOBPR2VO.js} +17 -17
  53. package/dist/cli/{chunk-EFFHRXKB.js → chunk-IOMEJKGK.js} +2 -2
  54. package/dist/cli/{chunk-A7ZMG2QZ.mjs → chunk-IRDYBMA7.mjs} +34 -11
  55. package/dist/cli/{chunk-B2JE3HD6.js → chunk-JO2JZUBR.js} +3 -3
  56. package/dist/cli/{chunk-4IP5MLWU.js → chunk-JO5FFSR7.js} +6 -1
  57. package/dist/cli/{chunk-O2FB42N2.js → chunk-KCDZWS2B.js} +56 -56
  58. package/dist/cli/{chunk-CGDUFVNE.mjs → chunk-KGDDQMI7.mjs} +2 -2
  59. package/dist/cli/{chunk-UUH4GQRL.mjs → chunk-KKSKYZO4.mjs} +1 -1
  60. package/dist/cli/{chunk-OTDX4A4W.js → chunk-LGTZYI5B.js} +21 -21
  61. package/dist/cli/{chunk-JJAHWKJ2.js → chunk-MLEUOTEQ.js} +73 -59
  62. package/dist/cli/{chunk-YOCEY4EI.mjs → chunk-NALJJTPS.mjs} +5 -5
  63. package/dist/cli/{chunk-HFEJ7JJT.js → chunk-NPNAEPY4.js} +26 -26
  64. package/dist/cli/{chunk-3IBKEOL4.js → chunk-NWIDPT7H.js} +4 -4
  65. package/dist/cli/{chunk-AUQQVDAB.js → chunk-PKV5CD3W.js} +1 -0
  66. package/dist/cli/{chunk-4RB74KJX.js → chunk-QTPS5RLG.js} +15 -15
  67. package/dist/cli/{chunk-4OLXMJ2L.js → chunk-RLX5ZFNX.js} +8 -6
  68. package/dist/cli/{chunk-DEJIN4DF.mjs → chunk-SAW3FBCA.mjs} +5 -0
  69. package/dist/cli/{chunk-RC366IJS.mjs → chunk-SXD2EYAH.mjs} +6 -6
  70. package/dist/cli/{chunk-YNWET57Z.js → chunk-TIFRRLZT.js} +7 -7
  71. package/dist/cli/{chunk-ZCKUNXXR.mjs → chunk-TNQOR6XQ.mjs} +1 -1
  72. package/dist/cli/{chunk-OGNIB64W.js → chunk-UCMY2SO2.js} +23 -15
  73. package/dist/cli/{chunk-O65HDVA7.mjs → chunk-VFHIYWMC.mjs} +5 -5
  74. package/dist/cli/{chunk-JHBRJDUC.js → chunk-WCZFCOMZ.js} +7 -7
  75. package/dist/cli/{chunk-FFOJRD53.mjs → chunk-WTFI7BVH.mjs} +3 -3
  76. package/dist/cli/{chunk-42Z6VC2Q.js → chunk-XLE7KXE7.js} +2 -2
  77. package/dist/cli/{chunk-Q3CCCTRQ.js → chunk-XQX476QK.js} +14 -14
  78. package/dist/cli/{chunk-F6EQWY4E.mjs → chunk-Y3NN2UAF.mjs} +2 -2
  79. package/dist/cli/{chunk-MJFVF5AW.mjs → chunk-ZQH4TXM2.mjs} +2 -2
  80. package/dist/cli/{chunk-DVGCPOEA.mjs → chunk-ZVW7EWTC.mjs} +7 -7
  81. package/dist/cli/{chunk-4GJIJHRQ.mjs → chunk-ZVXB7OU7.mjs} +1 -1
  82. package/dist/cli/command-docs.js +2 -2
  83. package/dist/cli/command-docs.mjs +1 -1
  84. package/dist/cli/{csv-JGJNDRSA.js → csv-DKYZE2KM.js} +13 -13
  85. package/dist/cli/{csv-VGXGV7YM.mjs → csv-XR22YQXT.mjs} +4 -4
  86. package/dist/cli/{db-OYG27ZBM.mjs → db-EOKG36YN.mjs} +7 -7
  87. package/dist/cli/{db-W52WJ6E5.js → db-RNYRTCMV.js} +28 -28
  88. package/dist/cli/describe-ICFXOQBW.mjs +50 -0
  89. package/dist/cli/describe-RS75I33X.js +50 -0
  90. package/dist/cli/describe-core.d.mts +2 -2
  91. package/dist/cli/describe-core.d.ts +2 -2
  92. package/dist/cli/describe-core.js +4 -4
  93. package/dist/cli/describe-core.mjs +3 -3
  94. package/dist/cli/{executions-EVE4KUGL.mjs → executions-3RAOACNS.mjs} +7 -7
  95. package/dist/cli/{executions-LAJHZGPY.js → executions-OBWPSWH7.js} +9 -9
  96. package/dist/cli/{feedback-75QB7KVG.mjs → feedback-6EQRVBKF.mjs} +4 -4
  97. package/dist/cli/{feedback-ZABCN7RT.js → feedback-6GPEUBLF.js} +8 -8
  98. package/dist/cli/getting-started.d.mts +12 -10
  99. package/dist/cli/getting-started.d.ts +12 -10
  100. package/dist/cli/getting-started.js +4 -2
  101. package/dist/cli/getting-started.mjs +3 -1
  102. package/dist/cli/{git-QIFEYQGY.mjs → git-CVQ24DTR.mjs} +5 -5
  103. package/dist/cli/git-DEFE4SSB.js +25 -0
  104. package/dist/cli/index.js +143 -143
  105. package/dist/cli/index.mjs +43 -43
  106. package/dist/cli/{legacy-noops-PNTWBBGY.mjs → legacy-noops-QULJZYNH.mjs} +5 -5
  107. package/dist/cli/{legacy-noops-2TBIAMCM.js → legacy-noops-XPOATG5V.js} +8 -8
  108. package/dist/cli/{monitors-LOHUYJEI.mjs → monitors-AFT5YJPZ.mjs} +49 -9
  109. package/dist/cli/{monitors-UKBOEGBS.js → monitors-OJ4CMREE.js} +169 -129
  110. package/dist/cli/{org-E7A6QLBW.js → org-RKT52CSL.js} +73 -73
  111. package/dist/cli/{org-JRUKUOUF.mjs → org-WHKNXANG.mjs} +7 -7
  112. package/dist/cli/{pages-K76HA473.mjs → pages-EEAQFGVD.mjs} +7 -7
  113. package/dist/cli/{pages-EUDFFLLD.js → pages-SOE3R667.js} +18 -18
  114. package/dist/cli/{play-DG2N66SV.mjs → play-LXFWHUBP.mjs} +147 -52
  115. package/dist/cli/{play-UWHNUJRA.js → play-OTJJ4E4T.js} +661 -566
  116. package/dist/cli/{providers-DZX6TTC6.js → providers-RU4HIAT3.js} +10 -10
  117. package/dist/cli/{providers-RUTTPUZD.mjs → providers-U3CPKTMM.mjs} +7 -7
  118. package/dist/cli/{quickstart-RGZZN2YE.mjs → quickstart-75AO2AJC.mjs} +5 -5
  119. package/dist/cli/{quickstart-U4NMD7KX.js → quickstart-N72IVA2Y.js} +13 -13
  120. package/dist/cli/{run-MOJWQYFQ.mjs → run-IGWFL6WH.mjs} +29 -28
  121. package/dist/cli/{run-5UNF4FHG.js → run-MMYES3IW.js} +44 -43
  122. package/dist/cli/search-EQURI7SZ.js +32 -0
  123. package/dist/cli/{search-5B3ZDU7H.mjs → search-FIYESBLZ.mjs} +8 -8
  124. package/dist/cli/{search-output-VQWJS3FN.js → search-output-2FXN4ZWD.js} +9 -6
  125. package/dist/cli/{search-output-QS4IWWHA.mjs → search-output-3I5KSW36.mjs} +7 -4
  126. package/dist/cli/{secrets-S3PJMEAC.js → secrets-HCZQ6JNP.js} +16 -16
  127. package/dist/cli/{secrets-V5XVDBIS.mjs → secrets-O7IUQ3VT.mjs} +7 -7
  128. package/dist/cli/{sessions-Y5QMEZ3D.js → sessions-5AYTT4IW.js} +6 -6
  129. package/dist/cli/{sessions-5V3X24XI.mjs → sessions-KY7A3EZO.mjs} +5 -5
  130. package/dist/cli/{settings-3U6RRO5F.js → settings-P4VFYWJK.js} +80 -80
  131. package/dist/cli/{settings-LHZYY5PT.mjs → settings-WSMRR2GS.mjs} +13 -13
  132. package/dist/cli/{setup-MLLIGO2S.js → setup-J7CA3EJL.js} +57 -57
  133. package/dist/cli/{setup-AJLWXYAN.mjs → setup-YTVKVQC7.mjs} +13 -13
  134. package/dist/cli/skills-KKPEGLAR.js +36 -0
  135. package/dist/cli/{skills-5O2MUWKK.mjs → skills-W5WY764N.mjs} +10 -10
  136. package/dist/cli/tools-65Y4QTW6.js +57 -0
  137. package/dist/cli/{tools-PWNMI5CD.mjs → tools-YECI6N3N.mjs} +20 -20
  138. package/dist/cli/{update-SXT4QW7S.mjs → update-BIFBIEII.mjs} +10 -10
  139. package/dist/cli/update-WDG7VFOW.js +34 -0
  140. package/dist/cli/{workflow-3WTF5IYT.js → workflow-D2TUFFH6.js} +18 -18
  141. package/dist/cli/{workflow-KPRM6ARO.mjs → workflow-XZVDNARC.mjs} +8 -8
  142. package/dist/{client-Cb1ej1Vr.d.ts → client-BDB_VbE4.d.ts} +1 -1
  143. package/dist/{client-vWpbLNCB.d.mts → client-CNzJ1LTF.d.mts} +1 -1
  144. package/dist/{client-core-CoBTvsXG.d.mts → client-core-CSv3DlPD.d.mts} +10 -3
  145. package/dist/{client-core-BmVs6SP0.d.ts → client-core-xEa9x3pl.d.ts} +10 -3
  146. package/dist/index.d.mts +3 -3
  147. package/dist/index.d.ts +3 -3
  148. package/dist/index.js +10 -10
  149. package/dist/index.mjs +7 -7
  150. package/dist/install-integrity.json +115 -114
  151. package/dist/plays/play-description.d.mts +1 -1
  152. package/dist/plays/play-description.d.ts +1 -1
  153. package/dist/plays/run-request.d.mts +1 -1
  154. package/dist/plays/run-request.d.ts +1 -1
  155. package/dist/plays/run-request.js +2 -2
  156. package/dist/plays/run-request.mjs +1 -1
  157. package/dist/release.d.mts +1 -1
  158. package/dist/release.d.ts +1 -1
  159. package/dist/release.js +2 -2
  160. package/dist/release.mjs +1 -1
  161. package/dist/server.d.mts +2 -2
  162. package/dist/server.d.ts +2 -2
  163. package/dist/server.js +6 -6
  164. package/dist/server.mjs +4 -4
  165. package/package.json +1 -1
  166. package/dist/cli/auth-7BCLZU6K.js +0 -43
  167. package/dist/cli/describe-FIXCRO5N.mjs +0 -50
  168. package/dist/cli/describe-G3O6OUBG.js +0 -50
  169. package/dist/cli/git-QBAR46NW.js +0 -25
  170. package/dist/cli/search-3DAEJL6S.js +0 -32
  171. package/dist/cli/skills-BBLIML5M.js +0 -36
  172. package/dist/cli/tools-X5SQXUMM.js +0 -57
  173. package/dist/cli/update-AEJ2ZSZQ.js +0 -34
@@ -5,6 +5,10 @@ import {
5
5
  } from '../terminal-runtime-performance';
6
6
  import { escapeLiteral } from 'pg';
7
7
  import { assertWorkReceiptKeyMutable } from '../work-receipt-storage-contract';
8
+ import {
9
+ schedulerWorkReceiptClaimTransition,
10
+ schedulerWorkReceiptFromStatuses,
11
+ } from '../work-receipt-state-machine';
8
12
  import {
9
13
  readRowFailureCounts,
10
14
  type RowFailureCounts,
@@ -58,6 +62,10 @@ import type { PlayRunnerRuntimeResource } from '../runner-backends/types';
58
62
  import {
59
63
  RuntimeSandboxOperationState,
60
64
  type RuntimeSandboxProvider,
65
+ runtimeSandboxOperationFromStates,
66
+ runtimeSandboxOperationFromStatesSqlCast,
67
+ runtimeSandboxOperationStateSqlType,
68
+ runtimeSandboxOperationTargetState,
61
69
  runtimeSandboxProviderForResourceKind,
62
70
  } from './runtime-sandbox-operation';
63
71
  import {
@@ -1136,6 +1144,15 @@ function tableName(
1136
1144
  return `${quoteIdent(schemaName(options))}.${quoteIdent(table)}`;
1137
1145
  }
1138
1146
 
1147
+ /** The cast a sandbox operation allowed-from parameter takes in this schema. */
1148
+ function runtimeSandboxOperationFromStatesCast(
1149
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
1150
+ ): string {
1151
+ return runtimeSandboxOperationFromStatesSqlCast(
1152
+ quoteIdent(schemaName(options)),
1153
+ );
1154
+ }
1155
+
1139
1156
  /**
1140
1157
  * `now()` is transaction-stable in Postgres, so two causal outbox writes in
1141
1158
  * one transaction can otherwise tie and fall back to random event-id order.
@@ -10166,6 +10183,7 @@ export async function recordPostgresSchedulerManagedSandboxOperationLive(
10166
10183
  input.resource.runtimeEnvironment ??
10167
10184
  input.resource.daytonaEnvironment ??
10168
10185
  'production';
10186
+ const operationStates = runtimeSandboxOperationFromStatesCast(options);
10169
10187
  const recorded = await client.query<{ operation_key: string }>(
10170
10188
  `
10171
10189
  WITH ${runtimeSandboxCustodyLocksSql('run.run_id = $1', options)}, eligible_attempt AS (
@@ -10203,7 +10221,7 @@ export async function recordPostgresSchedulerManagedSandboxOperationLive(
10203
10221
  AND operation.run_id = $1
10204
10222
  AND operation.attempt = $2
10205
10223
  AND operation.provider = $10
10206
- AND operation.state = $11
10224
+ AND operation.state = ANY($11::${operationStates})
10207
10225
  RETURNING operation.operation_key
10208
10226
  ), recorded_attempt AS (
10209
10227
  UPDATE ${tableName('attempts', options)} AS attempt
@@ -10243,9 +10261,9 @@ export async function recordPostgresSchedulerManagedSandboxOperationLive(
10243
10261
  input.resource.sandboxId,
10244
10262
  routingDomain,
10245
10263
  environment,
10246
- RuntimeSandboxOperationState.Live,
10264
+ runtimeSandboxOperationTargetState('bind_live'),
10247
10265
  provider,
10248
- RuntimeSandboxOperationState.Reserved,
10266
+ runtimeSandboxOperationFromStates('bind_live'),
10249
10267
  ],
10250
10268
  );
10251
10269
  if (recorded.rows.length === 1) return true;
@@ -10274,7 +10292,7 @@ export async function recordPostgresSchedulerManagedSandboxOperationLive(
10274
10292
  AND NOT EXISTS (SELECT 1 FROM custody_attempts AS newer WHERE newer.attempt > $2)
10275
10293
  AND EXISTS (SELECT 1 FROM custody_runs WHERE status IN ('queued', 'running', 'waiting'))
10276
10294
  AND operation.operation_key = $5 AND operation.sandbox_id = $6
10277
- AND operation.provider = $7 AND operation.state IN ($8, 'deleting')
10295
+ AND operation.provider = $7 AND operation.state = ANY($8::${operationStates})
10278
10296
  AND operation.environment = $9 AND operation.routing_domain IS NOT DISTINCT FROM $10
10279
10297
  AND lease.sandbox_id = $6 AND lease.released_at IS NULL
10280
10298
  AND EXISTS (
@@ -10284,7 +10302,7 @@ export async function recordPostgresSchedulerManagedSandboxOperationLive(
10284
10302
  )
10285
10303
  ), retiring_operation AS (
10286
10304
  UPDATE ${tableName('runtime_sandbox_operations', options)} AS operation
10287
- SET state = 'deleting', updated_at = clock_timestamp()
10305
+ SET state = $11, updated_at = clock_timestamp()
10288
10306
  FROM eligible_retirement
10289
10307
  WHERE operation.operation_key = eligible_retirement.operation_key
10290
10308
  RETURNING operation.operation_key
@@ -10318,9 +10336,10 @@ export async function recordPostgresSchedulerManagedSandboxOperationLive(
10318
10336
  input.resource.sandboxCapacityLeaseId,
10319
10337
  input.resource.sandboxId,
10320
10338
  provider,
10321
- RuntimeSandboxOperationState.Live,
10339
+ runtimeSandboxOperationFromStates('retire_live'),
10322
10340
  environment,
10323
10341
  routingDomain,
10342
+ runtimeSandboxOperationTargetState('retire_live'),
10324
10343
  ],
10325
10344
  );
10326
10345
  return updated.rows.length === 1;
@@ -10561,6 +10580,7 @@ export async function resolvePostgresSchedulerAmbiguousModalCreateIntentFromProv
10561
10580
  >,
10562
10581
  options?: Pick<PostgresSchedulerOptions, 'schema'>,
10563
10582
  ): Promise<boolean> {
10583
+ const operationStates = runtimeSandboxOperationFromStatesCast(options);
10564
10584
  const resolved = await client.query<{ run_id: string }>(
10565
10585
  `
10566
10586
  WITH ${runtimeSandboxCustodyLocksSql('run.run_id = $1', options)}, resolved AS (
@@ -10574,10 +10594,10 @@ export async function resolvePostgresSchedulerAmbiguousModalCreateIntentFromProv
10574
10594
  RETURNING run_id, sandbox_capacity_lease_id
10575
10595
  ), abandoned AS (
10576
10596
  UPDATE ${tableName('runtime_sandbox_operations', options)} AS operation
10577
- SET state = 'abandoned', updated_at = clock_timestamp()
10597
+ SET state = $4, updated_at = clock_timestamp()
10578
10598
  FROM resolved
10579
10599
  WHERE operation.operation_key = resolved.sandbox_capacity_lease_id
10580
- AND operation.state = 'reserved'
10600
+ AND operation.state = ANY($5::${operationStates})
10581
10601
  RETURNING operation.operation_key
10582
10602
  ), released AS (
10583
10603
  UPDATE ${tableName('runtime_sandbox_capacity_leases', options)} AS lease
@@ -10588,7 +10608,13 @@ export async function resolvePostgresSchedulerAmbiguousModalCreateIntentFromProv
10588
10608
  )
10589
10609
  SELECT run_id FROM resolved
10590
10610
  `,
10591
- [input.runId, input.attempt, input.modalAppId],
10611
+ [
10612
+ input.runId,
10613
+ input.attempt,
10614
+ input.modalAppId,
10615
+ runtimeSandboxOperationTargetState('abandon_unresolved_modal_intent'),
10616
+ runtimeSandboxOperationFromStates('abandon_unresolved_modal_intent'),
10617
+ ],
10592
10618
  );
10593
10619
  return resolved.rows.length > 0;
10594
10620
  }
@@ -10617,6 +10643,7 @@ export async function recordPostgresSchedulerReconciledModalResourcesForCleanup(
10617
10643
  );
10618
10644
  if (resources.length === 0) return false;
10619
10645
  const payload = stringifyPostgresJson(resources);
10646
+ const operationStates = runtimeSandboxOperationFromStatesCast(options);
10620
10647
  const recorded = await client.query<{ run_id: string }>(
10621
10648
  `
10622
10649
  WITH ${runtimeSandboxCustodyLocksSql('run.run_id = $1', options)}, claimed_intent AS (
@@ -10660,7 +10687,7 @@ export async function recordPostgresSchedulerReconciledModalResourcesForCleanup(
10660
10687
  AND operation.provider = 'modal'
10661
10688
  AND operation.run_id = recorded.run_id
10662
10689
  AND operation.attempt = recorded.attempt
10663
- AND operation.state = $7
10690
+ AND operation.state = ANY($7::${operationStates})
10664
10691
  RETURNING operation.operation_key, operation.sandbox_id,
10665
10692
  operation.routing_domain
10666
10693
  ), recovered_operations AS (
@@ -10674,7 +10701,7 @@ export async function recordPostgresSchedulerReconciledModalResourcesForCleanup(
10674
10701
  'modal', recorded.run_id, recorded.attempt, run.org_id,
10675
10702
  coalesce(resource->>'runtimeEnvironment', 'production'),
10676
10703
  resource->>'sandboxId', nullif(resource->>'modalAppId', ''),
10677
- $6, clock_timestamp()
10704
+ $8, clock_timestamp()
10678
10705
  FROM recorded
10679
10706
  JOIN ${tableName('runs', options)} AS run ON run.run_id = recorded.run_id
10680
10707
  CROSS JOIN LATERAL jsonb_array_elements($4::jsonb) AS resource
@@ -10736,8 +10763,9 @@ export async function recordPostgresSchedulerReconciledModalResourcesForCleanup(
10736
10763
  input.intent.modalAppId,
10737
10764
  payload,
10738
10765
  input.intent.sandboxCapacityLeaseId ?? null,
10739
- RuntimeSandboxOperationState.Deleting,
10740
- RuntimeSandboxOperationState.Reserved,
10766
+ runtimeSandboxOperationTargetState('promote_reconciled_modal'),
10767
+ runtimeSandboxOperationFromStates('promote_reconciled_modal'),
10768
+ runtimeSandboxOperationTargetState('record_reconciled_modal'),
10741
10769
  ],
10742
10770
  );
10743
10771
  return recorded.rows.length > 0;
@@ -10843,6 +10871,7 @@ export async function recordPostgresSchedulerLateManagedSandboxOperationForClean
10843
10871
  input.resource.runtimeEnvironment ??
10844
10872
  input.resource.daytonaEnvironment ??
10845
10873
  'production';
10874
+ const operationStates = runtimeSandboxOperationFromStatesCast(options);
10846
10875
  const result = await client.query<{ operation_key: string }>(
10847
10876
  `
10848
10877
  WITH ${runtimeSandboxCustodyLocksSql('run.run_id = $1', options)}, eligible_lease AS MATERIALIZED (
@@ -10872,7 +10901,7 @@ export async function recordPostgresSchedulerLateManagedSandboxOperationForClean
10872
10901
  AND operation.run_id = $1
10873
10902
  AND operation.attempt = $2
10874
10903
  AND operation.provider = $10
10875
- AND operation.state = $11
10904
+ AND operation.state = ANY($11::${operationStates})
10876
10905
  RETURNING operation.operation_key
10877
10906
  ), recorded_attempt AS (
10878
10907
  UPDATE ${tableName('attempts', options)} AS attempt
@@ -10917,9 +10946,9 @@ export async function recordPostgresSchedulerLateManagedSandboxOperationForClean
10917
10946
  input.resource.sandboxId,
10918
10947
  routingDomain,
10919
10948
  environment,
10920
- RuntimeSandboxOperationState.Deleting,
10949
+ runtimeSandboxOperationTargetState('record_late'),
10921
10950
  provider,
10922
- RuntimeSandboxOperationState.Reserved,
10951
+ runtimeSandboxOperationFromStates('record_late'),
10923
10952
  ],
10924
10953
  );
10925
10954
  return result.rows.length === 1;
@@ -12824,14 +12853,15 @@ export async function abandonUnstartedModalCancellationReservations(
12824
12853
  input: { runId: string },
12825
12854
  options?: Pick<PostgresSchedulerOptions, 'schema'>,
12826
12855
  ): Promise<void> {
12856
+ const operationStates = runtimeSandboxOperationFromStatesCast(options);
12827
12857
  await client.query(
12828
12858
  `WITH ${runtimeSandboxCustodyLocksSql('run.run_id = $1', options)}, abandoned AS (
12829
12859
  UPDATE ${tableName('runtime_sandbox_operations', options)} AS operation
12830
- SET state = 'abandoned', updated_at = clock_timestamp()
12860
+ SET state = $3, updated_at = clock_timestamp()
12831
12861
  FROM (SELECT count(*) FROM custody_operations) AS operation_locks
12832
12862
  WHERE operation.run_id = $1
12833
12863
  AND operation.provider = 'modal'
12834
- AND operation.state = 'reserved'
12864
+ AND operation.state = ANY($4::${operationStates})
12835
12865
  AND operation.created_at <= clock_timestamp()
12836
12866
  - ($2::double precision * interval '1 millisecond')
12837
12867
  AND NOT EXISTS (
@@ -12859,7 +12889,12 @@ export async function abandonUnstartedModalCancellationReservations(
12859
12889
  FROM abandoned
12860
12890
  WHERE lease.lease_id = abandoned.operation_key
12861
12891
  AND lease.released_at IS NULL`,
12862
- [input.runId, RUNTIME_RELIABILITY_POLICY.recovery.horizonMs],
12892
+ [
12893
+ input.runId,
12894
+ RUNTIME_RELIABILITY_POLICY.recovery.horizonMs,
12895
+ runtimeSandboxOperationTargetState('abandon_unstarted_modal'),
12896
+ runtimeSandboxOperationFromStates('abandon_unstarted_modal'),
12897
+ ],
12863
12898
  );
12864
12899
  }
12865
12900
 
@@ -13032,6 +13067,10 @@ export async function claimPostgresSchedulerSandboxCleanupJobs(
13032
13067
  (provider) => provider === 'daytona' || provider === 'modal',
13033
13068
  );
13034
13069
  if (providers?.length === 0) return [];
13070
+ const operationStates = runtimeSandboxOperationFromStatesCast(options);
13071
+ const operationState = runtimeSandboxOperationStateSqlType(
13072
+ quoteIdent(schemaName(options)),
13073
+ );
13035
13074
  const claimablePredicate = `EXISTS (
13036
13075
  SELECT 1 FROM ${tableName('sandbox_cleanup_jobs_v2', options)} AS cleanup
13037
13076
  WHERE cleanup.status <> 'deleted' AND cleanup.blocked_at IS NULL
@@ -13393,7 +13432,10 @@ export async function claimPostgresSchedulerSandboxCleanupJobs(
13393
13432
  ),
13394
13433
  operation_claimed AS (
13395
13434
  UPDATE ${tableName('runtime_sandbox_operations', options)} AS operation
13396
- SET state = $6,
13435
+ SET state = CASE
13436
+ WHEN operation.state = ANY($7::${operationStates}) THEN $6::${operationState}
13437
+ ELSE $15::${operationState}
13438
+ END,
13397
13439
  sandbox_id = claimed.sandbox_id,
13398
13440
  routing_domain = claimed.routing_domain,
13399
13441
  provider_created_at = COALESCE(operation.provider_created_at, clock_timestamp()),
@@ -13402,10 +13444,10 @@ export async function claimPostgresSchedulerSandboxCleanupJobs(
13402
13444
  WHERE operation.run_id = claimed.run_id
13403
13445
  AND operation.provider = claimed.provider
13404
13446
  AND (
13405
- (operation.state = $7
13447
+ (operation.state = ANY($7::${operationStates})
13406
13448
  AND operation.sandbox_id = claimed.sandbox_id
13407
13449
  AND operation.routing_domain IS NOT DISTINCT FROM claimed.routing_domain)
13408
- OR (operation.state = 'reserved'
13450
+ OR (operation.state = ANY($14::${operationStates})
13409
13451
  AND operation.sandbox_id IS NULL
13410
13452
  AND EXISTS (
13411
13453
  SELECT 1 FROM custody_leases AS lease
@@ -13456,14 +13498,16 @@ export async function claimPostgresSchedulerSandboxCleanupJobs(
13456
13498
  leaseSeconds,
13457
13499
  input.environment?.trim() || null,
13458
13500
  providers,
13459
- RuntimeSandboxOperationState.Deleting,
13460
- RuntimeSandboxOperationState.Live,
13501
+ runtimeSandboxOperationTargetState('cleanup_claim_live'),
13502
+ runtimeSandboxOperationFromStates('cleanup_claim_live'),
13461
13503
  input.runId ?? null,
13462
13504
  input.throughAttempt ?? null,
13463
13505
  input.exactResource?.provider ?? null,
13464
13506
  input.exactResource?.sandboxId ?? null,
13465
13507
  input.exactResource?.routingDomain ?? null,
13466
13508
  input.exactResource?.attempt ?? null,
13509
+ runtimeSandboxOperationFromStates('cleanup_claim_reserved'),
13510
+ runtimeSandboxOperationTargetState('cleanup_claim_reserved'),
13467
13511
  ],
13468
13512
  );
13469
13513
  return claimed.rows.map((row) => {
@@ -13697,6 +13741,7 @@ export async function completePostgresSchedulerSandboxCleanupJob(
13697
13741
  // `deleted_at` feeds billing end times, so it stays the moment the provider
13698
13742
  // took the delete. Waiting for the read-back must not bill the customer for
13699
13743
  // Daytona's record outliving it; `delete_confirmed_at` keeps the confirmation.
13744
+ const operationStates = runtimeSandboxOperationFromStatesCast(options);
13700
13745
  const completed = await client.query<{ outcome: string }>(
13701
13746
  `
13702
13747
  WITH ${runtimeSandboxCustodyLocksSql('run.run_id = $3', options)}, current_job AS MATERIALIZED (
@@ -13889,7 +13934,7 @@ export async function completePostgresSchedulerSandboxCleanupJob(
13889
13934
  AND operation.provider = $8
13890
13935
  AND operation.sandbox_id = $1
13891
13936
  AND operation.routing_domain IS NOT DISTINCT FROM $9
13892
- AND operation.state = $11
13937
+ AND operation.state = ANY($11::${operationStates})
13893
13938
  RETURNING operation.operation_key
13894
13939
  ),
13895
13940
  released_capacity AS (
@@ -14000,8 +14045,8 @@ export async function completePostgresSchedulerSandboxCleanupJob(
14000
14045
  input.observedRoutingDomain?.trim() || null,
14001
14046
  input.provider ?? 'daytona',
14002
14047
  input.routingDomain?.trim() || null,
14003
- RuntimeSandboxOperationState.Deleted,
14004
- RuntimeSandboxOperationState.Deleting,
14048
+ runtimeSandboxOperationTargetState('cleanup_complete'),
14049
+ runtimeSandboxOperationFromStates('cleanup_complete'),
14005
14050
  ],
14006
14051
  );
14007
14052
  const outcome = completed.rows[0]?.outcome;
@@ -17734,11 +17779,9 @@ export async function claimPostgresSchedulerReceipt(
17734
17779
  [
17735
17780
  input.key,
17736
17781
  input.runId,
17737
- input.forceRefresh
17738
- ? ['pending', 'failed', 'running', 'completed', 'skipped']
17739
- : input.reclaimRunning
17740
- ? ['pending', 'failed', 'running']
17741
- : ['pending', 'failed', 'queued', 'running'],
17782
+ schedulerWorkReceiptFromStatuses(
17783
+ schedulerWorkReceiptClaimTransition(input),
17784
+ ),
17742
17785
  leaseId,
17743
17786
  runAttempt,
17744
17787
  PLAY_RUNTIME_WORK_RECEIPT_LEASE_TTL_MS,
@@ -18024,11 +18067,9 @@ export async function claimPostgresSchedulerReceipts(
18024
18067
  [
18025
18068
  input.keys,
18026
18069
  input.runId,
18027
- input.forceRefresh
18028
- ? ['pending', 'failed', 'running', 'completed', 'skipped']
18029
- : input.reclaimRunning
18030
- ? ['pending', 'failed', 'running']
18031
- : ['pending', 'failed', 'queued', 'running'],
18070
+ schedulerWorkReceiptFromStatuses(
18071
+ schedulerWorkReceiptClaimTransition(input),
18072
+ ),
18032
18073
  leaseIds,
18033
18074
  runAttempt,
18034
18075
  PLAY_RUNTIME_WORK_RECEIPT_LEASE_TTL_MS,
@@ -18141,7 +18182,7 @@ export async function completePostgresSchedulerReceipt(
18141
18182
  lease_owner_attempt = NULL,
18142
18183
  lease_expires_at = NULL,
18143
18184
  updated_at = now()
18144
- WHERE receipt.status NOT IN ('completed', 'skipped')
18185
+ WHERE receipt.status = ANY($7::text[])
18145
18186
  RETURNING k, status,
18146
18187
  CASE WHEN $6::boolean THEN output_json ELSE NULL::jsonb END AS output_json,
18147
18188
  output_ref,
@@ -18155,6 +18196,7 @@ export async function completePostgresSchedulerReceipt(
18155
18196
  receiptOutputRefJson(input),
18156
18197
  input.runId,
18157
18198
  input.returnOutput !== false,
18199
+ schedulerWorkReceiptFromStatuses('publish_completed'),
18158
18200
  ],
18159
18201
  );
18160
18202
  if (inserted.rows[0]) {
@@ -18206,7 +18248,7 @@ export async function completePostgresSchedulerReceipt(
18206
18248
  WHERE k = $1
18207
18249
  AND org_id = $6
18208
18250
  AND run_id = $2
18209
- AND status = 'running'
18251
+ AND status = ANY($9::text[])
18210
18252
  AND COALESCE(lease_owner_run_id, run_id) = $2
18211
18253
  AND COALESCE(lease_owner_attempt, 0) = $4::integer
18212
18254
  AND (
@@ -18230,6 +18272,7 @@ export async function completePostgresSchedulerReceipt(
18230
18272
  receiptOrgId(options),
18231
18273
  receiptOutputRefJson(input),
18232
18274
  input.returnOutput !== false,
18275
+ schedulerWorkReceiptFromStatuses('complete'),
18233
18276
  ],
18234
18277
  );
18235
18278
  return result.rows[0]
@@ -18300,7 +18343,7 @@ async function completePostgresSchedulerCacheInsertReceipts(
18300
18343
  lease_owner_attempt = NULL,
18301
18344
  lease_expires_at = NULL,
18302
18345
  updated_at = now()
18303
- WHERE receipt.status NOT IN ('completed', 'skipped')
18346
+ WHERE receipt.status = ANY($7::text[])
18304
18347
  RETURNING k, status,
18305
18348
  CASE WHEN $6::boolean THEN output_json ELSE NULL::jsonb END AS output_json,
18306
18349
  output_ref,
@@ -18316,6 +18359,7 @@ async function completePostgresSchedulerCacheInsertReceipts(
18316
18359
  ),
18317
18360
  insertIndexes.map((index) => input.receipts[index]!.runId),
18318
18361
  returnOutput,
18362
+ schedulerWorkReceiptFromStatuses('publish_completed'),
18319
18363
  ],
18320
18364
  );
18321
18365
  const persistedByKey = new Map(inserted.rows.map((row) => [row.k, row]));
@@ -18477,7 +18521,7 @@ export async function completePostgresSchedulerReceipts(
18477
18521
  WHERE target.k = inputs.k
18478
18522
  AND target.org_id = $7
18479
18523
  AND target.run_id = inputs.run_id
18480
- AND target.status = 'running'
18524
+ AND target.status = ANY($9::text[])
18481
18525
  AND COALESCE(target.lease_owner_run_id, target.run_id) = inputs.run_id
18482
18526
  AND COALESCE(target.lease_owner_attempt, 0) = inputs.run_attempt
18483
18527
  AND (
@@ -18527,6 +18571,7 @@ export async function completePostgresSchedulerReceipts(
18527
18571
  normalized.map((receipt) => receiptOutputRefJson(receipt)),
18528
18572
  receiptOrgId(options),
18529
18573
  input.returnOutput !== false,
18574
+ schedulerWorkReceiptFromStatuses('complete'),
18530
18575
  ],
18531
18576
  );
18532
18577
  return result.rows.map((row) =>
@@ -18564,7 +18609,7 @@ export async function failPostgresSchedulerReceipt(
18564
18609
  WHERE k = $1
18565
18610
  AND org_id = $7
18566
18611
  AND run_id = $2
18567
- AND status = 'running'
18612
+ AND status = ANY($9::text[])
18568
18613
  AND COALESCE(lease_owner_run_id, run_id) = $2
18569
18614
  AND COALESCE(lease_owner_attempt, 0) = $4::integer
18570
18615
  AND (
@@ -18585,6 +18630,7 @@ export async function failPostgresSchedulerReceipt(
18585
18630
  workReceiptFailureKindCodeForWrite(input.failureKind),
18586
18631
  receiptOrgId(options),
18587
18632
  input.errorPayload ? JSON.stringify(input.errorPayload) : null,
18633
+ schedulerWorkReceiptFromStatuses('fail'),
18588
18634
  ],
18589
18635
  );
18590
18636
  return result.rows[0] ? mapReceiptRow(result.rows[0]) : null;
@@ -18647,7 +18693,7 @@ export async function failPostgresSchedulerReceipts(
18647
18693
  WHERE target.k = inputs.k
18648
18694
  AND target.org_id = $8
18649
18695
  AND target.run_id = inputs.run_id
18650
- AND target.status = 'running'
18696
+ AND target.status = ANY($9::text[])
18651
18697
  AND COALESCE(target.lease_owner_run_id, target.run_id) = inputs.run_id
18652
18698
  AND COALESCE(target.lease_owner_attempt, 0) = inputs.run_attempt
18653
18699
  AND (
@@ -18695,6 +18741,7 @@ export async function failPostgresSchedulerReceipts(
18695
18741
  normalized.map((receipt) => receipt.failureKind),
18696
18742
  normalized.map((receipt) => receipt.errorPayload),
18697
18743
  receiptOrgId(options),
18744
+ schedulerWorkReceiptFromStatuses('fail'),
18698
18745
  ],
18699
18746
  );
18700
18747
  return result.rows.map((row) => (row.k ? mapReceiptRow(row) : null));
@@ -18710,11 +18757,11 @@ export async function releasePostgresSchedulerReceipt(
18710
18757
  input.runAttempt,
18711
18758
  );
18712
18759
  const leaseId = input.leaseId?.trim() || null;
18760
+ // This scheduler gateway claims pending receipts. Exact release must return
18761
+ // to that claimable state for a later run to retry it.
18713
18762
  const result = await client.query<ReceiptRow>(
18714
18763
  `
18715
18764
  UPDATE ${tableName('receipts', options)}
18716
- -- This scheduler gateway claims pending receipts. Exact release must
18717
- -- return to that claimable state for a later run to retry it.
18718
18765
  SET status = 'pending',
18719
18766
  output_json = NULL,
18720
18767
  output_ref = NULL,
@@ -18727,7 +18774,7 @@ export async function releasePostgresSchedulerReceipt(
18727
18774
  WHERE k = $1
18728
18775
  AND org_id = $5
18729
18776
  AND run_id = $2
18730
- AND status = 'running'
18777
+ AND status = ANY($6::text[])
18731
18778
  AND COALESCE(lease_owner_run_id, run_id) = $2
18732
18779
  AND COALESCE(lease_owner_attempt, 0) = $3::integer
18733
18780
  AND (
@@ -18739,7 +18786,14 @@ export async function releasePostgresSchedulerReceipt(
18739
18786
  )
18740
18787
  RETURNING k, status, output_json, error, error_payload, failure_kind, run_id, lease_id, lease_owner_run_id, lease_owner_attempt, lease_expires_at
18741
18788
  `,
18742
- [input.key, input.runId, runAttempt, leaseId, receiptOrgId(options)],
18789
+ [
18790
+ input.key,
18791
+ input.runId,
18792
+ runAttempt,
18793
+ leaseId,
18794
+ receiptOrgId(options),
18795
+ schedulerWorkReceiptFromStatuses('release'),
18796
+ ],
18743
18797
  );
18744
18798
  return result.rows[0] ? mapReceiptRow(result.rows[0]) : null;
18745
18799
  }
@@ -18773,25 +18827,22 @@ export async function releasePostgresSchedulerReceiptsForAttempt(
18773
18827
  SET ${RELEASE_RECEIPT_TO_PENDING_SET_CLAUSE}
18774
18828
  WHERE org_id = $1
18775
18829
  AND run_id = $2
18776
- AND status IN ('queued', 'running')
18830
+ AND status = ANY($4::text[])
18777
18831
  AND COALESCE(lease_owner_run_id, run_id) = $2
18778
18832
  AND COALESCE(lease_owner_attempt, 0) = $3::integer
18779
18833
  RETURNING k
18780
18834
  `,
18781
- [receiptOrgId(options), input.runId, runAttempt],
18835
+ [
18836
+ receiptOrgId(options),
18837
+ input.runId,
18838
+ runAttempt,
18839
+ schedulerWorkReceiptFromStatuses('release_attempt'),
18840
+ ],
18782
18841
  );
18783
18842
  const releasedKeys = released.rows.map((row) => row.k);
18784
18843
  return { released: releasedKeys.length, releasedKeys };
18785
18844
  }
18786
18845
 
18787
- /**
18788
- * Marking only moves a receipt between its two live states. `completed` and
18789
- * `skipped` are reusable cache hits, `failed` is reclaimed through a claim,
18790
- * and `pending` was released by its owner, so none of them may be revived
18791
- * here. Matches `workReceiptActiveOwnerPredicateSql` in the tenant store.
18792
- */
18793
- const RECEIPT_MARK_ALLOWED_FROM_STATUSES = ['queued', 'running'] as const;
18794
-
18795
18846
  async function markPostgresSchedulerReceiptsStatus(
18796
18847
  client: PostgresSchedulerQueryClient,
18797
18848
  input:
@@ -18883,7 +18934,12 @@ async function markPostgresSchedulerReceiptsStatus(
18883
18934
  status,
18884
18935
  PLAY_RUNTIME_WORK_RECEIPT_LEASE_TTL_MS,
18885
18936
  receiptOrgId(options),
18886
- [...RECEIPT_MARK_ALLOWED_FROM_STATUSES],
18937
+ // Marking only moves a receipt between its two live states. Completed
18938
+ // and skipped are reusable cache hits, failed is reclaimed through a
18939
+ // claim, and pending was released by its owner: none may be revived.
18940
+ schedulerWorkReceiptFromStatuses(
18941
+ status === 'running' ? 'mark_running' : 'mark_queued',
18942
+ ),
18887
18943
  ],
18888
18944
  );
18889
18945
  return result.rows.map((row) => (row.k ? mapReceiptRow(row) : null));
@@ -19042,7 +19098,7 @@ export async function skipPostgresSchedulerReceipt(
19042
19098
  error_payload = NULL,
19043
19099
  failure_kind = 0,
19044
19100
  updated_at = now()
19045
- WHERE ${tableName('receipts', options)}.status IN ('pending', 'failed', 'running')
19101
+ WHERE ${tableName('receipts', options)}.status = ANY($7::text[])
19046
19102
  AND ${tableName('receipts', options)}.org_id = $6
19047
19103
  AND COALESCE(${tableName('receipts', options)}.lease_owner_run_id, ${tableName('receipts', options)}.run_id, $2) = $2
19048
19104
  AND COALESCE(${tableName('receipts', options)}.lease_owner_attempt, 0) <= $4::integer
@@ -19062,6 +19118,7 @@ export async function skipPostgresSchedulerReceipt(
19062
19118
  runAttempt,
19063
19119
  leaseId,
19064
19120
  receiptOrgId(options),
19121
+ schedulerWorkReceiptFromStatuses('skip'),
19065
19122
  ],
19066
19123
  );
19067
19124
  return result.rows[0] ? mapReceiptRow(result.rows[0]) : null;
@@ -21859,6 +21916,302 @@ export async function readPostgresSchedulerOutboxBlockedSummary(
21859
21916
  };
21860
21917
  }
21861
21918
 
21919
+ /**
21920
+ * One failed lane head an operator closes without delivering it, with the
21921
+ * exact failure epoch and the undelivered events queued behind it. Those
21922
+ * successors close with it: releasing them alone would deliver a lane whose
21923
+ * head never landed.
21924
+ */
21925
+ export type PostgresSchedulerOutboxCloseoutCandidate = {
21926
+ eventId: string;
21927
+ runId: string;
21928
+ eventType: string;
21929
+ searchOnly: boolean;
21930
+ failedAt: string;
21931
+ projectionAttempts: number;
21932
+ failureFingerprint: string;
21933
+ successorEventIds: string[];
21934
+ };
21935
+
21936
+ export type PostgresSchedulerOutboxCloseoutHead =
21937
+ PostgresSchedulerOutboxCloseoutCandidate & {
21938
+ orgId: string | null;
21939
+ playName: string | null;
21940
+ runStatus: string | null;
21941
+ createdAt: string;
21942
+ failureCode: string | null;
21943
+ failureStatus: string | null;
21944
+ failureRetryable: boolean | null;
21945
+ };
21946
+
21947
+ const OUTBOX_EPOCH_TIME_FORMAT = `'YYYY-MM-DD"T"HH24:MI:SS.US"Z"'`;
21948
+
21949
+ /**
21950
+ * Scheduler run statuses after which no new lane fact is expected. A closeout
21951
+ * needs one: a nonterminal run still executes, and closing its
21952
+ * `run.created` head would release the worker's created-projection gate for
21953
+ * a run Convex never received.
21954
+ */
21955
+ const OUTBOX_CLOSEOUT_TERMINAL_RUN_STATUSES_SQL = `('completed', 'failed', 'cancelled')`;
21956
+
21957
+ /** Head event types the closeout audit record accepts. */
21958
+ export const POSTGRES_SCHEDULER_OUTBOX_CLOSEOUT_HEAD_EVENT_TYPES: readonly string[] =
21959
+ [
21960
+ RUN_EVENT_KIND.runCompleted,
21961
+ RUN_EVENT_KIND.runFailed,
21962
+ RUN_EVENT_KIND.runCancelled,
21963
+ RUN_EVENT_KIND.runCreated,
21964
+ 'run.events',
21965
+ 'runner.logs',
21966
+ ];
21967
+
21968
+ /**
21969
+ * Terminal Run Ledger delivery owns retiring a run's staged array input
21970
+ * (`retireTerminalRuntimeArrayInput`). Closing that lane would skip it, so a
21971
+ * Run Ledger lane of a run that staged array input is never closed out.
21972
+ */
21973
+ function outboxCloseoutRetiresArrayInputSql(head: string, run: string): string {
21974
+ return `(${searchLaneSql(head)} OR ${run}.array_input_started IS NOT TRUE)`;
21975
+ }
21976
+
21977
+ /**
21978
+ * Read failed lane heads for an operator closeout; read-only. A head is the
21979
+ * first undelivered event of its run and lane, so a failed event queued
21980
+ * behind another failure appears only as that head's successor. Only heads of
21981
+ * terminal scheduler runs are offered.
21982
+ */
21983
+ export async function listPostgresSchedulerOutboxCloseoutHeads(
21984
+ client: PostgresSchedulerQueryClient,
21985
+ input: { eventIds?: string[]; failedBefore?: string; limit: number },
21986
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
21987
+ ): Promise<{
21988
+ heads: PostgresSchedulerOutboxCloseoutHead[];
21989
+ hasMore: boolean;
21990
+ }> {
21991
+ const params: unknown[] = [];
21992
+ const filters: string[] = [];
21993
+ if (input.eventIds) {
21994
+ params.push(input.eventIds);
21995
+ filters.push(`head.event_id = ANY($${params.length}::text[])`);
21996
+ }
21997
+ if (input.failedBefore) {
21998
+ params.push(input.failedBefore);
21999
+ filters.push(`head.failed_at < $${params.length}::timestamptz`);
22000
+ }
22001
+ if (filters.length === 0) {
22002
+ throw new Error('A closeout selection needs eventIds or failedBefore.');
22003
+ }
22004
+ const headTypesParameter = params.push([
22005
+ ...POSTGRES_SCHEDULER_OUTBOX_CLOSEOUT_HEAD_EVENT_TYPES,
22006
+ ]);
22007
+ params.push(input.limit + 1);
22008
+ const outbox = tableName('outbox', options);
22009
+ const result = await client.query<{
22010
+ event_id: string;
22011
+ run_id: string;
22012
+ event_type: string;
22013
+ search_only: boolean;
22014
+ failed_at: string;
22015
+ created_at: string;
22016
+ projection_attempts: number;
22017
+ failure_fingerprint: string;
22018
+ failure_code: string | null;
22019
+ failure_status: string | null;
22020
+ failure_retryable: string | null;
22021
+ org_id: string | null;
22022
+ play_name: string | null;
22023
+ run_status: string | null;
22024
+ successor_event_ids: string[] | null;
22025
+ }>(
22026
+ `SELECT head.event_id, head.run_id, head.event_type,
22027
+ ${searchLaneSql('head')} AS search_only,
22028
+ to_char(head.failed_at AT TIME ZONE 'UTC', ${OUTBOX_EPOCH_TIME_FORMAT}) AS failed_at,
22029
+ to_char(head.created_at AT TIME ZONE 'UTC', ${OUTBOX_EPOCH_TIME_FORMAT}) AS created_at,
22030
+ head.projection_attempts,
22031
+ md5(coalesce(head.last_error_json::text, '')) AS failure_fingerprint,
22032
+ head.last_error_json ->> 'code' AS failure_code,
22033
+ head.last_error_json ->> 'status' AS failure_status,
22034
+ head.last_error_json ->> 'retryable' AS failure_retryable,
22035
+ run.org_id, run.play_name, run.status AS run_status,
22036
+ ARRAY(
22037
+ SELECT successor.event_id
22038
+ FROM ${outbox} AS successor
22039
+ WHERE successor.run_id = head.run_id
22040
+ AND successor.delivered_at IS NULL
22041
+ AND successor.event_id <> head.event_id
22042
+ AND ${runLedgerPrecedesSql('head', 'successor')}
22043
+ ORDER BY ${runLedgerOrderSql('successor')}
22044
+ ) AS successor_event_ids
22045
+ FROM ${outbox} AS head
22046
+ JOIN ${tableName('runs', options)} AS run ON run.run_id = head.run_id
22047
+ WHERE head.delivered_at IS NULL
22048
+ AND head.failed_at IS NOT NULL
22049
+ AND run.status IN ${OUTBOX_CLOSEOUT_TERMINAL_RUN_STATUSES_SQL}
22050
+ AND head.event_type = ANY($${headTypesParameter}::text[])
22051
+ AND ${outboxCloseoutRetiresArrayInputSql('head', 'run')}
22052
+ AND ${filters.join(' AND ')}
22053
+ AND NOT EXISTS (
22054
+ SELECT 1 FROM ${outbox} AS predecessor
22055
+ WHERE predecessor.run_id = head.run_id
22056
+ AND predecessor.delivered_at IS NULL
22057
+ AND predecessor.event_id <> head.event_id
22058
+ AND ${runLedgerPrecedesSql('predecessor', 'head')}
22059
+ )
22060
+ ORDER BY head.failed_at, head.event_id
22061
+ LIMIT $${params.length}::int`,
22062
+ params,
22063
+ );
22064
+ const rows = result.rows.slice(0, input.limit);
22065
+ return {
22066
+ hasMore: result.rows.length > input.limit,
22067
+ heads: rows.map((row) => ({
22068
+ eventId: row.event_id,
22069
+ runId: row.run_id,
22070
+ eventType: row.event_type,
22071
+ searchOnly: row.search_only === true,
22072
+ failedAt: row.failed_at,
22073
+ createdAt: row.created_at,
22074
+ projectionAttempts: Number(row.projection_attempts),
22075
+ failureFingerprint: row.failure_fingerprint,
22076
+ failureCode: row.failure_code,
22077
+ failureStatus: row.failure_status,
22078
+ failureRetryable:
22079
+ row.failure_retryable === 'true'
22080
+ ? true
22081
+ : row.failure_retryable === 'false'
22082
+ ? false
22083
+ : null,
22084
+ orgId: row.org_id,
22085
+ playName: row.play_name,
22086
+ runStatus: row.run_status,
22087
+ successorEventIds: row.successor_event_ids ?? [],
22088
+ })),
22089
+ };
22090
+ }
22091
+
22092
+ export type PostgresSchedulerOutboxCloseoutSkipReason =
22093
+ | 'run_not_terminal'
22094
+ | 'array_input_staged'
22095
+ | 'head_changed'
22096
+ | 'not_lane_front'
22097
+ | 'successors_changed';
22098
+
22099
+ /**
22100
+ * Close one reviewed failed head and its successors without delivering them.
22101
+ * Run inside the caller's transaction. Every check reads the locked rows, so
22102
+ * a head that was replayed, refailed with a new epoch, or gained or lost a
22103
+ * successor since review is skipped and nothing in its lane changes.
22104
+ *
22105
+ * Only the reviewed head and the exact reviewed successor IDs change. An
22106
+ * event added to the lane after the successor read, which a terminal run's
22107
+ * writers do not produce, is not one of them: it stays pending and delivers
22108
+ * normally, as any late event after a terminal delivery would.
22109
+ *
22110
+ * The head keeps `failed_at` and `last_error_json`, so retention never purges
22111
+ * it and its failure stays readable. Successors are marked delivered like any
22112
+ * other delivered event and age out under the ordinary retention policy.
22113
+ */
22114
+ export async function closeOutPostgresSchedulerOutboxHead(
22115
+ client: PostgresSchedulerQueryClient,
22116
+ candidate: PostgresSchedulerOutboxCloseoutCandidate,
22117
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
22118
+ ): Promise<
22119
+ | { closed: true; successorCount: number }
22120
+ | { closed: false; reason: PostgresSchedulerOutboxCloseoutSkipReason }
22121
+ > {
22122
+ const outbox = tableName('outbox', options);
22123
+ const run = await client.query<{
22124
+ terminal: boolean;
22125
+ retires_array_input: boolean;
22126
+ }>(
22127
+ `SELECT run.status IN ${OUTBOX_CLOSEOUT_TERMINAL_RUN_STATUSES_SQL} AS terminal,
22128
+ ($2::boolean OR run.array_input_started IS NOT TRUE) AS retires_array_input
22129
+ FROM ${tableName('runs', options)} AS run
22130
+ WHERE run.run_id = $1`,
22131
+ [candidate.runId, candidate.searchOnly],
22132
+ );
22133
+ if (run.rows[0]?.terminal !== true) {
22134
+ return { closed: false, reason: 'run_not_terminal' };
22135
+ }
22136
+ if (run.rows[0].retires_array_input !== true) {
22137
+ return { closed: false, reason: 'array_input_staged' };
22138
+ }
22139
+ const head = await client.query<{ event_id: string }>(
22140
+ `SELECT head.event_id
22141
+ FROM ${outbox} AS head
22142
+ WHERE head.event_id = $1
22143
+ AND head.run_id = $2
22144
+ AND head.event_type = $3
22145
+ AND ${searchLaneSql('head')} = $4
22146
+ AND head.delivered_at IS NULL
22147
+ AND to_char(head.failed_at AT TIME ZONE 'UTC', ${OUTBOX_EPOCH_TIME_FORMAT}) = $5
22148
+ AND head.projection_attempts = $6
22149
+ AND md5(coalesce(head.last_error_json::text, '')) = $7
22150
+ FOR UPDATE`,
22151
+ [
22152
+ candidate.eventId,
22153
+ candidate.runId,
22154
+ candidate.eventType,
22155
+ candidate.searchOnly,
22156
+ candidate.failedAt,
22157
+ candidate.projectionAttempts,
22158
+ candidate.failureFingerprint,
22159
+ ],
22160
+ );
22161
+ if (head.rows.length !== 1) return { closed: false, reason: 'head_changed' };
22162
+ const lane = await client.query<{
22163
+ event_id: string;
22164
+ is_successor: boolean;
22165
+ }>(
22166
+ `SELECT other.event_id,
22167
+ ${runLedgerPrecedesSql('head', 'other')} AS is_successor
22168
+ FROM ${outbox} AS head
22169
+ JOIN ${outbox} AS other
22170
+ ON other.run_id = head.run_id
22171
+ AND other.event_id <> head.event_id
22172
+ AND other.delivered_at IS NULL
22173
+ AND ${searchLaneSql('other')} = ${searchLaneSql('head')}
22174
+ WHERE head.event_id = $1
22175
+ ORDER BY ${runLedgerOrderSql('other')}
22176
+ FOR UPDATE OF other`,
22177
+ [candidate.eventId],
22178
+ );
22179
+ if (lane.rows.some((row) => !row.is_successor)) {
22180
+ return { closed: false, reason: 'not_lane_front' };
22181
+ }
22182
+ const successorEventIds = lane.rows.map((row) => row.event_id);
22183
+ if (
22184
+ successorEventIds.length !== candidate.successorEventIds.length ||
22185
+ successorEventIds.some(
22186
+ (eventId, index) => eventId !== candidate.successorEventIds[index],
22187
+ )
22188
+ ) {
22189
+ return { closed: false, reason: 'successors_changed' };
22190
+ }
22191
+ await client.query(
22192
+ `UPDATE ${outbox}
22193
+ SET delivered_at = now(),
22194
+ next_attempt_at = NULL,
22195
+ lease_owner = NULL,
22196
+ lease_expires_at = NULL
22197
+ WHERE event_id = $1`,
22198
+ [candidate.eventId],
22199
+ );
22200
+ if (successorEventIds.length > 0) {
22201
+ await client.query(
22202
+ `UPDATE ${outbox}
22203
+ SET delivered_at = now(),
22204
+ next_attempt_at = NULL,
22205
+ lease_owner = NULL,
22206
+ lease_expires_at = NULL
22207
+ WHERE event_id = ANY($1::text[])
22208
+ AND delivered_at IS NULL`,
22209
+ [successorEventIds],
22210
+ );
22211
+ }
22212
+ return { closed: true, successorCount: successorEventIds.length };
22213
+ }
22214
+
21862
22215
  export type PostgresSchedulerDeliveredOutboxRow = {
21863
22216
  eventId: string;
21864
22217
  runId: string;