@proofoftech/flowsafe 0.20.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 (233) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/README.md +55 -8
  3. package/deployment-identity-protocol.d.mts +28 -3
  4. package/deployment-identity-protocol.mjs +275 -21
  5. package/dist/agent-host/router.d.ts.map +1 -1
  6. package/dist/agent-host/router.js +11 -2
  7. package/dist/agent-host/router.js.map +1 -1
  8. package/dist/agent-host/thread-host.d.ts +3 -1
  9. package/dist/agent-host/thread-host.d.ts.map +1 -1
  10. package/dist/agent-host/thread-host.js +837 -332
  11. package/dist/agent-host/thread-host.js.map +1 -1
  12. package/dist/agent-host/thread-topology.d.ts +8 -0
  13. package/dist/agent-host/thread-topology.d.ts.map +1 -1
  14. package/dist/agent-host/thread-topology.js +239 -62
  15. package/dist/agent-host/thread-topology.js.map +1 -1
  16. package/dist/agent-runner/durable-agent-runner.d.ts +90 -6
  17. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  18. package/dist/agent-runner/durable-agent-runner.js +371 -29
  19. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  20. package/dist/agent-runner/index.d.ts +1 -1
  21. package/dist/agent-runner/index.d.ts.map +1 -1
  22. package/dist/agent-runner/index.js.map +1 -1
  23. package/dist/approval-api/actor-context.d.ts +4 -0
  24. package/dist/approval-api/actor-context.d.ts.map +1 -1
  25. package/dist/approval-api/actor-context.js +53 -5
  26. package/dist/approval-api/actor-context.js.map +1 -1
  27. package/dist/approval-api/principal.d.ts +1 -1
  28. package/dist/approval-api/principal.js +1 -1
  29. package/dist/approval-api/retention.d.ts +1 -2
  30. package/dist/approval-api/retention.d.ts.map +1 -1
  31. package/dist/approval-api/retention.js.map +1 -1
  32. package/dist/approval-api/service.d.ts +10 -14
  33. package/dist/approval-api/service.d.ts.map +1 -1
  34. package/dist/approval-api/service.js +49 -22
  35. package/dist/approval-api/service.js.map +1 -1
  36. package/dist/audit-export/index.d.ts +2 -2
  37. package/dist/audit-export/index.js +2 -2
  38. package/dist/background-tasks/d1-storage.d.ts +4 -3
  39. package/dist/background-tasks/d1-storage.d.ts.map +1 -1
  40. package/dist/background-tasks/d1-storage.js +7 -13
  41. package/dist/background-tasks/d1-storage.js.map +1 -1
  42. package/dist/do-runner/constants.d.ts +3 -0
  43. package/dist/do-runner/constants.d.ts.map +1 -0
  44. package/dist/do-runner/constants.js +3 -0
  45. package/dist/do-runner/constants.js.map +1 -0
  46. package/dist/do-runner/d1-storage.d.ts +31 -157
  47. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  48. package/dist/do-runner/d1-storage.js +933 -402
  49. package/dist/do-runner/d1-storage.js.map +1 -1
  50. package/dist/do-runner/durable-object.d.ts.map +1 -1
  51. package/dist/do-runner/durable-object.js +462 -175
  52. package/dist/do-runner/durable-object.js.map +1 -1
  53. package/dist/do-runner/execution-admission.d.ts +114 -0
  54. package/dist/do-runner/execution-admission.d.ts.map +1 -0
  55. package/dist/do-runner/execution-admission.js +206 -0
  56. package/dist/do-runner/execution-admission.js.map +1 -0
  57. package/dist/do-runner/execution-context.d.ts.map +1 -1
  58. package/dist/do-runner/execution-context.js +1 -0
  59. package/dist/do-runner/execution-context.js.map +1 -1
  60. package/dist/do-runner/execution-fence.d.ts +74 -30
  61. package/dist/do-runner/execution-fence.d.ts.map +1 -1
  62. package/dist/do-runner/execution-fence.js +684 -120
  63. package/dist/do-runner/execution-fence.js.map +1 -1
  64. package/dist/do-runner/fenced-workflow-capability.d.ts +64 -0
  65. package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -0
  66. package/dist/do-runner/fenced-workflow-capability.js +3 -0
  67. package/dist/do-runner/fenced-workflow-capability.js.map +1 -0
  68. package/dist/do-runner/fenced-workflows-d1.d.ts +15 -0
  69. package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -0
  70. package/dist/do-runner/fenced-workflows-d1.js +894 -0
  71. package/dist/do-runner/fenced-workflows-d1.js.map +1 -0
  72. package/dist/do-runner/index.d.ts +13 -8
  73. package/dist/do-runner/index.d.ts.map +1 -1
  74. package/dist/do-runner/index.js +6 -2
  75. package/dist/do-runner/index.js.map +1 -1
  76. package/dist/do-runner/initial-admission-refusal.d.ts +7 -0
  77. package/dist/do-runner/initial-admission-refusal.d.ts.map +1 -0
  78. package/dist/do-runner/initial-admission-refusal.js +41 -0
  79. package/dist/do-runner/initial-admission-refusal.js.map +1 -0
  80. package/dist/do-runner/inventory.d.ts +2 -1
  81. package/dist/do-runner/inventory.d.ts.map +1 -1
  82. package/dist/do-runner/inventory.js +28 -39
  83. package/dist/do-runner/inventory.js.map +1 -1
  84. package/dist/do-runner/notification-predicate.d.ts +7 -7
  85. package/dist/do-runner/notification-predicate.d.ts.map +1 -1
  86. package/dist/do-runner/notification-predicate.js +134 -7
  87. package/dist/do-runner/notification-predicate.js.map +1 -1
  88. package/dist/do-runner/run-lifecycle.d.ts +20 -1
  89. package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
  90. package/dist/do-runner/run-lifecycle.js +67 -13
  91. package/dist/do-runner/run-lifecycle.js.map +1 -1
  92. package/dist/do-runner/run-provenance.d.ts +38 -0
  93. package/dist/do-runner/run-provenance.d.ts.map +1 -0
  94. package/dist/do-runner/run-provenance.js +152 -0
  95. package/dist/do-runner/run-provenance.js.map +1 -0
  96. package/dist/do-runner/run-storage-tables.d.ts +2 -0
  97. package/dist/do-runner/run-storage-tables.d.ts.map +1 -0
  98. package/dist/do-runner/run-storage-tables.js +4 -0
  99. package/dist/do-runner/run-storage-tables.js.map +1 -0
  100. package/dist/do-runner/run-terminal-state.d.ts +29 -0
  101. package/dist/do-runner/run-terminal-state.d.ts.map +1 -0
  102. package/dist/do-runner/run-terminal-state.js +105 -0
  103. package/dist/do-runner/run-terminal-state.js.map +1 -0
  104. package/dist/do-runner/runtime.d.ts +108 -46
  105. package/dist/do-runner/runtime.d.ts.map +1 -1
  106. package/dist/do-runner/runtime.js +927 -438
  107. package/dist/do-runner/runtime.js.map +1 -1
  108. package/dist/do-runner/start-idempotency.d.ts +35 -258
  109. package/dist/do-runner/start-idempotency.d.ts.map +1 -1
  110. package/dist/do-runner/start-idempotency.js +602 -494
  111. package/dist/do-runner/start-idempotency.js.map +1 -1
  112. package/dist/do-runner/start-reservation-contract.d.ts +103 -0
  113. package/dist/do-runner/start-reservation-contract.d.ts.map +1 -0
  114. package/dist/do-runner/start-reservation-contract.js +338 -0
  115. package/dist/do-runner/start-reservation-contract.js.map +1 -0
  116. package/dist/do-runner/suspension-deadline.d.ts +4 -11
  117. package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
  118. package/dist/do-runner/suspension-deadline.js +8 -12
  119. package/dist/do-runner/suspension-deadline.js.map +1 -1
  120. package/dist/do-runner/table-prefix.d.ts.map +1 -1
  121. package/dist/do-runner/table-prefix.js +2 -1
  122. package/dist/do-runner/table-prefix.js.map +1 -1
  123. package/dist/do-runner/testing.d.ts +3 -0
  124. package/dist/do-runner/testing.d.ts.map +1 -0
  125. package/dist/do-runner/testing.js +3 -0
  126. package/dist/do-runner/testing.js.map +1 -0
  127. package/dist/do-runner/thread-do.d.ts +2 -1
  128. package/dist/do-runner/thread-do.d.ts.map +1 -1
  129. package/dist/do-runner/thread-do.js +14 -10
  130. package/dist/do-runner/thread-do.js.map +1 -1
  131. package/dist/do-runner/workflow-snapshot-row.d.ts +49 -0
  132. package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -0
  133. package/dist/do-runner/workflow-snapshot-row.js +97 -0
  134. package/dist/do-runner/workflow-snapshot-row.js.map +1 -0
  135. package/dist/goals/objective-routes.d.ts +1 -5
  136. package/dist/goals/objective-routes.d.ts.map +1 -1
  137. package/dist/goals/objective-routes.js +32 -53
  138. package/dist/goals/objective-routes.js.map +1 -1
  139. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  140. package/dist/host-kit/approval-bridge.js +10 -7
  141. package/dist/host-kit/approval-bridge.js.map +1 -1
  142. package/dist/host-kit/do-response.d.ts +16 -0
  143. package/dist/host-kit/do-response.d.ts.map +1 -1
  144. package/dist/host-kit/do-response.js +181 -0
  145. package/dist/host-kit/do-response.js.map +1 -1
  146. package/dist/host-kit/do-run-topology.d.ts +2 -14
  147. package/dist/host-kit/do-run-topology.d.ts.map +1 -1
  148. package/dist/host-kit/do-run-topology.js +31 -24
  149. package/dist/host-kit/do-run-topology.js.map +1 -1
  150. package/dist/host-kit/env-vars.d.ts.map +1 -1
  151. package/dist/host-kit/env-vars.js +5 -6
  152. package/dist/host-kit/env-vars.js.map +1 -1
  153. package/dist/host-kit/flowsafe-worker.d.ts +38 -6
  154. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  155. package/dist/host-kit/flowsafe-worker.js +110 -93
  156. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  157. package/dist/host-kit/host-approval-service.d.ts +4 -14
  158. package/dist/host-kit/host-approval-service.d.ts.map +1 -1
  159. package/dist/host-kit/host-approval-service.js +23 -40
  160. package/dist/host-kit/host-approval-service.js.map +1 -1
  161. package/dist/host-kit/index.d.ts +7 -1
  162. package/dist/host-kit/index.d.ts.map +1 -1
  163. package/dist/host-kit/index.js +4 -0
  164. package/dist/host-kit/index.js.map +1 -1
  165. package/dist/host-kit/run-route-error.d.ts +3 -17
  166. package/dist/host-kit/run-route-error.d.ts.map +1 -1
  167. package/dist/host-kit/run-route-error.js +4 -24
  168. package/dist/host-kit/run-route-error.js.map +1 -1
  169. package/dist/host-kit/run-router.d.ts +6 -2
  170. package/dist/host-kit/run-router.d.ts.map +1 -1
  171. package/dist/host-kit/run-router.js +93 -80
  172. package/dist/host-kit/run-router.js.map +1 -1
  173. package/dist/host-kit/thread-topology.d.ts +1 -1
  174. package/dist/host-kit/thread-topology.d.ts.map +1 -1
  175. package/dist/host-kit/thread-topology.js +7 -3
  176. package/dist/host-kit/thread-topology.js.map +1 -1
  177. package/dist/internal-error-response.d.ts.map +1 -1
  178. package/dist/internal-error-response.js +16 -6
  179. package/dist/internal-error-response.js.map +1 -1
  180. package/dist/schedules/index.d.ts +1 -0
  181. package/dist/schedules/index.d.ts.map +1 -1
  182. package/dist/schedules/index.js +1 -7
  183. package/dist/schedules/index.js.map +1 -1
  184. package/dist/schedules/mutation-contract.d.ts +38 -0
  185. package/dist/schedules/mutation-contract.d.ts.map +1 -0
  186. package/dist/schedules/mutation-contract.js +21 -0
  187. package/dist/schedules/mutation-contract.js.map +1 -0
  188. package/dist/schedules/router.d.ts +11 -19
  189. package/dist/schedules/router.d.ts.map +1 -1
  190. package/dist/schedules/router.js +130 -49
  191. package/dist/schedules/router.js.map +1 -1
  192. package/dist/schedules/schedules-d1.d.ts +11 -5
  193. package/dist/schedules/schedules-d1.d.ts.map +1 -1
  194. package/dist/schedules/schedules-d1.js +570 -143
  195. package/dist/schedules/schedules-d1.js.map +1 -1
  196. package/dist/schedules/storage.d.ts +0 -7
  197. package/dist/schedules/storage.d.ts.map +1 -1
  198. package/dist/schedules/storage.js +0 -27
  199. package/dist/schedules/storage.js.map +1 -1
  200. package/dist/schedules/tick.d.ts.map +1 -1
  201. package/dist/schedules/tick.js +7 -1
  202. package/dist/schedules/tick.js.map +1 -1
  203. package/dist/signal-providers/webhook-route.d.ts +1 -1
  204. package/dist/signal-providers/webhook-route.d.ts.map +1 -1
  205. package/dist/signal-providers/webhook-route.js +99 -109
  206. package/dist/signal-providers/webhook-route.js.map +1 -1
  207. package/dist/signals/d1-shared.d.ts +11 -8
  208. package/dist/signals/d1-shared.d.ts.map +1 -1
  209. package/dist/signals/d1-shared.js +1 -6
  210. package/dist/signals/d1-shared.js.map +1 -1
  211. package/dist/signals/index.d.ts +1 -1
  212. package/dist/signals/index.d.ts.map +1 -1
  213. package/dist/signals/index.js +1 -1
  214. package/dist/signals/index.js.map +1 -1
  215. package/dist/signals/notification-dispatch.d.ts +96 -5
  216. package/dist/signals/notification-dispatch.d.ts.map +1 -1
  217. package/dist/signals/notification-dispatch.js +418 -53
  218. package/dist/signals/notification-dispatch.js.map +1 -1
  219. package/dist/signals/notifications-d1.d.ts +6 -1
  220. package/dist/signals/notifications-d1.d.ts.map +1 -1
  221. package/dist/signals/notifications-d1.js +215 -10
  222. package/dist/signals/notifications-d1.js.map +1 -1
  223. package/dist/signals/router.d.ts +6 -4
  224. package/dist/signals/router.d.ts.map +1 -1
  225. package/dist/signals/router.js +49 -84
  226. package/dist/signals/router.js.map +1 -1
  227. package/dist/signals/thread-do-routes.d.ts +2 -0
  228. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  229. package/dist/signals/thread-do-routes.js +252 -73
  230. package/dist/signals/thread-do-routes.js.map +1 -1
  231. package/package.json +6 -3
  232. package/patches/@mastra__core@1.53.0.patch +54 -0
  233. package/scripts/seed-deployment-identity.mjs +12 -5
