deepline 0.3.522 → 0.3.523

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 (170) hide show
  1. package/dist/bundling-sources/sdk/src/client-core.ts +118 -0
  2. package/dist/bundling-sources/sdk/src/index.ts +3 -0
  3. package/dist/bundling-sources/sdk/src/release.ts +1 -1
  4. package/dist/bundling-sources/shared_libs/play-runtime/context.ts +47 -18
  5. package/dist/bundling-sources/shared_libs/play-runtime/ctx-types.ts +1 -0
  6. package/dist/bundling-sources/shared_libs/play-runtime/db-session-renewal.ts +209 -0
  7. package/dist/bundling-sources/shared_libs/play-runtime/durable-runs-rollout.ts +16 -6
  8. package/dist/bundling-sources/shared_libs/play-runtime/runner-app/runtime-tool-hooks.ts +5 -0
  9. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona-modal-fallback.ts +1 -0
  10. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/daytona.ts +38 -5
  11. package/dist/bundling-sources/shared_libs/play-runtime/runner-backends/backends/modal.ts +92 -10
  12. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-deadline-reconciliation.ts +96 -25
  13. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd-runtime-worker.ts +29 -0
  14. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/absurd.ts +139 -17
  15. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/durable-run-sql.ts +26 -3
  16. package/dist/bundling-sources/shared_libs/play-runtime/scheduler-backends/postgres.ts +145 -5
  17. package/dist/bundling-sources/shared_libs/play-runtime/tool-cache-policy.ts +190 -10
  18. package/dist/bundling-sources/shared_libs/play-runtime/tool-execute-retry-policy.ts +85 -5
  19. package/dist/bundling-sources/shared_libs/plays/authoring-contract.ts +21 -11
  20. package/dist/cli/{artifacts-RY2MK74N.mjs → artifacts-RBHR2DG4.mjs} +6 -6
  21. package/dist/cli/{artifacts-GIZZH5VA.js → artifacts-RZTS2JHZ.js} +18 -18
  22. package/dist/cli/auth-DPWYFQR5.js +43 -0
  23. package/dist/cli/{auth-YIBY5IKT.mjs → auth-ENQUQS56.mjs} +5 -5
  24. package/dist/cli/{billing-G3IX3SNY.mjs → billing-6A27ULCX.mjs} +7 -7
  25. package/dist/cli/{billing-UDKL53GI.js → billing-6HONTJOY.js} +82 -82
  26. package/dist/cli/{chunk-4DFWDA2Q.js → chunk-2BRDHM4S.js} +9 -9
  27. package/dist/cli/{chunk-EJBW7Y6Z.js → chunk-326WVSWS.js} +108 -96
  28. package/dist/cli/{chunk-7JEN3FX4.js → chunk-36LQQL5C.js} +5 -5
  29. package/dist/cli/{chunk-GVKW3LCA.js → chunk-4NWY7JBB.js} +11 -11
  30. package/dist/cli/{chunk-RKE5YTHY.mjs → chunk-4V63IJCL.mjs} +5 -5
  31. package/dist/cli/{chunk-VFCVH2LV.mjs → chunk-5WFQXAD4.mjs} +5 -5
  32. package/dist/cli/{chunk-4TUMKJZX.mjs → chunk-6DBRBWHC.mjs} +2 -2
  33. package/dist/cli/{chunk-CFXERH7F.mjs → chunk-6OZ2WSHD.mjs} +1 -1
  34. package/dist/cli/{chunk-5H22VJPE.js → chunk-7GNKAACY.js} +6 -6
  35. package/dist/cli/{chunk-G65FJ5JX.mjs → chunk-7M5FRSFP.mjs} +2 -2
  36. package/dist/cli/{chunk-PDLRUZ42.mjs → chunk-DNXP3D5H.mjs} +5 -5
  37. package/dist/cli/{chunk-OAQIVJFY.mjs → chunk-F3WRLFFM.mjs} +2 -2
  38. package/dist/cli/{chunk-RI672VNY.js → chunk-FBMOBNJY.js} +2 -2
  39. package/dist/cli/{chunk-NDNG3MAT.mjs → chunk-H7275EZU.mjs} +5 -5
  40. package/dist/cli/{chunk-C6WGMODR.mjs → chunk-HSVGP4CI.mjs} +2 -2
  41. package/dist/cli/{chunk-DNJJ3ULJ.js → chunk-HUC5SGJQ.js} +2 -2
  42. package/dist/cli/{chunk-DARD7TJ7.js → chunk-HUIFUE4L.js} +53 -53
  43. package/dist/cli/{chunk-52MHE7B4.mjs → chunk-I62LJ7NU.mjs} +1 -1
  44. package/dist/cli/{chunk-BZY335JP.js → chunk-IEVXYHGJ.js} +5 -5
  45. package/dist/cli/{chunk-FQQAAR3Q.mjs → chunk-JCTTXLAZ.mjs} +1 -1
  46. package/dist/cli/{chunk-3KMGVOBM.mjs → chunk-JGZQBDYG.mjs} +4 -4
  47. package/dist/cli/{chunk-ZUAKRBZB.js → chunk-JMMNCJ7Z.js} +1 -1
  48. package/dist/cli/{chunk-UV6XCHOZ.mjs → chunk-JVEFMOY2.mjs} +1 -1
  49. package/dist/cli/{chunk-FNHUDCJE.js → chunk-K326BEVR.js} +10 -10
  50. package/dist/cli/{chunk-MD524MRB.mjs → chunk-KILRUAXF.mjs} +1 -1
  51. package/dist/cli/{chunk-XXY4E57R.mjs → chunk-LZL6V5M5.mjs} +2 -2
  52. package/dist/cli/{chunk-GMYDVW7Z.js → chunk-MCXPJYBN.js} +3 -3
  53. package/dist/cli/{chunk-VE6FHVXZ.mjs → chunk-MHTRYBXY.mjs} +78 -1
  54. package/dist/cli/{chunk-ISUUSSS4.js → chunk-MT3WG3KR.js} +16 -16
  55. package/dist/cli/{chunk-37SXIFIU.js → chunk-MZROKQV3.js} +44 -44
  56. package/dist/cli/{chunk-4MF44THR.js → chunk-N5MLEXZ7.js} +50 -8
  57. package/dist/cli/{chunk-XR6TN5DT.mjs → chunk-NWTMQGPP.mjs} +6 -6
  58. package/dist/cli/{chunk-Y3LDRCMB.mjs → chunk-PCORO245.mjs} +2 -2
  59. package/dist/cli/{chunk-534YYHIF.js → chunk-PESMXAUG.js} +6 -6
  60. package/dist/cli/{chunk-RDJTCW3I.mjs → chunk-QMBL5ZIQ.mjs} +3 -3
  61. package/dist/cli/{chunk-LFSOBW7E.mjs → chunk-QOO5W5XS.mjs} +22 -10
  62. package/dist/cli/{chunk-ZZ7U4YJS.mjs → chunk-QSAC3IVI.mjs} +1 -1
  63. package/dist/cli/{chunk-HYR34KFA.js → chunk-QYXIODWH.js} +78 -1
  64. package/dist/cli/{chunk-BONXEWYF.mjs → chunk-RKREB7MU.mjs} +3 -3
  65. package/dist/cli/{chunk-KMBF3N2Z.js → chunk-RQN4PHRE.js} +16 -16
  66. package/dist/cli/{chunk-XT25FX6T.js → chunk-S4YKRH3W.js} +3 -3
  67. package/dist/cli/{chunk-F5D623KO.js → chunk-SBGKKOCC.js} +26 -26
  68. package/dist/cli/{chunk-5477PEHL.mjs → chunk-SXTVJIGB.mjs} +1 -1
  69. package/dist/cli/{chunk-7J5PLHII.mjs → chunk-U6DLLV3S.mjs} +1 -1
  70. package/dist/cli/{chunk-ENWJFUWK.mjs → chunk-UH3EAFFN.mjs} +2 -2
  71. package/dist/cli/{chunk-DLDWAPA5.js → chunk-UQN4VTZL.js} +4 -4
  72. package/dist/cli/{chunk-DRDZBRXV.js → chunk-V46J3UTM.js} +7 -7
  73. package/dist/cli/{chunk-5BQPEHEP.js → chunk-WGVJA4I5.js} +14 -14
  74. package/dist/cli/{chunk-SFMCKB57.mjs → chunk-WVQOXYTQ.mjs} +44 -2
  75. package/dist/cli/{chunk-VIM6I7RC.js → chunk-XVXEARHC.js} +41 -41
  76. package/dist/cli/{chunk-6SJPZV5E.js → chunk-XYL26236.js} +2 -2
  77. package/dist/cli/{chunk-ZZLZCO6Y.js → chunk-ZWN4RXC2.js} +22 -22
  78. package/dist/cli/command-docs.js +2 -2
  79. package/dist/cli/command-docs.mjs +1 -1
  80. package/dist/cli/{csv-3HIE4VCO.js → csv-UBACJK75.js} +13 -13
  81. package/dist/cli/{csv-PE35WGRO.mjs → csv-YFJ2JLUP.mjs} +4 -4
  82. package/dist/cli/{db-O2YRTTDO.js → db-2ZPA2LZ7.js} +27 -27
  83. package/dist/cli/{db-L7ZMMQKW.mjs → db-NKGYTAQO.mjs} +6 -6
  84. package/dist/cli/{describe-NI324Y2M.mjs → describe-GX7DRKWZ.mjs} +18 -18
  85. package/dist/cli/describe-WQZF7MEG.js +50 -0
  86. package/dist/cli/describe-core.d.mts +3 -3
  87. package/dist/cli/describe-core.d.ts +3 -3
  88. package/dist/cli/{executions-T6KU2OKK.mjs → executions-HTHQ7KKD.mjs} +6 -6
  89. package/dist/cli/{executions-VH4DKLFI.js → executions-NXMRGPIL.js} +8 -8
  90. package/dist/cli/{feedback-ZLC6G5OK.js → feedback-TGVQACRO.js} +10 -10
  91. package/dist/cli/{feedback-SCSJC3FX.mjs → feedback-USP4T34P.mjs} +5 -5
  92. package/dist/cli/{git-I4LVQCID.mjs → git-KUONEHCD.mjs} +5 -5
  93. package/dist/cli/git-X3SCQREB.js +25 -0
  94. package/dist/cli/index.js +145 -145
  95. package/dist/cli/index.mjs +44 -44
  96. package/dist/cli/{legacy-noops-UPFWEHPG.js → legacy-noops-2JY3CQ24.js} +9 -9
  97. package/dist/cli/{legacy-noops-44FQ2256.mjs → legacy-noops-B2GMHU42.mjs} +6 -6
  98. package/dist/cli/{monitors-LMSASWXE.mjs → monitors-2OVBZJ6Z.mjs} +7 -7
  99. package/dist/cli/{monitors-JN6IQGK6.js → monitors-XI6I52AX.js} +100 -100
  100. package/dist/cli/{org-F7O3ZU5O.js → org-5TUQ2H6Y.js} +235 -72
  101. package/dist/cli/{org-QYLVEE7A.mjs → org-BNJW764Y.mjs} +169 -6
  102. package/dist/cli/{pages-5XE4LBZN.mjs → pages-QC3TQIPW.mjs} +6 -6
  103. package/dist/cli/{pages-KEL3Y4L4.js → pages-UXCLX53Y.js} +18 -18
  104. package/dist/cli/{play-MWQG3G32.mjs → play-45PPG5SZ.mjs} +18 -18
  105. package/dist/cli/{play-OURHH6KV.js → play-KRWMZ7FG.js} +317 -317
  106. package/dist/cli/{providers-IQY7LUBB.mjs → providers-JDT35MRL.mjs} +6 -6
  107. package/dist/cli/{providers-ZCBWPE3C.js → providers-RBUJ72Y3.js} +9 -9
  108. package/dist/cli/{quickstart-L45NGRMI.mjs → quickstart-GD2SWGAC.mjs} +4 -4
  109. package/dist/cli/{quickstart-O53OXTN6.js → quickstart-JZ4Q3HFT.js} +6 -6
  110. package/dist/cli/{run-W745Z3Z5.js → run-JEAHA367.js} +41 -41
  111. package/dist/cli/{run-VCSIWLEU.mjs → run-KIZ3HBI2.mjs} +23 -23
  112. package/dist/cli/{search-THELKULN.mjs → search-5UFNXHFK.mjs} +8 -8
  113. package/dist/cli/search-6JULJMD7.js +33 -0
  114. package/dist/cli/{search-output-N7MJLYYD.mjs → search-output-HAXPKQO6.mjs} +4 -4
  115. package/dist/cli/{search-output-SJW7LEOM.js → search-output-W3RDSVLE.js} +6 -6
  116. package/dist/cli/{secrets-44ST3FJH.mjs → secrets-JAWT66B2.mjs} +6 -6
  117. package/dist/cli/{secrets-GDXPX3KB.js → secrets-PC7C2Q32.js} +15 -15
  118. package/dist/cli/{sessions-LYCBI77S.mjs → sessions-325V7G35.mjs} +6 -6
  119. package/dist/cli/sessions-WFUCOJHZ.js +18 -0
  120. package/dist/cli/{settings-GXPDMJFG.mjs → settings-FKHTA65P.mjs} +13 -13
  121. package/dist/cli/{settings-3WOFF642.js → settings-RGU6Y2QR.js} +86 -86
  122. package/dist/cli/{setup-YM6JEB64.mjs → setup-43GOYTFC.mjs} +10 -10
  123. package/dist/cli/{setup-YHLMBJP4.js → setup-ZMZ7HU2I.js} +50 -50
  124. package/dist/cli/skills-3XTQ6FFM.js +37 -0
  125. package/dist/cli/{skills-WX4XWEAT.mjs → skills-Q2VAHSXM.mjs} +8 -8
  126. package/dist/cli/{tools-K24VSQ7S.mjs → tools-BUH7ZWDS.mjs} +17 -17
  127. package/dist/cli/tools-UK2R4YXQ.js +57 -0
  128. package/dist/cli/{update-PSSCF5AT.mjs → update-JFALWOHD.mjs} +10 -10
  129. package/dist/cli/update-LNKPHS54.js +35 -0
  130. package/dist/cli/{workflow-DGOPYATO.mjs → workflow-ISJKLY6X.mjs} +7 -7
  131. package/dist/cli/{workflow-FPVI3NIA.js → workflow-YELST32A.js} +17 -17
  132. package/dist/{client-DA71-2_u.d.mts → client-C2N7MofG.d.mts} +1 -1
  133. package/dist/{client-B-2Am2y6.d.ts → client-C7lTRJjw.d.ts} +1 -1
  134. package/dist/{client-core-BXbds1cb.d.mts → client-core-BTkDSKGn.d.mts} +79 -2
  135. package/dist/{client-core-C0IzDKMJ.d.ts → client-core-hmhBi7Ib.d.ts} +79 -2
  136. package/dist/{compiler-manifest-B4mIIbw7.d.mts → compiler-manifest-DsxsQP-T.d.mts} +14 -7
  137. package/dist/{compiler-manifest-B4mIIbw7.d.ts → compiler-manifest-DsxsQP-T.d.ts} +14 -7
  138. package/dist/{errors-Gj9i5Rkd.d.ts → errors-Bk5h1D-C.d.ts} +1 -1
  139. package/dist/{errors-C2F4qzAq.d.mts → errors-qdJUVQ3g.d.mts} +1 -1
  140. package/dist/{index-5JZBufdF.d.mts → index-PaupwX1B.d.mts} +1 -1
  141. package/dist/{index-BXtSj8bv.d.ts → index-bL66eHYz.d.ts} +1 -1
  142. package/dist/index.d.mts +7 -7
  143. package/dist/index.d.ts +7 -7
  144. package/dist/index.js +9 -9
  145. package/dist/index.mjs +6 -6
  146. package/dist/install-integrity.json +117 -116
  147. package/dist/plays/bundle-play-file.d.mts +3 -3
  148. package/dist/plays/bundle-play-file.d.ts +3 -3
  149. package/dist/plays/bundle-play-file.mjs +7 -5
  150. package/dist/plays/play-description.d.mts +2 -2
  151. package/dist/plays/play-description.d.ts +2 -2
  152. package/dist/plays/run-request.d.mts +2 -2
  153. package/dist/plays/run-request.d.ts +2 -2
  154. package/dist/release.d.mts +1 -1
  155. package/dist/release.d.ts +1 -1
  156. package/dist/release.js +2 -2
  157. package/dist/release.mjs +1 -1
  158. package/dist/server.d.mts +4 -4
  159. package/dist/server.d.ts +4 -4
  160. package/dist/server.js +5 -5
  161. package/dist/server.mjs +3 -3
  162. package/package.json +1 -1
  163. package/dist/cli/auth-JSES2JOQ.js +0 -43
  164. package/dist/cli/describe-EB336DAO.js +0 -50
  165. package/dist/cli/git-23T7TXAH.js +0 -25
  166. package/dist/cli/search-R6K7ZAMU.js +0 -33
  167. package/dist/cli/sessions-2V5ZFOWL.js +0 -18
  168. package/dist/cli/skills-XNGADDO6.js +0 -37
  169. package/dist/cli/tools-ROUMCB7B.js +0 -57
  170. package/dist/cli/update-RXURGIRW.js +0 -35
