@proofoftech/flowsafe 0.19.0 → 0.21.0

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 (297) hide show
  1. package/CHANGELOG.md +106 -0
  2. package/README.md +68 -6
  3. package/deployment-identity-protocol.d.mts +70 -1
  4. package/deployment-identity-protocol.mjs +423 -5
  5. package/dist/agent-host/index.d.ts +1 -1
  6. package/dist/agent-host/index.d.ts.map +1 -1
  7. package/dist/agent-host/index.js.map +1 -1
  8. package/dist/agent-host/router.d.ts.map +1 -1
  9. package/dist/agent-host/router.js +17 -4
  10. package/dist/agent-host/router.js.map +1 -1
  11. package/dist/agent-host/thread-host.d.ts +14 -1
  12. package/dist/agent-host/thread-host.d.ts.map +1 -1
  13. package/dist/agent-host/thread-host.js +865 -308
  14. package/dist/agent-host/thread-host.js.map +1 -1
  15. package/dist/agent-host/thread-topology.d.ts +43 -1
  16. package/dist/agent-host/thread-topology.d.ts.map +1 -1
  17. package/dist/agent-host/thread-topology.js +301 -28
  18. package/dist/agent-host/thread-topology.js.map +1 -1
  19. package/dist/agent-runner/durable-agent-runner.d.ts +107 -8
  20. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  21. package/dist/agent-runner/durable-agent-runner.js +427 -55
  22. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  23. package/dist/agent-runner/index.d.ts +1 -1
  24. package/dist/agent-runner/index.d.ts.map +1 -1
  25. package/dist/agent-runner/index.js.map +1 -1
  26. package/dist/approval-api/actor-context.d.ts +4 -0
  27. package/dist/approval-api/actor-context.d.ts.map +1 -1
  28. package/dist/approval-api/actor-context.js +53 -5
  29. package/dist/approval-api/actor-context.js.map +1 -1
  30. package/dist/approval-api/d1-store.d.ts.map +1 -1
  31. package/dist/approval-api/d1-store.js +6 -3
  32. package/dist/approval-api/d1-store.js.map +1 -1
  33. package/dist/approval-api/principal-identity.d.ts +32 -0
  34. package/dist/approval-api/principal-identity.d.ts.map +1 -0
  35. package/dist/approval-api/principal-identity.js +69 -0
  36. package/dist/approval-api/principal-identity.js.map +1 -0
  37. package/dist/approval-api/principal.d.ts +10 -13
  38. package/dist/approval-api/principal.d.ts.map +1 -1
  39. package/dist/approval-api/principal.js +10 -46
  40. package/dist/approval-api/principal.js.map +1 -1
  41. package/dist/approval-api/retention.d.ts +1 -2
  42. package/dist/approval-api/retention.d.ts.map +1 -1
  43. package/dist/approval-api/retention.js.map +1 -1
  44. package/dist/approval-api/router.d.ts.map +1 -1
  45. package/dist/approval-api/router.js +9 -1
  46. package/dist/approval-api/router.js.map +1 -1
  47. package/dist/approval-api/service.d.ts +29 -14
  48. package/dist/approval-api/service.d.ts.map +1 -1
  49. package/dist/approval-api/service.js +83 -25
  50. package/dist/approval-api/service.js.map +1 -1
  51. package/dist/approval-api/types.d.ts +12 -0
  52. package/dist/approval-api/types.d.ts.map +1 -1
  53. package/dist/approval-api/types.js +12 -0
  54. package/dist/approval-api/types.js.map +1 -1
  55. package/dist/audit-export/index.d.ts +2 -2
  56. package/dist/audit-export/index.js +2 -2
  57. package/dist/background-tasks/d1-storage.d.ts +4 -3
  58. package/dist/background-tasks/d1-storage.d.ts.map +1 -1
  59. package/dist/background-tasks/d1-storage.js +7 -13
  60. package/dist/background-tasks/d1-storage.js.map +1 -1
  61. package/dist/background-tasks/host.d.ts +127 -14
  62. package/dist/background-tasks/host.d.ts.map +1 -1
  63. package/dist/background-tasks/host.js +579 -50
  64. package/dist/background-tasks/host.js.map +1 -1
  65. package/dist/background-tasks/index.d.ts +2 -2
  66. package/dist/background-tasks/index.d.ts.map +1 -1
  67. package/dist/background-tasks/index.js +11 -6
  68. package/dist/background-tasks/index.js.map +1 -1
  69. package/dist/background-tasks/routes.d.ts +19 -2
  70. package/dist/background-tasks/routes.d.ts.map +1 -1
  71. package/dist/background-tasks/routes.js +4 -4
  72. package/dist/background-tasks/routes.js.map +1 -1
  73. package/dist/deployment-identity-protocol.d.ts +2 -2
  74. package/dist/deployment-identity-protocol.d.ts.map +1 -1
  75. package/dist/deployment-identity-protocol.js +1 -1
  76. package/dist/deployment-identity-protocol.js.map +1 -1
  77. package/dist/do-runner/cause-chain.d.ts +53 -0
  78. package/dist/do-runner/cause-chain.d.ts.map +1 -0
  79. package/dist/do-runner/cause-chain.js +96 -0
  80. package/dist/do-runner/cause-chain.js.map +1 -0
  81. package/dist/do-runner/constants.d.ts +3 -0
  82. package/dist/do-runner/constants.d.ts.map +1 -0
  83. package/dist/do-runner/constants.js +3 -0
  84. package/dist/do-runner/constants.js.map +1 -0
  85. package/dist/do-runner/d1-storage.d.ts +47 -69
  86. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  87. package/dist/do-runner/d1-storage.js +972 -196
  88. package/dist/do-runner/d1-storage.js.map +1 -1
  89. package/dist/do-runner/deployment-identity.d.ts +29 -5
  90. package/dist/do-runner/deployment-identity.d.ts.map +1 -1
  91. package/dist/do-runner/deployment-identity.js +23 -6
  92. package/dist/do-runner/deployment-identity.js.map +1 -1
  93. package/dist/do-runner/do-error-response.d.ts +4 -23
  94. package/dist/do-runner/do-error-response.d.ts.map +1 -1
  95. package/dist/do-runner/do-error-response.js +19 -24
  96. package/dist/do-runner/do-error-response.js.map +1 -1
  97. package/dist/do-runner/do-status-error.d.ts +37 -0
  98. package/dist/do-runner/do-status-error.d.ts.map +1 -0
  99. package/dist/do-runner/do-status-error.js +42 -0
  100. package/dist/do-runner/do-status-error.js.map +1 -0
  101. package/dist/do-runner/durable-object.d.ts +2 -1
  102. package/dist/do-runner/durable-object.d.ts.map +1 -1
  103. package/dist/do-runner/durable-object.js +617 -144
  104. package/dist/do-runner/durable-object.js.map +1 -1
  105. package/dist/do-runner/execution-admission.d.ts +114 -0
  106. package/dist/do-runner/execution-admission.d.ts.map +1 -0
  107. package/dist/do-runner/execution-admission.js +206 -0
  108. package/dist/do-runner/execution-admission.js.map +1 -0
  109. package/dist/do-runner/execution-context.d.ts.map +1 -1
  110. package/dist/do-runner/execution-context.js +1 -0
  111. package/dist/do-runner/execution-context.js.map +1 -1
  112. package/dist/do-runner/execution-fence.d.ts +379 -0
  113. package/dist/do-runner/execution-fence.d.ts.map +1 -0
  114. package/dist/do-runner/execution-fence.js +1098 -0
  115. package/dist/do-runner/execution-fence.js.map +1 -0
  116. package/dist/do-runner/fenced-workflow-capability.d.ts +64 -0
  117. package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -0
  118. package/dist/do-runner/fenced-workflow-capability.js +3 -0
  119. package/dist/do-runner/fenced-workflow-capability.js.map +1 -0
  120. package/dist/do-runner/fenced-workflows-d1.d.ts +15 -0
  121. package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -0
  122. package/dist/do-runner/fenced-workflows-d1.js +894 -0
  123. package/dist/do-runner/fenced-workflows-d1.js.map +1 -0
  124. package/dist/do-runner/index.d.ts +20 -8
  125. package/dist/do-runner/index.d.ts.map +1 -1
  126. package/dist/do-runner/index.js +21 -4
  127. package/dist/do-runner/index.js.map +1 -1
  128. package/dist/do-runner/init.d.ts +82 -1
  129. package/dist/do-runner/init.d.ts.map +1 -1
  130. package/dist/do-runner/init.js +58 -3
  131. package/dist/do-runner/init.js.map +1 -1
  132. package/dist/do-runner/initial-admission-refusal.d.ts +7 -0
  133. package/dist/do-runner/initial-admission-refusal.d.ts.map +1 -0
  134. package/dist/do-runner/initial-admission-refusal.js +41 -0
  135. package/dist/do-runner/initial-admission-refusal.js.map +1 -0
  136. package/dist/do-runner/inventory.d.ts +295 -0
  137. package/dist/do-runner/inventory.d.ts.map +1 -0
  138. package/dist/do-runner/inventory.js +800 -0
  139. package/dist/do-runner/inventory.js.map +1 -0
  140. package/dist/do-runner/notification-predicate.d.ts +8 -0
  141. package/dist/do-runner/notification-predicate.d.ts.map +1 -0
  142. package/dist/do-runner/notification-predicate.js +136 -0
  143. package/dist/do-runner/notification-predicate.js.map +1 -0
  144. package/dist/do-runner/run-lifecycle.d.ts +20 -1
  145. package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
  146. package/dist/do-runner/run-lifecycle.js +67 -13
  147. package/dist/do-runner/run-lifecycle.js.map +1 -1
  148. package/dist/do-runner/run-provenance.d.ts +38 -0
  149. package/dist/do-runner/run-provenance.d.ts.map +1 -0
  150. package/dist/do-runner/run-provenance.js +152 -0
  151. package/dist/do-runner/run-provenance.js.map +1 -0
  152. package/dist/do-runner/run-storage-tables.d.ts +2 -0
  153. package/dist/do-runner/run-storage-tables.d.ts.map +1 -0
  154. package/dist/do-runner/run-storage-tables.js +4 -0
  155. package/dist/do-runner/run-storage-tables.js.map +1 -0
  156. package/dist/do-runner/run-terminal-state.d.ts +29 -0
  157. package/dist/do-runner/run-terminal-state.d.ts.map +1 -0
  158. package/dist/do-runner/run-terminal-state.js +105 -0
  159. package/dist/do-runner/run-terminal-state.js.map +1 -0
  160. package/dist/do-runner/runtime.d.ts +191 -46
  161. package/dist/do-runner/runtime.d.ts.map +1 -1
  162. package/dist/do-runner/runtime.js +994 -378
  163. package/dist/do-runner/runtime.js.map +1 -1
  164. package/dist/do-runner/start-idempotency.d.ts +285 -0
  165. package/dist/do-runner/start-idempotency.d.ts.map +1 -0
  166. package/dist/do-runner/start-idempotency.js +994 -0
  167. package/dist/do-runner/start-idempotency.js.map +1 -0
  168. package/dist/do-runner/start-reservation-contract.d.ts +103 -0
  169. package/dist/do-runner/start-reservation-contract.d.ts.map +1 -0
  170. package/dist/do-runner/start-reservation-contract.js +338 -0
  171. package/dist/do-runner/start-reservation-contract.js.map +1 -0
  172. package/dist/do-runner/suspension-deadline.d.ts +4 -11
  173. package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
  174. package/dist/do-runner/suspension-deadline.js +8 -12
  175. package/dist/do-runner/suspension-deadline.js.map +1 -1
  176. package/dist/do-runner/table-prefix.d.ts.map +1 -1
  177. package/dist/do-runner/table-prefix.js +2 -1
  178. package/dist/do-runner/table-prefix.js.map +1 -1
  179. package/dist/do-runner/testing.d.ts +3 -0
  180. package/dist/do-runner/testing.d.ts.map +1 -0
  181. package/dist/do-runner/testing.js +3 -0
  182. package/dist/do-runner/testing.js.map +1 -0
  183. package/dist/do-runner/thread-do.d.ts +2 -1
  184. package/dist/do-runner/thread-do.d.ts.map +1 -1
  185. package/dist/do-runner/thread-do.js +14 -10
  186. package/dist/do-runner/thread-do.js.map +1 -1
  187. package/dist/do-runner/workflow-snapshot-row.d.ts +49 -0
  188. package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -0
  189. package/dist/do-runner/workflow-snapshot-row.js +97 -0
  190. package/dist/do-runner/workflow-snapshot-row.js.map +1 -0
  191. package/dist/goals/objective-routes.d.ts +15 -5
  192. package/dist/goals/objective-routes.d.ts.map +1 -1
  193. package/dist/goals/objective-routes.js +64 -64
  194. package/dist/goals/objective-routes.js.map +1 -1
  195. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  196. package/dist/host-kit/approval-bridge.js +10 -7
  197. package/dist/host-kit/approval-bridge.js.map +1 -1
  198. package/dist/host-kit/do-response.d.ts +16 -0
  199. package/dist/host-kit/do-response.d.ts.map +1 -1
  200. package/dist/host-kit/do-response.js +181 -0
  201. package/dist/host-kit/do-response.js.map +1 -1
  202. package/dist/host-kit/do-run-topology.d.ts +3 -0
  203. package/dist/host-kit/do-run-topology.d.ts.map +1 -1
  204. package/dist/host-kit/do-run-topology.js +36 -8
  205. package/dist/host-kit/do-run-topology.js.map +1 -1
  206. package/dist/host-kit/env-vars.d.ts.map +1 -1
  207. package/dist/host-kit/env-vars.js +5 -6
  208. package/dist/host-kit/env-vars.js.map +1 -1
  209. package/dist/host-kit/flowsafe-worker.d.ts +49 -6
  210. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  211. package/dist/host-kit/flowsafe-worker.js +409 -111
  212. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  213. package/dist/host-kit/host-approval-service.d.ts +24 -14
  214. package/dist/host-kit/host-approval-service.d.ts.map +1 -1
  215. package/dist/host-kit/host-approval-service.js +29 -40
  216. package/dist/host-kit/host-approval-service.js.map +1 -1
  217. package/dist/host-kit/index.d.ts +9 -3
  218. package/dist/host-kit/index.d.ts.map +1 -1
  219. package/dist/host-kit/index.js +5 -1
  220. package/dist/host-kit/index.js.map +1 -1
  221. package/dist/host-kit/run-route-error.d.ts +8 -4
  222. package/dist/host-kit/run-route-error.d.ts.map +1 -1
  223. package/dist/host-kit/run-route-error.js +14 -11
  224. package/dist/host-kit/run-route-error.js.map +1 -1
  225. package/dist/host-kit/run-router.d.ts +63 -2
  226. package/dist/host-kit/run-router.d.ts.map +1 -1
  227. package/dist/host-kit/run-router.js +167 -45
  228. package/dist/host-kit/run-router.js.map +1 -1
  229. package/dist/host-kit/stream-router.d.ts.map +1 -1
  230. package/dist/host-kit/stream-router.js +18 -9
  231. package/dist/host-kit/stream-router.js.map +1 -1
  232. package/dist/host-kit/thread-topology.d.ts +1 -1
  233. package/dist/host-kit/thread-topology.d.ts.map +1 -1
  234. package/dist/host-kit/thread-topology.js +7 -3
  235. package/dist/host-kit/thread-topology.js.map +1 -1
  236. package/dist/internal-error-response.d.ts.map +1 -1
  237. package/dist/internal-error-response.js +16 -6
  238. package/dist/internal-error-response.js.map +1 -1
  239. package/dist/schedules/index.d.ts +1 -0
  240. package/dist/schedules/index.d.ts.map +1 -1
  241. package/dist/schedules/index.js +1 -7
  242. package/dist/schedules/index.js.map +1 -1
  243. package/dist/schedules/mutation-contract.d.ts +38 -0
  244. package/dist/schedules/mutation-contract.d.ts.map +1 -0
  245. package/dist/schedules/mutation-contract.js +21 -0
  246. package/dist/schedules/mutation-contract.js.map +1 -0
  247. package/dist/schedules/router.d.ts +15 -8
  248. package/dist/schedules/router.d.ts.map +1 -1
  249. package/dist/schedules/router.js +170 -59
  250. package/dist/schedules/router.js.map +1 -1
  251. package/dist/schedules/schedules-d1.d.ts +11 -5
  252. package/dist/schedules/schedules-d1.d.ts.map +1 -1
  253. package/dist/schedules/schedules-d1.js +570 -143
  254. package/dist/schedules/schedules-d1.js.map +1 -1
  255. package/dist/schedules/storage.d.ts +0 -7
  256. package/dist/schedules/storage.d.ts.map +1 -1
  257. package/dist/schedules/storage.js +0 -27
  258. package/dist/schedules/storage.js.map +1 -1
  259. package/dist/schedules/tick.d.ts +13 -0
  260. package/dist/schedules/tick.d.ts.map +1 -1
  261. package/dist/schedules/tick.js +66 -40
  262. package/dist/schedules/tick.js.map +1 -1
  263. package/dist/signal-providers/host-do.d.ts +12 -1
  264. package/dist/signal-providers/host-do.d.ts.map +1 -1
  265. package/dist/signal-providers/host-do.js +28 -3
  266. package/dist/signal-providers/host-do.js.map +1 -1
  267. package/dist/signal-providers/webhook-route.d.ts +15 -1
  268. package/dist/signal-providers/webhook-route.d.ts.map +1 -1
  269. package/dist/signal-providers/webhook-route.js +126 -113
  270. package/dist/signal-providers/webhook-route.js.map +1 -1
  271. package/dist/signals/d1-shared.d.ts +11 -8
  272. package/dist/signals/d1-shared.d.ts.map +1 -1
  273. package/dist/signals/d1-shared.js +1 -6
  274. package/dist/signals/d1-shared.js.map +1 -1
  275. package/dist/signals/index.d.ts +1 -1
  276. package/dist/signals/index.d.ts.map +1 -1
  277. package/dist/signals/index.js +1 -1
  278. package/dist/signals/index.js.map +1 -1
  279. package/dist/signals/notification-dispatch.d.ts +109 -5
  280. package/dist/signals/notification-dispatch.d.ts.map +1 -1
  281. package/dist/signals/notification-dispatch.js +430 -46
  282. package/dist/signals/notification-dispatch.js.map +1 -1
  283. package/dist/signals/notifications-d1.d.ts +14 -1
  284. package/dist/signals/notifications-d1.d.ts.map +1 -1
  285. package/dist/signals/notifications-d1.js +229 -18
  286. package/dist/signals/notifications-d1.js.map +1 -1
  287. package/dist/signals/router.d.ts +6 -4
  288. package/dist/signals/router.d.ts.map +1 -1
  289. package/dist/signals/router.js +49 -84
  290. package/dist/signals/router.js.map +1 -1
  291. package/dist/signals/thread-do-routes.d.ts +2 -0
  292. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  293. package/dist/signals/thread-do-routes.js +330 -83
  294. package/dist/signals/thread-do-routes.js.map +1 -1
  295. package/package.json +6 -3
  296. package/patches/@mastra__core@1.53.0.patch +54 -0
  297. package/scripts/seed-deployment-identity.mjs +34 -9