@@ -15,11 +15,16 @@ import { decodeExecutionPrincipal, isExecutionPrincipalId, isExecutionPrincipalK
15
15
  import { newWebSocketPair, safeSend } from './cf-types.js';
16
16
  import { isDatabaseBinding, verifyDurableObjectDeploymentIdentity, verifyDurableObjectDeploymentRequest, } from './deployment-identity.js';
17
17
  import { DoStatusError, doErrorResponse } from './do-error-response.js';
18
- import { admitsExistingRun, admitsRunStart, ExecutionFencedError, isExecutionFenceRefusal, readExecutionFence, } from './execution-fence.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';
19
20
  import { EXECUTION_PRINCIPAL_HEADER } from './execution-principal-header.js';
21
+ import { isDefinitiveInitialAdmissionRefusal } from './initial-admission-refusal.js';
20
22
  import { isPathSafeId } from './path-safe-id.js';
23
+ import { lifecycleFromRequestContext, terminalCleanupFor, } from './run-lifecycle.js';
24
+ import { isTerminalRunStatus } from './run-terminal-state.js';
21
25
  import { InvalidRunRequestError, RunAlreadyExistsError, RunnerRuntime, RunStateUnreadableError, UnknownRunError, } from './runtime.js';
22
26
  import { resolveScheduleStartOwner, } from './schedule-source.js';
27
+ import { captureReservation, sameReservationIdentity, } from './start-reservation-contract.js';
23
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';
24
29
  const RUN_OWNER_RECOVERY_KEY = 'flowsafe:run-owner-recovery:v1';
25
30
  export const RUN_OWNER_RECOVERY_DELAY_MS = 60_000;
@@ -54,6 +59,39 @@ const SUSPENSION_DEADLINE_UNREADABLE_LIMIT_MS = 86_400_000;
54
59
  // deferred to the watchdog — up to a minute late, and only while the fault
55
60
  // lasts.
56
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
+ }
57
95
  class DurableObjectRunIdentityError extends DoStatusError {
58
96
  status = 403;
59
97
  }