@@ -14,7 +14,8 @@
14
14
  * retain lazy queue setup for local app-before-worker startup.
15
15
  * observe/result → reuse the postgres LISTEN/NOTIFY run handle.
16
16
  * cancel → commit the Absurd stop and a durable cancellation request;
17
- * the worker deletes sandboxes before the final run write.
17
+ * the worker deletes sandboxes before the final run write. A run
18
+ * no worker ever claimed is cancelled in that same transaction.
18
19
  * signal → durable signal row (authoritative payload) + absurd emitEvent
19
20
  * (the wakeup only; payload is re-read from the signal row).
20
21
  */
@@ -30,6 +31,7 @@ import {
30
31
  } from '../scheduler-backend';
31
32
  import {
32
33
  cancelPostgresSchedulerRun,
34
+ postgresSchedulerCancellationOutboxLease,
33
35
  postgresSchedulerRunHandle,
34
36
  readPostgresSchedulerLaunch,
35
37
  readPostgresSchedulerAbsurdTaskId,
@@ -49,6 +51,7 @@ import {
49
51
  withWorkspaceAdmissionLock,
50
52
  } from './postgres-pool';
51
53
  import { resolveRuntimeSchedulerSchemaEnv } from './runtime-scheduler-schema';
54
+ import { noteUndrainedRuntimeCancellations } from './absurd-deadline-reconciliation';
52
55
  import { withRuntimeSchedulerSubmitAdmission } from './submit-admission';
53
56
  import {
54
57
  ABSURD_PLAY_RUN_MAX_ATTEMPTS,
@@ -81,6 +84,7 @@ const cancellationFlights = new Map<
81
84
  Promise<PlaySchedulerCancelOutcome>
82
85
  >();
83
86
  const ABSURD_CANCEL_TASK_SAVEPOINT = 'deepline_cancel_absurd_task';
87
+ const ABSURD_FINALIZE_UNCLAIMED_SAVEPOINT = 'deepline_finalize_unclaimed_run';
84
88
 
85
89
  function quotePostgresIdentifier(identifier: string): string {
86
90
  return `"${identifier.replaceAll('"', '""')}"`;
@@ -167,6 +171,93 @@ export async function cancelPostgresSchedulerRunWithoutProjection(
167
171
  return { cancelled, engineTaskCancelled };
168
172
  }
169
173
 
174
+ /**
175
+ * Finish a caller stop inline when no worker ever claimed the run.
176
+ *
177
+ * Runs inside the stop transaction, after `absurd.cancel_task` has locked and
178
+ * cancelled the engine run and task rows. A concurrent `claim_task` either
179
+ * committed first, so this statement's fresh READ COMMITTED snapshot sees its
180
+ * `first_started_at`, or it now re-checks the cancelled run row under its
181
+ * lock and cannot start customer code. `cancel_task` never clears
182
+ * `first_started_at`, so a claimed task always keeps the worker-owned path.
183
+ *
184
+ * Returns false, leaving the transaction as it was, when the run was claimed,
185
+ * fails the scheduler fence, or the terminal write fails; the caller then
186
+ * records the durable request the worker drain finalizes.
187
+ */
188
+ async function finalizeUnclaimedAbsurdRunInline(
189
+ client: PostgresSchedulerQueryClient,
190
+ input: {
191
+ queue: string;
192
+ taskId: string;
193
+ runId: string;
194
+ reason: string;
195
+ schedulerSchema: string;
196
+ schedulerOptions: Pick<AbsurdSchedulerOptions, 'schema'>;
197
+ },
198
+ ): Promise<boolean> {
199
+ await client.query(`SAVEPOINT ${ABSURD_FINALIZE_UNCLAIMED_SAVEPOINT}`);
200
+ const rollBack = async () => {
201
+ await client.query(
202
+ `ROLLBACK TO SAVEPOINT ${ABSURD_FINALIZE_UNCLAIMED_SAVEPOINT}`,
203
+ );
204
+ await client.query(
205
+ `RELEASE SAVEPOINT ${ABSURD_FINALIZE_UNCLAIMED_SAVEPOINT}`,
206
+ );
207
+ };
208
+ let cancelled: boolean;
209
+ try {
210
+ const engineTask = await client.query<{ claimed: boolean }>(
211
+ `SELECT first_started_at IS NOT NULL AS claimed
212
+ FROM absurd.${quotePostgresIdentifier(`t_${input.queue}`)}
213
+ WHERE task_id = $1::uuid`,
214
+ [input.taskId],
215
+ );
216
+ cancelled =
217
+ engineTask.rows[0]?.claimed === false &&
218
+ (await cancelPostgresSchedulerRun(
219
+ client,
220
+ {
221
+ runId: input.runId,
222
+ reason: input.reason,
223
+ onlyIfUnclaimed: { absurdTaskId: input.taskId },
224
+ outboxLease: postgresSchedulerCancellationOutboxLease(input.runId),
225
+ },
226
+ input.schedulerOptions,
227
+ ));
228
+ if (cancelled) {
229
+ // A request queued by an earlier stop (or an older server) is now done.
230
+ await client.query(
231
+ `DELETE FROM ${input.schedulerSchema}.control WHERE key = $1`,
232
+ [`runtime_cancel:${input.runId}`],
233
+ );
234
+ await client.query(
235
+ `RELEASE SAVEPOINT ${ABSURD_FINALIZE_UNCLAIMED_SAVEPOINT}`,
236
+ );
237
+ }
238
+ } catch (error) {
239
+ try {
240
+ await rollBack();
241
+ } catch (rollbackError) {
242
+ throw new AggregateError(
243
+ [error, rollbackError],
244
+ 'Unclaimed cancellation savepoint rollback failed.',
245
+ { cause: error },
246
+ );
247
+ }
248
+ // The durable request below keeps the stop safe; the worker drain
249
+ // finalizes it exactly as before this fast path existed.
250
+ console.warn('[absurd-runtime.cancel] unclaimed_finalize_deferred', {
251
+ runId: input.runId,
252
+ error: error instanceof Error ? error.message : String(error),
253
+ });
254
+ return false;
255
+ }
256
+ // Claimed or fenced out: undo only this savepoint's work.
257
+ if (!cancelled) await rollBack();
258
+ return cancelled;
259
+ }
260
+
170
261
  function runCancellationSingleFlight(
171
262
  key: string,
172
263
  operation: () => Promise<PlaySchedulerCancelOutcome>,
@@ -279,14 +370,16 @@ function absurdRunHandle(input: {
279
370
  effectiveOptions,
280
371
  )
281
372
  ) {
282
- return false;
373
+ return 'stopped' as const;
283
374
  }
375
+ let engineTaskCancelled = false;
284
376
  if (taskId) {
285
377
  const engineTaskPresent = await cancelAbsurdTaskIfPresent(client, {
286
378
  queue: cancellationQueue,
287
379
  taskId,
288
380
  runId: input.runId,
289
381
  });
382
+ engineTaskCancelled = engineTaskPresent;
290
383
  if (engineTaskPresent) {
291
384
  // Older workers only reconcile `manual` or `max_delay`. This
292
385
  // marker is diagnostic; the control row is the cross-lane queue.
@@ -305,19 +398,49 @@ function absurdRunHandle(input: {
305
398
  resolveRuntimeSchedulerSchemaEnv() ||
306
399
  'runtime_scheduler',
307
400
  );
308
- await client.query(
401
+ const cancellationReason = reason?.trim() || 'Cancelled play run.';
402
+ if (
403
+ taskId &&
404
+ engineTaskCancelled &&
405
+ (await finalizeUnclaimedAbsurdRunInline(client, {
406
+ queue: cancellationQueue,
407
+ taskId,
408
+ runId: input.runId,
409
+ reason: cancellationReason,
410
+ schedulerSchema,
411
+ schedulerOptions: effectiveOptions,
412
+ }))
413
+ ) {
414
+ return 'stopped' as const;
415
+ }
416
+ const recorded = await client.query(
309
417
  `INSERT INTO ${schedulerSchema}.control (key, value)
310
418
  VALUES ($1, jsonb_build_object(
311
419
  'reason', left($2::text, 4000),
312
420
  'requestedAt', clock_timestamp()
313
421
  ))
314
- ON CONFLICT (key) DO NOTHING`,
315
- [
316
- `runtime_cancel:${input.runId}`,
317
- reason?.trim() || 'Cancelled play run.',
318
- ],
422
+ ON CONFLICT (key) DO NOTHING
423
+ RETURNING key`,
424
+ [`runtime_cancel:${input.runId}`, cancellationReason],
319
425
  );
320
- return true;
426
+ if (recorded.rows.length === 0) {
427
+ // A repeated stop is the one caller that can see a request no worker
428
+ // drained; report its age without adding a poll.
429
+ const existing = await client.query<{ requested_at: string | null }>(
430
+ `SELECT value->>'requestedAt' AS requested_at
431
+ FROM ${schedulerSchema}.control
432
+ WHERE key = $1`,
433
+ [`runtime_cancel:${input.runId}`],
434
+ );
435
+ noteUndrainedRuntimeCancellations({
436
+ source: 'repeat_stop',
437
+ requests: existing.rows.map((row) => ({
438
+ runId: input.runId,
439
+ requestedAt: row.requested_at,
440
+ })),
441
+ });
442
+ }
443
+ return 'cancelling' as const;
321
444
  },
322
445
  {
323
446
  runId: input.runId,
@@ -327,17 +450,16 @@ function absurdRunHandle(input: {
327
450
  { maxAttempts: 1 },
328
451
  );
329
452
 
330
- // A queued cancellation is the normal Absurd outcome: the worker owns
331
- // sandbox cleanup and the final run update. Report it as a typed state, not
332
- // an error; `stopped` means the scheduler result was already terminal.
453
+ // A queued cancellation is the normal Absurd outcome for a claimed run: the
454
+ // worker owns sandbox cleanup and the final run update. Report it as a typed
455
+ // state, not an error. `stopped` means the scheduler result is terminal:
456
+ // already, or now because no worker ever claimed the run.
333
457
  const requestCancellation = (
334
458
  reason?: string,
335
459
  ): Promise<PlaySchedulerCancelOutcome> =>
336
- runCancellationSingleFlight(cancellationKey, async () =>
337
- (await queueCancellation(reason))
338
- ? { state: 'cancelling' }
339
- : { state: 'stopped' },
340
- );
460
+ runCancellationSingleFlight(cancellationKey, async () => ({
461
+ state: await queueCancellation(reason),
462
+ }));
341
463
 
342
464
  return {
343
465
  ...delegate,
@@ -9,6 +9,7 @@ import {
9
9
  type DurableRunFailureClass,
10
10
  } from '../../observability/dlq';
11
11
  import { resolveRuntimeSchedulerSchemaEnv } from './runtime-scheduler-schema';
12
+ import { RUNTIME_DB_SESSION_PRELOAD_INCOMPLETE } from '../play-admission-outcome';
12
13
 
13
14
  export type DurableRunSqlOptions = { readonly schema?: string };
14
15
  type Options = DurableRunSqlOptions;
@@ -66,6 +67,20 @@ export type DurableRunFailureCause = DurableRunFailureCauseFilter;
66
67
  export const isDurableRunFailureCause = isDurableRunFailureCauseFilter;
67
68
 
68
69
  const PLATFORM_RECOVERY_EXHAUSTED_PREFIX = 'PLATFORM_RECOVERY_EXHAUSTED:';
70
+ /**
71
+ * Leading codes the runtime writes when Deepline, not the Play, failed the
72
+ * run: the sandbox never started a runner, or the scheduler was unavailable.
73
+ */
74
+ const PLATFORM_RUNTIME_FAILURE_CODES = [
75
+ 'RUNTIME_SANDBOX_START_FAILED',
76
+ 'RUNTIME_SCHEDULER_UNAVAILABLE',
77
+ ] as const;
78
+ /**
79
+ * Runtime error classes whose stored message is `<Class>: <CODE>: ...`. Only
80
+ * these names are stripped before reading the leading code: a Play's own
81
+ * `Error: <CODE>: ...` keeps its class prefix and stays the Play's.
82
+ */
83
+ const RUNTIME_ERROR_CLASS_PREFIXES = ['DaytonaRunnerInitializationError'] as const;
69
84
  /**
70
85
  * The exhausted-recovery message is a fixed Deepline template
71
86
  * (`platformRecoveryExhaustedMessage` and the pre-code variant), well under
@@ -85,7 +100,15 @@ export const DURABLE_RUN_FAILURE_MESSAGE_MAX_CHARS = 512;
85
100
  * fixed exhausted-recovery template. Platform-vs-Play mirrors
86
101
  * `runtimeTerminalReasonFromError`: sandbox killed/lost and lost leases are
87
102
  * platform; runtime limit and sandbox OOM are the Play's; scheduler-written
88
- * codes (`SCHEDULER_*`, `CTX_RUN_PLAY_INLINE_ONLY`) are platform.
103
+ * codes (`SCHEDULER_*`, `CTX_RUN_PLAY_INLINE_ONLY`) are platform. A run whose
104
+ * data plane had no usable Runtime DB session
105
+ * (`RUNTIME_DB_SESSION_PRELOAD_INCOMPLETE`, e.g. one that woke after its
106
+ * admission sessions expired) failed on Deepline's authority, not its code.
107
+ * So did a sandbox that never started a runner (`RUNTIME_SANDBOX_START_FAILED`,
108
+ * also behind a known runtime error class such as
109
+ * `DaytonaRunnerInitializationError: `) and an unavailable scheduler
110
+ * (`RUNTIME_SCHEDULER_UNAVAILABLE`). Only the leading code position counts,
111
+ * so stored rows of any age read the same way.
89
112
  */
90
113
  export function durableRunFailureLateralSql(): string {
91
114
  return `LEFT JOIN LATERAL (
@@ -98,7 +121,7 @@ export function durableRunFailureLateralSql(): string {
98
121
  THEN 'platform_recovery_exhausted'
99
122
  WHEN parsed.message IS NULL THEN 'unknown'
100
123
  WHEN parsed.terminal_reason IN ('sandbox_killed', 'sandbox_missing', 'lease_expired')
101
- OR parsed.code = 'CTX_RUN_PLAY_INLINE_ONLY'
124
+ OR parsed.code IN ('CTX_RUN_PLAY_INLINE_ONLY', '${RUNTIME_DB_SESSION_PRELOAD_INCOMPLETE}', ${PLATFORM_RUNTIME_FAILURE_CODES.map((code) => `'${code}'`).join(', ')})
102
125
  OR starts_with(parsed.code, 'SCHEDULER_')
103
126
  THEN 'platform_failure'
104
127
  ELSE 'play_error'
@@ -130,7 +153,7 @@ export function durableRunFailureLateralSql(): string {
130
153
  raw.exhausted_at_ms,
131
154
  coalesce(
132
155
  CASE WHEN raw.stored_code ~ '^[A-Z][A-Z0-9_]{2,63}$' THEN raw.stored_code END,
133
- substring(raw.message FROM '^([A-Z][A-Z0-9_]{2,63}):')
156
+ substring(raw.message FROM '^(?:(?:${RUNTIME_ERROR_CLASS_PREFIXES.join('|')}): )?([A-Z][A-Z0-9_]{2,63}):')
134
157
  ) AS code,
135
158
  CASE
136
159
  WHEN raw.message ~* 'RUNTIME_LIMIT_EXCEEDED' THEN 'runtime_limit'
@@ -69,6 +69,7 @@ import {
69
69
  } from './runtime-event-search';
70
70
  import type { PlayRunnerRuntimeResource } from '../runner-backends/types';
71
71
  import {
72
+ RUNTIME_SANDBOX_OPERATION_TERMINAL_STATES,
72
73
  RuntimeSandboxOperationState,
73
74
  type RuntimeSandboxProvider,
74
75
  runtimeSandboxOperationFromStates,
@@ -11012,10 +11013,23 @@ const POSTGRES_SCHEDULER_ATTEMPT_AUTHORITY_FIELDS = [
11012
11013
  export type PostgresSchedulerAttemptAuthority = Pick<
11013
11014
  PlaySchedulerSubmitInput,
11014
11015
  (typeof POSTGRES_SCHEDULER_ATTEMPT_AUTHORITY_FIELDS)[number]
11015
- > & { computeSessionIntentPersisted?: boolean };
11016
+ > & {
11017
+ computeSessionIntentPersisted?: boolean;
11018
+ /**
11019
+ * Present only when the caller asked for it: the stored preloaded Runtime
11020
+ * DB session array (null when the launch has none) and the key that sealed
11021
+ * it, falling back to the stored submit-time token as every reader does.
11022
+ */
11023
+ preloadedDbSessionRenewalSource?: {
11024
+ sessions: unknown[] | null;
11025
+ unwrapKey: string | null;
11026
+ };
11027
+ };
11016
11028
 
11017
11029
  type PostgresSchedulerAuthorityRow = PostgresSchedulerAttemptAuthority & {
11018
11030
  launch_required_fields_valid: boolean;
11031
+ preloaded_db_sessions?: unknown;
11032
+ preloaded_db_session_unwrap_key?: unknown;
11019
11033
  };
11020
11034
 
11021
11035
  // Keep JSON types intact: text columns would coerce malformed launch scalars.
@@ -11035,13 +11049,31 @@ function parsePostgresSchedulerAuthorityRow(
11035
11049
  row: PostgresSchedulerAuthorityRow | undefined,
11036
11050
  ): PostgresSchedulerAttemptAuthority | null {
11037
11051
  if (!row) return null;
11038
- const { launch_required_fields_valid, ...authority } = row;
11052
+ const {
11053
+ launch_required_fields_valid,
11054
+ preloaded_db_sessions,
11055
+ preloaded_db_session_unwrap_key,
11056
+ ...authority
11057
+ } = row;
11039
11058
  if (launch_required_fields_valid !== true) {
11040
11059
  throw new Error(
11041
11060
  'Postgres scheduler launch_json is missing required fields.',
11042
11061
  );
11043
11062
  }
11044
- return authority;
11063
+ if (preloaded_db_sessions === undefined) return authority;
11064
+ return {
11065
+ ...authority,
11066
+ preloadedDbSessionRenewalSource: {
11067
+ sessions: Array.isArray(preloaded_db_sessions)
11068
+ ? preloaded_db_sessions
11069
+ : null,
11070
+ unwrapKey:
11071
+ typeof preloaded_db_session_unwrap_key === 'string' &&
11072
+ preloaded_db_session_unwrap_key
11073
+ ? preloaded_db_session_unwrap_key
11074
+ : null,
11075
+ },
11076
+ };
11045
11077
  }
11046
11078
 
11047
11079
  /**
@@ -11053,12 +11085,31 @@ function parsePostgresSchedulerAuthorityRow(
11053
11085
  */
11054
11086
  export async function readPostgresSchedulerAttemptAuthorityForLease(
11055
11087
  client: PostgresSchedulerQueryClient,
11056
- input: { runId: string; attempt: number; leaseToken: string },
11088
+ input: {
11089
+ runId: string;
11090
+ attempt: number;
11091
+ leaseToken: string;
11092
+ /**
11093
+ * Also return the stored preloaded sessions and their sealing key, so the
11094
+ * token issuer can renew expired sessions without a second round trip.
11095
+ * Bounded: the array holds one entry per declared sheet plus receipts.
11096
+ */
11097
+ includePreloadedDbSessions?: boolean;
11098
+ },
11057
11099
  options?: Pick<PostgresSchedulerOptions, 'schema'>,
11058
11100
  ): Promise<PostgresSchedulerAttemptAuthority | null> {
11059
11101
  const result = await client.query<PostgresSchedulerAuthorityRow>(
11060
11102
  `
11061
11103
  SELECT ${POSTGRES_SCHEDULER_AUTHORITY_SELECT},
11104
+ ${
11105
+ input.includePreloadedDbSessions === true
11106
+ ? `runs.launch_json -> 'preloadedDbSessions' AS preloaded_db_sessions,
11107
+ coalesce(
11108
+ nullif(runs.launch_json ->> 'preloadedDbSessionUnwrapKey', ''),
11109
+ runs.launch_json ->> 'executorToken'
11110
+ ) AS preloaded_db_session_unwrap_key,`
11111
+ : ''
11112
+ }
11062
11113
  EXISTS (
11063
11114
  SELECT 1 FROM jsonb_array_elements(
11064
11115
  CASE
@@ -11085,6 +11136,56 @@ export async function readPostgresSchedulerAttemptAuthorityForLease(
11085
11136
  return parsePostgresSchedulerAuthorityRow(result.rows[0]);
11086
11137
  }
11087
11138
 
11139
+ /**
11140
+ * Replace the stored preloaded sessions with renewed ones, only while the
11141
+ * attempt lease is active and only if the stored array is still the one the
11142
+ * caller renewed. `preloadedDbSessions` is outside the launch admission
11143
+ * identity and is never part of `admission_json`, so this changes no run
11144
+ * identity. Returns false when the lease ended or another issuer already
11145
+ * replaced the array; the caller retries and then sees the fresh sessions.
11146
+ */
11147
+ export async function replacePostgresSchedulerPreloadedDbSessionsForLease(
11148
+ client: PostgresSchedulerQueryClient,
11149
+ input: {
11150
+ runId: string;
11151
+ attempt: number;
11152
+ leaseToken: string;
11153
+ expected: unknown[];
11154
+ sessions: unknown[];
11155
+ },
11156
+ options?: Pick<PostgresSchedulerOptions, 'schema'>,
11157
+ ): Promise<boolean> {
11158
+ const result = await client.query<{ run_id: string }>(
11159
+ `
11160
+ UPDATE ${tableName('runs', options)} AS runs
11161
+ SET launch_json = jsonb_set(
11162
+ runs.launch_json,
11163
+ '{preloadedDbSessions}',
11164
+ $5::jsonb
11165
+ )
11166
+ WHERE runs.run_id = $1
11167
+ AND runs.launch_json -> 'preloadedDbSessions' = $4::jsonb
11168
+ AND runs.status IN ('queued', 'running', 'waiting')
11169
+ AND EXISTS (
11170
+ SELECT 1 FROM ${tableName('attempts', options)} AS attempts
11171
+ WHERE attempts.run_id = runs.run_id
11172
+ AND attempts.attempt = $2
11173
+ AND attempts.lease_token = $3
11174
+ AND attempts.status IN ('claimed', 'running', 'waiting')
11175
+ )
11176
+ RETURNING runs.run_id
11177
+ `,
11178
+ [
11179
+ input.runId,
11180
+ input.attempt,
11181
+ input.leaseToken,
11182
+ JSON.stringify(input.expected),
11183
+ JSON.stringify(input.sessions),
11184
+ ],
11185
+ );
11186
+ return result.rows.length === 1;
11187
+ }
11188
+
11088
11189
  /**
11089
11190
  * Absurd scheduler backend: persist the vendored engine's task id on the run
11090
11191
  * row after `spawn`. Idempotent (last write wins); a re-submit under the same
@@ -17079,6 +17180,14 @@ export async function cancelPostgresSchedulerRun(
17079
17180
  * exists to cancel through. Zero attempts proves execution never began.
17080
17181
  */
17081
17182
  onlyIfCreatedProjectionFailed?: { absurdTaskId: string };
17183
+ /**
17184
+ * Fence for a caller stop of a run no worker ever started. The caller has
17185
+ * already cancelled the engine task in this transaction and proved the
17186
+ * engine never claimed it. Zero scheduler attempts and no unfinished
17187
+ * sandbox operation, cleanup job or ambiguous create prove there is no
17188
+ * execution or provider resource left to wait for.
17189
+ */
17190
+ onlyIfUnclaimed?: { absurdTaskId: string };
17082
17191
  /**
17083
17192
  * Optional control-plane ownership for the oldest pending causal fact.
17084
17193
  * Cancellation makes the remaining prefix due without sharing this lease
@@ -17096,9 +17205,33 @@ export async function cancelPostgresSchedulerRun(
17096
17205
  );
17097
17206
  const strandedFence = input.onlyIfStrandedPreExecution;
17098
17207
  const createdFence = input.onlyIfCreatedProjectionFailed;
17099
- if (strandedFence && createdFence) {
17208
+ const unclaimedFence = input.onlyIfUnclaimed;
17209
+ if (
17210
+ [strandedFence, createdFence, unclaimedFence].filter(Boolean).length > 1
17211
+ ) {
17100
17212
  throw new Error('A scheduler cancellation accepts one operator fence.');
17101
17213
  }
17214
+ const unclaimedEligibility = unclaimedFence
17215
+ ? `AND target.status = 'queued'
17216
+ AND target.absurd_task_id = $8
17217
+ AND NOT EXISTS (
17218
+ SELECT 1 FROM ${tableName('attempts', options)} AS attempt
17219
+ WHERE attempt.run_id = target.run_id
17220
+ )
17221
+ AND NOT EXISTS (
17222
+ SELECT 1 FROM ${tableName('runtime_sandbox_operations', options)} AS operation
17223
+ WHERE operation.run_id = target.run_id
17224
+ AND operation.state::text <> ALL($9::text[])
17225
+ )
17226
+ AND NOT EXISTS (
17227
+ SELECT 1 FROM ${tableName('sandbox_cleanup_jobs_v2', options)} AS cleanup
17228
+ WHERE cleanup.run_id = target.run_id AND cleanup.status <> 'deleted'
17229
+ )
17230
+ AND NOT EXISTS (
17231
+ SELECT 1 FROM ${tableName('ambiguous_modal_creates', options)} AS intent
17232
+ WHERE intent.run_id = target.run_id AND intent.status = 'pending'
17233
+ )`
17234
+ : '';
17102
17235
  const createdEligibility = createdFence
17103
17236
  ? `AND target.status = 'queued'
17104
17237
  AND target.absurd_task_id = $8
@@ -17149,6 +17282,7 @@ export async function cancelPostgresSchedulerRun(
17149
17282
  AND target.status IN ('queued', 'running', 'waiting')
17150
17283
  ${strandedEligibility}
17151
17284
  ${createdEligibility}
17285
+ ${unclaimedEligibility}
17152
17286
  RETURNING target.run_id, target.launch_json
17153
17287
  ),
17154
17288
  cancelled_attempts AS (
@@ -17325,6 +17459,12 @@ export async function cancelPostgresSchedulerRun(
17325
17459
  ? [strandedFence.releaseId, strandedFence.absurdTaskId]
17326
17460
  : []),
17327
17461
  ...(createdFence ? [createdFence.absurdTaskId] : []),
17462
+ ...(unclaimedFence
17463
+ ? [
17464
+ unclaimedFence.absurdTaskId,
17465
+ [...RUNTIME_SANDBOX_OPERATION_TERMINAL_STATES],
17466
+ ]
17467
+ : []),
17328
17468
  ],
17329
17469
  );
17330
17470
  if (cancelled.rows.length === 0 && outboxLeaseOwner) {