@@ -13,15 +13,21 @@
13
13
  // both duties share one wake, armed at the earliest of the two due times.
14
14
  import { decodeExecutionPrincipal, isExecutionPrincipalId, isExecutionPrincipalKind, } from '../approval-api/principal.js';
15
15
  import { newWebSocketPair, safeSend } from './cf-types.js';
16
- import { verifyDurableObjectDeploymentIdentity, verifyDurableObjectDeploymentRequest, } from './deployment-identity.js';
16
+ import { isDatabaseBinding, verifyDurableObjectDeploymentIdentity, verifyDurableObjectDeploymentRequest, } from './deployment-identity.js';
17
17
  import { DoStatusError, doErrorResponse } from './do-error-response.js';
18
+ import { ExecutionFenceUnreadableError, isRunStartPendingError, MUTATION_EPOCH_HEADER, mutationEpochFromHeader, normalizeD1RunExecutionIdentity, normalizeRunExecutionIdentity, normalizeStartExecutionIdentity, normalizeStartIdentity, RunStartPendingError, } from './execution-admission.js';
19
+ import { admitsRunStart, ExecutionFencedError, isExecutionFenceRefusal, readExecutionFence, } from './execution-fence.js';
18
20
  import { EXECUTION_PRINCIPAL_HEADER } from './execution-principal-header.js';