@@ -110,16 +148,8 @@ export class DurableObjectRunner {
110
148
  #operationTail = Promise.resolve();
111
149
  /** `step\0reason` of every suspension deadline this object has reported. */
112
150
  #reportedSuspensionRejections = new Set();
113
- /**
114
- * `workflowId:runId` of every start this object is currently executing — the
115
- * liveness half of the idempotent-start replay decision.
116
- *
117
- * A SET rather than a stored key, because liveness is not durable state: the
118
- * question is "is code running for this run right now", and the honest answer
119
- * after an eviction is no. Anything written to storage would survive the
120
- * isolate that wrote it and keep saying yes.
121
- */
122
- #startsInFlight = new Set();
151
+ /** Persisted claims outlive an isolate and cannot establish run liveness. */
152
+ #startsInFlight = new Map();
123
153
  constructor(state, env) {
124
154
  this.state = state;
125
155
  this.env = env;
@@ -134,13 +164,16 @@ export class DurableObjectRunner {
134
164
  }
135
165
  async fetch(request) {
136
166
  try {
167
+ const encodedPrincipal = request.headers.get(EXECUTION_PRINCIPAL_HEADER);
168
+ const encodedEpoch = request.headers.get(MUTATION_EPOCH_HEADER);
137
169
  // Deployment-identity check BEFORE any routing or storage work: under
138
170
  // workerd this instance refuses to serve until its env tag matches the
139
171
  // database sentinel (fail closed on a mis-provisioned binding); off
140
172
  // workerd (node tests, state undefined) it is a no-op. Memoized after
141
173
  // the first success, so steady-state requests pay nothing.
142
174
  await verifyDurableObjectDeploymentRequest(request, this.state, this.env);
143
- return await this.#route(request);
175
+ const mutationEpoch = mutationEpochFromHeader(encodedEpoch);
176
+ return await this.#route(request, encodedPrincipal, mutationEpoch);
144
177
  }
145
178
  catch (error) {
146
179
  return doErrorResponse(error);
@@ -230,14 +263,7 @@ export class DurableObjectRunner {
230
263
  }
231
264
  return value;
232
265
  }
233
- /**
234
- * The reserved timeout envelope is minted by the alarm and by nothing else.
235
- * A caller allowed to resume could otherwise drive a step's timeout branch
236
- * while provenance still names them as the requester, which would make the
237
- * one contract this feature sells — a timeout resume is distinguishable from
238
- * a real signal — untrue. The KEY is refused, not just a well-formed
239
- * envelope, so a step that reads the key directly cannot be fooled either.
240
- */
266
+ /** Caller-supplied timeout data would select the timeout branch with caller provenance. */
241
267
  #resumeData(value) {
242
268
  if (value !== null &&
243
269
  typeof value === 'object' &&
@@ -246,15 +272,72 @@ export class DurableObjectRunner {
246
272
  }
247
273
  return value;
248
274
  }
249
- #trustedExecutionPrincipal(request) {
250
- const encoded = request.headers.get(EXECUTION_PRINCIPAL_HEADER);
275
+ #trustedExecutionPrincipal(encoded) {
251
276
  const principal = encoded ? decodeExecutionPrincipal(encoded) : undefined;
252
277
  if (!principal) {
253
278
  throw new DurableObjectRunIdentityError('run request carries no valid trusted execution principal');
254
279
  }
255
280
  return principal;
256
281
  }
257
- 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();
258
341
  if (result.cleanup.cleanupCompleted)
259
342
  return result.summary;
260
343
  const hooks = this.runLifecycle(this.env);
@@ -262,24 +345,35 @@ export class DurableObjectRunner {
262
345
  throw new Error('run termination requires lifecycle cleanup hooks');
263
346
  }
264
347
  await hooks.abandonApprovals(workflowId, runId, result.cleanup.status);
348
+ if (validate)
349
+ await validate();
265
350
  if (result.cleanup.scheduleDispatch) {
266
351
  if (!hooks?.discardScheduleDispatch) {
267
352
  throw new Error('scheduled run termination requires a dispatch-settlement hook');
268
353
  }
269
354
  await hooks.discardScheduleDispatch(result.cleanup.scheduleDispatch.scheduleId, result.cleanup.scheduleDispatch.dispatchId, runId);
355
+ if (validate)
356
+ await validate();
270
357
  }
271
358
  const ownership = this.runOwnership(this.env);
272
359
  if (!ownership.release) {
273
360
  throw new Error('run termination requires ownership release support');
274
361
  }
275
362
  const released = await ownership.release('run', runId, owner);
363
+ if (validate)
364
+ await validate();
276
365
  if (!released) {
277
366
  const current = await ownership.owner('run', runId);
367
+ if (validate)
368
+ await validate();
278
369
  if (current) {
279
370
  throw new Error(`run '${runId}' ownership could not be released`);
280
371
  }
281
372
  }
282
- 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;
283
377
  }
284
378
  async #startSource(principal, workflowId, runId, scheduleId, dispatchId) {
285
379
  if (scheduleId === undefined) {
@@ -388,6 +482,14 @@ export class DurableObjectRunner {
388
482
  }
389
483
  await storage.setAlarm(Date.now() + RUN_OWNER_RECOVERY_DELAY_MS);
390
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
+ */
391
493
  async #armRunOwnerRecovery(recovery) {
392
494
  const storage = this.state?.storage;
393
495
  if (!storage)
@@ -400,17 +502,21 @@ export class DurableObjectRunner {
400
502
  await this.#armNextAlarm(Date.now() + RUN_OWNER_RECOVERY_DELAY_MS);
401
503
  await storage.put(RUN_OWNER_RECOVERY_KEY, recovery);
402
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
+ }
403
511
  /**
404
- * `keepWake` is set by a caller whose reconciliation failed with something
405
- * to arm: the retry wake it left is the only thing that will re-derive that
406
- * deadline, and re-arming from storage here would find no record and no
407
- * journal and DELETE it. Keeping the recovery cadence instead costs one
408
- * 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.
409
514
  */
410
- async #clearRunOwnerRecovery(keepWake) {
515
+ async #clearRunOwnerRecovery(recovery, keepWake) {
411
516
  const storage = this.state?.storage;
412
517
  if (!storage)
413
518
  return;
519
+ await this.#assertRunOwnerRecoveryCurrent(recovery);
414
520
  await storage.delete(RUN_OWNER_RECOVERY_KEY);
415
521
  if (keepWake) {
416
522
  await this.#armAlarmWatchdog();
@@ -418,28 +524,82 @@ export class DurableObjectRunner {
418
524
  }
419
525
  await this.#armNextAlarm();
420
526
  }
421
- 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');
422
547
  try {
423
- await this.#clearRunOwnerRecovery(keepWake);
548
+ await storage.put(RUN_OWNER_RECOVERY_KEY, prepared);
424
549
  }
425
550
  catch (error) {
426
- 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;
427
555
  }
556
+ return prepared;
428
557
  }
429
- async #settleRunOwnerBestEffort(recovery, release, keepWake = false) {
430
- try {
431
- await this.runOwnership(this.env).settleReservation(recovery.token, release ? [{ kind: 'run', resourceId: recovery.runId }] : []);
432
- await this.#clearRunOwnerRecoveryBestEffort(keepWake);
433
- }
434
- catch (error) {
435
- console.error('run owner recovery settlement failed', error);
436
- try {
437
- await this.#rearmRunOwnerRecovery();
438
- }
439
- catch (alarmError) {
440
- console.error('run owner recovery rearm failed', alarmError);
441
- }
442
- }
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;
443
603
  }
444
604
  async #rearmRunOwnerRecovery() {
445
605
  const storage = this.state?.storage;
@@ -749,6 +909,8 @@ export class DurableObjectRunner {
749
909
  return await runtime.authoritativeStatus(workflowId, runId);
750
910
  }
751
911
  catch (error) {
912
+ if (isRunStartPendingError(error))
913
+ throw error;
752
914
  throw error instanceof RunStateUnreadableError
753
915
  ? error
754
916
  : new RunStateUnreadableError(workflowId, runId, { cause: error });
@@ -965,6 +1127,20 @@ export class DurableObjectRunner {
965
1127
  return true;
966
1128
  }
967
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
+ }
968
1144
  // The deployment is fenced (or its fence could not be read). Classified
969
1145
  // with the same THREE outcomes as an unreadable read — uncharged,
970
1146
  // unconverged, watchdog cadence — because a wake refused by an
@@ -1021,42 +1197,128 @@ export class DurableObjectRunner {
1021
1197
  }
1022
1198
  }
1023
1199
  }
1024
- async #recoverRunOwner(recovery) {
1025
- const summary = await this.#ensureRuntime().recoverStartAttempt(recovery.workflowId, recovery.runId, recovery.token);
1026
- await this.runOwnership(this.env).settleReservation(recovery.token, summary ? [] : [{ kind: 'run', resourceId: recovery.runId }]);
1027
- // A start interrupted AFTER Mastra persisted a suspension is the one case
1028
- // where no other boundary is coming: the route that would have reconciled
1029
- // died with its isolate, and clearing the journal below re-arms the alarm
1030
- // from a record nothing ever wrote. This summary is the authoritative one
1031
- // recoverStartAttempt read back, so derive from it here or the run stays
1032
- // suspended with no wake at all. It needs no readability guard of its own:
1033
- // recoverStartAttempt now throws RunStateUnreadableError on Mastra's
1034
- // in-memory fallback BEFORE it concludes anything from it, so a degraded
1035
- // read never reaches this line. That throw leaves the journal and the
1036
- // reservation intact and propagates to alarm(), which classifies it and
1037
- // keeps the 60 s recovery cadence until the read heals.
1038
- const reconciled = summary
1039
- ? await this.#reconcileSuspensionDeadlinesBestEffort(recovery.workflowId, recovery.runId, summary)
1040
- : true;
1041
- 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;
1042
1268
  }