21
+ import { isDefinitiveInitialAdmissionRefusal } from './initial-admission-refusal.js';
19
22
  import { isPathSafeId } from './path-safe-id.js';
20
- import { InvalidRunRequestError, RunAlreadyExistsError, RunStateUnreadableError, UnknownRunError, } from './runtime.js';
23
+ import { lifecycleFromRequestContext, terminalCleanupFor, } from './run-lifecycle.js';
24
+ import { isTerminalRunStatus } from './run-terminal-state.js';
25
+ import { InvalidRunRequestError, RunAlreadyExistsError, RunnerRuntime, RunStateUnreadableError, UnknownRunError, } from './runtime.js';
21
26
  import { resolveScheduleStartOwner, } from './schedule-source.js';
27
+ import { captureReservation, sameReservationIdentity, } from './start-reservation-contract.js';
22
28
  import { dueSuspensionDeadline, isReadableRunSummary, isSuspensionDeadlineDue, MAX_SUSPENSION_DEADLINE_ATTEMPTS, MAX_SUSPENSION_DEADLINES_PER_RUN, mergeSuspensionDeadlines, nextSuspensionDeadlineAt, parseSuspensionDeadlineRecord, SUSPENSION_DEADLINE_PRINCIPAL_ID, SUSPENSION_DEADLINE_STORAGE_KEY, SUSPENSION_TIMEOUT_RESUME_KEY, suspensionDeadlinesOf, suspensionTimeoutResumeData, tombstoned, } from './suspension-deadline.js';
23
29
  const RUN_OWNER_RECOVERY_KEY = 'flowsafe:run-owner-recovery:v1';
24
- const RUN_OWNER_RECOVERY_DELAY_MS = 60_000;
30
+ export const RUN_OWNER_RECOVERY_DELAY_MS = 60_000;
25
31
  const SUSPENSION_DEADLINE_RETRY_MS = 60_000;
26
32
  // How long a run's state may stay unreadable before the entries due under it
27
33
  // are given up on. A read that never succeeds is never charged, so without this
@@ -53,9 +59,87 @@ const SUSPENSION_DEADLINE_UNREADABLE_LIMIT_MS = 86_400_000;
53
59
  // deferred to the watchdog — up to a minute late, and only while the fault
54
60
  // lasts.
55
61
  const SUSPENSION_DEADLINE_ARM_FLOOR_MS = 1_000;
62
+ function recoveryObject(value) {
63
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
64
+ throw new Error('stored run owner recovery is malformed');
65
+ const copy = Object.create(null);
66
+ for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(value))) {
67
+ if (!('value' in descriptor))
68
+ throw new Error('stored run owner recovery is malformed');
69
+ copy[key] = descriptor.value;
70
+ }
71
+ return copy;
72
+ }
73
+ function sameRunRecovery(actual, expected) {
74
+ const claim = actual.startReservation;
75
+ const wantedClaim = expected.startReservation;
76
+ return (actual.version === expected.version &&
77
+ actual.phase === expected.phase &&
78
+ actual.token === expected.token &&
79
+ actual.workflowId === expected.workflowId &&
80
+ actual.runId === expected.runId &&
81
+ actual.owner.kind === expected.owner.kind &&
82
+ actual.owner.id === expected.owner.id &&
83
+ actual.execution?.tablePrefix === expected.execution?.tablePrefix &&
84
+ actual.execution?.workflowId === expected.execution?.workflowId &&
85
+ actual.execution?.runId === expected.execution?.runId &&
86
+ actual.execution?.startToken === expected.execution?.startToken &&
87
+ (claim === undefined
88
+ ? wantedClaim === undefined
89
+ : wantedClaim !== undefined &&
90
+ sameReservationIdentity(claim, wantedClaim) &&
91
+ claim.state === wantedClaim.state &&
92
+ claim.updatedAt === wantedClaim.updatedAt &&
93
+ claim.binding.kind === wantedClaim.binding.kind));
94
+ }
56
95
  class DurableObjectRunIdentityError extends DoStatusError {
57
96
  status = 403;
58
97
  }
98
+ /**
99
+ * Does this env carry a database to fence against?
100
+ *
101
+ * `isDatabaseBinding` is deployment-identity's, imported rather than restated:
102
+ * it is the SAME question about the SAME binding (an RPC binding — a service
103
+ * binding with a named entrypoint, a Durable Object stub — is a proxy that
104
+ * answers every property with a callable, so `fetch` is what separates that
105
+ * family from a D1Database). Two copies would be two places for that
106
+ * discrimination to be revised, and a deployment where they disagreed would
107
+ * pass the identity check and skip the fence assert, or the reverse.
108
+ */
109
+ function hasDatabaseBinding(env) {
110
+ return isDatabaseBinding(env?.DB);
111
+ }
112
+ /**
113
+ * A run object bound to a real database must never serve from a fence-less
114
+ * runtime. `init()` makes that true for every host that hands it the binding —
115
+ * its `{ DB }` branch has no opt-out — so what is left for this assert is the
116
+ * host that builds a RunnerRuntime by hand inside `build()` and forgets: that
117
+ * deployment would then execute straight through a migration lock, silently,
118
+ * and the fence would look wired because every OTHER surface reports it.
119
+ *
120
+ * Scoped to runtimes THIS PACKAGE built. A test double cast to the type is not
121
+ * a RunnerRuntime and carries no fence by construction; asserting on it would
122
+ * indict every stub for a property it was never meant to have, and would say
123
+ * nothing about the production wiring this guard exists for.
124
+ */
125
+ function assertFencedRuntime(runtime, env) {
126
+ if (!(runtime instanceof RunnerRuntime))
127
+ return;
128
+ if (!hasDatabaseBinding(env))
129
+ return;
130
+ if (runtime.executionFence === undefined) {
131
+ throw new Error('DurableObjectRunner: build() returned a runtime with no execution fence while this deployment carries a DB binding — wire it through init({ DB }) (which builds one) or pass an ExecutionFenceStore, so a migration-locked deployment cannot execute');
132
+ }
133
+ // The same guard, for the same failure. A hand-built runtime with no
134
+ // reservation store still EXECUTES idempotent starts — the router reserves
135
+ // and claims above it — but never marks their reservations spent, so every
136
+ // key this deployment ever honoured stays in the drain inventory and never
137
+ // becomes purgeable. That is invisible until the day someone tries to prove
138
+ // the deployment empty, which is the day it matters most.
139
+ if (runtime.startIdempotency === undefined) {
140
+ throw new Error('DurableObjectRunner: build() returned a runtime with no start-reservation store while this deployment carries a DB binding — wire it through init({ DB }) (which builds one), so an idempotent start can be marked settled when its run ends');
141
+ }
142
+ }
59
143
  export class DurableObjectRunner {
60
144
  env;
61
145
  /** Absent in Node tests; present under workerd for storage and the alarm. */
@@ -64,6 +148,8 @@ export class DurableObjectRunner {
64
148
  #operationTail = Promise.resolve();
65
149
  /** `step\0reason` of every suspension deadline this object has reported. */
66
150
  #reportedSuspensionRejections = new Set();
151
+ /** Persisted claims outlive an isolate and cannot establish run liveness. */
152
+ #startsInFlight = new Map();
67
153
  constructor(state, env) {
68
154
  this.state = state;
69
155
  this.env = env;
@@ -78,13 +164,16 @@ export class DurableObjectRunner {
78
164
  }
79
165
  async fetch(request) {
80
166
  try {
167
+ const encodedPrincipal = request.headers.get(EXECUTION_PRINCIPAL_HEADER);
168
+ const encodedEpoch = request.headers.get(MUTATION_EPOCH_HEADER);
81
169
  // Deployment-identity check BEFORE any routing or storage work: under
82
170
  // workerd this instance refuses to serve until its env tag matches the
83
171
  // database sentinel (fail closed on a mis-provisioned binding); off
84
172
  // workerd (node tests, state undefined) it is a no-op. Memoized after
85
173
  // the first success, so steady-state requests pay nothing.
86
174
  await verifyDurableObjectDeploymentRequest(request, this.state, this.env);
87
- return await this.#route(request);
175
+ const mutationEpoch = mutationEpochFromHeader(encodedEpoch);
176
+ return await this.#route(request, encodedPrincipal, mutationEpoch);
88
177
  }
89
178
  catch (error) {
90
179
  return doErrorResponse(error);
@@ -92,12 +181,23 @@ export class DurableObjectRunner {
92
181
  }
93
182
  #ensureRuntime() {
94
183
  if (!this.#runtime) {
95
- this.#runtime = this.build(this.env);
184
+ const runtime = this.build(this.env);
185
+ assertFencedRuntime(runtime, this.env);
186
+ this.#runtime = runtime;
96
187
  }
97
188
  return this.#runtime;
98
189
  }
99
- // INV-1 enforcement at the DO boundary: this instance was addressed as
100
- // idFromName(`${workflowId}:${runId}`) by the trusted Worker, and id.name
190
+ /**
191
+ * This object's execution fence, or the open reading when the host built an
192
+ * unfenced runtime. Taken from the RUNTIME rather than constructed here, so
193
+ * the routes below and the start/resume backstop inside the runtime can
194
+ * never be gating two different databases.
195
+ */
196
+ async #readExecutionFence() {
197
+ return readExecutionFence(this.#ensureRuntime().executionFence);
198
+ }
199
+ // Enforce host-owned run ids at the DO boundary: this instance was addressed
200
+ // as idFromName(`${workflowId}:${runId}`) by the trusted Worker, and id.name
101
201
  // is unforgeable at this boundary. If a request asks the instance to act on
102
202
  // a DIFFERENT (workflowId, runId), someone routed around the name join —
103
203
  // acting on the request's ids would run outside this instance's identity
@@ -110,8 +210,46 @@ export class DurableObjectRunner {
110
210
  if (name === undefined)
111
211
  return;
112
212
  if (name !== `${workflowId}:${runId}`) {
113
- throw new Error(`DO identity mismatch: instance is '${name}' but the request names '${workflowId}:${runId}' — refusing (INV-1)`);
213
+ throw new Error(`DO identity mismatch: instance is '${name}' but the request names '${workflowId}:${runId}' — refusing`);
214
+ }
215
+ }
216
+ /**
217
+ * The same `workflowId:runId` join the DO name and the runtime's own run key
218
+ * use — composed here so the in-flight set cannot be keyed by runId alone,
219
+ * which would make two workflows' runs of the same id one another's liveness.
220
+ */
221
+ #inFlightKey(workflowId, runId) {
222
+ return `${workflowId}:${runId}`;
223
+ }
224
+ /**
225
+ * Is a start for this run executing in THIS object right now?
226
+ *
227
+ * Two sources, ORed, because they cover different halves of the window: the
228
+ * route's own set covers from the recovery journal to the response (including
229
+ * the gap before core persists anything), and the runtime's `#activeRuns`
230
+ * covers a run driven through this isolate's runtime by any other path — an
231
+ * in-process host, a resume, an agent loop sharing the runtime. Neither alone
232
+ * is the whole window, and a false negative here is the expensive direction:
233
+ * it turns a live run into an UNRESOLVABLE refusal.
234
+ */
235
+ #isStartLive(workflowId, runId) {
236
+ if (this.#startsInFlight.has(this.#inFlightKey(workflowId, runId))) {
237
+ return true;
238
+ }
239
+ return this.#ensureRuntime().isRunActive(workflowId, runId);
240
+ }
241
+ /**
242
+ * Validate an internal-channel idempotency key. Absent stays absent; anything
243
+ * present must be path-safe, because the same string is compared against the
244
+ * fence's proof key and stored as a reservation's primary key.
245
+ */
246
+ #startIdempotencyKey(value) {
247
+ if (value === undefined || value === null)
248
+ return undefined;
249
+ if (!isPathSafeId(value)) {
250
+ throw new InvalidRunRequestError('idempotencyKey must be a URL-path-safe identifier');
114
251
  }
252
+ return value;
115
253
  }
116
254
  #requestedBy(value) {
117
255
  if (!isExecutionPrincipalId(value)) {
@@ -125,14 +263,7 @@ export class DurableObjectRunner {
125
263
  }
126
264
  return value;
127
265
  }
128
- /**
129
- * The reserved timeout envelope is minted by the alarm and by nothing else.
130
- * A caller allowed to resume could otherwise drive a step's timeout branch
131
- * while provenance still names them as the requester, which would make the
132
- * one contract this feature sells — a timeout resume is distinguishable from
133
- * a real signal — untrue. The KEY is refused, not just a well-formed
134
- * envelope, so a step that reads the key directly cannot be fooled either.
135
- */
266
+ /** Caller-supplied timeout data would select the timeout branch with caller provenance. */
136
267
  #resumeData(value) {
137
268
  if (value !== null &&
138
269
  typeof value === 'object' &&
@@ -141,15 +272,72 @@ export class DurableObjectRunner {
141
272
  }
142
273
  return value;
143
274
  }
144
- #trustedExecutionPrincipal(request) {
145
- const encoded = request.headers.get(EXECUTION_PRINCIPAL_HEADER);
275
+ #trustedExecutionPrincipal(encoded) {
146
276
  const principal = encoded ? decodeExecutionPrincipal(encoded) : undefined;
147
277
  if (!principal) {
148
278
  throw new DurableObjectRunIdentityError('run request carries no valid trusted execution principal');
149
279
  }
150
280
  return principal;
151
281
  }
152
- async #finalizeTerminal(runtime, workflowId, runId, owner, result) {
282
+ async #finalizeTerminal(runtime, workflowId, runId, owner, result, selected, originalClaim) {
283
+ const claim = originalClaim === undefined
284
+ ? undefined
285
+ : captureReservation(originalClaim, 'started');
286
+ const assertQuiescent = () => {
287
+ if (this.#startsInFlight.has(this.#inFlightKey(workflowId, runId)) ||
288
+ runtime.isRunActive(workflowId, runId))
289
+ throw new RunStartPendingError();
290
+ };
291
+ assertQuiescent();
292
+ const state = selected ??
293
+ (await runtime.authoritativeStartState(workflowId, runId, {
294
+ includeLegacy: true,
295
+ }));
296
+ if (!state ||
297
+ state.kind === 'initial' ||
298
+ !isTerminalRunStatus(state.snapshot.status) ||
299
+ !isTerminalRunStatus(state.summary.status))
300
+ throw new RunStateUnreadableError(workflowId, runId);
301
+ const cleanup = terminalCleanupFor(lifecycleFromRequestContext(state.snapshot.requestContext));
302
+ if (!cleanup ||
303
+ state.summary.runId !== result.summary.runId ||
304
+ state.summary.status !== result.summary.status ||
305
+ cleanup.status !== result.cleanup.status ||
306
+ cleanup.revision !== result.cleanup.revision ||
307
+ cleanup.scheduleDispatch?.scheduleId !==
308
+ result.cleanup.scheduleDispatch?.scheduleId ||
309
+ cleanup.scheduleDispatch?.dispatchId !==
310
+ result.cleanup.scheduleDispatch?.dispatchId ||
311
+ (result.cleanup.cleanupCompleted && !cleanup.cleanupCompleted))
312
+ throw new RunStateUnreadableError(workflowId, runId);
313
+ const stored = await this.state?.storage?.get(RUN_OWNER_RECOVERY_KEY);
314
+ assertQuiescent();
315
+ if (state.kind === 'legacy') {
316
+ if (stored !== undefined || claim !== undefined)
317
+ throw new RunStateUnreadableError(workflowId, runId);
318
+ }
319
+ else if (stored !== undefined) {
320
+ const recovery = this.#runOwnerRecovery(stored);
321
+ this.#assertRunIdentity(recovery.workflowId, recovery.runId);
322
+ if (claim &&
323
+ !sameRunRecovery(recovery, { ...recovery, startReservation: claim }))
324
+ throw new RunStateUnreadableError(workflowId, runId);
325
+ return this.#finishRunOwner(recovery, state.summary, state);
326
+ }
327
+ else {
328
+ await runtime.settleStartExecution(state, claim);
329
+ }
330
+ const assertNoJournal = async () => {
331
+ assertQuiescent();
332
+ if ((await this.state?.storage?.get(RUN_OWNER_RECOVERY_KEY)) !== undefined)
333
+ throw new RunStateUnreadableError(workflowId, runId);
334
+ assertQuiescent();
335
+ };
336
+ return this.#completeTerminalEffects(runtime, workflowId, runId, owner, { ...result, summary: state.summary, cleanup }, assertNoJournal);
337
+ }
338
+ async #completeTerminalEffects(runtime, workflowId, runId, owner, result, validate) {
339
+ if (validate)
340
+ await validate();
153
341
  if (result.cleanup.cleanupCompleted)
154
342
  return result.summary;
155
343
  const hooks = this.runLifecycle(this.env);
@@ -157,24 +345,35 @@ export class DurableObjectRunner {
157
345
  throw new Error('run termination requires lifecycle cleanup hooks');
158
346
  }
159
347
  await hooks.abandonApprovals(workflowId, runId, result.cleanup.status);
348
+ if (validate)
349
+ await validate();
160
350
  if (result.cleanup.scheduleDispatch) {
161
351
  if (!hooks?.discardScheduleDispatch) {
162
352
  throw new Error('scheduled run termination requires a dispatch-settlement hook');
163
353
  }
164
354
  await hooks.discardScheduleDispatch(result.cleanup.scheduleDispatch.scheduleId, result.cleanup.scheduleDispatch.dispatchId, runId);
355
+ if (validate)
356
+ await validate();
165
357
  }