1043
1269
  #runOwnerRecovery(value) {
1044
- if (value === null || typeof value !== 'object') {
1045
- throw new Error('stored run owner recovery is malformed');
1046
- }
1047
- const stored = value;
1048
- if (stored.version !== 1 ||
1270
+ const stored = recoveryObject(value);
1271
+ const owner = recoveryObject(stored.owner);
1272
+ if (stored.version !== 2 ||
1049
1273
  !isPathSafeId(stored.workflowId) ||
1050
1274
  !isPathSafeId(stored.runId) ||
1051
- !isPathSafeId(stored.token)) {
1275
+ !isPathSafeId(stored.token) ||
1276
+ !isExecutionPrincipalKind(owner.kind) ||
1277
+ !isExecutionPrincipalId(owner.id))
1052
1278
  throw new Error('stored run owner recovery is malformed');
1053
- }
1054
- return {
1055
- 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,
1056
1297
  workflowId: stored.workflowId,
1057
1298
  runId: stored.runId,
1058
1299
  token: stored.token,
1300
+ owner: { kind: owner.kind, id: owner.id },
1301
+ ...(claim ? { startReservation: claim } : {}),
1059
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 };
1060
1322
  }
1061
1323
  async #recoverPendingRunOwner() {
1062
1324
  const stored = await this.state?.storage?.get(RUN_OWNER_RECOVERY_KEY);