166
358
  const ownership = this.runOwnership(this.env);
167
359
  if (!ownership.release) {
168
360
  throw new Error('run termination requires ownership release support');
169
361
  }
170
362
  const released = await ownership.release('run', runId, owner);
363
+ if (validate)
364
+ await validate();
171
365
  if (!released) {
172
366
  const current = await ownership.owner('run', runId);
367
+ if (validate)
368
+ await validate();
173
369
  if (current) {
174
370
  throw new Error(`run '${runId}' ownership could not be released`);
175
371
  }
176
372
  }
177
- return runtime.completeTerminalCleanup(workflowId, runId, result.cleanup.revision);
373
+ const summary = await runtime.completeTerminalCleanup(workflowId, runId, result.cleanup.revision);
374
+ if (validate)
375
+ await validate();
376
+ return summary;
178
377
  }
179
378
  async #startSource(principal, workflowId, runId, scheduleId, dispatchId) {
180
379
  if (scheduleId === undefined) {
@@ -283,6 +482,14 @@ export class DurableObjectRunner {
283
482
  }
284
483
  await storage.setAlarm(Date.now() + RUN_OWNER_RECOVERY_DELAY_MS);
285
484
  }
485
+ /**
486
+ * Arming is advisory: on a host with no storage this returns having
487
+ * journaled nothing. A host that journals nothing leaves no claim for a
488
+ * wake to recover, so there is nothing to arm. Promoting a claim to
489
+ * `prepared` (#prepareRunOwner) instead requires storage and refuses
490
+ * without it — a prepared run whose journal cannot be written leaves a
491
+ * claim no wake can find, so that path fails the start instead.
492
+ */
286
493
  async #armRunOwnerRecovery(recovery) {
287
494
  const storage = this.state?.storage;
288
495
  if (!storage)
@@ -295,17 +502,21 @@ export class DurableObjectRunner {
295
502
  await this.#armNextAlarm(Date.now() + RUN_OWNER_RECOVERY_DELAY_MS);
296
503
  await storage.put(RUN_OWNER_RECOVERY_KEY, recovery);
297
504
  }
505
+ async #assertRunOwnerRecoveryCurrent(recovery) {
506
+ const current = await this.state?.storage?.get(RUN_OWNER_RECOVERY_KEY);
507
+ if (current === undefined ||
508
+ !sameRunRecovery(this.#runOwnerRecovery(current), recovery))
509
+ throw new Error('run owner recovery changed');
510
+ }
298
511
  /**
299
- * `keepWake` is set by a caller whose reconciliation failed with something
300
- * to arm: the retry wake it left is the only thing that will re-derive that
301
- * deadline, and re-arming from storage here would find no record and no
302
- * journal and DELETE it. Keeping the recovery cadence instead costs one
303
- * spurious wake and cannot lose a deadline.
512
+ * Failed reconciliation can leave a retry wake without a stored deadline.
513
+ * Keeping that wake avoids losing it when alarms are rebuilt from storage.
304
514
  */
305
- async #clearRunOwnerRecovery(keepWake) {
515
+ async #clearRunOwnerRecovery(recovery, keepWake) {
306
516
  const storage = this.state?.storage;
307
517
  if (!storage)
308
518
  return;
519
+ await this.#assertRunOwnerRecoveryCurrent(recovery);
309
520
  await storage.delete(RUN_OWNER_RECOVERY_KEY);
310
521
  if (keepWake) {
311
522
  await this.#armAlarmWatchdog();
@@ -313,28 +524,82 @@ export class DurableObjectRunner {
313
524
  }
314
525
  await this.#armNextAlarm();
315
526
  }
316
- async #clearRunOwnerRecoveryBestEffort(keepWake) {
527
+ async #prepareRunOwner(recovery, execution) {
528
+ const identity = normalizeRunExecutionIdentity(execution);
529
+ if (identity.runId !== recovery.runId ||
530
+ identity.workflowId !== recovery.workflowId)
531
+ throw new Error('prepared run identity mismatch');
532
+ const prepared = this.#ensureRuntime().executionFence
533
+ ? {
534
+ ...recovery,
535
+ phase: 'prepared',
536
+ execution: normalizeD1RunExecutionIdentity(identity),
537
+ }
538
+ : { ...recovery, phase: 'prepared-unfenced', execution: identity };
539
+ const storage = this.state?.storage;
540
+ if (!storage)
541
+ throw new Error('run owner recovery requires durable storage');
542
+ const current = this.#runOwnerRecovery(await storage.get(RUN_OWNER_RECOVERY_KEY));
543
+ if (sameRunRecovery(current, prepared))
544
+ return prepared;
545
+ if (current.phase !== 'preparing' || !sameRunRecovery(current, recovery))
546
+ throw new Error('run owner recovery changed');
317
547
  try {
318
- await this.#clearRunOwnerRecovery(keepWake);
548
+ await storage.put(RUN_OWNER_RECOVERY_KEY, prepared);
319
549
  }
320
550
  catch (error) {
321
- console.error('run owner recovery cleanup failed', error);
551
+ const reread = await storage.get(RUN_OWNER_RECOVERY_KEY);
552
+ if (reread === undefined ||
553
+ !sameRunRecovery(this.#runOwnerRecovery(reread), prepared))
554
+ throw error;
322
555
  }
556
+ return prepared;
323
557
  }
324
- async #settleRunOwnerBestEffort(recovery, release, keepWake = false) {
325
- try {
326
- await this.runOwnership(this.env).settleReservation(recovery.token, release ? [{ kind: 'run', resourceId: recovery.runId }] : []);
327
- await this.#clearRunOwnerRecoveryBestEffort(keepWake);
328
- }
329
- catch (error) {
330
- console.error('run owner recovery settlement failed', error);
331
- try {
332
- await this.#rearmRunOwnerRecovery();
333
- }
334
- catch (alarmError) {
335
- console.error('run owner recovery rearm failed', alarmError);
336
- }
337
- }
558
+ #matchingRunState(recovery, state) {
559
+ const execution = recovery.execution;
560
+ if (!state ||
561
+ !execution ||
562
+ state.execution.tablePrefix !== execution.tablePrefix ||
563
+ state.execution.workflowId !== execution.workflowId ||
564
+ state.execution.runId !== execution.runId ||
565
+ state.execution.startToken !== execution.startToken)
566
+ throw new RunStateUnreadableError(recovery.workflowId, recovery.runId);
567
+ const identity = state.provenance.startIdentity;
568
+ if (identity?.target.kind !== 'workflow' ||
569
+ identity.target.id !== recovery.workflowId ||
570
+ state.provenance.agentStart !== undefined)
571
+ throw new RunStateUnreadableError(recovery.workflowId, recovery.runId);
572
+ const claim = recovery.startReservation;
573
+ if (claim &&
574
+ (identity.owner.kind !== claim.owner.kind ||
575
+ identity.owner.id !== claim.owner.id))
576
+ throw new RunStateUnreadableError(recovery.workflowId, recovery.runId);
577
+ return state;
578
+ }
579
+ async #finishRunOwner(recovery, summary, selected) {
580
+ const runtime = this.#ensureRuntime();
581
+ if (recovery.startReservation && !runtime.startIdempotency)
582
+ throw new ExecutionFenceUnreadableError('run start recovery is unresolved');
583
+ await this.#assertRunOwnerRecoveryCurrent(recovery);
584
+ const state = this.#matchingRunState(recovery, selected ??
585
+ (await runtime.authoritativeStartState(recovery.workflowId, recovery.runId)));
586
+ if (state.kind === 'initial')
587
+ throw new RunStartPendingError();
588
+ await this.#assertRunOwnerRecoveryCurrent(recovery);
589
+ if (isTerminalRunStatus(state.summary.status))
590
+ await runtime.settleStartExecution(state, recovery.startReservation);
591
+ await this.runOwnership(this.env).settleReservation(recovery.token, []);
592
+ const cleanup = terminalCleanupFor(lifecycleFromRequestContext(state.snapshot.requestContext));
593
+ if (cleanup)
594
+ summary = await this.#completeTerminalEffects(runtime, recovery.workflowId, recovery.runId, recovery.owner, {
595
+ summary: state.summary,
596
+ transitioned: false,
597
+ casMatched: true,
598
+ cleanup,
599
+ });
600
+ const reconciled = await this.#reconcileSuspensionDeadlinesBestEffort(recovery.workflowId, recovery.runId, summary);
601
+ await this.#clearRunOwnerRecovery(recovery, !reconciled);
602
+ return summary;
338
603
  }
339
604
  async #rearmRunOwnerRecovery() {
340
605
  const storage = this.state?.storage;
@@ -644,6 +909,8 @@ export class DurableObjectRunner {
644
909
  return await runtime.authoritativeStatus(workflowId, runId);
645
910
  }