@@ -1112,26 +1374,39 @@ export class DurableObjectRunner {
1112
1374
  await this.#armNextAlarm();
1113
1375
  });
1114
1376
  }
1115
- async #route(request) {
1377
+ async #route(request, encodedPrincipal, mutationEpoch) {
1116
1378
  const segments = new URL(request.url).pathname.split('/').filter(Boolean);
1117
1379
  if (segments[0] !== 'runs')
1118
1380
  return json({ error: 'not found' }, 404);
1119
1381
  const [, workflowId, runId, action] = segments;
1120
1382
  if (request.method === 'POST' && segments.length === 1) {
1383
+ const principal = this.#trustedExecutionPrincipal(encodedPrincipal);
1121
1384
  return this.#withOperationLock(async () => {
1122
- const principal = this.#trustedExecutionPrincipal(request);
1123
1385
  const body = await readJson(request);
1124
- 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') {
1125
1402
  return json({ error: 'workflowId is required' }, 400);
1126
1403
  }
1127
1404
  // The DO never generates a runId: the trusted Worker mints the id and
1128
1405
  // addresses this instance with it. A start without one is a caller bug,
1129
1406
  // not a request for generation.
1130
- if (typeof body.runId !== 'string') {
1407
+ if (typeof runId !== 'string') {
1131
1408
  return json({ error: 'runId is required (server-minted by the run router)' }, 400);
1132
1409
  }
1133
- const workflowId = body.workflowId;
1134
- const runId = body.runId;
1135
1410
  if (!isPathSafeId(workflowId) || !isPathSafeId(runId)) {
1136
1411
  throw new InvalidRunRequestError('workflowId and runId must be URL-path-safe identifiers');
1137
1412
  }
@@ -1140,133 +1415,132 @@ export class DurableObjectRunner {
1140
1415
  // rather than trusted because this body is JSON: an unvalidated value
1141
1416
  // would reach the fence's proof-only comparison and the runtime's
1142
1417
  // reservation as whatever the parser produced.
1143
- const idempotencyKey = this.#startIdempotencyKey(body.idempotencyKey);
1144
- // The fence BEFORE any of this object's own reads or writes: the
1145
- // schedule-source lookup below, the recovery pass, the journal at
1146
- // #armRunOwnerRecovery, and the owner reservation all touch storage,
1147
- // and a deployment that is refusing to execute must not leave a run
1148
- // half-claimed on its way to saying no. The runtime's own check inside
1149
- // start() stays the backstop for every other caller.
1150
- //
1151
- // The KEY is what admits a proof-only start: in that state the fence
1152
- // nominates exactly one key, and a start carrying it is the proof run.
1153
- // This check reads the fence but does NOT bind the proof to the run —
1154
- // `recordProofRun` belongs to the runtime's own assert, which is the
1155
- // last gate before execution and the only one every caller passes.
1156
- // Binding here as well would let a start that this route later refused
1157
- // (an existing run, a schedule-source mismatch) consume the deployment's
1158
- // one proof slot.
1159
- const startFence = await this.#readExecutionFence();
1160
- if (!admitsRunStart(startFence, idempotencyKey)) {
1161
- throw new ExecutionFencedError(startFence.state, 'run start');
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;
1162
1453
  }
1163
- const source = await this.#startSource(principal, workflowId, runId, body.scheduleId, body.dispatchId);
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;
1164
1463
  const runtime = this.#ensureRuntime();
1165
1464
  await this.#recoverPendingRunOwner();
1166
- // Stays on status(), and NOT because failing open would be safer: the
1167
- // dangerous shape here is a row miss with no in-memory Run, which
1168
- // carries no marker at all, so authoritativeStatus could not tell it
1169
- // from an absent run either. The recovery above is what covers the
1170
- // interrupted-start case, and it fails closed on an unreadable read.
1171
1465
  const existing = await runtime.status(workflowId, runId);
1172
1466
  if (existing) {
1173
1467
  const registered = await this.runOwnership(this.env).owner('run', runId);
1174
1468
  if (!registered ||
1175
- registered.kind !== source.owner.kind ||
1176
- registered.id !== source.owner.id) {
1469
+ registered.kind !== owner.kind ||
1470
+ registered.id !== owner.id) {
1177
1471
  throw new Error(`existing run '${runId}' has no matching committed owner`);
1178
1472
  }
1179
1473
  throw new RunAlreadyExistsError(workflowId, runId, existing.status);
1180
1474
  }
1181
- const recovery = {
1182
- version: 1,
1475
+ let recovery = {
1476
+ version: 2,
1477
+ phase: 'preparing',
1183
1478
  workflowId,
1184
1479
  runId,
1185
1480
  token: crypto.randomUUID(),
1481
+ owner,
1482
+ ...(startReservation ? { startReservation } : {}),
1186
1483
  };
1187
- await this.#armRunOwnerRecovery(recovery);
1188
- // From here to the finally below, this object IS the run's execution:
1189
- // everything past the journal either persists a snapshot or leaves the
1190
- // recovery pass to settle it. That window is exactly what a replaying
1191
- // start's liveness probe is asking about, and it is tracked in memory
1192
- // on purpose — an evicted isolate loses the entry, which is the true
1193
- // answer for a run that is no longer executing anywhere. Registered
1194
- // BEFORE the reservation and the runtime's own #activeRuns entry so the
1195
- // gap between the claim and core's first persisted snapshot — the one
1196
- // window where nothing else can see the run — is covered too.
1197
- this.#startsInFlight.add(this.#inFlightKey(workflowId, runId));
1484
+ const frame = { token: recovery.token, unwound: false };
1485
+ const frameKey = this.#inFlightKey(workflowId, runId);
1486
+ this.#startsInFlight.set(frameKey, frame);
1198
1487
  try {
1199
- await this.#reserveRunOwner(runId, source.owner, recovery.token);
1488
+ await this.#armRunOwnerRecovery(recovery);
1489
+ await this.#reserveRunOwner(runId, owner, recovery.token);
1200
1490
  let summary;
1201
1491
  try {
1202
1492
  summary = await runtime.start(workflowId, {
1203
1493
  runId,
1204
- inputData: source.target
1205
- ? source.target.inputData
1206
- : body.inputData,
1207
- initialState: source.target
1208
- ? source.target.initialState
1209
- : body.initialState,
1210
- ...(source.target?.requestContext !== undefined
1211
- ? { storedRequestContext: source.target.requestContext }
1494
+ inputData: resolvedInput,
1495
+ initialState: resolvedState,
1496
+ ...(storedRequestContext !== undefined
1497
+ ? { storedRequestContext }
1212
1498
  : {}),
1213
1499
  requestedBy: principal.id,
1214
1500
  requestedByKind: principal.kind,
1215
1501
  attemptToken: recovery.token,
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
+ },
1216
1509
  ...(idempotencyKey === undefined ? {} : { idempotencyKey }),
1217
- ...(body.deadlineMs === undefined
1510
+ ...(deadlineMs === undefined
1218
1511
  ? {}
1219
- : { deadlineMs: body.deadlineMs }),
1512
+ : { deadlineMs: deadlineMs }),
1220
1513
  });
1221
1514
  }
1222
- catch (error) {
1223
- let persisted;
1224
- try {
1225
- persisted = await runtime.recoverStartAttempt(workflowId, runId, recovery.token);
1226
- }
1227
- catch (recoverError) {
1228
- // Logged, never swallowed silently: this read is the only thing
1229
- // that could tell an interrupted start apart from a failed one,
1230
- // and its own failure is the reason the journal is being left
1231
- // armed for the alarm to retry.
1232
- console.error('interrupted start could not read authoritative state', recoverError);
1233
- await this.#rearmRunOwnerRecovery();
1234
- throw error;
1235
- }
1236
- if (persisted) {
1237
- const reconciled = await this.#reconcileSuspensionDeadlinesBestEffort(workflowId, runId, persisted);
1238
- await this.#settleRunOwnerBestEffort(recovery, false, !reconciled);
1239
- return json(persisted);
1240
- }
1241
- await this.#settleRunOwnerBestEffort(recovery, true);
1242
- throw error;
1515
+ finally {
1516
+ frame.unwound = true;
1243
1517
  }
1244
- // Reconcile BEFORE settling, never after: settling clears the
1245
- // recovery journal, and clearing it re-arms from storage — which, on
1246
- // a run whose FIRST deadline write has not happened yet, finds no
1247
- // record and no journal and deletes the alarm. With the journal
1248
- // still stored the write's own arm takes the min of the two due
1249
- // times, so no interleaving leaves this object without a wake.
1250
- const reconciled = await this.#reconcileSuspensionDeadlinesBestEffort(workflowId, runId, summary);
1251
- await this.#settleRunOwnerBestEffort(recovery, false, !reconciled);
1252
- // The authoritative RunSummary is the run-progress frame; push it
1253
- // to any subscribed run-channel socket at this lifecycle boundary.
1518
+ summary = await this.#finishRunOwner(recovery, summary);
1254
1519
  this.#broadcastRunSummary(summary);
1255
1520
  return json(summary);
1256
1521
  }
1257
1522
  catch (error) {
1258
- const stored = await this.state?.storage?.get(RUN_OWNER_RECOVERY_KEY);
1259
- 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);
1260
1537
  await this.#rearmRunOwnerRecovery();
1261
1538
  }
1262
1539
  throw error;
1263
1540
  }
1264
1541
  finally {
1265
- // Whatever happened, this object is no longer starting the run. The
1266
- // delete must be unconditional: an entry left behind would answer
1267
- // every later probe "live" for the lifetime of the isolate, turning a
1268
- // crashed start's honest UNRESOLVABLE into an endless PENDING.
1269
- this.#startsInFlight.delete(this.#inFlightKey(workflowId, runId));
1542
+ if (this.#startsInFlight.get(frameKey) === frame)
1543
+ this.#startsInFlight.delete(frameKey);
1270
1544
  }
1271
1545
  });
1272
1546
  }
@@ -1288,6 +1562,22 @@ export class DurableObjectRunner {
1288
1562
  runId) {
1289
1563
  this.#assertRunIdentity(workflowId, runId);
1290
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
+ }
1291
1581
  const summary = await runtime.status(workflowId, runId);
1292
1582
  if (!summary)
1293
1583
  return json({ error: 'run not found' }, 404);
@@ -1359,10 +1649,7 @@ export class DurableObjectRunner {
1359
1649
  // answers before it takes the per-run lock. A drain still admits
1360
1650
  // resumes — the suspended runs it is draining are waiting for exactly
1361
1651
  // these — and proof-only admits its one nominated run.
1362
- const resumeFence = await this.#readExecutionFence();
1363
- if (!admitsExistingRun(resumeFence, runId)) {
1364
- throw new ExecutionFencedError(resumeFence.state, 'run resume');
1365
- }
1652
+ await runtime.assertExistingRunAllowed(workflowId, runId);
1366
1653
  const summary = await runtime.resume(workflowId, runId, {
1367
1654
  step: body.step,
1368
1655
  resumeData,
@@ -1384,7 +1671,7 @@ export class DurableObjectRunner {
1384
1671
  workflowId &&
1385
1672
  runId) {
1386
1673
  this.#assertRunIdentity(workflowId, runId);
1387
- const principal = this.#trustedExecutionPrincipal(request);
1674
+ const principal = this.#trustedExecutionPrincipal(encodedPrincipal);
1388
1675
  const runtime = this.#ensureRuntime();
1389
1676
  const preflightOwner = await this.runOwnership(this.env).owner('run', runId);
1390
1677
  if (action === 'terminate') {
@@ -1419,7 +1706,7 @@ export class DurableObjectRunner {
1419
1706
  workflowId &&
1420
1707
  runId) {
1421
1708
  this.#assertRunIdentity(workflowId, runId);
1422
- const principal = this.#trustedExecutionPrincipal(request);
1709
+ const principal = this.#trustedExecutionPrincipal(encodedPrincipal);
1423
1710
  const body = (await readJson(request)) ?? {};
1424
1711
  const cas = {
1425
1712
  expectedRevision: body.expectedRevision,