646
911
  catch (error) {
912
+ if (isRunStartPendingError(error))
913
+ throw error;
647
914
  throw error instanceof RunStateUnreadableError
648
915
  ? error
649
916
  : new RunStateUnreadableError(workflowId, runId, { cause: error });
@@ -662,11 +929,11 @@ export class DurableObjectRunner {
662
929
  */
663
930
  async #resumeDueSuspensionDeadline(runtime, stored, entry, now) {
664
931
  const { workflowId, runId } = stored;
665
- // INV-1 at the one boundary whose ids come from storage rather than from
666
- // the trusted Worker: this wake is about to execute a workflow body, so it
667
- // must be this object's own run (and its per-run serialization). Charged
668
- // like any other duty failure, deliberately: it is the one charged failure
669
- // that read nothing, and charging is what quiets a foreign record's entry
932
+ // Enforce host-owned run ids at the boundary whose ids come from storage,
933
+ // rather than from the trusted Worker. This wake is about to execute a
934
+ // workflow body, so it must be this object's own run and serialization.
935
+ // Charge it like any other duty failure: it is the one charged failure that
936
+ // read nothing, and charging is what quiets a foreign record's entry
670
937
  // (five wakes to a tombstone). It stays here rather than moving up with the
671
938
  // runtime because the nothing-due path below deliberately prefers `id.name`
672
939
  // over a foreign record, which asserting early would break.
@@ -860,6 +1127,39 @@ export class DurableObjectRunner {
860
1127
  return true;
861
1128
  }
862
1129
  catch (error) {
1130
+ if (isRunStartPendingError(error)) {
1131
+ if (stored?.entries.some((entry) => entry.unreadableSince !== undefined)) {
1132
+ try {
1133
+ await this.state?.storage?.put(SUSPENSION_DEADLINE_STORAGE_KEY, {
1134
+ ...stored,
1135
+ entries: stored.entries.map(({ unreadableSince: _unreadableSince, ...entry }) => entry),
1136
+ });
1137
+ }
1138
+ catch (resetError) {
1139
+ console.error('suspension deadline pending stamp reset failed', resetError);
1140
+ }
1141
+ }
1142
+ return false;
1143
+ }
1144
+ // The deployment is fenced (or its fence could not be read). Classified
1145
+ // with the same THREE outcomes as an unreadable read — uncharged,
1146
+ // unconverged, watchdog cadence — because a wake refused by an
1147
+ // operational control is no evidence about the entry it was working on.
1148
+ // Charging it would spend the abandonment budget in about sixteen
1149
+ // minutes of lock and tombstone a live deadline; converging would arm
1150
+ // from a still-due entry no ledger backed off, which lands on the
1151
+ // one-second floor and spins.
1152
+ //
1153
+ // What it deliberately does NOT do is stamp `unreadableSince`. That
1154
+ // clock exists to bound a run whose state became PERMANENTLY unreadable,
1155
+ // and abandons its entries after a day; a fence is a deliberate,
1156
+ // operator-visible, bounded state, and answering a long migration by
1157
+ // discarding every deadline due inside it would be the same fault the
1158
+ // no-charge rule above exists to prevent, one order of magnitude later.
1159
+ if (isExecutionFenceRefusal(error)) {
1160
+ console.error('suspension deadline wake refused by the deployment execution fence', error);
1161
+ return false;
1162
+ }
863
1163
  // Classified FIRST, or every degraded wake would also log the generic
864
1164
  // failure below. A read that did not succeed converges nothing and
865
1165
  // charges nothing: it keeps the watchdog cadence until it heals, and the
@@ -897,42 +1197,128 @@ export class DurableObjectRunner {
897
1197
  }
898
1198
  }
899
1199
  }
900
- async #recoverRunOwner(recovery) {
901
- const summary = await this.#ensureRuntime().recoverStartAttempt(recovery.workflowId, recovery.runId, recovery.token);
902
- await this.runOwnership(this.env).settleReservation(recovery.token, summary ? [] : [{ kind: 'run', resourceId: recovery.runId }]);
903
- // A start interrupted AFTER Mastra persisted a suspension is the one case
904
- // where no other boundary is coming: the route that would have reconciled
905
- // died with its isolate, and clearing the journal below re-arms the alarm
906
- // from a record nothing ever wrote. This summary is the authoritative one
907
- // recoverStartAttempt read back, so derive from it here or the run stays
908
- // suspended with no wake at all. It needs no readability guard of its own:
909
- // recoverStartAttempt now throws RunStateUnreadableError on Mastra's
910
- // in-memory fallback BEFORE it concludes anything from it, so a degraded
911
- // read never reaches this line. That throw leaves the journal and the
912
- // reservation intact and propagates to alarm(), which classifies it and
913
- // keeps the 60 s recovery cadence until the read heals.
914
- const reconciled = summary
915
- ? await this.#reconcileSuspensionDeadlinesBestEffort(recovery.workflowId, recovery.runId, summary)
916
- : true;
917
- await this.#clearRunOwnerRecovery(!reconciled);
1200
+ async #recoverRunOwner(recovery, ownFrame, ownFailure) {
1201
+ this.#assertRunIdentity(recovery.workflowId, recovery.runId);
1202
+ const runtime = this.#ensureRuntime();
1203
+ if (recovery.startReservation && !runtime.startIdempotency)
1204
+ throw new ExecutionFenceUnreadableError('run start recovery is unresolved');
1205
+ const key = this.#inFlightKey(recovery.workflowId, recovery.runId);
1206
+ const quiescent = () => {
1207
+ const active = this.#startsInFlight.get(key);
1208
+ return (active === undefined ||
1209
+ (active === ownFrame &&
1210
+ ownFrame.unwound &&
1211
+ ownFrame.token === recovery.token));
1212
+ };
1213
+ if (!quiescent() ||
1214
+ runtime.isRunActive(recovery.workflowId, recovery.runId))
1215
+ throw new RunStartPendingError();
1216
+ await this.#assertRunOwnerRecoveryCurrent(recovery);
1217
+ let recovered = null;
1218
+ if (recovery.phase === 'prepared') {
1219
+ recovered = await runtime.recoverStartAttempt(recovery.execution, {
1220
+ attemptToken: recovery.token,
1221
+ isOwnerQuiescent: quiescent,
1222
+ startReservation: recovery.startReservation,
1223
+ expectedTarget: { kind: 'workflow' },
1224
+ });
1225
+ }
1226
+ else if (recovery.phase === 'prepared-unfenced') {
1227
+ const state = this.#matchingRunState(recovery, await runtime.authoritativeStartState(recovery.workflowId, recovery.runId));
1228
+ if (state.kind === 'initial')
1229
+ throw new RunStartPendingError();
1230
+ return this.#finishRunOwner(recovery, state.summary, state);
1231
+ }
1232
+ await this.#assertRunOwnerRecoveryCurrent(recovery);
1233
+ if (recovered) {
1234
+ const summary = recovered.kind === 'ordinary'
1235
+ ? recovered.summary
1236
+ : recovered.transition.summary;
1237
+ if (recovered.kind === 'lifecycle') {
1238
+ // Runtime already strictly settled the single selected recovery observation.
1239
+ await this.runOwnership(this.env).settleReservation(recovery.token, []);
1240
+ const completed = recovered.transition.cleanup.cleanupCompleted
1241
+ ? summary
1242
+ : await this.#completeTerminalEffects(runtime, recovery.workflowId, recovery.runId, recovery.owner, recovered.transition);
1243
+ const reconciled = await this.#reconcileSuspensionDeadlinesBestEffort(recovery.workflowId, recovery.runId, completed);
1244
+ await this.#clearRunOwnerRecovery(recovery, !reconciled);
1245
+ return completed;
1246
+ }
1247
+ await this.runOwnership(this.env).settleReservation(recovery.token, []);
1248
+ const reconciled = await this.#reconcileSuspensionDeadlinesBestEffort(recovery.workflowId, recovery.runId, summary);
1249
+ await this.#clearRunOwnerRecovery(recovery, !reconciled);
1250
+ return summary;
1251
+ }
1252
+ const localZero = () => recovery.phase === 'prepared' &&
1253
+ ownFrame !== undefined &&
1254
+ this.#startsInFlight.get(key) === ownFrame &&
1255
+ ownFrame.unwound &&
1256
+ ownFrame.token === recovery.token &&
1257
+ isDefinitiveInitialAdmissionRefusal(ownFailure, recovery.execution);
1258
+ await this.runOwnership(this.env).settleReservation(recovery.token, [
1259
+ { kind: 'run', resourceId: recovery.runId },
1260
+ ]);
1261
+ if (recovery.phase === 'prepared' && !localZero()) {
1262
+ await this.#rearmRunOwnerRecovery();
1263
+ throw new ExecutionFenceUnreadableError('run start recovery is unresolved');
1264
+ }
1265
+ await this.#assertRunOwnerRecoveryCurrent(recovery);
1266
+ await this.#clearRunOwnerRecovery(recovery, false);
1267
+ return null;
918
1268
  }
919
1269
  #runOwnerRecovery(value) {
920
- if (value === null || typeof value !== 'object') {
921
- throw new Error('stored run owner recovery is malformed');
922
- }
923
- const stored = value;
924
- if (stored.version !== 1 ||
1270
+ const stored = recoveryObject(value);
1271
+ const owner = recoveryObject(stored.owner);
1272
+ if (stored.version !== 2 ||
925
1273
  !isPathSafeId(stored.workflowId) ||
926
1274
  !isPathSafeId(stored.runId) ||
927
- !isPathSafeId(stored.token)) {
1275
+ !isPathSafeId(stored.token) ||
1276
+ !isExecutionPrincipalKind(owner.kind) ||
1277
+ !isExecutionPrincipalId(owner.id))
928
1278
  throw new Error('stored run owner recovery is malformed');
929
- }
930
- return {
931
- version: 1,
1279
+ const rawClaim = stored.startReservation === undefined
1280
+ ? undefined
1281
+ : recoveryObject(stored.startReservation);
1282
+ const claim = rawClaim === undefined
1283
+ ? undefined
1284
+ : captureReservation({
1285
+ ...rawClaim,
1286
+ owner: recoveryObject(rawClaim.owner),
1287
+ binding: recoveryObject(rawClaim.binding),
1288
+ }, 'started');
1289
+ if (claim &&
1290
+ (claim.targetKind !== 'workflow' ||
1291
+ claim.targetId !== stored.workflowId ||
1292
+ claim.runId !== stored.runId ||
1293
+ claim.threadId !== undefined))
1294
+ throw new Error('stored run owner recovery is malformed');
1295
+ const base = {
1296
+ version: 2,
932
1297
  workflowId: stored.workflowId,
933
1298
  runId: stored.runId,
934
1299
  token: stored.token,
1300
+ owner: { kind: owner.kind, id: owner.id },
1301
+ ...(claim ? { startReservation: claim } : {}),
935
1302
  };
1303
+ if (stored.phase === 'preparing' && !Object.hasOwn(stored, 'execution'))
1304
+ return { ...base, phase: 'preparing' };
1305
+ if (stored.phase !== 'prepared' && stored.phase !== 'prepared-unfenced')
1306
+ throw new Error('stored run owner recovery is malformed');
1307
+ const raw = recoveryObject(stored.execution);
1308
+ const execution = stored.phase === 'prepared'
1309
+ ? normalizeD1RunExecutionIdentity(raw)
1310
+ : normalizeRunExecutionIdentity(raw);
1311
+ if (execution.tablePrefix !== raw.tablePrefix ||
1312
+ execution.workflowId !== base.workflowId ||
1313
+ execution.runId !== base.runId)
1314
+ throw new Error('stored run owner recovery is malformed');
1315
+ return stored.phase === 'prepared'
1316
+ ? {
1317
+ ...base,
1318
+ phase: 'prepared',
1319
+ execution: normalizeD1RunExecutionIdentity(execution),
1320
+ }
1321
+ : { ...base, phase: 'prepared-unfenced', execution };
936
1322
  }
937
1323
  async #recoverPendingRunOwner() {
938
1324
  const stored = await this.state?.storage?.get(RUN_OWNER_RECOVERY_KEY);
@@ -988,128 +1374,210 @@ export class DurableObjectRunner {
988
1374
  await this.#armNextAlarm();
989
1375
  });
990
1376
  }
991
- async #route(request) {
1377
+ async #route(request, encodedPrincipal, mutationEpoch) {
992
1378
  const segments = new URL(request.url).pathname.split('/').filter(Boolean);
993
1379
  if (segments[0] !== 'runs')
994
1380
  return json({ error: 'not found' }, 404);
995
1381
  const [, workflowId, runId, action] = segments;
996
1382
  if (request.method === 'POST' && segments.length === 1) {
1383
+ const principal = this.#trustedExecutionPrincipal(encodedPrincipal);
997
1384
  return this.#withOperationLock(async () => {
998
- const principal = this.#trustedExecutionPrincipal(request);
999
1385
  const body = await readJson(request);
1000
- if (!body || typeof body.workflowId !== 'string') {
1386
+ if (body &&
1387
+ [
1388
+ 'mutationEpoch',
1389
+ 'startIdentity',
1390
+ 'agentStart',
1391
+ 'execution',
1392
+ 'tablePrefix',
1393
+ 'startToken',
1394
+ 'attemptToken',
1395
+ 'runOwnerGuard',
1396
+ 'onPreparedStartIdentity',
1397
+ ].some((key) => Object.hasOwn(body, key))) {
1398
+ throw new InvalidRunRequestError('start authority is derived from trusted provenance');
1399
+ }
1400
+ const { workflowId, runId, inputData, initialState, requestContext, scheduleId, dispatchId, deadlineMs, idempotencyKey: rawIdempotencyKey, startReservation: suppliedReservation, } = body ?? {};
1401
+ if (typeof workflowId !== 'string') {
1001
1402
  return json({ error: 'workflowId is required' }, 400);
1002
1403
  }
1003
- // The DO never generates a runId (INV-1): the trusted Worker mints the
1004
- // id and addresses this instance with it. A start without one is a
1005
- // caller bug, not a request for generation.
1006
- if (typeof body.runId !== 'string') {
1404
+ // The DO never generates a runId: the trusted Worker mints the id and
1405
+ // addresses this instance with it. A start without one is a caller bug,
1406
+ // not a request for generation.
1407
+ if (typeof runId !== 'string') {
1007
1408
  return json({ error: 'runId is required (server-minted by the run router)' }, 400);
1008
1409
  }
1009
- const workflowId = body.workflowId;
1010
- const runId = body.runId;
1011
1410
  if (!isPathSafeId(workflowId) || !isPathSafeId(runId)) {
1012
1411
  throw new InvalidRunRequestError('workflowId and runId must be URL-path-safe identifiers');
1013
1412
  }
1014
1413
  this.#assertRunIdentity(workflowId, runId);
1015
- const source = await this.#startSource(principal, workflowId, runId, body.scheduleId, body.dispatchId);
1414
+ // The key rides the internal channel and nothing else. Validated here
1415
+ // rather than trusted because this body is JSON: an unvalidated value
1416
+ // would reach the fence's proof-only comparison and the runtime's
1417
+ // reservation as whatever the parser produced.
1418
+ const idempotencyKey = this.#startIdempotencyKey(rawIdempotencyKey);
1419
+ const startReservation = suppliedReservation === undefined
1420
+ ? undefined
1421
+ : captureReservation(suppliedReservation, 'started');
1422
+ if (startReservation &&
1423
+ (startReservation.key !== idempotencyKey ||
1424
+ startReservation.runId !== runId ||
1425
+ startReservation.targetKind !== 'workflow' ||
1426
+ startReservation.targetId !== workflowId ||
1427
+ startReservation.threadId !== undefined ||
1428
+ startReservation.owner.kind !== principal.kind ||
1429
+ startReservation.owner.id !== principal.id ||
1430
+ !this.#ensureRuntime().startIdempotency))
1431
+ throw new InvalidRunRequestError('start reservation does not match the trusted start');
1432
+ const startIdentity = normalizeStartIdentity({
1433
+ owner: { kind: principal.kind, id: principal.id },
1434
+ target: { kind: 'workflow', id: workflowId },
1435
+ });
1436
+ // Only this local preflight can release the captured claim. Admission
1437
+ // and proof binding belong to Runtime after durable preparation.
1438
+ try {
1439
+ const startFence = await this.#readExecutionFence();
1440
+ if (!admitsRunStart(startFence, idempotencyKey))
1441
+ throw new ExecutionFencedError(startFence.state, 'run start');
1442
+ }
1443
+ catch (error) {
1444
+ if (startReservation) {
1445
+ try {
1446
+ await this.#ensureRuntime().startIdempotency?.releaseReservation(startReservation);
1447
+ }
1448
+ catch (releaseError) {
1449
+ console.error('start reservation preflight release failed', releaseError);
1450
+ }
1451
+ }
1452
+ throw error;
1453
+ }
1454
+ const source = await this.#startSource(principal, workflowId, runId, scheduleId, dispatchId);
1455
+ const rawOwner = source.owner;
1456
+ const owner = Object.freeze({ kind: rawOwner.kind, id: rawOwner.id });
1457
+ const target = source.target;
1458
+ const resolvedInput = target ? target.inputData : inputData;
1459
+ const resolvedState = target ? target.initialState : initialState;
1460
+ const storedRequestContext = target
1461
+ ? target.requestContext
1462
+ : requestContext;
1016
1463
  const runtime = this.#ensureRuntime();
1017
1464
  await this.#recoverPendingRunOwner();
1018
- // Stays on status(), and NOT because failing open would be safer: the
1019
- // dangerous shape here is a row miss with no in-memory Run, which
1020
- // carries no marker at all, so authoritativeStatus could not tell it
1021
- // from an absent run either. The recovery above is what covers the
1022
- // interrupted-start case, and it fails closed on an unreadable read.
1023
1465
  const existing = await runtime.status(workflowId, runId);
1024
1466
  if (existing) {
1025
1467
  const registered = await this.runOwnership(this.env).owner('run', runId);
1026
1468
  if (!registered ||
1027
- registered.kind !== source.owner.kind ||
1028
- registered.id !== source.owner.id) {
1469
+ registered.kind !== owner.kind ||
1470
+ registered.id !== owner.id) {
1029
1471
  throw new Error(`existing run '${runId}' has no matching committed owner`);
1030
1472
  }
1031
1473
  throw new RunAlreadyExistsError(workflowId, runId, existing.status);
1032
1474
  }
1033
- const recovery = {
1034
- version: 1,
1475
+ let recovery = {
1476
+ version: 2,
1477
+ phase: 'preparing',
1035
1478
  workflowId,
1036
1479
  runId,
1037
1480
  token: crypto.randomUUID(),
1481
+ owner,
1482
+ ...(startReservation ? { startReservation } : {}),
1038
1483
  };
1039
- await this.#armRunOwnerRecovery(recovery);
1484
+ const frame = { token: recovery.token, unwound: false };
1485
+ const frameKey = this.#inFlightKey(workflowId, runId);
1486
+ this.#startsInFlight.set(frameKey, frame);
1040
1487
  try {
1041
- await this.#reserveRunOwner(runId, source.owner, recovery.token);
1488
+ await this.#armRunOwnerRecovery(recovery);
1489
+ await this.#reserveRunOwner(runId, owner, recovery.token);
1042
1490
  let summary;
1043
1491
  try {
1044
1492
  summary = await runtime.start(workflowId, {
1045
1493
  runId,
1046
- inputData: source.target
1047
- ? source.target.inputData
1048
- : body.inputData,
1049
- initialState: source.target
1050
- ? source.target.initialState
1051
- : body.initialState,
1052
- ...(source.target?.requestContext !== undefined
1053
- ? { storedRequestContext: source.target.requestContext }
1494
+ inputData: resolvedInput,
1495
+ initialState: resolvedState,
1496
+ ...(storedRequestContext !== undefined
1497
+ ? { storedRequestContext }
1054
1498
  : {}),
1055
1499
  requestedBy: principal.id,
1056
1500
  requestedByKind: principal.kind,
1057
1501
  attemptToken: recovery.token,
1058
- ...(body.deadlineMs === undefined
1502
+ ...(mutationEpoch === undefined ? {} : { mutationEpoch }),
1503
+ startIdentity,
1504
+ startReservation,
1505
+ runOwnerGuard: { owner, reservationToken: recovery.token },
1506
+ onPreparedStartIdentity: async (execution) => {
1507
+ recovery = await this.#prepareRunOwner(recovery, execution);
1508
+ },
1509
+ ...(idempotencyKey === undefined ? {} : { idempotencyKey }),
1510
+ ...(deadlineMs === undefined
1059
1511
  ? {}
1060
- : { deadlineMs: body.deadlineMs }),
1512
+ : { deadlineMs: deadlineMs }),
1061
1513
  });
1062
1514
  }
1063
- catch (error) {
1064
- let persisted;
1065
- try {
1066
- persisted = await runtime.recoverStartAttempt(workflowId, runId, recovery.token);
1067
- }
1068
- catch (recoverError) {
1069
- // Logged, never swallowed silently: this read is the only thing
1070
- // that could tell an interrupted start apart from a failed one,
1071
- // and its own failure is the reason the journal is being left
1072
- // armed for the alarm to retry.
1073
- console.error('interrupted start could not read authoritative state', recoverError);
1074
- await this.#rearmRunOwnerRecovery();
1075
- throw error;
1076
- }
1077
- if (persisted) {
1078
- const reconciled = await this.#reconcileSuspensionDeadlinesBestEffort(workflowId, runId, persisted);
1079
- await this.#settleRunOwnerBestEffort(recovery, false, !reconciled);
1080
- return json(persisted);
1081
- }
1082
- await this.#settleRunOwnerBestEffort(recovery, true);
1083
- throw error;
1515
+ finally {
1516
+ frame.unwound = true;
1084
1517
  }
1085
- // Reconcile BEFORE settling, never after: settling clears the
1086
- // recovery journal, and clearing it re-arms from storage — which, on
1087
- // a run whose FIRST deadline write has not happened yet, finds no
1088
- // record and no journal and deletes the alarm. With the journal
1089
- // still stored the write's own arm takes the min of the two due
1090
- // times, so no interleaving leaves this object without a wake.
1091
- const reconciled = await this.#reconcileSuspensionDeadlinesBestEffort(workflowId, runId, summary);
1092
- await this.#settleRunOwnerBestEffort(recovery, false, !reconciled);
1093
- // DL-018: the authoritative RunSummary is the run-progress frame; push it
1094
- // to any subscribed run-channel socket at this lifecycle boundary.
1518
+ summary = await this.#finishRunOwner(recovery, summary);
1095
1519
  this.#broadcastRunSummary(summary);
1096
1520
  return json(summary);
1097
1521
  }
1098
1522
  catch (error) {
1099
- const stored = await this.state?.storage?.get(RUN_OWNER_RECOVERY_KEY);
1100
- if (stored !== undefined) {
1523
+ frame.unwound = true;
1524
+ try {
1525
+ const stored = await this.state?.storage?.get(RUN_OWNER_RECOVERY_KEY);
1526
+ if (stored !== undefined) {
1527
+ const current = this.#runOwnerRecovery(stored);
1528
+ if (!sameRunRecovery(current, recovery))
1529
+ throw new Error('run owner recovery changed');
1530
+ const recovered = await this.#recoverRunOwner(current, frame, error);
1531
+ if (recovered)
1532
+ return json(recovered);
1533
+ }
1534
+ }
1535
+ catch (recoveryError) {
1536
+ console.error('interrupted start recovery failed', recoveryError);
1101
1537
  await this.#rearmRunOwnerRecovery();
1102
1538
  }
1103
1539
  throw error;
1104
1540
  }
1541
+ finally {
1542
+ if (this.#startsInFlight.get(frameKey) === frame)
1543
+ this.#startsInFlight.delete(frameKey);
1544
+ }
1105
1545
  });
1106
1546
  }
1547
+ // The liveness probe, answered OUTSIDE #withOperationLock on purpose: the
1548
+ // start it is asking about holds that lock for the whole first leg, so a
1549
+ // probe that queued behind it would block for exactly as long as the run it
1550
+ // was trying to describe — and time out reporting nothing.
1551
+ if (request.method === 'GET' &&
1552
+ segments.length === 4 &&
1553
+ action === 'start-liveness' &&
1554
+ workflowId &&
1555
+ runId) {
1556
+ this.#assertRunIdentity(workflowId, runId);
1557
+ return json({ live: this.#isStartLive(workflowId, runId) });
1558
+ }
1107
1559
  if (request.method === 'GET' &&
1108
1560
  segments.length === 3 &&
1109
1561
  workflowId &&
1110
1562
  runId) {
1111
1563
  this.#assertRunIdentity(workflowId, runId);
1112
1564
  const runtime = this.#ensureRuntime();
1565
+ if (new URL(request.url).searchParams.get('replay') === '1') {
1566
+ const state = await runtime.authoritativeStartState(workflowId, runId);
1567
+ if (!state)
1568
+ return json({ error: 'run not found' }, 404);
1569
+ const identity = state.provenance.startIdentity;
1570
+ if (identity?.target.kind !== 'workflow' ||
1571
+ identity.target.id !== workflowId)
1572
+ throw new RunStateUnreadableError(workflowId, runId);
1573
+ const execution = normalizeStartExecutionIdentity({
1574
+ ...state.execution,
1575
+ ...identity,
1576
+ });
1577
+ return json(state.kind === 'initial'
1578
+ ? { kind: 'initial', execution }
1579
+ : { kind: 'result', execution, value: state.summary });
1580
+ }
1113
1581
  const summary = await runtime.status(workflowId, runId);
1114
1582
  if (!summary)
1115
1583
  return json({ error: 'run not found' }, 404);
@@ -1147,7 +1615,7 @@ export class DurableObjectRunner {
1147
1615
  }, 426);
1148
1616
  }
1149
1617
  // The trusted Worker already verified the run ticket and routed by
1150
- // ticket.runId to idFromName; re-bind to this instance's identity (INV-1)
1618
+ // ticket.runId to idFromName; re-bind to this instance's identity
1151
1619
  // before accepting so a mis-routed upgrade is refused.
1152
1620
  this.#assertRunIdentity(workflowId, runId);
1153
1621
  const runtime = this.#ensureRuntime();
@@ -1157,7 +1625,7 @@ export class DurableObjectRunner {
1157
1625
  const { 0: client, 1: server } = newWebSocketPair();
1158
1626
  state.acceptWebSocket(server);
1159
1627
  // On-connect snapshot: seed the new subscriber with the current
1160
- // authoritative summary (DL-018) so it need not wait for the next
1628
+ // authoritative summary so it need not wait for the next
1161
1629
  // lifecycle transition. Nothing to send if the run is not yet queryable.
1162
1630
  safeSend(server, runFrame(snapshot));
1163
1631
  return new Response(null, {
@@ -1177,6 +1645,11 @@ export class DurableObjectRunner {
1177
1645
  const resumeData = this.#resumeData(body.resumeData);
1178
1646
  return this.#withOperationLock(async () => {
1179
1647
  const runtime = this.#ensureRuntime();
1648
+ // Refused here as well as inside resume(), so a fenced deployment
1649
+ // answers before it takes the per-run lock. A drain still admits
1650
+ // resumes — the suspended runs it is draining are waiting for exactly
1651
+ // these — and proof-only admits its one nominated run.
1652
+ await runtime.assertExistingRunAllowed(workflowId, runId);
1180
1653
  const summary = await runtime.resume(workflowId, runId, {
1181
1654
  step: body.step,
1182
1655
  resumeData,
@@ -1187,7 +1660,7 @@ export class DurableObjectRunner {
1187
1660
  : { deadlineMs: body.deadlineMs }),
1188
1661
  });
1189
1662
  await this.#reconcileSuspensionDeadlinesBestEffort(workflowId, runId, summary);
1190
- // DL-018: broadcast the post-resume authoritative summary.
1663
+ // Broadcast the post-resume authoritative summary.
1191
1664
  this.#broadcastRunSummary(summary);
1192
1665
  return json(summary);
1193
1666
  });
@@ -1198,7 +1671,7 @@ export class DurableObjectRunner {
1198
1671
  workflowId &&
1199
1672
  runId) {
1200
1673
  this.#assertRunIdentity(workflowId, runId);
1201
- const principal = this.#trustedExecutionPrincipal(request);
1674
+ const principal = this.#trustedExecutionPrincipal(encodedPrincipal);
1202
1675
  const runtime = this.#ensureRuntime();
1203
1676
  const preflightOwner = await this.runOwnership(this.env).owner('run', runId);
1204
1677
  if (action === 'terminate') {
@@ -1233,7 +1706,7 @@ export class DurableObjectRunner {
1233
1706
  workflowId &&
1234
1707
  runId) {
1235
1708
  this.#assertRunIdentity(workflowId, runId);
1236
- const principal = this.#trustedExecutionPrincipal(request);
1709
+ const principal = this.#trustedExecutionPrincipal(encodedPrincipal);
1237
1710
  const body = (await readJson(request)) ?? {};
1238
1711
  const cas = {
1239
1712
  expectedRevision: body.expectedRevision,