@proofoftech/flowsafe 0.35.0 → 0.37.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 (176) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/README.md +14 -2
  3. package/dist/agent-runner/durable-agent-runner.d.ts +1 -2
  4. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  5. package/dist/agent-runner/durable-agent-runner.js +1 -1
  6. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  7. package/dist/answer-schema.d.ts +30 -0
  8. package/dist/answer-schema.d.ts.map +1 -0
  9. package/dist/answer-schema.js +311 -0
  10. package/dist/answer-schema.js.map +1 -0
  11. package/dist/approval-api/answer-schema.d.ts +2 -0
  12. package/dist/approval-api/answer-schema.d.ts.map +1 -0
  13. package/dist/approval-api/answer-schema.js +3 -0
  14. package/dist/approval-api/answer-schema.js.map +1 -0
  15. package/dist/approval-api/d1-store.d.ts +3 -16
  16. package/dist/approval-api/d1-store.d.ts.map +1 -1
  17. package/dist/approval-api/d1-store.js +117 -33
  18. package/dist/approval-api/d1-store.js.map +1 -1
  19. package/dist/approval-api/grants.d.ts +2 -3
  20. package/dist/approval-api/grants.d.ts.map +1 -1
  21. package/dist/approval-api/grants.js +5 -3
  22. package/dist/approval-api/grants.js.map +1 -1
  23. package/dist/approval-api/human-notifications.d.ts +34 -0
  24. package/dist/approval-api/human-notifications.d.ts.map +1 -0
  25. package/dist/approval-api/human-notifications.js +160 -0
  26. package/dist/approval-api/human-notifications.js.map +1 -0
  27. package/dist/approval-api/index.d.ts +3 -1
  28. package/dist/approval-api/index.d.ts.map +1 -1
  29. package/dist/approval-api/index.js +1 -0
  30. package/dist/approval-api/index.js.map +1 -1
  31. package/dist/approval-api/retention.d.ts +3 -1
  32. package/dist/approval-api/retention.d.ts.map +1 -1
  33. package/dist/approval-api/retention.js +21 -1
  34. package/dist/approval-api/retention.js.map +1 -1
  35. package/dist/approval-api/router.d.ts +1 -1
  36. package/dist/approval-api/router.d.ts.map +1 -1
  37. package/dist/approval-api/router.js +7 -0
  38. package/dist/approval-api/router.js.map +1 -1
  39. package/dist/approval-api/service.d.ts +6 -1
  40. package/dist/approval-api/service.d.ts.map +1 -1
  41. package/dist/approval-api/service.js +55 -10
  42. package/dist/approval-api/service.js.map +1 -1
  43. package/dist/approval-api/store-factory.d.ts +2 -0
  44. package/dist/approval-api/store-factory.d.ts.map +1 -1
  45. package/dist/approval-api/store-factory.js.map +1 -1
  46. package/dist/approval-api/store.d.ts +3 -0
  47. package/dist/approval-api/store.d.ts.map +1 -1
  48. package/dist/approval-api/store.js +2 -1
  49. package/dist/approval-api/store.js.map +1 -1
  50. package/dist/approval-api/types.d.ts +78 -4
  51. package/dist/approval-api/types.d.ts.map +1 -1
  52. package/dist/approval-api/types.js +1 -0
  53. package/dist/approval-api/types.js.map +1 -1
  54. package/dist/do-runner/child-run-ledger.d.ts +84 -0
  55. package/dist/do-runner/child-run-ledger.d.ts.map +1 -0
  56. package/dist/do-runner/child-run-ledger.js +272 -0
  57. package/dist/do-runner/child-run-ledger.js.map +1 -0
  58. package/dist/do-runner/child-runs.d.ts +95 -0
  59. package/dist/do-runner/child-runs.d.ts.map +1 -0
  60. package/dist/do-runner/child-runs.js +185 -0
  61. package/dist/do-runner/child-runs.js.map +1 -0
  62. package/dist/do-runner/constants.d.ts +3 -0
  63. package/dist/do-runner/constants.d.ts.map +1 -1
  64. package/dist/do-runner/constants.js +3 -0
  65. package/dist/do-runner/constants.js.map +1 -1
  66. package/dist/do-runner/d1-storage.d.ts +1 -0
  67. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  68. package/dist/do-runner/d1-storage.js +108 -39
  69. package/dist/do-runner/d1-storage.js.map +1 -1
  70. package/dist/do-runner/durable-object.d.ts +26 -5
  71. package/dist/do-runner/durable-object.d.ts.map +1 -1
  72. package/dist/do-runner/durable-object.js +1857 -124
  73. package/dist/do-runner/durable-object.js.map +1 -1
  74. package/dist/do-runner/execution-context.d.ts +6 -0
  75. package/dist/do-runner/execution-context.d.ts.map +1 -1
  76. package/dist/do-runner/execution-context.js +10 -0
  77. package/dist/do-runner/execution-context.js.map +1 -1
  78. package/dist/do-runner/fenced-workflow-capability.d.ts +12 -1
  79. package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -1
  80. package/dist/do-runner/fenced-workflow-capability.js +17 -0
  81. package/dist/do-runner/fenced-workflow-capability.js.map +1 -1
  82. package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -1
  83. package/dist/do-runner/fenced-workflows-d1.js +169 -22
  84. package/dist/do-runner/fenced-workflows-d1.js.map +1 -1
  85. package/dist/do-runner/index.d.ts +9 -5
  86. package/dist/do-runner/index.d.ts.map +1 -1
  87. package/dist/do-runner/index.js +6 -2
  88. package/dist/do-runner/index.js.map +1 -1
  89. package/dist/do-runner/init.d.ts +4 -3
  90. package/dist/do-runner/init.d.ts.map +1 -1
  91. package/dist/do-runner/init.js +1 -0
  92. package/dist/do-runner/init.js.map +1 -1
  93. package/dist/do-runner/inventory.d.ts +2 -2
  94. package/dist/do-runner/inventory.d.ts.map +1 -1
  95. package/dist/do-runner/inventory.js +112 -5
  96. package/dist/do-runner/inventory.js.map +1 -1
  97. package/dist/do-runner/questions.d.ts +70 -0
  98. package/dist/do-runner/questions.d.ts.map +1 -0
  99. package/dist/do-runner/questions.js +440 -0
  100. package/dist/do-runner/questions.js.map +1 -0
  101. package/dist/do-runner/resume-refusal-codes.d.ts +3 -0
  102. package/dist/do-runner/resume-refusal-codes.d.ts.map +1 -0
  103. package/dist/do-runner/resume-refusal-codes.js +4 -0
  104. package/dist/do-runner/resume-refusal-codes.js.map +1 -0
  105. package/dist/do-runner/run-lifecycle.d.ts +42 -7
  106. package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
  107. package/dist/do-runner/run-lifecycle.js +77 -1
  108. package/dist/do-runner/run-lifecycle.js.map +1 -1
  109. package/dist/do-runner/run-lineage.d.ts +26 -0
  110. package/dist/do-runner/run-lineage.d.ts.map +1 -0
  111. package/dist/do-runner/run-lineage.js +38 -0
  112. package/dist/do-runner/run-lineage.js.map +1 -0
  113. package/dist/do-runner/run-storage-tables.d.ts +2 -0
  114. package/dist/do-runner/run-storage-tables.d.ts.map +1 -1
  115. package/dist/do-runner/run-storage-tables.js +2 -0
  116. package/dist/do-runner/run-storage-tables.js.map +1 -1
  117. package/dist/do-runner/run-terminal-state.d.ts +1 -1
  118. package/dist/do-runner/run-terminal-state.d.ts.map +1 -1
  119. package/dist/do-runner/run-terminal-state.js +2 -2
  120. package/dist/do-runner/run-terminal-state.js.map +1 -1
  121. package/dist/do-runner/runtime.d.ts +148 -20
  122. package/dist/do-runner/runtime.d.ts.map +1 -1
  123. package/dist/do-runner/runtime.js +726 -99
  124. package/dist/do-runner/runtime.js.map +1 -1
  125. package/dist/do-runner/suspension-deadline.d.ts +4 -1
  126. package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
  127. package/dist/do-runner/suspension-deadline.js +32 -7
  128. package/dist/do-runner/suspension-deadline.js.map +1 -1
  129. package/dist/do-runner/suspension-kinds.d.ts +15 -0
  130. package/dist/do-runner/suspension-kinds.d.ts.map +1 -0
  131. package/dist/do-runner/suspension-kinds.js +65 -0
  132. package/dist/do-runner/suspension-kinds.js.map +1 -0
  133. package/dist/durable-agent-workflow-id.d.ts +2 -0
  134. package/dist/durable-agent-workflow-id.d.ts.map +1 -0
  135. package/dist/durable-agent-workflow-id.js +3 -0
  136. package/dist/durable-agent-workflow-id.js.map +1 -0
  137. package/dist/host-kit/approval-bridge.d.ts +12 -14
  138. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  139. package/dist/host-kit/approval-bridge.js +40 -18
  140. package/dist/host-kit/approval-bridge.js.map +1 -1
  141. package/dist/host-kit/do-response.d.ts.map +1 -1
  142. package/dist/host-kit/do-response.js +50 -1
  143. package/dist/host-kit/do-response.js.map +1 -1
  144. package/dist/host-kit/do-run-topology.d.ts +10 -3
  145. package/dist/host-kit/do-run-topology.d.ts.map +1 -1
  146. package/dist/host-kit/do-run-topology.js +124 -1
  147. package/dist/host-kit/do-run-topology.js.map +1 -1
  148. package/dist/host-kit/flowsafe-worker.d.ts +30 -9
  149. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  150. package/dist/host-kit/flowsafe-worker.js +168 -21
  151. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  152. package/dist/host-kit/host-approval-service.d.ts +1 -1
  153. package/dist/host-kit/host-approval-service.d.ts.map +1 -1
  154. package/dist/host-kit/host-approval-service.js +10 -4
  155. package/dist/host-kit/host-approval-service.js.map +1 -1
  156. package/dist/host-kit/index.d.ts +3 -1
  157. package/dist/host-kit/index.d.ts.map +1 -1
  158. package/dist/host-kit/index.js +1 -0
  159. package/dist/host-kit/index.js.map +1 -1
  160. package/dist/host-kit/run-router.d.ts +39 -3
  161. package/dist/host-kit/run-router.d.ts.map +1 -1
  162. package/dist/host-kit/run-router.js +136 -21
  163. package/dist/host-kit/run-router.js.map +1 -1
  164. package/dist/human-notification-storage.d.ts +5 -0
  165. package/dist/human-notification-storage.d.ts.map +1 -0
  166. package/dist/human-notification-storage.js +57 -0
  167. package/dist/human-notification-storage.js.map +1 -0
  168. package/dist/notification-retry.d.ts +3 -0
  169. package/dist/notification-retry.d.ts.map +1 -0
  170. package/dist/notification-retry.js +6 -0
  171. package/dist/notification-retry.js.map +1 -0
  172. package/dist/signals/notification-dispatch.d.ts +1 -1
  173. package/dist/signals/notification-dispatch.d.ts.map +1 -1
  174. package/dist/signals/notification-dispatch.js +3 -4
  175. package/dist/signals/notification-dispatch.js.map +1 -1
  176. package/package.json +1 -1
@@ -12,28 +12,37 @@
12
12
  // recovering run-owner claims that outlive an interrupted start, and for the
13
13
  // per-suspension deadlines of this run (suspension-deadline.ts); the duties
14
14
  // share one wake, armed at the earliest due time.
15
+ import { AnswersInvalidError } from '../answer-schema.js';
15
16
  import { decodeExecutionPrincipal, isExecutionPrincipalId, isExecutionPrincipalKind, isOwnedBy, samePrincipal, } from '../approval-api/principal.js';
17
+ import { DURABLE_AGENTIC_LOOP_WORKFLOW_ID } from '../durable-agent-workflow-id.js';
16
18
  import { readBoundedBody } from '../http-body.js';
17
19
  import { errorMessageOf } from './cause-chain.js';
18
20
  import { newWebSocketPair, safeSend } from './cf-types.js';
21
+ import { ChildRunLedger, } from './child-run-ledger.js';
22
+ import { assertChildRunKey, CHILD_RUN_CALL_TIMEOUT_MS, ChildRunRefusedError, captureChildRunStart, childJsonDigest, deriveChildRunId, withChildRunHost, withinChildRunCall, } from './child-runs.js';
19
23
  import { isDatabaseBinding, verifyDurableObjectDeploymentIdentity, verifyDurableObjectDeploymentRequest, } from './deployment-identity.js';
20
24
  import { DoStatusError, doErrorResponse } from './do-error-response.js';
21
25
  import { ExecutionFenceUnreadableError, isRunStartPendingError, MUTATION_EPOCH_HEADER, mutationEpochFromHeader, normalizeD1RunExecutionIdentity, normalizeRunExecutionIdentity, normalizeStartExecutionIdentity, normalizeStartIdentity, RunStartPendingError, } from './execution-admission.js';
26
+ import { assertNoReservedExecutionContext } from './execution-context.js';
22
27
  import { admitsRunStart, ExecutionFencedError, isExecutionFenceRefusal, readExecutionFence, } from './execution-fence.js';
23
28
  import { EXECUTION_PRINCIPAL_HEADER } from './execution-principal-header.js';
24
29
  import { isDefinitiveInitialAdmissionRefusal } from './initial-admission-refusal.js';
25
30
  import { ownDataCopy } from './own-data-copy.js';
26
31
  import { isPathSafeId } from './path-safe-id.js';
32
+ import { answerQuestion, currentQuestions, deleteEarlyAnswer, expireQuestion, getQuestion, isQuestionFingerprint, isQuestionId, listQuestions, openQuestion, QUESTION_ANSWER_RESUME_KEY, QuestionNotOpenError, readEarlyAnswer, retainEarlyAnswer, sameQuestionSuspension, supersedeOpenQuestions, supersedeQuestion, } from './questions.js';
27
33
  import { RemoteStepSettlementFencedError, WORKFLOW_REMOTE_STEP_RESULT_KEY, } from './remote-step-journal.js';
28
34
  import { lifecycleFromRequestContext, terminalCleanupFor, } from './run-lifecycle.js';
29
- import { decodeRunRequester, RUN_REQUESTER_HEADER } from './run-requester.js';
35
+ import { parseRunLineage, projectRunLineage, RUN_LINEAGE_CONTEXT_KEY, } from './run-lineage.js';
36
+ import { decodeRunRequester, RUN_REQUESTER_HEADER, } from './run-requester.js';
30
37
  import { isDurableRunStatus, isTerminalRunStatus, } from './run-terminal-state.js';
31
- import { InvalidRunRequestError, RunAlreadyExistsError, RunnerRuntime, RunStateUnreadableError, SuspensionChangedError, UnknownRunError, } from './runtime.js';
38
+ import { assertRunInputDepth, ChildAwaitResumeSchemaError, currentWorkflowLeg, InvalidRunRequestError, parsePauseGeneration, parsePauseRunOptions, RunAlreadyExistsError, RunNotSuspendedError, RunnerRuntime, RunStateUnreadableError, RunTerminalConflictError, SuspensionChangedError, UnknownRunError, } from './runtime.js';
32
39
  import { resolveScheduleStartOwner, } from './schedule-source.js';
33
40
  import { captureReservation, sameReservationIdentity, } from './start-reservation-contract.js';
34
- import { dueSuspensionDeadline, isReadableRunSummary, isSuspensionDeadlineDue, MAX_SUSPENSION_DEADLINE_ATTEMPTS, MAX_SUSPENSION_DEADLINES_PER_RUN, mergeSuspensionDeadlines, nextSuspensionDeadlineAt, ownSuspensionDeadlines, parseSuspensionDeadlineRecord, SUSPENSION_DEADLINE_PRINCIPAL_ID, SUSPENSION_DEADLINE_STORAGE_KEY, SUSPENSION_TIMEOUT_RESUME_KEY, suspensionDeadlinesOf, suspensionTimeoutResumeData, suspensionTimerSteps, tombstoned, } from './suspension-deadline.js';
41
+ import { dueSuspensionDeadline, hasInvalidChildAwait, isReadableRunSummary, isSuspensionDeadlineDue, MAX_SUSPENSION_DEADLINE_ATTEMPTS, MAX_SUSPENSION_DEADLINES_PER_RUN, mergeSuspensionDeadlines, nextSuspensionDeadlineAt, ownSuspensionDeadlines, parseSuspensionDeadlineRecord, SUSPENSION_DEADLINE_PRINCIPAL_ID, SUSPENSION_DEADLINE_STORAGE_KEY, SUSPENSION_TIMEOUT_RESUME_KEY, suspensionDeadlinesOf, suspensionTimeoutResumeData, suspensionTimerSteps, tombstoned, } from './suspension-deadline.js';
42
+ import { CHILDREN_RESUME_KEY, childAwaitForStep, suspensionKindsOf, } from './suspension-kinds.js';
35
43
  const RUN_OWNER_RECOVERY_KEY = 'flowsafe:run-owner-recovery:v1';
36
44
  const START_PRINCIPAL_RECEIPT_KEY = 'flowsafe:start-principal:v1';
45
+ const CHILD_START_RECOVERY_KEY = 'flowsafe:child-start-recovery:v1';
37
46
  export const RUN_OWNER_RECOVERY_DELAY_MS = 60_000;
38
47
  const SUSPENSION_DEADLINE_RETRY_MS = 60_000;
39
48
  // How long a run's state may stay unreadable before the entries due under it
@@ -70,6 +79,10 @@ const SUSPENSION_DEADLINE_ARM_FLOOR_MS = 1_000;
70
79
  // isolate that dies mid-step, which is how the next wake learns that a run
71
80
  // left `running` has nothing driving it.
72
81
  const RUN_LEG_KEY = 'flowsafe:run-leg:v1';
82
+ const QUESTION_RECOVERY_KEY = 'flowsafe:question-recovery:v1';
83
+ const PARENT_NOTIFY_KEY = 'flowsafe:parent-notify:v1';
84
+ const CHILD_CASCADE_KEY = 'flowsafe:child-cascade:v1';
85
+ const CHILD_RUN_RETRY_LIMIT_MS = 86_400_000;
73
86
  // Far past the 15 minutes a pending operation keeps a Durable Object running
74
87
  // without a connected client. A leg frame this old belongs to an invocation
75
88
  // that ended without settling the leg's promise — which still holds this
@@ -80,6 +93,9 @@ const RUN_LEG_MAX_AGE_MS = 7_200_000;
80
93
  // deploy unregistered its workflow: the bound the suspension-deadline duty
81
94
  // allows an unreadable run.
82
95
  const RUN_LEG_UNSETTLED_LIMIT_MS = SUSPENSION_DEADLINE_UNREADABLE_LIMIT_MS;
96
+ class QuestionResumeUnresolvedError extends DoStatusError {
97
+ status = 503;
98
+ }
83
99
  function recoveryObject(value) {
84
100
  return ownDataCopy(value, () => {
85
101
  throw new Error('stored run owner recovery is malformed');
@@ -134,7 +150,7 @@ function sameRunRecovery(actual, expected) {
134
150
  claim.binding.kind === wantedClaim.binding.kind));
135
151
  }
136
152
  function preparedRunExecution(recovery) {
137
- return recovery.phase === 'preparing' ? undefined : recovery.execution;
153
+ return recovery.execution;
138
154
  }
139
155
  class DurableObjectRunIdentityError extends DoStatusError {
140
156
  status = 403;
@@ -189,6 +205,8 @@ export class DurableObjectRunner {
189
205
  /** Absent in Node tests; present under workerd for storage and the alarm. */
190
206
  state;
191
207
  #runtime;
208
+ #childStartsInFlight = new Map();
209
+ #childLedger;
192
210
  #workflowRemoteReader;
193
211
  #operationTail = Promise.resolve();
194
212
  /** `step\0reason` of every suspension deadline this object has reported. */
@@ -204,6 +222,15 @@ export class DurableObjectRunner {
204
222
  async workflowRemoteSteps(_env, _runtime) {
205
223
  return undefined;
206
224
  }
225
+ childRunTopology(env) {
226
+ return this.runLifecycle(env)?.childRunTopology;
227
+ }
228
+ beforeStartChild(env) {
229
+ return this.runLifecycle(env)?.beforeStartChild;
230
+ }
231
+ workflowVersion(env) {
232
+ return this.runLifecycle(env)?.workflowVersion;
233
+ }
207
234
  /** Existing schedules domain used only for target-verifiable schedule fires. */
208
235
  scheduleSource(_env) {
209
236
  return undefined;
@@ -322,17 +349,1289 @@ export class DurableObjectRunner {
322
349
  }
323
350
  /** Caller-supplied timeout data would select the timeout branch with caller provenance. */
324
351
  #resumeData(value) {
325
- if (value !== null &&
326
- typeof value === 'object' &&
327
- (SUSPENSION_TIMEOUT_RESUME_KEY in value ||
328
- WORKFLOW_REMOTE_STEP_RESULT_KEY in value)) {
329
- const key = SUSPENSION_TIMEOUT_RESUME_KEY in value
330
- ? SUSPENSION_TIMEOUT_RESUME_KEY
331
- : WORKFLOW_REMOTE_STEP_RESULT_KEY;
332
- throw new InvalidRunRequestError(`resume data must not carry the reserved '${key}' key`);
352
+ if (value !== null && typeof value === 'object') {
353
+ for (const key of [
354
+ SUSPENSION_TIMEOUT_RESUME_KEY,
355
+ WORKFLOW_REMOTE_STEP_RESULT_KEY,
356
+ QUESTION_ANSWER_RESUME_KEY,
357
+ CHILDREN_RESUME_KEY,
358
+ ]) {
359
+ if (key in value) {
360
+ throw new InvalidRunRequestError(`resume data must not carry the reserved '${key}' key`);
361
+ }
362
+ }
333
363
  }
334
364
  return value;
335
365
  }
366
+ #questionDatabase() {
367
+ const db = this.env?.DB;
368
+ return isDatabaseBinding(db) ? db : undefined;
369
+ }
370
+ #childRunLedger() {
371
+ const db = this.env?.DB;
372
+ if (!isDatabaseBinding(db))
373
+ throw new ChildRunRefusedError('HOST_REFUSED');
374
+ if (!this.#childLedger) {
375
+ this.#childLedger = new ChildRunLedger(db);
376
+ }
377
+ return this.#childLedger;
378
+ }
379
+ async #childParent(workflowId, runId, key) {
380
+ const source = await this.#ensureRuntime().authoritativeStartState(workflowId, runId, { includeLegacy: true });
381
+ if (!source || isTerminalRunStatus(source.snapshot.status))
382
+ throw new ChildRunRefusedError('HOST_REFUSED');
383
+ const context = source.snapshot.requestContext;
384
+ const lifecycle = lifecycleFromRequestContext(context);
385
+ if (lifecycle?.transitionIntent || lifecycle?.terminal)
386
+ throw new ChildRunRefusedError('HOST_REFUSED');
387
+ const { rootWorkflowId, rootRunId, depth } = projectRunLineage(workflowId, runId, parseRunLineage(context?.[RUN_LINEAGE_CONTEXT_KEY]));
388
+ const provenance = source.kind === 'legacy' ? undefined : source.provenance;
389
+ const runRequester = provenance?.runRequester;
390
+ const parent = Object.freeze({
391
+ workflowId,
392
+ runId,
393
+ rootRunId,
394
+ depth,
395
+ key,
396
+ ...(runRequester === undefined ? {} : { runRequester }),
397
+ });
398
+ return {
399
+ parent,
400
+ rootWorkflowId,
401
+ deadlineAt: lifecycle?.deadlineAt,
402
+ originalOwner: provenance?.startIdentity?.owner,
403
+ };
404
+ }
405
+ async #registeredChildOwner(parentRunId, principal, originalOwner) {
406
+ if (!principal)
407
+ throw new ChildRunRefusedError('HOST_REFUSED');
408
+ const ownership = this.runOwnership(this.env);
409
+ const owner = (await ownership.owner('run', parentRunId)) ??
410
+ (await ownership.reservedOwner?.('run', parentRunId)) ??
411
+ (await ownership.owner('run', parentRunId));
412
+ if (!owner ||
413
+ !isOwnedBy(owner, principal) ||
414
+ (originalOwner && !isOwnedBy(owner, originalOwner)))
415
+ throw new ChildRunRefusedError('HOST_REFUSED');
416
+ return principal;
417
+ }
418
+ async #startChild(workflowId, runId, supplied) {
419
+ const request = captureChildRunStart(supplied);
420
+ const { key, version, inputData, deadlineMs, requestContext } = request;
421
+ const ledger = this.#childRunLedger();
422
+ const topology = this.childRunTopology(this.env);
423
+ if (!topology)
424
+ throw new ChildRunRefusedError('HOST_REFUSED');
425
+ if (typeof topology.cascadeTerminate !== 'function')
426
+ throw new ChildRunRefusedError('CHILD_CASCADE_UNAVAILABLE');
427
+ const address = {
428
+ parentWorkflowId: workflowId,
429
+ parentRunId: runId,
430
+ childKey: key,
431
+ };
432
+ const inputDigest = await childJsonDigest(inputData);
433
+ const dispatchDigest = await childJsonDigest([
434
+ deadlineMs ?? null,
435
+ requestContext ?? null,
436
+ ]);
437
+ let entry = await ledger.get(address);
438
+ let existing = entry !== undefined;
439
+ if (!entry) {
440
+ const { parent, deadlineAt, originalOwner } = await this.#childParent(workflowId, runId, key);
441
+ const { maxDepth, maxChildrenPerRun } = this.#ensureRuntime().childRunLimits;
442
+ let refusalCode;
443
+ if (parent.depth >= maxDepth)
444
+ refusalCode = 'DEPTH_EXCEEDED';
445
+ else if ((await ledger.countAccepted(address)) >= maxChildrenPerRun)
446
+ refusalCode = 'CHILD_LIMIT_EXCEEDED';
447
+ else if (deadlineAt !== undefined && deadlineAt <= Date.now()) {
448
+ refusalCode = 'HOST_REFUSED';
449
+ }
450
+ const childRunId = await deriveChildRunId(workflowId, runId, key);
451
+ if (refusalCode === undefined) {
452
+ const fence = await this.#readExecutionFence();
453
+ if (!admitsRunStart(fence))
454
+ throw new ExecutionFencedError(fence.state, 'child run start');
455
+ try {
456
+ const receipt = await this.#readStartPrincipalReceipt(workflowId, runId);
457
+ const owner = await this.#registeredChildOwner(runId, receipt?.principal, originalOwner);
458
+ const authority = this.runLifecycle(this.env)?.authorizeChildStart;
459
+ if (!authority)
460
+ throw new ChildRunRefusedError('HOST_REFUSED');
461
+ const startParent = Object.freeze({ ...parent, owner });
462
+ await authority(startParent, structuredClone(request), fence.mutationEpoch);
463
+ if ((await this.beforeStartChild(this.env)?.(startParent, structuredClone(request))) === false)
464
+ throw new ChildRunRefusedError('HOST_REFUSED');
465
+ }
466
+ catch (error) {
467
+ if (!(error instanceof ChildRunRefusedError))
468
+ throw error;
469
+ refusalCode = error.code;
470
+ }
471
+ }
472
+ if (refusalCode === undefined) {
473
+ await this.#armNextAlarm(Date.now() + RUN_OWNER_RECOVERY_DELAY_MS);
474
+ await this.state?.storage.put(CHILD_START_RECOVERY_KEY, true);
475
+ }
476
+ if (!currentWorkflowLeg()?.isActive())
477
+ throw new ChildRunRefusedError('HOST_REFUSED');
478
+ const reservation = await ledger.reserve({
479
+ ...address,
480
+ childRunId,
481
+ childWorkflowId: request.workflowId,
482
+ versionPin: version,
483
+ inputDigest,
484
+ dispatchDigest,
485
+ rootRunId: parent.rootRunId,
486
+ depth: parent.depth + 1,
487
+ }, Date.now(), { refusalCode, maxChildrenPerRun });
488
+ ({ entry, existing } = reservation);
489
+ }
490
+ if (entry.inputDigest !== inputDigest ||
491
+ entry.childWorkflowId !== request.workflowId ||
492
+ entry.versionPin !== version) {
493
+ throw new ChildRunRefusedError('CHILD_KEY_CONFLICT');
494
+ }
495
+ if (entry.state === 'refused')
496
+ throw new ChildRunRefusedError(entry.refusalCode ?? 'HOST_REFUSED');
497
+ if (entry.state === 'starting') {
498
+ if (entry.dispatchDigest !== dispatchDigest)
499
+ throw new ChildRunRefusedError('CHILD_KEY_CONFLICT');
500
+ const leg = currentWorkflowLeg();
501
+ if (!leg?.isActive())
502
+ throw new ChildRunRefusedError('HOST_REFUSED');
503
+ const childRunId = entry.childRunId;
504
+ let dispatch = this.#childStartsInFlight.get(childRunId);
505
+ if (!dispatch) {
506
+ dispatch = withinChildRunCall(topology.startChild({
507
+ workflowId: entry.childWorkflowId,
508
+ runId: childRunId,
509
+ inputData,
510
+ deadlineMs,
511
+ requestContext,
512
+ }))
513
+ .catch(async (error) => {
514
+ if (error instanceof ChildRunRefusedError)
515
+ await ledger.markRefused(childRunId, Date.now(), error.code);
516
+ throw error;
517
+ })
518
+ .finally(() => this.#childStartsInFlight.delete(childRunId));
519
+ this.#childStartsInFlight.set(childRunId, dispatch);
520
+ }
521
+ // Releasing the leg lets the parent cascade even while admission is pending.
522
+ await waitForChildCall(dispatch, leg.signal);
523
+ }
524
+ return { key, runId: entry.childRunId, existing };
525
+ }
526
+ async #cascadeChildren(workflowId, runId, status, commitIntent) {
527
+ if (!hasDatabaseBinding(this.env))
528
+ return;
529
+ const parent = { parentWorkflowId: workflowId, parentRunId: runId };
530
+ const rows = await this.#childRunLedger().listUnresolved(parent);
531
+ if (rows.length === 0)
532
+ return;
533
+ const topology = this.childRunTopology(this.env);
534
+ if (commitIntent && typeof topology?.cascadeTerminate !== 'function')
535
+ throw new ChildRunRefusedError('CHILD_CASCADE_UNAVAILABLE');
536
+ if (!rows.some((row) => row.state !== 'indeterminate' || row.cancelRequestedAt === undefined))
537
+ return;
538
+ if (!commitIntent) {
539
+ const selected = await this.#ensureRuntime().authoritativeStartState(workflowId, runId, { includeLegacy: true });
540
+ const lifecycle = lifecycleFromRequestContext(selected?.snapshot.requestContext);
541
+ if (!isTerminalRunStatus(selected?.summary?.status) ||
542
+ lifecycle?.transitionIntent)
543
+ return;
544
+ status = lifecycle?.terminal?.status ?? status;
545
+ }
546
+ const storage = this.state?.storage;
547
+ if (!storage)
548
+ throw new Error('child cascade requires durable storage');
549
+ const previous = await storage.get(CHILD_CASCADE_KEY);
550
+ const now = Date.now();
551
+ const prior = previous?.status === status ? previous : undefined;
552
+ const cascade = {
553
+ ...parent,
554
+ status,
555
+ startedAt: prior?.startedAt ?? now,
556
+ nextAttemptAt: prior?.nextAttemptAt ?? now,
557
+ attempts: prior?.attempts ?? 0,
558
+ childRunIds: rows.map((row) => row.childRunId),
559
+ ...(commitIntent ? { pendingCommit: true } : {}),
560
+ };
561
+ // The alarm can finish a committed intent if the request stops before its terminal write.
562
+ await this.#armNextAlarm(now + SUSPENSION_DEADLINE_RETRY_MS);
563
+ await storage.put(CHILD_CASCADE_KEY, cascade);
564
+ await commitIntent?.();
565
+ await this.#runChildCascade(cascade, topology);
566
+ }
567
+ async #runChildCascade(cascade, topology) {
568
+ const storage = this.state?.storage;
569
+ if (!storage)
570
+ return;
571
+ const { parentWorkflowId, parentRunId, status, attempts } = cascade;
572
+ this.#assertRunIdentity(parentWorkflowId, parentRunId);
573
+ const parent = { parentWorkflowId, parentRunId, status };
574
+ const ledger = this.#childRunLedger();
575
+ const now = Date.now();
576
+ let nextExpiry = Infinity;
577
+ const rows = cascade.childRunIds
578
+ ? await ledger.requestCancellation(parent, cascade.childRunIds, now)
579
+ : (await ledger.listUnresolved(parent)).filter((row) => row.cancelRequestedAt !== undefined);
580
+ const outcomes = await Promise.allSettled(rows.map(async (row) => {
581
+ const expiresAt = row.state === 'indeterminate'
582
+ ? row.updatedAt + CHILD_RUN_RETRY_LIMIT_MS
583
+ : Infinity;
584
+ const remaining = expiresAt - Date.now();
585
+ if (remaining <= 0) {
586
+ if (cascade.nextAttemptAt <= expiresAt)
587
+ logChildRunRetryAbandoned(row.childWorkflowId, row.childRunId);
588
+ return;
589
+ }
590
+ try {
591
+ if (typeof topology?.cascadeTerminate !== 'function')
592
+ throw new ChildRunRefusedError('CHILD_CASCADE_UNAVAILABLE');
593
+ const signal = AbortSignal.timeout(Math.min(CHILD_RUN_CALL_TIMEOUT_MS, remaining));
594
+ const cancel = topology.cascadeTerminate(row.childWorkflowId, row.childRunId, parent, signal);
595
+ // The probe can wait for the child's lock, which cancellation helps release.
596
+ const probe = row.state === 'starting'
597
+ ? Promise.resolve()
598
+ .then(() => topology.resolveChildStart(row.childWorkflowId, row.childRunId))
599
+ .catch((error) => {
600
+ console.error('child start resolution failed', error);
601
+ })
602
+ : undefined;
603
+ await waitForChildCall(Promise.all([cancel, probe]), signal);
604
+ const settled = await ledger.getByRunId(row.childRunId);
605
+ if (settled?.state !== 'terminal' && settled?.state !== 'refused')
606
+ throw new RunStateUnreadableError(row.childWorkflowId, row.childRunId);
607
+ }
608
+ catch (error) {
609
+ await ledger.markIndeterminate(row.childRunId);
610
+ const unresolved = await ledger.getByRunId(row.childRunId);
611
+ if (!unresolved ||
612
+ unresolved.state === 'starting' ||
613
+ unresolved.state === 'started')
614
+ throw new RunStateUnreadableError(row.childWorkflowId, row.childRunId);
615
+ if (unresolved.state === 'indeterminate') {
616
+ console.error('child cascade failed', error);
617
+ return unresolved.updatedAt + CHILD_RUN_RETRY_LIMIT_MS;
618
+ }
619
+ }
620
+ }));
621
+ for (const outcome of outcomes) {
622
+ if (outcome.status === 'rejected')
623
+ throw outcome.reason;
624
+ if (outcome.value !== undefined)
625
+ nextExpiry = Math.min(nextExpiry, outcome.value);
626
+ }
627
+ if (nextExpiry === Infinity) {
628
+ if (cascade.pendingCommit)
629
+ await storage.put(CHILD_CASCADE_KEY, {
630
+ ...cascade,
631
+ retryChildren: false,
632
+ });
633
+ else
634
+ await storage.delete(CHILD_CASCADE_KEY);
635
+ return;
636
+ }
637
+ await storage.put(CHILD_CASCADE_KEY, {
638
+ ...cascade,
639
+ attempts: attempts + 1,
640
+ nextAttemptAt: childRunRetryAt(Date.now(), attempts + 1, nextExpiry),
641
+ });
642
+ }
643
+ async #cascadeAfterRunEnd(workflowId, summary) {
644
+ if (isTerminalRunStatus(summary.status))
645
+ await this.#cascadeChildren(workflowId, summary.runId, 'cancelled');
646
+ }
647
+ async #recordRunEnd(workflowId, summary) {
648
+ await this.#cascadeAfterRunEnd(workflowId, summary);
649
+ await this.#recordChildOutcome(workflowId, summary);
650
+ }
651
+ async #completeChildCascade() {
652
+ const storage = this.state?.storage;
653
+ const cascade = await storage?.get(CHILD_CASCADE_KEY);
654
+ if (!storage || !cascade?.pendingCommit)
655
+ return;
656
+ if (cascade.retryChildren === false) {
657
+ await storage.delete(CHILD_CASCADE_KEY);
658
+ }
659
+ else {
660
+ const { pendingCommit: _pendingCommit, ...retry } = cascade;
661
+ await storage.put(CHILD_CASCADE_KEY, retry);
662
+ }
663
+ }
664
+ async #retryChildCascade() {
665
+ const storage = this.state?.storage;
666
+ const cascade = await storage?.get(CHILD_CASCADE_KEY);
667
+ if (!storage || !cascade || cascade.nextAttemptAt > Date.now())
668
+ return;
669
+ const { parentWorkflowId: workflowId, parentRunId: runId, status, } = cascade;
670
+ try {
671
+ this.#assertRunIdentity(workflowId, runId);
672
+ const runtime = this.#ensureRuntime();
673
+ const current = await runtime.authoritativeStartState(workflowId, runId, {
674
+ includeLegacy: true,
675
+ });
676
+ const lifecycle = lifecycleFromRequestContext(current?.snapshot.requestContext);
677
+ const intent = lifecycle?.transitionIntent;
678
+ const terminal = lifecycle?.terminal;
679
+ const terminalStatus = !intent && isTerminalRunStatus(current?.summary?.status)
680
+ ? (terminal?.status ?? 'cancelled')
681
+ : undefined;
682
+ const pendingTransition = (intent?.childCascadeStarted && intent.status === status
683
+ ? intent
684
+ : undefined) ??
685
+ (terminalStatus === status && terminal?.cleanupCompletedAt === undefined
686
+ ? terminal
687
+ : undefined);
688
+ if (cascade.pendingCommit && pendingTransition) {
689
+ const [principal] = pendingTransition.replayPrincipals;
690
+ if (!principal)
691
+ throw new RunStateUnreadableError(workflowId, runId);
692
+ const owner = (await this.runOwnership(this.env).owner('run', runId)) ?? principal;
693
+ const result = await runtime.cascadeTerminateAsPrincipal(workflowId, runId, status, owner, (nextStatus, commitIntent) => this.#cascadeChildren(workflowId, runId, nextStatus, commitIntent), { recordedIntentOnly: true });
694
+ await this.#finalizeAndPublishTerminal(runtime, workflowId, runId, owner, result);
695
+ }
696
+ else if (terminalStatus === status && cascade.retryChildren !== false) {
697
+ await this.#runChildCascade(cascade, this.childRunTopology(this.env));
698
+ }
699
+ else {
700
+ await storage.delete(CHILD_CASCADE_KEY);
701
+ }
702
+ }
703
+ catch (error) {
704
+ const pending = await storage.get(CHILD_CASCADE_KEY);
705
+ if (!pending)
706
+ throw error;
707
+ const expiresAt = pending.startedAt + CHILD_RUN_RETRY_LIMIT_MS;
708
+ if (Date.now() >= expiresAt) {
709
+ logChildRunRetryAbandoned(workflowId, runId);
710
+ await storage.delete(CHILD_CASCADE_KEY);
711
+ }
712
+ else {
713
+ await storage.put(CHILD_CASCADE_KEY, {
714
+ ...pending,
715
+ attempts: pending.attempts + 1,
716
+ nextAttemptAt: childRunRetryAt(Date.now(), pending.attempts + 1, expiresAt),
717
+ });
718
+ }
719
+ throw error;
720
+ }
721
+ }
722
+ async #childResult(workflowId, runId, key) {
723
+ assertChildRunKey(key);
724
+ const ledger = this.#childRunLedger();
725
+ const address = {
726
+ parentWorkflowId: workflowId,
727
+ parentRunId: runId,
728
+ childKey: key,
729
+ };
730
+ const topology = this.childRunTopology(this.env);
731
+ let entry = await ledger.get(address);
732
+ if (topology && entry?.state === 'starting') {
733
+ await withinChildRunCall(topology.resolveChildStart(entry.childWorkflowId, entry.childRunId));
734
+ entry = await ledger.get(address);
735
+ }
736
+ if (!entry || entry.state === 'refused')
737
+ throw new ChildRunRefusedError(entry?.refusalCode ?? 'HOST_REFUSED');
738
+ const result = await topology?.status(entry.childWorkflowId, entry.childRunId);
739
+ if (!result)
740
+ throw new UnknownRunError(entry.childWorkflowId, entry.childRunId);
741
+ return result;
742
+ }
743
+ async #stageParentNotice(workflowId, runId, cleanupRevision) {
744
+ const storage = this.state?.storage;
745
+ if (!storage)
746
+ throw new ChildRunRefusedError('HOST_REFUSED');
747
+ if ((await storage.get(PARENT_NOTIFY_KEY)) !== undefined)
748
+ return;
749
+ const now = Date.now();
750
+ const nextAttemptAt = now + SUSPENSION_DEADLINE_ARM_FLOOR_MS;
751
+ // The wake can finish the ledger CAS if the object stops after writing the marker.
752
+ await this.#armNextAlarm(nextAttemptAt);
753
+ await storage.put(PARENT_NOTIFY_KEY, {
754
+ workflowId,
755
+ runId,
756
+ settledAt: now,
757
+ nextAttemptAt,
758
+ attempts: 0,
759
+ cleanupRevision,
760
+ });
761
+ }
762
+ async #recordChildOutcome(workflowId, summary) {
763
+ if (!summary.parentRunId || !isTerminalRunStatus(summary.status))
764
+ return;
765
+ try {
766
+ const entry = await this.#childRunLedger().getByRunId(summary.runId);
767
+ if (!entry || entry.state === 'terminal' || entry.state === 'refused')
768
+ return;
769
+ const selected = await this.#ensureRuntime().authoritativeStartState(workflowId, summary.runId);
770
+ if (selected?.kind !== 'result')
771
+ throw new RunStateUnreadableError(workflowId, summary.runId);
772
+ const lifecycle = lifecycleFromRequestContext(selected.snapshot.requestContext);
773
+ if (lifecycle?.transitionIntent ||
774
+ (lifecycle?.terminal &&
775
+ !terminalCleanupFor(lifecycle)?.cleanupCompleted))
776
+ return;
777
+ await this.#stageParentNotice(workflowId, summary.runId);
778
+ await this.#settleChildOutcome(entry, selected);
779
+ }
780
+ catch (error) {
781
+ console.error('child outcome recording failed', error);
782
+ // Managed terminal cleanup stages its own notice before completion.
783
+ if (summary.status === 'cancelled' || summary.status === 'timed_out')
784
+ return;
785
+ try {
786
+ await this.#stageParentNotice(workflowId, summary.runId);
787
+ }
788
+ catch (noticeError) {
789
+ console.error('child outcome recovery could not be armed', noticeError);
790
+ }
791
+ }
792
+ }
793
+ async #settleChildOutcome(entry, selected) {
794
+ if (selected.kind !== 'result' ||
795
+ !isTerminalRunStatus(selected.summary.status))
796
+ throw new RunStateUnreadableError(entry.childWorkflowId, entry.childRunId);
797
+ const lineage = parseRunLineage(selected.snapshot.requestContext?.[RUN_LINEAGE_CONTEXT_KEY]);
798
+ if (!matchesChildLineage(entry, lineage))
799
+ throw new Error('child outcome does not match its reservation');
800
+ const ledger = this.#childRunLedger();
801
+ if (entry.state === 'starting')
802
+ await ledger.resolveStarting(entry.childRunId, 'admitted');
803
+ await ledger.settle(entry.childRunId, selected.summary);
804
+ }
805
+ async #receiveChildCascade(request, workflowId, runId) {
806
+ this.#assertRunIdentity(workflowId, runId);
807
+ const { status, parentWorkflowId, parentRunId } = (await readJson(request)) ?? {};
808
+ if ((status !== 'cancelled' && status !== 'timed_out') ||
809
+ !isPathSafeId(parentWorkflowId) ||
810
+ !isPathSafeId(parentRunId))
811
+ throw new InvalidRunRequestError('invalid child cascade body');
812
+ const ledger = this.#childRunLedger();
813
+ const entry = await ledger.getByRunId(runId);
814
+ if (!entry ||
815
+ entry.childWorkflowId !== workflowId ||
816
+ entry.parentWorkflowId !== parentWorkflowId ||
817
+ entry.parentRunId !== parentRunId ||
818
+ entry.cancelRequestedAt === undefined)
819
+ throw new ChildRunRefusedError('HOST_REFUSED');
820
+ const done = () => new Response(null, { status: 204 });
821
+ if (entry.state === 'terminal' || entry.state === 'refused')
822
+ return done();
823
+ const runtime = this.#ensureRuntime();
824
+ const read = async () => {
825
+ const selected = await runtime.authoritativeStartState(workflowId, runId);
826
+ const lineage = parseRunLineage(selected?.snapshot.requestContext?.[RUN_LINEAGE_CONTEXT_KEY]);
827
+ if (selected && !matchesChildLineage(entry, lineage))
828
+ throw new ChildRunRefusedError('HOST_REFUSED');
829
+ return selected;
830
+ };
831
+ const selected = await read();
832
+ const frameKey = this.#inFlightKey(workflowId, runId);
833
+ const frame = this.#startsInFlight.get(frameKey);
834
+ const frameOwner = matchesChildLineage(entry, frame?.childLineage)
835
+ ? frame?.owner
836
+ : undefined;
837
+ const owner = selected?.provenance.startIdentity?.owner ?? frameOwner;
838
+ const lifecycle = lifecycleFromRequestContext(selected?.snapshot.requestContext);
839
+ if (owner && !lifecycle?.terminal) {
840
+ try {
841
+ await runtime.cancelActiveExecution(workflowId, runId, lifecycle?.transitionIntent?.status ?? status, [owner]);
842
+ }
843
+ catch (error) {
844
+ if (!(error instanceof RunTerminalConflictError)) {
845
+ if (!(error instanceof UnknownRunError) ||
846
+ !frameOwner ||
847
+ !frame ||
848
+ frame.unwound ||
849
+ this.#startsInFlight.get(frameKey) !== frame)
850
+ throw error;
851
+ frame.pendingTerminal ??= { status, replayPrincipals: [frameOwner] };
852
+ }
853
+ }
854
+ }
855
+ return this.#withOperationLock(async () => {
856
+ const current = await read();
857
+ if (!current) {
858
+ const journal = await this.state?.storage?.get(RUN_OWNER_RECOVERY_KEY);
859
+ if (journal !== undefined)
860
+ throw new RunStartPendingError();
861
+ // A queued start rechecks the stamped reservation before admission.
862
+ if (await ledger.refuseCancelledStart(runId))
863
+ return done();
864
+ const row = await ledger.getByRunId(runId);
865
+ if (row?.state === 'refused' || row?.state === 'terminal')
866
+ return done();
867
+ throw new RunStateUnreadableError(workflowId, runId);
868
+ }
869
+ const currentLifecycle = lifecycleFromRequestContext(current.snapshot.requestContext);
870
+ if (current.kind === 'result' &&
871
+ isTerminalRunStatus(current.summary.status) &&
872
+ !currentLifecycle?.transitionIntent &&
873
+ (!currentLifecycle?.terminal ||
874
+ terminalCleanupFor(currentLifecycle)?.cleanupCompleted)) {
875
+ await this.#recordRunEnd(workflowId, current.summary);
876
+ return done();
877
+ }
878
+ const currentOwner = current.provenance.startIdentity?.owner;
879
+ if (!currentOwner)
880
+ throw new ChildRunRefusedError('HOST_REFUSED');
881
+ const transition = await runtime.cascadeTerminateAsPrincipal(workflowId, runId, currentLifecycle?.transitionIntent?.status ?? status, currentOwner, (terminalStatus, commitIntent) => this.#cascadeChildren(workflowId, runId, terminalStatus, commitIntent));
882
+ await this.#finalizeAndPublishTerminal(runtime, workflowId, runId, currentOwner, transition);
883
+ return done();
884
+ });
885
+ }
886
+ async #sendParentNotice() {
887
+ const storage = this.state?.storage;
888
+ const notice = await storage?.get(PARENT_NOTIFY_KEY);
889
+ if (!storage || !notice || notice.nextAttemptAt > Date.now())
890
+ return;
891
+ const { workflowId, runId } = notice;
892
+ this.#assertRunIdentity(workflowId, runId);
893
+ const abandon = async () => {
894
+ await storage.delete(PARENT_NOTIFY_KEY);
895
+ logChildRunRetryAbandoned(workflowId, runId);
896
+ };
897
+ let expiresAt = notice.settledAt + CHILD_RUN_RETRY_LIMIT_MS;
898
+ try {
899
+ const ledger = this.#childRunLedger();
900
+ let entry = await ledger.getByRunId(runId);
901
+ if (entry && entry.state !== 'terminal' && entry.state !== 'refused') {
902
+ const runtime = this.#ensureRuntime();
903
+ const selected = await runtime.authoritativeStartState(workflowId, runId);
904
+ if (selected?.kind !== 'result' ||
905
+ !isTerminalRunStatus(selected.summary.status))
906
+ throw new RunStateUnreadableError(workflowId, runId);
907
+ const lifecycle = lifecycleFromRequestContext(selected.snapshot.requestContext);
908
+ const cleanup = terminalCleanupFor(lifecycle);
909
+ if (lifecycle?.transitionIntent ||
910
+ (cleanup &&
911
+ !cleanup.cleanupCompleted &&
912
+ cleanup.revision !== notice.cleanupRevision))
913
+ throw new RunStateUnreadableError(workflowId, runId);
914
+ const summary = cleanup && !cleanup.cleanupCompleted
915
+ ? await runtime.completeTerminalCleanup(workflowId, runId, cleanup.revision)
916
+ : selected.summary;
917
+ await this.#settleChildOutcome(entry, { ...selected, summary });
918
+ entry = await ledger.getByRunId(runId);
919
+ }
920
+ if (!entry || entry.state === 'refused') {
921
+ await storage.delete(PARENT_NOTIFY_KEY);
922
+ return;
923
+ }
924
+ if (entry.state !== 'terminal')
925
+ throw new RunStateUnreadableError(workflowId, runId);
926
+ expiresAt = entry.updatedAt + CHILD_RUN_RETRY_LIMIT_MS;
927
+ if (Date.now() >= expiresAt) {
928
+ await abandon();
929
+ return;
930
+ }
931
+ const topology = this.childRunTopology(this.env);
932
+ if (topology?.notifyChildSettled) {
933
+ const signal = AbortSignal.timeout(Math.min(CHILD_RUN_CALL_TIMEOUT_MS, Math.max(0, expiresAt - Date.now())));
934
+ await waitForChildCall(topology.notifyChildSettled(entry.parentWorkflowId, entry.parentRunId, signal), signal);
935
+ }
936
+ await storage.delete(PARENT_NOTIFY_KEY);
937
+ }
938
+ catch (error) {
939
+ const now = Date.now();
940
+ if (now >= expiresAt) {
941
+ await abandon();
942
+ return;
943
+ }
944
+ const attempts = notice.attempts + 1;
945
+ await storage.put(PARENT_NOTIFY_KEY, {
946
+ ...notice,
947
+ attempts,
948
+ nextAttemptAt: childRunRetryAt(now, attempts, expiresAt),
949
+ });
950
+ console.error('child settlement notice failed', error);
951
+ }
952
+ }
953
+ async #readChildAwait(workflowId, summary, entry) {
954
+ const awaitChildren = childAwaitForStep(summary, entry.step);
955
+ if (!awaitChildren)
956
+ return undefined;
957
+ const { keys, mode } = awaitChildren;
958
+ const rows = await this.#childRunLedger().listTerminal({ parentWorkflowId: workflowId, parentRunId: summary.runId }, keys);
959
+ const childRunIds = [];
960
+ const outcomes = new Map();
961
+ let finishedOnTime = 0;
962
+ let newlyFinishedOnTime = false;
963
+ for (const row of rows) {
964
+ if (!row.outcome)
965
+ continue;
966
+ const undelivered = row.deliveredAt === undefined;
967
+ if (undelivered)
968
+ childRunIds.push(row.childRunId);
969
+ outcomes.set(row.childKey, row.outcome);
970
+ if (row.updatedAt <= entry.deadlineAt) {
971
+ finishedOnTime++;
972
+ if (undelivered)
973
+ newlyFinishedOnTime = true;
974
+ }
975
+ }
976
+ return {
977
+ ready: newlyFinishedOnTime &&
978
+ (mode === 'any' || finishedOnTime === keys.length),
979
+ childRunIds,
980
+ resumeData: {
981
+ [CHILDREN_RESUME_KEY]: { mode, outcomes: Object.fromEntries(outcomes) },
982
+ },
983
+ };
984
+ }
985
+ async #resumeChildAwait(runtime, workflowId, summary, entry, delivery, armed, timeout) {
986
+ const { runId, requestedBy, requestedByKind } = summary;
987
+ const next = await this.#withLeg(workflowId, runId, timeout ? 'deadline' : 'resume', () => runtime.resumeChildAwait(workflowId, runId, {
988
+ step: [entry.step],
989
+ expectedSuspension: {
990
+ suspendedAt: entry.suspendedAt,
991
+ resumeCount: entry.resumeCount,
992
+ },
993
+ resumeData: { ...timeout, ...delivery.resumeData },
994
+ ...(requestedBy === undefined && timeout
995
+ ? {
996
+ requestedBy: SUSPENSION_DEADLINE_PRINCIPAL_ID,
997
+ requestedByKind: 'system',
998
+ }
999
+ : requestedBy !== undefined && requestedByKind === undefined
1000
+ ? { requestedBy, requestedByKind: 'human' }
1001
+ : {}),
1002
+ }), armed, false);
1003
+ if (this.#suspensionFenceMatches(next, entry))
1004
+ throw new Error('child await resume outcome is unresolved');
1005
+ try {
1006
+ await this.#childRunLedger().markDelivered(delivery.childRunIds);
1007
+ if (hasChildAwait(next))
1008
+ this.#queueChildAwait(workflowId, runId);
1009
+ }
1010
+ catch (error) {
1011
+ console.error('child await delivery bookkeeping failed', error);
1012
+ }
1013
+ return next;
1014
+ }
1015
+ async #attemptChildAwait(runtime, summary, stored, entry, armed, now) {
1016
+ const { workflowId, runId } = stored;
1017
+ const attempts = (entry.attempts ?? 0) + 1;
1018
+ const exhausted = attempts >= MAX_SUSPENSION_DEADLINE_ATTEMPTS;
1019
+ let settling = entry.childRetry === 'settle';
1020
+ let failure;
1021
+ if (!settling) {
1022
+ try {
1023
+ const delivery = await this.#readChildAwait(workflowId, summary, entry);
1024
+ if (!delivery)
1025
+ return undefined;
1026
+ if (!delivery.ready && now < entry.deadlineAt) {
1027
+ if (entry.childRetry === undefined)
1028
+ return undefined;
1029
+ await this.#writeSuspensionDeadlines(workflowId, runId, stored, [
1030
+ ...entriesWithoutStep(stored.entries, entry.step),
1031
+ { ...entry, nextAttemptAt: entry.deadlineAt },
1032
+ ]);
1033
+ return null;
1034
+ }
1035
+ await runtime.assertExistingRunAllowed(workflowId, runId);
1036
+ return await this.#resumeChildAwait(runtime, workflowId, summary, entry, delivery, armed, delivery.ready ? undefined : suspensionTimeoutResumeData(entry, now));
1037
+ }
1038
+ catch (error) {
1039
+ failure = error;
1040
+ settling =
1041
+ error instanceof ChildAwaitResumeSchemaError ||
1042
+ (exhausted && !isExecutionFenceRefusal(error));
1043
+ }
1044
+ }
1045
+ if (settling) {
1046
+ try {
1047
+ const failed = await runtime.failChildAwaitResume(workflowId, runId, entry);
1048
+ if (failed) {
1049
+ try {
1050
+ await this.#reconcileQuestions(workflowId, failed);
1051
+ }
1052
+ catch (error) {
1053
+ console.error('child await failure question reconciliation failed', error);
1054
+ }
1055
+ await this.#recordRunEnd(workflowId, failed);
1056
+ await this.#settleClosedRunInvocationsBestEffort(workflowId, runId);
1057
+ }
1058
+ return failed ?? (await runtime.authoritativeStatus(workflowId, runId));
1059
+ }
1060
+ catch (error) {
1061
+ failure = error;
1062
+ }
1063
+ }
1064
+ console.error(exhausted
1065
+ ? 'child await retry budget exhausted'
1066
+ : 'child await resume will retry', { workflowId, runId, step: entry.step, attempts, error: failure });
1067
+ const retryAt = Date.now() + SUSPENSION_DEADLINE_RETRY_MS * 2 ** (attempts - 1);
1068
+ await this.#writeSuspensionDeadlines(workflowId, runId, stored, [
1069
+ ...entriesWithoutStep(stored.entries, entry.step),
1070
+ exhausted
1071
+ ? tombstoned(entry)
1072
+ : {
1073
+ ...entry,
1074
+ attempts,
1075
+ childRetry: settling ? 'settle' : 'resume',
1076
+ // Keep one attempt for the deadline after pre-deadline failures.
1077
+ nextAttemptAt: !settling && attempts === MAX_SUSPENSION_DEADLINE_ATTEMPTS - 1
1078
+ ? Math.max(retryAt, entry.deadlineAt)
1079
+ : retryAt,
1080
+ },
1081
+ ]);
1082
+ return null;
1083
+ }
1084
+ async #resumeReadyChildAwait(workflowId, runId, armed, stored) {
1085
+ const runtime = this.#ensureRuntime();
1086
+ const selected = await runtime.authoritativeStartState(workflowId, runId, {
1087
+ includeLegacy: true,
1088
+ });
1089
+ if (selected?.summary?.status !== 'suspended' ||
1090
+ lifecycleFromRequestContext(selected.snapshot.requestContext)
1091
+ ?.transitionIntent)
1092
+ return undefined;
1093
+ const { summary } = selected;
1094
+ if (hasInvalidChildAwait(summary))
1095
+ return undefined;
1096
+ const previous = stored === undefined
1097
+ ? await this.#readSuspensionDeadlines()
1098
+ : (stored ?? undefined);
1099
+ const record = {
1100
+ version: 1,
1101
+ workflowId,
1102
+ runId,
1103
+ entries: mergeSuspensionDeadlines(ownSuspensionDeadlines(previous, workflowId, runId), suspensionDeadlinesOf(summary).entries),
1104
+ };
1105
+ for (const entry of record.entries) {
1106
+ const now = Date.now();
1107
+ if (entry.deadlineAt <= now || entry.attempts !== undefined)
1108
+ continue;
1109
+ const next = await this.#attemptChildAwait(runtime, summary, record, entry, armed, now);
1110
+ if (next !== undefined)
1111
+ return next && { summary: next, ended: entry };
1112
+ }
1113
+ return undefined;
1114
+ }
1115
+ #queueChildAwait(workflowId, runId) {
1116
+ const queued = this.#withOperationLock(async () => {
1117
+ try {
1118
+ const resumed = await this.#resumeReadyChildAwait(workflowId, runId, false);
1119
+ if (!resumed)
1120
+ return;
1121
+ if (await this.#reconcileSuspensionDeadlinesBestEffort(workflowId, runId, resumed.summary))
1122
+ await this.#armNextAlarm();
1123
+ await this.#publishChildAwaitResume(workflowId, resumed.summary, resumed.ended);
1124
+ }
1125
+ catch (error) {
1126
+ console.error('child await reconciliation failed', error);
1127
+ await this.#armNextAlarm(Date.now() + SUSPENSION_DEADLINE_RETRY_MS);
1128
+ }
1129
+ }).catch((error) => console.error('child await wake failed', error));
1130
+ this.state?.waitUntil?.(queued);
1131
+ }
1132
+ async #publishChildAwaitResume(workflowId, summary, ended) {
1133
+ try {
1134
+ this.#broadcastRunSummary(summary);
1135
+ }
1136
+ catch (error) {
1137
+ console.error('child await broadcast failed', error);
1138
+ }
1139
+ await this.#reconcileApprovalsBestEffort(workflowId, summary.runId, summary, ended);
1140
+ }
1141
+ async #rejectInvalidChildAwait(workflowId, summary) {
1142
+ if (!hasInvalidChildAwait(summary))
1143
+ return summary;
1144
+ const failed = await this.#ensureRuntime().failInvalidChildAwait(workflowId, summary.runId, hasInvalidChildAwait);
1145
+ if (failed)
1146
+ await this.#settleClosedRunInvocationsBestEffort(workflowId, summary.runId);
1147
+ return failed ?? summary;
1148
+ }
1149
+ async #reconcileChildStarts(workflowId, runId) {
1150
+ const storage = this.state?.storage;
1151
+ if (!storage || !hasDatabaseBinding(this.env))
1152
+ return;
1153
+ const topology = this.childRunTopology(this.env);
1154
+ if (!topology)
1155
+ return;
1156
+ const address = { parentWorkflowId: workflowId, parentRunId: runId };
1157
+ const ledger = this.#childRunLedger();
1158
+ const starting = await ledger.listStarting(address);
1159
+ const recovery = await storage.get(CHILD_START_RECOVERY_KEY);
1160
+ if (starting.length === 0) {
1161
+ if (recovery !== undefined)
1162
+ await storage.delete(CHILD_START_RECOVERY_KEY);
1163
+ return;
1164
+ }
1165
+ if (recovery === undefined)
1166
+ await storage.put(CHILD_START_RECOVERY_KEY, true);
1167
+ const resolutions = await Promise.allSettled(starting.map((entry) => withinChildRunCall(topology.resolveChildStart(entry.childWorkflowId, entry.childRunId))));
1168
+ for (const resolution of resolutions) {
1169
+ if (resolution.status === 'rejected')
1170
+ console.error('child start resolution failed', resolution.reason);
1171
+ }
1172
+ if ((await ledger.listStarting(address)).length === 0)
1173
+ await storage.delete(CHILD_START_RECOVERY_KEY);
1174
+ }
1175
+ async #resolveChildStart(workflowId, runId) {
1176
+ const ledger = this.#childRunLedger();
1177
+ const runtime = this.#ensureRuntime();
1178
+ const resolve = async (allowAbsence) => {
1179
+ const entry = await ledger.getByRunId(runId);
1180
+ if (entry?.state !== 'starting' || entry.childWorkflowId !== workflowId)
1181
+ return true;
1182
+ const state = await runtime.authoritativeStartState(workflowId, runId);
1183
+ if (state) {
1184
+ const lineage = parseRunLineage(state.snapshot.requestContext?.[RUN_LINEAGE_CONTEXT_KEY]);
1185
+ if (!matchesChildLineage(entry, lineage))
1186
+ throw new RunStateUnreadableError(workflowId, runId);
1187
+ // Start recovery and cascade record the outcome after their own cleanup.
1188
+ const recordOutcome = entry.cancelRequestedAt === undefined &&
1189
+ state.kind === 'result' &&
1190
+ isTerminalRunStatus(state.summary.status) &&
1191
+ (await this.state?.storage.get(RUN_OWNER_RECOVERY_KEY)) === undefined;
1192
+ await ledger.resolveStarting(runId, 'admitted');
1193
+ if (recordOutcome)
1194
+ await this.#recordChildOutcome(workflowId, state.summary);
1195
+ return true;
1196
+ }
1197
+ if (Date.now() - entry.createdAt < CHILD_RUN_CALL_TIMEOUT_MS &&
1198
+ entry.cancelRequestedAt === undefined)
1199
+ return true;
1200
+ if (!allowAbsence)
1201
+ return false;
1202
+ if (entry.cancelRequestedAt !== undefined &&
1203
+ (await this.state?.storage.get(RUN_OWNER_RECOVERY_KEY)) !== undefined)
1204
+ throw new RunStartPendingError();
1205
+ await ledger.resolveStarting(runId, 'absent');
1206
+ return true;
1207
+ };
1208
+ // An absent observation must exclude a concurrent initial admission.
1209
+ if (!(await resolve(false)))
1210
+ await this.#withOperationLock(() => resolve(true));
1211
+ }
1212
+ async #childStartEntry(workflowId, runId, body) {
1213
+ const { inputData, deadlineMs, requestContext } = body;
1214
+ assertRunInputDepth('inputData', inputData);
1215
+ for (const value of Object.values(requestContext ?? {}))
1216
+ assertRunInputDepth('a requestContext value', value);
1217
+ const entry = await this.#childRunLedger().getByRunId(runId);
1218
+ if (!entry ||
1219
+ entry.childWorkflowId !== workflowId ||
1220
+ entry.inputDigest !== (await childJsonDigest(inputData)) ||
1221
+ (entry.state === 'starting' &&
1222
+ entry.dispatchDigest !==
1223
+ (await childJsonDigest([deadlineMs ?? null, requestContext ?? null])))) {
1224
+ throw new ChildRunRefusedError('HOST_REFUSED');
1225
+ }
1226
+ if (entry.state === 'refused')
1227
+ throw new ChildRunRefusedError(entry.refusalCode ?? 'HOST_REFUSED');
1228
+ return entry;
1229
+ }
1230
+ async #childAdmission(entry) {
1231
+ try {
1232
+ return await this.#readChildAdmission(entry);
1233
+ }
1234
+ catch (error) {
1235
+ if (error instanceof ChildRunRefusedError)
1236
+ await this.#childRunLedger().markRefused(entry.childRunId, Date.now(), error.code);
1237
+ throw error;
1238
+ }
1239
+ }
1240
+ async #readChildAdmission(entry) {
1241
+ const ledger = this.#childRunLedger();
1242
+ const { parentWorkflowId, parentRunId, childKey, childWorkflowId } = entry;
1243
+ const source = await this.#childParent(parentWorkflowId, parentRunId, childKey);
1244
+ const receipt = await this.childRunTopology(this.env)?.startPrincipal(parentWorkflowId, parentRunId);
1245
+ const owner = await this.#registeredChildOwner(parentRunId, receipt?.principal, source.originalOwner);
1246
+ if (source.parent.rootRunId !== entry.rootRunId ||
1247
+ source.parent.depth + 1 !== entry.depth) {
1248
+ throw new ChildRunRefusedError('HOST_REFUSED');
1249
+ }
1250
+ if (entry.versionPin !== undefined &&
1251
+ (await this.workflowVersion(this.env)?.(childWorkflowId)) !==
1252
+ entry.versionPin) {
1253
+ throw new ChildRunRefusedError('VERSION_UNAVAILABLE');
1254
+ }
1255
+ const current = await ledger.getByRunId(entry.childRunId);
1256
+ if (current?.state !== 'starting' ||
1257
+ current.cancelRequestedAt !== undefined ||
1258
+ (source.deadlineAt !== undefined && source.deadlineAt <= Date.now())) {
1259
+ throw new ChildRunRefusedError('HOST_REFUSED');
1260
+ }
1261
+ const lineage = {
1262
+ version: 1,
1263
+ parentWorkflowId,
1264
+ parentRunId,
1265
+ rootWorkflowId: source.rootWorkflowId,
1266
+ rootRunId: entry.rootRunId,
1267
+ depth: entry.depth,
1268
+ childKey,
1269
+ };
1270
+ return {
1271
+ owner,
1272
+ lineage,
1273
+ parentDeadlineAt: source.deadlineAt,
1274
+ runRequester: source.parent.runRequester,
1275
+ };
1276
+ }
1277
+ async #reconcileQuestions(workflowId, summary) {
1278
+ const questions = currentQuestions(workflowId, summary);
1279
+ if (questions.length === 0 && !isTerminalRunStatus(summary.status))
1280
+ return;
1281
+ const db = this.#questionDatabase();
1282
+ if (!db) {
1283
+ if (questions.length > 0)
1284
+ throw new Error('question suspensions require a D1 database');
1285
+ return;
1286
+ }
1287
+ if (isTerminalRunStatus(summary.status)) {
1288
+ await supersedeOpenQuestions(db, workflowId, summary.runId);
1289
+ }
1290
+ for (const question of questions) {
1291
+ let existing = await getQuestion(db, workflowId, summary.runId, question.questionId, question);
1292
+ if (!existing) {
1293
+ await this.#ensureRuntime().assertExistingRunAllowed(workflowId, summary.runId);
1294
+ await openQuestion(db, question, this.runLifecycle(this.env)?.humanNotifications);
1295
+ existing = await getQuestion(db, workflowId, summary.runId, question.questionId, question);
1296
+ }
1297
+ if (existing)
1298
+ await this.#applyEarlyAnswer(db, existing);
1299
+ }
1300
+ }
1301
+ async #armQuestionRecovery(workflowId, runId) {
1302
+ const storage = this.state?.storage;
1303
+ if (!storage)
1304
+ return;
1305
+ await this.#armNextAlarm(Date.now() + RUN_OWNER_RECOVERY_DELAY_MS);
1306
+ const previous = await storage.get(QUESTION_RECOVERY_KEY);
1307
+ if (previous?.workflowId !== workflowId || previous.runId !== runId)
1308
+ await storage.put(QUESTION_RECOVERY_KEY, {
1309
+ workflowId,
1310
+ runId,
1311
+ });
1312
+ }
1313
+ async #applyEarlyAnswer(db, question) {
1314
+ const early = await readEarlyAnswer(db, question);
1315
+ if (!early)
1316
+ return;
1317
+ if (question.state !== 'open') {
1318
+ await deleteEarlyAnswer(db, question);
1319
+ return;
1320
+ }
1321
+ const { workflowId, runId, questionId } = question;
1322
+ await this.#ensureRuntime().assertExistingRunAllowed(workflowId, runId);
1323
+ const hooks = this.runLifecycle(this.env);
1324
+ let decision = 'denied';
1325
+ let reason = 'forbidden';
1326
+ let fieldIds = [];
1327
+ let allowed = false;
1328
+ if (early.state === 'invalid') {
1329
+ decision = 'error';
1330
+ reason = 'invalid stored submission';
1331
+ }
1332
+ else {
1333
+ try {
1334
+ allowed =
1335
+ (await hooks?.authorizeAnswer?.(question, early.principal, {
1336
+ storedSubmission: true,
1337
+ })) === true;
1338
+ }
1339
+ catch {
1340
+ decision = 'error';
1341
+ reason = 'authorization failed';
1342
+ }
1343
+ }
1344
+ if (early.state === 'ready' && allowed) {
1345
+ await this.#armQuestionRecovery(workflowId, runId);
1346
+ try {
1347
+ await answerQuestion(db, question, early.principal, early.answers, early.idempotencyKey);
1348
+ await deleteEarlyAnswer(db, question);
1349
+ return;
1350
+ }
1351
+ catch (error) {
1352
+ if (!(error instanceof AnswersInvalidError))
1353
+ throw error;
1354
+ fieldIds = error.fieldIds;
1355
+ reason = 'invalid answers';
1356
+ }
1357
+ }
1358
+ await deleteEarlyAnswer(db, question);
1359
+ const event = {
1360
+ action: 'question.early-answer',
1361
+ actor: early.principal?.kind === 'human'
1362
+ ? { id: early.principal.id, role: early.principal.role }
1363
+ : null,
1364
+ resource: `question:${workflowId}:${runId}:${questionId}`,
1365
+ decision,
1366
+ reason,
1367
+ detail: { fieldIds },
1368
+ };
1369
+ try {
1370
+ if (hooks?.audit) {
1371
+ Promise.resolve(hooks.audit(event)).catch((error) => {
1372
+ console.error('early question answer audit failed', error);
1373
+ });
1374
+ }
1375
+ else {
1376
+ console.log(JSON.stringify({ type: 'audit', ...event }));
1377
+ }
1378
+ }
1379
+ catch (error) {
1380
+ console.error('early question answer audit failed', error);
1381
+ }
1382
+ }
1383
+ async #reconcileQuestionsOnRead(workflowId, summary) {
1384
+ const questions = currentQuestions(workflowId, summary);
1385
+ if (questions.length === 0)
1386
+ return summary;
1387
+ const db = this.#questionDatabase();
1388
+ if (db) {
1389
+ const settled = await Promise.all(questions.map(async (question) => {
1390
+ const existing = await getQuestion(db, workflowId, summary.runId, question.questionId, question);
1391
+ return (existing !== null &&
1392
+ existing.state !== 'answered' &&
1393
+ existing.state !== 'expired' &&
1394
+ (existing.state !== 'open' ||
1395
+ !(await readEarlyAnswer(db, question))));
1396
+ }));
1397
+ if (settled.every(Boolean))
1398
+ return summary;
1399
+ }
1400
+ return this.#withOperationLock(async () => {
1401
+ const runtime = this.#ensureRuntime();
1402
+ const current = await runtime.authoritativeStatus(workflowId, summary.runId);
1403
+ if (!current)
1404
+ return summary;
1405
+ try {
1406
+ return await this.#recoverQuestionResumes(runtime, workflowId, current, false);
1407
+ }
1408
+ catch (error) {
1409
+ console.error('question status reconciliation failed', error);
1410
+ return current;
1411
+ }
1412
+ });
1413
+ }
1414
+ async #recoverQuestionResumes(runtime, workflowId, summary, armed) {
1415
+ await this.#reconcileQuestions(workflowId, summary);
1416
+ const db = this.#questionDatabase();
1417
+ let pending = false;
1418
+ if (db) {
1419
+ for (const question of currentQuestions(workflowId, summary)) {
1420
+ const stored = await getQuestion(db, workflowId, summary.runId, question.questionId, question);
1421
+ if (stored?.state !== 'answered' && stored?.state !== 'expired')
1422
+ continue;
1423
+ pending = true;
1424
+ const resumed = await this.#resumeSettledQuestion(runtime, db, stored, summary, armed);
1425
+ if (resumed === null)
1426
+ continue;
1427
+ return (resumed ??
1428
+ (await runtime.authoritativeStatus(workflowId, summary.runId)) ??
1429
+ summary);
1430
+ }
1431
+ }
1432
+ if (!pending)
1433
+ await this.#clearQuestionRecovery();
1434
+ return summary;
1435
+ }
1436
+ async #clearQuestionRecovery() {
1437
+ const storage = this.state?.storage;
1438
+ if (storage && (await storage.get(QUESTION_RECOVERY_KEY)) !== undefined)
1439
+ await storage.delete(QUESTION_RECOVERY_KEY);
1440
+ }
1441
+ async #resumeSettledQuestion(runtime, db, question, summary, armed) {
1442
+ const { workflowId, runId, questionId, stepKey, suspendedAt, resumeCount } = question;
1443
+ const storage = this.state?.storage;
1444
+ const recovery = await storage?.get(QUESTION_RECOVERY_KEY);
1445
+ const retries = recovery?.workflowId === workflowId && recovery.runId === runId
1446
+ ? (recovery.retries ?? [])
1447
+ : [];
1448
+ const retry = retries.find((entry) => entry.questionId === questionId &&
1449
+ sameQuestionSuspension(entry, question));
1450
+ if (retry && retry.nextAttemptAt > Date.now())
1451
+ return null;
1452
+ if (recovery?.workflowId !== workflowId || recovery.runId !== runId)
1453
+ await this.#armQuestionRecovery(workflowId, runId);
1454
+ const settle = async () => {
1455
+ const failed = await runtime.failQuestionResume(workflowId, runId, question);
1456
+ if (failed) {
1457
+ await this.#reconcileQuestions(workflowId, failed);
1458
+ await this.#recordRunEnd(workflowId, failed);
1459
+ await this.#finishQuestionResume(workflowId, failed);
1460
+ }
1461
+ return failed;
1462
+ };
1463
+ if (retry?.attempts === MAX_SUSPENSION_DEADLINE_ATTEMPTS)
1464
+ return settle();
1465
+ try {
1466
+ return await this.#resumeQuestion(runtime, db, question, summary, armed);
1467
+ }
1468
+ catch (error) {
1469
+ if (isExecutionFenceRefusal(error) ||
1470
+ isRunStartPendingError(error) ||
1471
+ error instanceof RunStateUnreadableError ||
1472
+ error instanceof RunTerminalConflictError)
1473
+ throw error;
1474
+ const attempts = (retry?.attempts ?? 0) + 1;
1475
+ const exhausted = attempts >= MAX_SUSPENSION_DEADLINE_ATTEMPTS;
1476
+ const current = currentQuestions(workflowId, summary);
1477
+ const now = Date.now();
1478
+ await storage?.put(QUESTION_RECOVERY_KEY, {
1479
+ workflowId,
1480
+ runId,
1481
+ retries: [
1482
+ ...retries.filter((entry) => entry !== retry &&
1483
+ current.some((candidate) => candidate.questionId === entry.questionId &&
1484
+ sameQuestionSuspension(candidate, entry))),
1485
+ {
1486
+ questionId,
1487
+ stepKey,
1488
+ suspendedAt,
1489
+ resumeCount,
1490
+ attempts,
1491
+ nextAttemptAt: exhausted
1492
+ ? now
1493
+ : now + SUSPENSION_DEADLINE_RETRY_MS * 2 ** (attempts - 1),
1494
+ },
1495
+ ],
1496
+ });
1497
+ if (exhausted)
1498
+ return settle();
1499
+ throw error;
1500
+ }
1501
+ }
1502
+ async #resumeQuestion(runtime, db, question, summary, armed) {
1503
+ const { workflowId, runId, questionId, stepKey, suspendedAt, resumeCount } = question;
1504
+ const expired = question.state === 'expired';
1505
+ let answer;
1506
+ let requestedBy;
1507
+ let requestedByKind;
1508
+ if (expired) {
1509
+ answer = { questionId, answered: false, reason: 'expired' };
1510
+ requestedBy = summary.requestedBy ?? SUSPENSION_DEADLINE_PRINCIPAL_ID;
1511
+ requestedByKind =
1512
+ summary.requestedByKind ??
1513
+ (summary.requestedBy === undefined ? 'system' : 'human');
1514
+ }
1515
+ else {
1516
+ const { answers, answeredBy } = question;
1517
+ if (!answers || !answeredBy)
1518
+ throw new Error('stored question answer has no answers');
1519
+ answer = { questionId, answered: true, answers, answeredBy };
1520
+ requestedBy = answeredBy.id;
1521
+ requestedByKind = answeredBy.kind;
1522
+ }
1523
+ let resumed;
1524
+ try {
1525
+ resumed = await this.#withLeg(workflowId, runId, expired ? 'deadline' : 'resume', () => runtime.resume(workflowId, runId, {
1526
+ // The storage key is the complete step id, which can contain dots.
1527
+ step: [stepKey],
1528
+ expectedSuspension: {
1529
+ suspendedAt,
1530
+ ...(resumeCount === 0 ? {} : { resumeCount }),
1531
+ },
1532
+ requestedBy,
1533
+ requestedByKind,
1534
+ resumeData: {
1535
+ [QUESTION_ANSWER_RESUME_KEY]: answer,
1536
+ },
1537
+ }), armed);
1538
+ }
1539
+ catch (error) {
1540
+ if (error instanceof SuspensionChangedError) {
1541
+ await supersedeQuestion(db, question);
1542
+ return undefined;
1543
+ }
1544
+ if (error instanceof RunNotSuspendedError)
1545
+ return undefined;
1546
+ throw error;
1547
+ }
1548
+ const remaining = currentQuestions(workflowId, resumed);
1549
+ if (remaining.some((entry) => entry.questionId === questionId &&
1550
+ sameQuestionSuspension(entry, question))) {
1551
+ throw new QuestionResumeUnresolvedError('question resume outcome is unresolved');
1552
+ }
1553
+ await this.#finishQuestionResume(workflowId, resumed);
1554
+ return resumed;
1555
+ }
1556
+ async #finishQuestionResume(workflowId, summary) {
1557
+ const { runId } = summary;
1558
+ try {
1559
+ if (currentQuestions(workflowId, summary).length === 0)
1560
+ await this.#clearQuestionRecovery();
1561
+ if (await this.#reconcileSuspensionDeadlinesBestEffort(workflowId, runId, summary))
1562
+ await this.#armNextAlarm();
1563
+ this.#broadcastRunSummary(summary);
1564
+ }
1565
+ catch (error) {
1566
+ console.error('question resume finalization failed', error);
1567
+ }
1568
+ await this.#reconcileApprovalsBestEffort(workflowId, runId, summary);
1569
+ }
1570
+ async #answerQuestion(request, db, workflowId, runId, questionId, encodedPrincipal) {
1571
+ const principal = this.#trustedExecutionPrincipal(encodedPrincipal);
1572
+ const body = await readJson(request);
1573
+ const idempotencyKey = body?.idempotencyKey;
1574
+ if (!isPathSafeId(idempotencyKey))
1575
+ throw new InvalidRunRequestError('question answer requires an idempotency key');
1576
+ let expected;
1577
+ const runtime = this.#ensureRuntime();
1578
+ const early = body?.early === true;
1579
+ if (early) {
1580
+ if (body?.expected !== undefined)
1581
+ throw new InvalidRunRequestError('early answers cannot name a suspension');
1582
+ if (!this.runLifecycle(this.env)?.authorizeAnswer)
1583
+ return json({
1584
+ error: 'question answer authorization is not configured',
1585
+ reason: { code: 'ANSWER_AUTHORIZATION_UNCONFIGURED' },
1586
+ }, 403);
1587
+ // A running leg holds the operation lock until it suspends.
1588
+ const summary = await runtime.authoritativeStatus(workflowId, runId);
1589
+ if (!summary)
1590
+ throw new UnknownRunError(workflowId, runId);
1591
+ if (isTerminalRunStatus(summary.status))
1592
+ throw new QuestionNotOpenError('question is not open');
1593
+ await runtime.assertExistingRunAllowed(workflowId, runId);
1594
+ const current = currentQuestions(workflowId, summary).find((entry) => entry.questionId === questionId);
1595
+ if (!current) {
1596
+ const retained = await retainEarlyAnswer(db, { workflowId, runId, questionId }, principal, body?.answers, idempotencyKey);
1597
+ return json(retained, 202);
1598
+ }
1599
+ if (await getQuestion(db, workflowId, runId, questionId))
1600
+ throw new QuestionNotOpenError('question requires a suspension fingerprint');
1601
+ expected = current;
1602
+ }
1603
+ else {
1604
+ if (!isQuestionFingerprint(body?.expected))
1605
+ throw new InvalidRunRequestError('question answer requires a suspension fingerprint');
1606
+ expected = body.expected;
1607
+ }
1608
+ return this.#withOperationLock(async () => {
1609
+ const summary = await runtime.authoritativeStatus(workflowId, runId);
1610
+ if (!summary)
1611
+ throw new UnknownRunError(workflowId, runId);
1612
+ const isCurrent = currentQuestions(workflowId, summary).some((entry) => entry.questionId === questionId &&
1613
+ sameQuestionSuspension(entry, expected));
1614
+ if (isCurrent) {
1615
+ await runtime.assertExistingRunAllowed(workflowId, runId);
1616
+ await this.#reconcileQuestions(workflowId, summary);
1617
+ }
1618
+ const question = await getQuestion(db, workflowId, runId, questionId, expected);
1619
+ if (!question ||
1620
+ (question.state !== 'answered' &&
1621
+ (question.state !== 'open' || !isCurrent)))
1622
+ throw new QuestionNotOpenError('question is not open');
1623
+ if (early &&
1624
+ (await this.runLifecycle(this.env)?.authorizeAnswer?.(question, principal)) !== true)
1625
+ return json({ error: 'forbidden' }, 403);
1626
+ if (isCurrent)
1627
+ await this.#armQuestionRecovery(workflowId, runId);
1628
+ const stored = await answerQuestion(db, question, principal, body?.answers, idempotencyKey);
1629
+ if (isCurrent &&
1630
+ (await this.#resumeSettledQuestion(runtime, db, stored, summary, false)) === undefined)
1631
+ throw new SuspensionChangedError(workflowId, runId, question.stepKey);
1632
+ return json(stored);
1633
+ });
1634
+ }
336
1635
  #trustedExecutionPrincipal(encoded) {
337
1636
  const principal = encoded ? decodeExecutionPrincipal(encoded) : undefined;
338
1637
  if (!principal) {
@@ -396,6 +1695,13 @@ export class DurableObjectRunner {
396
1695
  };
397
1696
  return this.#completeTerminalEffects(runtime, workflowId, runId, owner, { ...result, summary: state.summary, cleanup }, assertNoJournal);
398
1697
  }
1698
+ async #finalizeAndPublishTerminal(runtime, workflowId, runId, owner, result) {
1699
+ const summary = await this.#finalizeTerminal(runtime, workflowId, runId, owner, result);
1700
+ await this.#settleClosedRunInvocationsBestEffort(workflowId, runId);
1701
+ await this.#reconcileSuspensionDeadlinesBestEffort(workflowId, runId, summary);
1702
+ this.#broadcastRunSummary(summary);
1703
+ return summary;
1704
+ }
399
1705
  async #resolveWorkflowRemoteReader(runtime) {
400
1706
  this.#workflowRemoteReader ??= await this.workflowRemoteSteps(this.env, runtime);
401
1707
  return this.#workflowRemoteReader;
@@ -423,8 +1729,12 @@ export class DurableObjectRunner {
423
1729
  async #completeTerminalEffects(runtime, workflowId, runId, owner, result, validate) {
424
1730
  if (validate)
425
1731
  await validate();
426
- if (result.cleanup.cleanupCompleted)
1732
+ await this.#reconcileQuestions(workflowId, result.summary);
1733
+ if (result.cleanup.cleanupCompleted) {
1734
+ await this.#recordRunEnd(workflowId, result.summary);
1735
+ await this.#completeChildCascade();
427
1736
  return result.summary;
1737
+ }
428
1738
  const hooks = this.runLifecycle(this.env);
429
1739
  if (!hooks) {
430
1740
  throw new Error('run termination requires lifecycle cleanup hooks');
@@ -455,9 +1765,13 @@ export class DurableObjectRunner {
455
1765
  throw new Error(`run '${runId}' ownership could not be released`);
456
1766
  }
457
1767
  }
1768
+ if (result.summary.parentRunId)
1769
+ await this.#stageParentNotice(workflowId, runId, result.cleanup.revision);
458
1770
  const summary = await runtime.completeTerminalCleanup(workflowId, runId, result.cleanup.revision);
459
1771
  if (validate)
460
1772
  await validate();
1773
+ await this.#recordRunEnd(workflowId, summary);
1774
+ await this.#completeChildCascade();
461
1775
  return summary;
462
1776
  }
463
1777
  async #startSource(principal, workflowId, runId, scheduleId, dispatchId) {
@@ -538,13 +1852,20 @@ export class DurableObjectRunner {
538
1852
  // leg which stopped without reaching a durable state.
539
1853
  const recoveryDue = recoveryDueAt ??
540
1854
  ((await storage.get(RUN_OWNER_RECOVERY_KEY)) !== undefined ||
541
- (await storage.get(RUN_LEG_KEY)) !== undefined
1855
+ (await storage.get(RUN_LEG_KEY)) !== undefined ||
1856
+ (await storage.get(CHILD_START_RECOVERY_KEY)) !== undefined ||
1857
+ (await storage.get(QUESTION_RECOVERY_KEY)) !== undefined
542
1858
  ? Date.now() + RUN_OWNER_RECOVERY_DELAY_MS
543
1859
  : undefined);
544
1860
  // `now` is sampled AFTER the awaited recovery-key read above. Hoisting it
545
1861
  // before the read would shrink the floor by the read's latency, and the
546
1862
  // floor is the anti-spin guarantee for an entry that is already due.
547
- const due = nextDutyAlarmAt(suspensionDueAt, recoveryDue, Date.now());
1863
+ const noticeDue = (await storage.get(PARENT_NOTIFY_KEY))
1864
+ ?.nextAttemptAt;
1865
+ const cascadeDue = (await storage.get(CHILD_CASCADE_KEY))
1866
+ ?.nextAttemptAt;
1867
+ const recoveryTimes = [recoveryDue, noticeDue, cascadeDue].filter((time) => time !== undefined);
1868
+ const due = nextDutyAlarmAt(suspensionDueAt, recoveryTimes.length === 0 ? undefined : Math.min(...recoveryTimes), Date.now());
548
1869
  if (due === undefined) {
549
1870
  await storage.deleteAlarm?.();
550
1871
  return;
@@ -694,20 +2015,19 @@ export class DurableObjectRunner {
694
2015
  console.error('start principal receipt could not be verified', error);
695
2016
  }
696
2017
  }
697
- async #startPrincipalReceipt(workflowId, runId) {
698
- const unavailable = () => json({ error: 'run not found' }, 404);
2018
+ async #readStartPrincipalReceipt(workflowId, runId) {
699
2019
  const storage = this.state?.storage;
700
2020
  if (!storage || this.state?.id?.name !== `${workflowId}:${runId}`)
701
- return unavailable();
2021
+ return undefined;
702
2022
  try {
703
2023
  const raw = await storage.get(START_PRINCIPAL_RECEIPT_KEY);
704
2024
  if (typeof raw !== 'string')
705
- return unavailable();
2025
+ return undefined;
706
2026
  const parsed = JSON.parse(raw);
707
2027
  if (parsed === null ||
708
2028
  typeof parsed !== 'object' ||
709
2029
  Array.isArray(parsed))
710
- return unavailable();
2030
+ return undefined;
711
2031
  const receipt = parsed;
712
2032
  if (receipt.version !== 1 ||
713
2033
  receipt.owner === null ||
@@ -716,7 +2036,7 @@ export class DurableObjectRunner {
716
2036
  receipt.principal === null ||
717
2037
  typeof receipt.principal !== 'object' ||
718
2038
  Array.isArray(receipt.principal))
719
- return unavailable();
2039
+ return undefined;
720
2040
  const execution = normalizeD1RunExecutionIdentity(receipt.execution);
721
2041
  const owner = receipt.owner;
722
2042
  const principal = decodeExecutionPrincipal(JSON.stringify(receipt.principal));
@@ -727,7 +2047,7 @@ export class DurableObjectRunner {
727
2047
  execution.runId !== runId ||
728
2048
  owner.kind !== principal.kind ||
729
2049
  owner.id !== principal.id)
730
- return unavailable();
2050
+ return undefined;
731
2051
  const canonical = {
732
2052
  version: 1,
733
2053
  execution,
@@ -735,7 +2055,7 @@ export class DurableObjectRunner {
735
2055
  principal,
736
2056
  };
737
2057
  if (JSON.stringify(canonical) !== raw)
738
- return unavailable();
2058
+ return undefined;
739
2059
  const state = await this.#ensureRuntime().authoritativeStartState(workflowId, runId);
740
2060
  const identity = state?.provenance.startIdentity;
741
2061
  if (state?.storage !== 'd1' ||
@@ -749,11 +2069,11 @@ export class DurableObjectRunner {
749
2069
  identity.owner.kind !== owner.kind ||
750
2070
  identity.owner.id !== owner.id ||
751
2071
  state.provenance.agentStart !== undefined)
752
- return unavailable();
753
- return json(canonical);
2072
+ return undefined;
2073
+ return canonical;
754
2074
  }
755
2075
  catch {
756
- return unavailable();
2076
+ return undefined;
757
2077
  }
758
2078
  }
759
2079
  #matchingRunState(recovery, state) {
@@ -798,6 +2118,8 @@ export class DurableObjectRunner {
798
2118
  casMatched: true,
799
2119
  cleanup,
800
2120
  });
2121
+ else
2122
+ await this.#recordRunEnd(recovery.workflowId, state.summary);
801
2123
  const reconciled = await this.#reconcileSuspensionDeadlinesBestEffort(recovery.workflowId, recovery.runId, summary);
802
2124
  await this.#clearRunOwnerRecovery(recovery, !reconciled);
803
2125
  return summary;
@@ -907,30 +2229,31 @@ export class DurableObjectRunner {
907
2229
  console.error(`suspension deadline not armed for step '${rejection.step}' of run '${runId}': ${rejection.reason}`);
908
2230
  }
909
2231
  /**
910
- * The summary with its timer steps listed, so approval bridges file nothing
911
- * for a step this object will resume itself. It never throws and never
912
- * deletes: the lifecycle change behind the response has already persisted,
913
- * and the status and replay routes run outside the operation lock. Without a
914
- * scheduled wake nothing would resume a timer, so a step this read cannot
915
- * vouch for is left out and gets an approval a person can resume.
2232
+ * Without a scheduled wake nothing resumes a timer, so a timer this read
2233
+ * cannot vouch for gets an approval a person can resume.
916
2234
  */
917
2235
  async #withSuspensionTimers(workflowId, summary) {
2236
+ let timers = [];
918
2237
  try {
919
2238
  // Most suspensions ask for no timer; they pay no storage read.
920
- if (suspensionTimerSteps(summary, undefined).length === 0)
921
- return summary;
922
- const storage = this.state?.storage;
923
- if (!storage?.getAlarm || (await storage.getAlarm()) === null)
924
- return summary;
925
- const steps = suspensionTimerSteps(summary, ownSuspensionDeadlines(parseSuspensionDeadlineRecord(await storage.get(SUSPENSION_DEADLINE_STORAGE_KEY)), workflowId, summary.runId));
926
- return steps.length === 0
927
- ? summary
928
- : { ...summary, suspensionTimers: steps };
2239
+ if (suspensionTimerSteps(summary, undefined).length > 0) {
2240
+ const storage = this.state?.storage;
2241
+ if (storage?.getAlarm && (await storage.getAlarm()) !== null) {
2242
+ timers = suspensionTimerSteps(summary, ownSuspensionDeadlines(parseSuspensionDeadlineRecord(await storage.get(SUSPENSION_DEADLINE_STORAGE_KEY)), workflowId, summary.runId));
2243
+ }
2244
+ }
929
2245
  }
930
2246
  catch (error) {
931
2247
  console.error('suspension timer read failed', error);
932
- return summary;
933
2248
  }
2249
+ const suspensionKinds = suspensionKindsOf(summary, timers);
2250
+ if (suspensionKinds === undefined)
2251
+ return summary;
2252
+ return {
2253
+ ...summary,
2254
+ ...(timers.length > 0 ? { suspensionTimers: timers } : {}),
2255
+ suspensionKinds,
2256
+ };
934
2257
  }
935
2258
  /**
936
2259
  * Reconciliation is bookkeeping ABOUT a transition that has already been
@@ -1210,7 +2533,7 @@ export class DurableObjectRunner {
1210
2533
  // the caller can then keep the watchdog instead of spending an abandonment
1211
2534
  // budget on an incident, and nothing AFTER this fence can masquerade as
1212
2535
  // one.
1213
- const summary = await this.#authoritativeStatusOrUnreadable(runtime, workflowId, runId);
2536
+ let summary = await this.#authoritativeStatusOrUnreadable(runtime, workflowId, runId);
1214
2537
  // A read that succeeded and found NOTHING is not evidence that a signal got
1215
2538
  // there first either — a read replica may not yet show a snapshot this
1216
2539
  // object itself wrote — but it is evidence the store answered, and D1
@@ -1224,7 +2547,49 @@ export class DurableObjectRunner {
1224
2547
  if (!summary || !isReadableRunSummary(summary)) {
1225
2548
  throw new Error(`run '${runId}' of workflow '${workflowId}' read back absent or self-inconsistent`);
1226
2549
  }
1227
- if (!this.#suspensionFenceMatches(summary, entry)) {
2550
+ let matches = this.#suspensionFenceMatches(summary, entry);
2551
+ if (matches &&
2552
+ suspensionKindsOf(summary, [])?.[entry.step] === 'question') {
2553
+ await this.#reconcileQuestions(workflowId, summary);
2554
+ const question = currentQuestions(workflowId, summary).find((candidate) => candidate.stepKey === entry.step);
2555
+ const db = this.#questionDatabase();
2556
+ if (!question || !db)
2557
+ throw new Error('deadline has no valid question record');
2558
+ await runtime.assertExistingRunAllowed(workflowId, runId);
2559
+ await this.#armQuestionRecovery(workflowId, runId);
2560
+ const settled = await expireQuestion(db, question);
2561
+ if (settled?.state !== 'expired' && settled?.state !== 'answered')
2562
+ throw new QuestionNotOpenError('question is not open');
2563
+ // Once the question's outcome is durable, recovery owns its delivery.
2564
+ await this.#writeSuspensionDeadlines(workflowId, runId, stored, [
2565
+ ...entriesWithoutStep(stored.entries, entry.step),
2566
+ tombstoned(entry),
2567
+ ]);
2568
+ try {
2569
+ const resumed = await this.#resumeSettledQuestion(runtime, db, settled, summary, true);
2570
+ if (resumed === undefined)
2571
+ await this.#reconcileFromAuthoritativeStatus();
2572
+ }
2573
+ catch (error) {
2574
+ console.error('question deadline resume failed', error);
2575
+ }
2576
+ return;
2577
+ }
2578
+ try {
2579
+ const recovered = await this.#recoverQuestionResumes(runtime, workflowId, summary, true);
2580
+ if (recovered !== summary)
2581
+ return;
2582
+ }
2583
+ catch (error) {
2584
+ // A question recovery failure does not spend another step's deadline budget.
2585
+ console.error('question recovery before suspension deadline failed', error);
2586
+ const current = await this.#authoritativeStatusOrUnreadable(runtime, workflowId, runId);
2587
+ if (!current || !isReadableRunSummary(current))
2588
+ throw new RunStateUnreadableError(workflowId, runId);
2589
+ summary = current;
2590
+ matches = this.#suspensionFenceMatches(summary, entry);
2591
+ }
2592
+ if (!matches) {
1228
2593
  // A discarded deadline must be visible: this is the branch a real signal
1229
2594
  // reaches, and also the one a projection disagreement would reach.
1230
2595
  console.error(`suspension deadline for step '${entry.step}' of run '${runId}' dropped: the suspension it was armed against has moved on`);
@@ -1240,6 +2605,21 @@ export class DurableObjectRunner {
1240
2605
  await this.#reconcileApprovalsBestEffort(workflowId, runId, summary);
1241
2606
  return;
1242
2607
  }
2608
+ if (hasInvalidChildAwait(summary)) {
2609
+ const failed = await this.#rejectInvalidChildAwait(workflowId, summary);
2610
+ await this.#recordRunEnd(workflowId, failed);
2611
+ await this.#reconcileSuspensionDeadlinesBestEffort(workflowId, runId, failed);
2612
+ await this.#publishChildAwaitResume(workflowId, failed, entry);
2613
+ return;
2614
+ }
2615
+ if (childAwaitForStep(summary, entry.step)) {
2616
+ const resumed = await this.#attemptChildAwait(runtime, summary, stored, entry, true, now);
2617
+ if (resumed) {
2618
+ await this.#reconcileSuspensionDeadlinesBestEffort(workflowId, runId, resumed);
2619
+ await this.#publishChildAwaitResume(workflowId, resumed, entry);
2620
+ }
2621
+ return;
2622
+ }
1243
2623
  const next = await this.#withLeg(workflowId, runId, 'deadline', () => runtime.resume(workflowId, runId, {
1244
2624
  step: [entry.step],
1245
2625
  resumeData: suspensionTimeoutResumeData(entry, now),
@@ -1311,13 +2691,9 @@ export class DurableObjectRunner {
1311
2691
  * idFromName(`${workflowId}:${runId}`), PATH_SAFE_ID_PATTERN excludes ':'
1312
2692
  * from both ids, and stored ids are never asserted against it (a foreign
1313
2693
  * record's entries are simply dropped by the merge). A name that is present
1314
- * but does not split into two path-safe ids skips the step entirely — a
1315
- * record written from an unvalidated name would discard itself on read-back,
1316
- * and a foreign record must not steer a status read either. Without a name
1317
- * (Node stubs) the stored record supplies the ids; without either, the wake
1318
- * converges to no alarm and a deadline whose record was never written is
1319
- * lost. Production is safe from that last case because the exported topology
1320
- * (host-kit/do-run-topology.ts) always addresses this object by idFromName.
2694
+ * but does not split into two path-safe ids skips the step entirely. In
2695
+ * Node stubs without a name, the deadline record or question recovery
2696
+ * marker supplies the IDs.
1321
2697
  */
1322
2698
  async #reconcileFromAuthoritativeStatus(stored) {
1323
2699
  const name = this.state?.id?.name;
@@ -1340,7 +2716,10 @@ export class DurableObjectRunner {
1340
2716
  runId = stored.runId;
1341
2717
  }
1342
2718
  else {
1343
- return;
2719
+ const pending = await this.state?.storage?.get(QUESTION_RECOVERY_KEY);
2720
+ if (!isPathSafeId(pending?.workflowId) || !isPathSafeId(pending?.runId))
2721
+ return;
2722
+ ({ workflowId, runId } = pending);
1344
2723
  }
1345
2724
  // Built outside the wrap below on purpose: a runtime that cannot be BUILT
1346
2725
  // is a binding fault, not an unreadable run, and its throw belongs to the
@@ -1366,7 +2745,19 @@ export class DurableObjectRunner {
1366
2745
  console.error(`run '${runId}' of workflow '${workflowId}' state read back self-inconsistent; keeping the record`);
1367
2746
  return;
1368
2747
  }
1369
- await this.#reconcileSuspensionDeadlines(workflowId, runId, summary, stored);
2748
+ const checked = await this.#rejectInvalidChildAwait(workflowId, summary);
2749
+ const recovered = await this.#recoverQuestionResumes(runtime, workflowId, checked, true);
2750
+ await this.#recordRunEnd(workflowId, recovered);
2751
+ const resumed = hasChildAwait(recovered)
2752
+ ? await this.#resumeReadyChildAwait(workflowId, runId, true, stored ?? null)
2753
+ : undefined;
2754
+ if (resumed === null)
2755
+ return;
2756
+ await this.#reconcileSuspensionDeadlines(workflowId, runId, resumed?.summary ?? recovered, stored);
2757
+ if (resumed)
2758
+ await this.#publishChildAwaitResume(workflowId, resumed.summary, resumed.ended);
2759
+ else if (checked !== summary)
2760
+ await this.#publishChildAwaitResume(workflowId, checked);
1370
2761
  }
1371
2762
  /**
1372
2763
  * Never rethrows. workerd retries a thrown alarm(), which would re-run this
@@ -1539,6 +2930,9 @@ export class DurableObjectRunner {
1539
2930
  : await this.#completeTerminalEffects(runtime, recovery.workflowId, recovery.runId, recovery.owner, recovered.transition);
1540
2931
  if (recovered.kind === 'lifecycle')
1541
2932
  await this.#settleClosedRunInvocationsBestEffort(recovery.workflowId, recovery.runId);
2933
+ if (recovered.kind === 'ordinary' ||
2934
+ recovered.transition.cleanup.cleanupCompleted)
2935
+ await this.#recordRunEnd(recovery.workflowId, completed);
1542
2936
  const reconciled = await this.#reconcileSuspensionDeadlinesBestEffort(recovery.workflowId, recovery.runId, completed);
1543
2937
  await this.#clearRunOwnerRecovery(recovery, !reconciled);
1544
2938
  return completed;
@@ -1652,20 +3046,31 @@ export class DurableObjectRunner {
1652
3046
  * Clearing never arms: each caller's own boundary re-arms from what is left.
1653
3047
  * Everything after `body` is best effort, because the leg has already run.
1654
3048
  */
1655
- async #withLeg(workflowId, runId, trigger, body, armed) {
3049
+ async #withLeg(workflowId, runId, trigger, body, armed, queueChildAwait = true) {
1656
3050
  const runtime = this.#ensureRuntime();
1657
3051
  const frame = {
1658
3052
  token: crypto.randomUUID(),
1659
3053
  startedAt: Date.now(),
1660
3054
  };
1661
3055
  this.#legs.add(frame);
1662
- const clearIfDurable = async (summary) => {
3056
+ const clearIfDurable = async (summary, completed) => {
1663
3057
  try {
1664
- if (summary && isDurableRunStatus(summary.status))
3058
+ if (summary && isDurableRunStatus(summary.status)) {
3059
+ const current = currentQuestions(workflowId, summary).length > 0
3060
+ ? await runtime.authoritativeStatus(workflowId, runId)
3061
+ : summary;
3062
+ if (!current || (!completed && hasInvalidChildAwait(current)))
3063
+ return;
3064
+ await this.#reconcileQuestions(workflowId, current);
3065
+ if (trigger !== 'start')
3066
+ await this.#recordRunEnd(workflowId, current);
1665
3067
  await this.#clearLegMarker(frame.token);
3068
+ if (completed && queueChildAwait && hasChildAwait(current))
3069
+ this.#queueChildAwait(workflowId, runId);
3070
+ }
1666
3071
  }
1667
3072
  catch (error) {
1668
- console.error('run leg marker clear failed', error);
3073
+ console.error('run leg finalization failed', error);
1669
3074
  }
1670
3075
  };
1671
3076
  try {
@@ -1682,9 +3087,21 @@ export class DurableObjectRunner {
1682
3087
  startedAt: frame.startedAt,
1683
3088
  });
1684
3089
  }
3090
+ if (trigger !== 'start') {
3091
+ try {
3092
+ await this.#reconcileChildStarts(workflowId, runId);
3093
+ }
3094
+ catch (error) {
3095
+ console.error('child start reconciliation failed', error);
3096
+ }
3097
+ }
1685
3098
  let summary;
1686
3099
  try {
1687
- summary = await body();
3100
+ summary = await withChildRunHost(workflowId, runId, {
3101
+ start: (request) => this.#startChild(workflowId, runId, request),
3102
+ result: (key) => this.#childResult(workflowId, runId, key),
3103
+ }, body);
3104
+ summary = await this.#rejectInvalidChildAwait(workflowId, summary);
1688
3105
  }
1689
3106
  catch (error) {
1690
3107
  let current = null;
@@ -1694,10 +3111,10 @@ export class DurableObjectRunner {
1694
3111
  catch {
1695
3112
  // Unreadable: the marker stays for the next wake.
1696
3113
  }
1697
- await clearIfDurable(current);
3114
+ await clearIfDurable(current, false);
1698
3115
  throw error;
1699
3116
  }
1700
- await clearIfDurable(summary);
3117
+ await clearIfDurable(summary, true);
1701
3118
  return summary;
1702
3119
  }
1703
3120
  finally {
@@ -1800,7 +3217,7 @@ export class DurableObjectRunner {
1800
3217
  try {
1801
3218
  this.#assertRunIdentity(workflowId, runId);
1802
3219
  runtime = this.#ensureRuntime();
1803
- settled = await runtime.settleInterruptedRun(workflowId, runId);
3220
+ settled = await runtime.settleInterruptedRun(workflowId, runId, undefined, (status, commitIntent) => this.#cascadeChildren(workflowId, runId, status, commitIntent));
1804
3221
  }
1805
3222
  catch (error) {
1806
3223
  if (await dropIfStale(error))
@@ -1812,7 +3229,10 @@ export class DurableObjectRunner {
1812
3229
  return;
1813
3230
  }
1814
3231
  let summary;
1815
- if (settled.kind === 'interrupted') {
3232
+ if (settled.kind === 'paused') {
3233
+ summary = settled.summary;
3234
+ }
3235
+ else if (settled.kind === 'interrupted') {
1816
3236
  summary = settled.summary;
1817
3237
  console.error(JSON.stringify({
1818
3238
  type: 'run-leg-interrupted',
@@ -1827,6 +3247,11 @@ export class DurableObjectRunner {
1827
3247
  await this.#settleClosedRunInvocationsBestEffort(workflowId, runId);
1828
3248
  }
1829
3249
  if (summary) {
3250
+ await this.#reconcileQuestions(workflowId, summary);
3251
+ if (marker.trigger !== 'start')
3252
+ await this.#recordRunEnd(workflowId, summary);
3253
+ else
3254
+ await this.#cascadeAfterRunEnd(workflowId, summary);
1830
3255
  try {
1831
3256
  this.#broadcastRunSummary(summary);
1832
3257
  }
@@ -1836,9 +3261,17 @@ export class DurableObjectRunner {
1836
3261
  await this.#reconcileSuspensionDeadlinesBestEffort(workflowId, runId, summary);
1837
3262
  }
1838
3263
  else if (settled.kind === 'durable') {
3264
+ const current = await this.#authoritativeStatusOrUnreadable(runtime, workflowId, runId);
3265
+ if (current) {
3266
+ await this.#reconcileQuestions(workflowId, current);
3267
+ if (marker.trigger !== 'start')
3268
+ await this.#recordRunEnd(workflowId, current);
3269
+ else
3270
+ await this.#cascadeAfterRunEnd(workflowId, current);
3271
+ }
1839
3272
  // A leg that stopped after persisting a suspension reached it with no
1840
3273
  // host request to file its approval.
1841
- await this.#reconcileApprovalsBestEffort(workflowId, runId);
3274
+ await this.#reconcileApprovalsBestEffort(workflowId, runId, current ?? undefined);
1842
3275
  }
1843
3276
  await this.#clearLegMarker(marker.token);
1844
3277
  }
@@ -1855,6 +3288,15 @@ export class DurableObjectRunner {
1855
3288
  // long as the misbinding lasts. Failing with the watchdog in place keeps
1856
3289
  // the recovery cadence this object woke at before it served deadlines.
1857
3290
  await verifyDurableObjectDeploymentIdentity(this.state, this.env);
3291
+ const [workflowId, runId] = this.state?.id?.name?.split(':') ?? [];
3292
+ if (isPathSafeId(workflowId) && isPathSafeId(runId)) {
3293
+ try {
3294
+ await this.#reconcileChildStarts(workflowId, runId);
3295
+ }
3296
+ catch (error) {
3297
+ console.error('child start reconciliation failed', error);
3298
+ }
3299
+ }
1858
3300
  // The duties are failure-isolated: none that throws may skip the
1859
3301
  // others (or their re-arm), and none may leave the object with no wake.
1860
3302
  // A leg settlement that fails keeps its marker, which the final arm
@@ -1866,6 +3308,12 @@ export class DurableObjectRunner {
1866
3308
  catch (error) {
1867
3309
  console.error('interrupted run leg settlement failed', error);
1868
3310
  }
3311
+ try {
3312
+ await this.#retryChildCascade();
3313
+ }
3314
+ catch (error) {
3315
+ console.error('child cascade recovery failed', error);
3316
+ }
1869
3317
  let recoveryError;
1870
3318
  try {
1871
3319
  const recovered = await this.#recoverPendingRunOwner();
@@ -1876,6 +3324,12 @@ export class DurableObjectRunner {
1876
3324
  catch (error) {
1877
3325
  recoveryError = error;
1878
3326
  }
3327
+ try {
3328
+ await this.#sendParentNotice();
3329
+ }
3330
+ catch (error) {
3331
+ console.error('child settlement notice recovery failed', error);
3332
+ }
1879
3333
  const converged = await this.#runDueSuspensionDeadline(Date.now());
1880
3334
  // A duty that converged nothing has no arm to compute: the watchdog set
1881
3335
  // at the top of this body IS the cadence it falls back to, and re-arming
@@ -1914,16 +3368,31 @@ export class DurableObjectRunner {
1914
3368
  if (segments[0] !== 'runs')
1915
3369
  return json({ error: 'not found' }, 404);
1916
3370
  const [, workflowId, runId, action] = segments;
1917
- if (request.method === 'POST' && segments.length === 1) {
1918
- const principal = this.#trustedExecutionPrincipal(encodedPrincipal);
1919
- const encodedRequester = request.headers.get(RUN_REQUESTER_HEADER);
3371
+ const childStart = segments.length === 4 && action === 'start-child';
3372
+ if (request.method === 'POST' && (segments.length === 1 || childStart)) {
3373
+ const principal = childStart
3374
+ ? undefined
3375
+ : this.#trustedExecutionPrincipal(encodedPrincipal);
3376
+ const encodedRequester = childStart
3377
+ ? null
3378
+ : request.headers.get(RUN_REQUESTER_HEADER);
1920
3379
  const runRequester = encodedRequester === null
1921
3380
  ? undefined
1922
3381
  : decodeRunRequester(encodedRequester);
1923
3382
  if (encodedRequester !== null && runRequester === undefined)
1924
3383
  throw new InvalidRunRequestError('runRequester is malformed');
1925
3384
  const body = await readJson(request);
1926
- return this.#withOperationLock(async () => {
3385
+ let acknowledge;
3386
+ let acknowledged = false;
3387
+ const admission = childStart
3388
+ ? new Promise((resolve) => {
3389
+ acknowledge = () => {
3390
+ acknowledged = true;
3391
+ resolve(new Response(null, { status: 202 }));
3392
+ };
3393
+ })
3394
+ : undefined;
3395
+ const operation = this.#withOperationLock(async () => {
1927
3396
  if (body &&
1928
3397
  [
1929
3398
  'mutationEpoch',
@@ -1935,16 +3404,17 @@ export class DurableObjectRunner {
1935
3404
  'attemptToken',
1936
3405
  'runOwnerGuard',
1937
3406
  'onPreparedStartIdentity',
3407
+ 'onAdmittedStartIdentity',
1938
3408
  ].some((key) => Object.hasOwn(body, key))) {
1939
3409
  throw new InvalidRunRequestError('start authority is derived from trusted provenance');
1940
3410
  }
1941
- const { workflowId: startWorkflowId, runId: startRunId, inputData, initialState, requestContext, scheduleId, dispatchId, deadlineMs, idempotencyKey: rawIdempotencyKey, startReservation: suppliedReservation, } = body ?? {};
3411
+ const { workflowId: bodyWorkflowId, runId: bodyRunId, inputData, initialState, requestContext, scheduleId, dispatchId, deadlineMs, idempotencyKey: rawIdempotencyKey, startReservation: suppliedReservation, } = body ?? {};
3412
+ const startWorkflowId = childStart ? workflowId : bodyWorkflowId;
3413
+ const startRunId = childStart ? runId : bodyRunId;
1942
3414
  if (typeof startWorkflowId !== 'string') {
1943
3415
  return json({ error: 'workflowId is required' }, 400);
1944
3416
  }
1945
- // The DO never generates a runId: the trusted Worker mints the id and
1946
- // addresses this instance with it. A start without one is a caller bug,
1947
- // not a request for generation.
3417
+ // The caller supplies the ID it used to address this object.
1948
3418
  if (typeof startRunId !== 'string') {
1949
3419
  return json({ error: 'runId is required (server-minted by the run router)' }, 400);
1950
3420
  }
@@ -1952,6 +3422,55 @@ export class DurableObjectRunner {
1952
3422
  throw new InvalidRunRequestError('workflowId and runId must be URL-path-safe identifiers');
1953
3423
  }
1954
3424
  this.#assertRunIdentity(startWorkflowId, startRunId);
3425
+ let child;
3426
+ let childEntry;
3427
+ if (childStart) {
3428
+ if (!body ||
3429
+ typeof body !== 'object' ||
3430
+ Array.isArray(body) ||
3431
+ Object.keys(body).some((key) => key !== 'inputData' &&
3432
+ key !== 'requestContext' &&
3433
+ key !== 'deadlineMs')) {
3434
+ throw new InvalidRunRequestError('invalid child start body');
3435
+ }
3436
+ if (requestContext !== undefined) {
3437
+ if (requestContext === null ||
3438
+ typeof requestContext !== 'object' ||
3439
+ Array.isArray(requestContext)) {
3440
+ throw new InvalidRunRequestError('child requestContext must be an object');
3441
+ }
3442
+ assertNoReservedExecutionContext(requestContext);
3443
+ }
3444
+ childEntry = await this.#childStartEntry(startWorkflowId, startRunId, body);
3445
+ const childRuntime = this.#ensureRuntime();
3446
+ if (startWorkflowId === DURABLE_AGENTIC_LOOP_WORKFLOW_ID ||
3447
+ !childRuntime.workflowIds().includes(startWorkflowId)) {
3448
+ const code = startWorkflowId === DURABLE_AGENTIC_LOOP_WORKFLOW_ID ||
3449
+ childEntry.versionPin === undefined
3450
+ ? 'HOST_REFUSED'
3451
+ : 'VERSION_UNAVAILABLE';
3452
+ await this.#childRunLedger().markRefused(startRunId, Date.now(), code);
3453
+ throw new ChildRunRefusedError(code);
3454
+ }
3455
+ await this.#recoverPendingRunOwner();
3456
+ const selected = await childRuntime.authoritativeStartState(startWorkflowId, startRunId);
3457
+ if (selected?.kind === 'result') {
3458
+ const lineage = parseRunLineage(selected.snapshot.requestContext?.[RUN_LINEAGE_CONTEXT_KEY]);
3459
+ if (!matchesChildLineage(childEntry, lineage)) {
3460
+ throw new Error('child run identity does not match its reservation');
3461
+ }
3462
+ await this.#childRunLedger().resolveStarting(startRunId, 'admitted');
3463
+ await this.#recordRunEnd(startWorkflowId, selected.summary);
3464
+ await this.#reconcileApprovalsBestEffort(startWorkflowId, startRunId, selected.summary);
3465
+ return new Response(null, { status: 202 });
3466
+ }
3467
+ if (selected?.kind === 'initial')
3468
+ throw new RunStartPendingError();
3469
+ child = await this.#childAdmission(childEntry);
3470
+ }
3471
+ const requester = child?.owner ?? principal;
3472
+ if (!requester)
3473
+ throw new ChildRunRefusedError('HOST_REFUSED');
1955
3474
  // The key rides the internal channel and nothing else. Validated here
1956
3475
  // rather than trusted because this body is JSON: an unvalidated value
1957
3476
  // would reach the fence's proof-only comparison and the runtime's
@@ -1966,20 +3485,23 @@ export class DurableObjectRunner {
1966
3485
  startReservation.targetKind !== 'workflow' ||
1967
3486
  startReservation.targetId !== startWorkflowId ||
1968
3487
  startReservation.threadId !== undefined ||
1969
- startReservation.owner.kind !== principal.kind ||
1970
- startReservation.owner.id !== principal.id ||
3488
+ startReservation.owner.kind !== requester.kind ||
3489
+ startReservation.owner.id !== requester.id ||
1971
3490
  !this.#ensureRuntime().startIdempotency))
1972
3491
  throw new InvalidRunRequestError('start reservation does not match the trusted start');
1973
3492
  const startIdentity = normalizeStartIdentity({
1974
- owner: { kind: principal.kind, id: principal.id },
3493
+ owner: { kind: requester.kind, id: requester.id },
1975
3494
  target: { kind: 'workflow', id: startWorkflowId },
1976
3495
  });
1977
3496
  // Only this local preflight can release the captured claim. Admission
1978
3497
  // and proof binding belong to Runtime after durable preparation.
3498
+ let startEpoch = mutationEpoch;
1979
3499
  try {
1980
3500
  const startFence = await this.#readExecutionFence();
1981
3501
  if (!admitsRunStart(startFence, idempotencyKey))
1982
3502
  throw new ExecutionFencedError(startFence.state, 'run start');
3503
+ if (childStart)
3504
+ startEpoch = startFence.mutationEpoch;
1983
3505
  }
1984
3506
  catch (error) {
1985
3507
  if (startReservation) {
@@ -1992,7 +3514,9 @@ export class DurableObjectRunner {
1992
3514
  }
1993
3515
  throw error;
1994
3516
  }
1995
- const source = await this.#startSource(principal, startWorkflowId, startRunId, scheduleId, dispatchId);
3517
+ const source = principal
3518
+ ? await this.#startSource(principal, startWorkflowId, startRunId, scheduleId, dispatchId)
3519
+ : { owner: requester, target: undefined };
1996
3520
  const rawOwner = source.owner;
1997
3521
  const owner = Object.freeze({ kind: rawOwner.kind, id: rawOwner.id });
1998
3522
  const target = source.target;
@@ -2002,7 +3526,8 @@ export class DurableObjectRunner {
2002
3526
  ? target.requestContext
2003
3527
  : requestContext;
2004
3528
  const runtime = this.#ensureRuntime();
2005
- await this.#recoverPendingRunOwner();
3529
+ if (!childEntry)
3530
+ await this.#recoverPendingRunOwner();
2006
3531
  const existing = await runtime.status(startWorkflowId, startRunId);
2007
3532
  if (existing) {
2008
3533
  const registered = await this.runOwnership(this.env).owner('run', startRunId);
@@ -2026,9 +3551,20 @@ export class DurableObjectRunner {
2026
3551
  token: recovery.token,
2027
3552
  owner,
2028
3553
  unwound: false,
3554
+ childLineage: child?.lineage,
2029
3555
  };
2030
3556
  const frameKey = this.#inFlightKey(startWorkflowId, startRunId);
2031
3557
  this.#startsInFlight.set(frameKey, frame);
3558
+ const startRunRequester = child ? child.runRequester : runRequester;
3559
+ const childOptions = child;
3560
+ const startPrincipal = child?.owner ?? principal;
3561
+ let receiptAttempted = false;
3562
+ const recordStartReceipt = async (execution) => {
3563
+ if (receiptAttempted || !startPrincipal || scheduleId !== undefined)
3564
+ return;
3565
+ receiptAttempted = true;
3566
+ await this.#recordStartPrincipal(execution, owner, startPrincipal);
3567
+ };
2032
3568
  try {
2033
3569
  await this.#armRunOwnerRecovery(recovery);
2034
3570
  await this.#reserveRunOwner(startRunId, owner, recovery.token);
@@ -2041,20 +3577,48 @@ export class DurableObjectRunner {
2041
3577
  ...(storedRequestContext !== undefined
2042
3578
  ? { storedRequestContext }
2043
3579
  : {}),
2044
- requestedBy: principal.id,
2045
- requestedByKind: principal.kind,
2046
- ...(runRequester === undefined || scheduleId !== undefined
3580
+ requestedBy: requester.id,
3581
+ requestedByKind: requester.kind,
3582
+ ...(startRunRequester === undefined ||
3583
+ scheduleId !== undefined
2047
3584
  ? {}
2048
- : { runRequester }),
3585
+ : { runRequester: startRunRequester }),
2049
3586
  attemptToken: recovery.token,
2050
- ...(mutationEpoch === undefined ? {} : { mutationEpoch }),
3587
+ ...(startEpoch === undefined
3588
+ ? {}
3589
+ : { mutationEpoch: startEpoch }),
2051
3590
  startIdentity,
3591
+ ...(childOptions === undefined
3592
+ ? {}
3593
+ : { child: childOptions }),
2052
3594
  startReservation,
2053
3595
  runOwnerGuard: { owner, reservationToken: recovery.token },
2054
3596
  pendingTerminal: () => frame.pendingTerminal,
2055
3597
  onPreparedStartIdentity: async (execution) => {
3598
+ if (childEntry && childOptions) {
3599
+ const current = await this.#childAdmission(childEntry);
3600
+ if (!isOwnedBy(current.owner, requester) ||
3601
+ (current.parentDeadlineAt !== undefined &&
3602
+ (childOptions.parentDeadlineAt === undefined ||
3603
+ current.parentDeadlineAt <
3604
+ childOptions.parentDeadlineAt))) {
3605
+ throw new ChildRunRefusedError('HOST_REFUSED');
3606
+ }
3607
+ }
2056
3608
  recovery = await this.#prepareRunOwner(recovery, execution);
2057
3609
  },
3610
+ onAdmittedStartIdentity: async (execution) => {
3611
+ await recordStartReceipt(execution);
3612
+ if (childEntry) {
3613
+ try {
3614
+ await this.#childRunLedger().resolveStarting(startRunId, 'admitted');
3615
+ }
3616
+ catch (error) {
3617
+ console.error('child admission could not update its ledger', error);
3618
+ }
3619
+ acknowledge?.();
3620
+ }
3621
+ },
2058
3622
  ...(idempotencyKey === undefined ? {} : { idempotencyKey }),
2059
3623
  ...(deadlineMs === undefined
2060
3624
  ? {}
@@ -2066,9 +3630,14 @@ export class DurableObjectRunner {
2066
3630
  }
2067
3631
  summary = await this.#finishRunOwner(recovery, summary);
2068
3632
  const preparedExecution = preparedRunExecution(recovery);
2069
- if (scheduleId === undefined && preparedExecution)
2070
- await this.#recordStartPrincipal(preparedExecution, owner, principal);
3633
+ if (preparedExecution)
3634
+ await recordStartReceipt(preparedExecution);
3635
+ if (childEntry) {
3636
+ await this.#reconcileApprovalsBestEffort(startWorkflowId, startRunId, summary);
3637
+ }
2071
3638
  this.#broadcastRunSummary(summary);
3639
+ if (childEntry)
3640
+ return new Response(null, { status: 202 });
2072
3641
  return json(await this.#withSuspensionTimers(startWorkflowId, summary));
2073
3642
  }
2074
3643
  catch (error) {
@@ -2080,8 +3649,13 @@ export class DurableObjectRunner {
2080
3649
  if (!sameRunRecovery(current, recovery))
2081
3650
  throw new Error('run owner recovery changed');
2082
3651
  const recovered = await this.#recoverRunOwner(current, frame, error);
2083
- if (recovered)
3652
+ if (recovered) {
3653
+ if (childEntry) {
3654
+ await this.#reconcileApprovalsBestEffort(startWorkflowId, startRunId, recovered);
3655
+ return new Response(null, { status: 202 });
3656
+ }
2084
3657
  return json(await this.#withSuspensionTimers(startWorkflowId, recovered));
3658
+ }
2085
3659
  }
2086
3660
  }
2087
3661
  catch (recoveryError) {
@@ -2095,6 +3669,34 @@ export class DurableObjectRunner {
2095
3669
  this.#startsInFlight.delete(frameKey);
2096
3670
  }
2097
3671
  });
3672
+ if (!admission)
3673
+ return operation;
3674
+ this.state?.waitUntil?.(operation.catch((error) => {
3675
+ if (acknowledged)
3676
+ console.error('child start leg failed', error);
3677
+ }));
3678
+ return Promise.race([admission, operation]);
3679
+ }
3680
+ if (request.method === 'POST' &&
3681
+ segments.length === 4 &&
3682
+ action === 'cascade-terminate' &&
3683
+ workflowId &&
3684
+ runId)
3685
+ return this.#receiveChildCascade(request, workflowId, runId);
3686
+ if (request.method === 'POST' &&
3687
+ segments.length === 4 &&
3688
+ action === 'child-settled' &&
3689
+ workflowId &&
3690
+ runId) {
3691
+ this.#assertRunIdentity(workflowId, runId);
3692
+ const current = await this.#ensureRuntime().authoritativeStartState(workflowId, runId, { includeLegacy: true });
3693
+ if (!current)
3694
+ return json({ error: 'run not found' }, 404);
3695
+ if (!isTerminalRunStatus(current.summary?.status) &&
3696
+ !lifecycleFromRequestContext(current.snapshot.requestContext)
3697
+ ?.transitionIntent)
3698
+ this.#queueChildAwait(workflowId, runId);
3699
+ return new Response(null, { status: 204 });
2098
3700
  }
2099
3701
  // The liveness probe, answered OUTSIDE #withOperationLock on purpose: the
2100
3702
  // start it is asking about holds that lock for the whole first leg, so a
@@ -2115,7 +3717,17 @@ export class DurableObjectRunner {
2115
3717
  runId) {
2116
3718
  if (!isPathSafeId(workflowId) || !isPathSafeId(runId))
2117
3719
  return json({ error: 'run not found' }, 404);
2118
- return this.#startPrincipalReceipt(workflowId, runId);
3720
+ const receipt = await this.#readStartPrincipalReceipt(workflowId, runId);
3721
+ return receipt ? json(receipt) : json({ error: 'run not found' }, 404);
3722
+ }
3723
+ if (request.method === 'POST' &&
3724
+ segments.length === 4 &&
3725
+ action === 'resolve-child-start' &&
3726
+ isPathSafeId(workflowId) &&
3727
+ isPathSafeId(runId)) {
3728
+ this.#assertRunIdentity(workflowId, runId);
3729
+ await this.#resolveChildStart(workflowId, runId);
3730
+ return new Response(null, { status: 204 });
2119
3731
  }
2120
3732
  if (request.method === 'GET' &&
2121
3733
  segments.length === 3 &&
@@ -2140,13 +3752,14 @@ export class DurableObjectRunner {
2140
3752
  : {
2141
3753
  kind: 'result',
2142
3754
  execution,
2143
- value: await this.#withSuspensionTimers(workflowId, state.summary),
3755
+ value: await this.#withSuspensionTimers(workflowId, await this.#reconcileQuestionsOnRead(workflowId, state.summary)),
2144
3756
  });
2145
3757
  }
2146
3758
  const summary = await runtime.status(workflowId, runId);
2147
3759
  if (!summary)
2148
3760
  return json({ error: 'run not found' }, 404);
2149
- return json(await this.#withSuspensionTimers(workflowId, summary));
3761
+ const current = await this.#reconcileQuestionsOnRead(workflowId, summary);
3762
+ return json(await this.#withSuspensionTimers(workflowId, current));
2150
3763
  }
2151
3764
  if (request.method === 'GET' &&
2152
3765
  segments.length === 4 &&
@@ -2157,7 +3770,7 @@ export class DurableObjectRunner {
2157
3770
  const summary = await this.#authoritativeStatusOrUnreadable(this.#ensureRuntime(), workflowId, runId);
2158
3771
  return summary === null
2159
3772
  ? new Response(null, { status: 204 })
2160
- : json(summary);
3773
+ : json(await this.#reconcileQuestionsOnRead(workflowId, summary));
2161
3774
  }
2162
3775
  if (request.method === 'GET' &&
2163
3776
  segments.length === 4 &&
@@ -2168,9 +3781,14 @@ export class DurableObjectRunner {
2168
3781
  return this.#withOperationLock(async () => {
2169
3782
  const runtime = this.#ensureRuntime();
2170
3783
  await this.#recoverPendingRunOwner();
2171
- const summary = await runtime.status(workflowId, runId);
3784
+ let summary = await runtime.status(workflowId, runId);
2172
3785
  if (!summary)
2173
3786
  return json({ error: 'run not found' }, 404);
3787
+ if (currentQuestions(workflowId, summary).length > 0) {
3788
+ const current = await runtime.authoritativeStatus(workflowId, runId);
3789
+ if (current)
3790
+ summary = await this.#recoverQuestionResumes(runtime, workflowId, current, false);
3791
+ }
2174
3792
  return json(await this.#withSuspensionTimers(workflowId, summary));
2175
3793
  });
2176
3794
  }
@@ -2274,11 +3892,8 @@ export class DurableObjectRunner {
2274
3892
  if (invocation.status === 'settled' &&
2275
3893
  invocation.settlementOutcome === 'applied') {
2276
3894
  if (!owner) {
2277
- const receipt = await this.#startPrincipalReceipt(workflowId, runId);
2278
- if (receipt.status !== 200)
2279
- return json({ error: 'run not found' }, 404);
2280
- const value = (await receipt.json());
2281
- if (!samePrincipal(value.principal, principal))
3895
+ const receipt = await this.#readStartPrincipalReceipt(workflowId, runId);
3896
+ if (!receipt || !samePrincipal(receipt.principal, principal))
2282
3897
  return json({ error: 'run not found' }, 404);
2283
3898
  }
2284
3899
  return json({ kind: 'already-applied', invocationId });
@@ -2337,16 +3952,105 @@ export class DurableObjectRunner {
2337
3952
  });
2338
3953
  });
2339
3954
  }
3955
+ if (action === 'questions' &&
3956
+ workflowId &&
3957
+ runId &&
3958
+ (request.method === 'GET' || request.method === 'POST')) {
3959
+ this.#assertRunIdentity(workflowId, runId);
3960
+ const questionId = segments[4];
3961
+ const db = this.#questionDatabase();
3962
+ if (segments.length === 4 && request.method === 'GET') {
3963
+ return json(db ? await listQuestions(db, workflowId, runId) : []);
3964
+ }
3965
+ if (!isQuestionId(questionId))
3966
+ return json({ error: 'question not found' }, 404);
3967
+ if (!db)
3968
+ return json({ error: 'question not found' }, 404);
3969
+ if (segments.length === 5 && request.method === 'GET') {
3970
+ const params = new URL(request.url).searchParams;
3971
+ const stepKey = params.get('stepKey');
3972
+ const expected = stepKey === null
3973
+ ? undefined
3974
+ : {
3975
+ stepKey,
3976
+ suspendedAt: Number(params.get('suspendedAt') || Number.NaN),
3977
+ resumeCount: Number(params.get('resumeCount') || Number.NaN),
3978
+ };
3979
+ if (expected && !isQuestionFingerprint(expected)) {
3980
+ throw new InvalidRunRequestError('invalid question suspension fingerprint');
3981
+ }
3982
+ const readQuestion = () => getQuestion(db, workflowId, runId, questionId, expected);
3983
+ const question = expected
3984
+ ? await this.#withOperationLock(async () => {
3985
+ const found = await readQuestion();
3986
+ if (found)
3987
+ return found;
3988
+ const current = await this.#ensureRuntime().authoritativeStatus(workflowId, runId);
3989
+ if (!current ||
3990
+ !currentQuestions(workflowId, current).some((entry) => entry.questionId === questionId &&
3991
+ sameQuestionSuspension(entry, expected))) {
3992
+ return null;
3993
+ }
3994
+ await this.#reconcileQuestions(workflowId, current);
3995
+ return readQuestion();
3996
+ })
3997
+ : await readQuestion();
3998
+ return question
3999
+ ? json(question)
4000
+ : json({ error: 'question not found' }, 404);
4001
+ }
4002
+ if (segments.length === 6 &&
4003
+ segments[5] === 'answer' &&
4004
+ request.method === 'POST') {
4005
+ return this.#answerQuestion(request, db, workflowId, runId, questionId, encodedPrincipal);
4006
+ }
4007
+ }
2340
4008
  if (request.method === 'POST' &&
2341
4009
  segments.length === 4 &&
2342
- action === 'resume' &&
4010
+ (action === 'resume' || action === 'resume-paused') &&
2343
4011
  workflowId &&
2344
4012
  runId) {
2345
4013
  this.#assertRunIdentity(workflowId, runId);
2346
- const body = (await readJson(request)) ?? {};
2347
- const requestedBy = this.#requestedBy(body.requestedBy);
2348
- const requestedByKind = this.#requestedByKind(body.requestedByKind);
2349
- const resumeData = this.#resumeData(body.resumeData);
4014
+ let resume;
4015
+ if (action === 'resume-paused') {
4016
+ const principal = this.#trustedExecutionPrincipal(encodedPrincipal);
4017
+ const body = await readJson(request);
4018
+ const expectedGeneration = parsePauseGeneration(body?.expectedGeneration);
4019
+ const cleared = await this.#ensureRuntime().clearPendingPause(workflowId, runId, expectedGeneration);
4020
+ if (cleared) {
4021
+ this.#broadcastRunSummary(cleared);
4022
+ return json(await this.#withSuspensionTimers(workflowId, cleared));
4023
+ }
4024
+ resume = (runtime) => runtime.restartPaused(workflowId, runId, principal, { expectedGeneration }, (summary) => {
4025
+ try {
4026
+ this.#broadcastRunSummary(summary);
4027
+ }
4028
+ catch (error) {
4029
+ console.error('restart state broadcast failed', error);
4030
+ }
4031
+ });
4032
+ }
4033
+ else {
4034
+ const body = (await readJson(request)) ?? {};
4035
+ const requestedBy = this.#requestedBy(body.requestedBy);
4036
+ const requestedByKind = this.#requestedByKind(body.requestedByKind);
4037
+ const resumeData = this.#resumeData(body.resumeData);
4038
+ resume = (runtime) => runtime.resume(workflowId, runId, {
4039
+ step: body.step,
4040
+ resumeData,
4041
+ requestedBy,
4042
+ requestedByKind,
4043
+ ...(body.deadlineMs === undefined
4044
+ ? {}
4045
+ : { deadlineMs: body.deadlineMs }),
4046
+ // The runtime validates it.
4047
+ ...(body.expectedSuspension === undefined
4048
+ ? {}
4049
+ : {
4050
+ expectedSuspension: body.expectedSuspension,
4051
+ }),
4052
+ });
4053
+ }
2350
4054
  return this.#withOperationLock(async () => {
2351
4055
  const runtime = this.#ensureRuntime();
2352
4056
  // Refused here as well as inside resume(), so a fenced deployment
@@ -2356,21 +4060,7 @@ export class DurableObjectRunner {
2356
4060
  await runtime.assertExistingRunAllowed(workflowId, runId);
2357
4061
  let summary;
2358
4062
  try {
2359
- summary = await this.#withLeg(workflowId, runId, 'resume', () => runtime.resume(workflowId, runId, {
2360
- step: body.step,
2361
- resumeData,
2362
- requestedBy,
2363
- requestedByKind,
2364
- ...(body.deadlineMs === undefined
2365
- ? {}
2366
- : { deadlineMs: body.deadlineMs }),
2367
- // The runtime validates it.
2368
- ...(body.expectedSuspension === undefined
2369
- ? {}
2370
- : {
2371
- expectedSuspension: body.expectedSuspension,
2372
- }),
2373
- }), false);
4063
+ summary = await this.#withLeg(workflowId, runId, 'resume', () => resume(runtime), false);
2374
4064
  }
2375
4065
  catch (error) {
2376
4066
  // The step moved on to another suspension: file that suspension's
@@ -2390,11 +4080,26 @@ export class DurableObjectRunner {
2390
4080
  console.error('resume boundary re-arm failed', error);
2391
4081
  }
2392
4082
  }
4083
+ if (action === 'resume-paused')
4084
+ await this.#reconcileApprovalsBestEffort(workflowId, runId, summary);
2393
4085
  // Broadcast the post-resume authoritative summary.
2394
4086
  this.#broadcastRunSummary(summary);
2395
4087
  return json(await this.#withSuspensionTimers(workflowId, summary));
2396
4088
  });
2397
4089
  }
4090
+ if (request.method === 'POST' &&
4091
+ segments.length === 4 &&
4092
+ action === 'pause' &&
4093
+ workflowId &&
4094
+ runId) {
4095
+ this.#assertRunIdentity(workflowId, runId);
4096
+ const principal = this.#trustedExecutionPrincipal(encodedPrincipal);
4097
+ const options = parsePauseRunOptions(await readJson(request));
4098
+ // The active leg holds the operation lock until it sees the pause.
4099
+ const summary = await this.#ensureRuntime().requestPause(workflowId, runId, principal, options);
4100
+ this.#broadcastRunSummary(summary);
4101
+ return json(await this.#withSuspensionTimers(workflowId, summary));
4102
+ }
2398
4103
  if (request.method === 'POST' &&
2399
4104
  segments.length === 4 &&
2400
4105
  (action === 'terminate' || action === 'terminate-replay') &&
@@ -2441,11 +4146,8 @@ export class DurableObjectRunner {
2441
4146
  throw new UnknownRunError(workflowId, runId);
2442
4147
  }
2443
4148
  }
2444
- const result = await runtime.terminateAsPrincipal(workflowId, runId, principal, owner ?? principal);
2445
- const summary = await this.#finalizeTerminal(runtime, workflowId, runId, owner ?? principal, result);
2446
- await this.#settleClosedRunInvocationsBestEffort(workflowId, runId);
2447
- await this.#reconcileSuspensionDeadlinesBestEffort(workflowId, runId, summary);
2448
- this.#broadcastRunSummary(summary);
4149
+ const result = await runtime.terminateAsPrincipal(workflowId, runId, principal, owner ?? principal, undefined, (status, commitIntent) => this.#cascadeChildren(workflowId, runId, status, commitIntent));
4150
+ const summary = await this.#finalizeAndPublishTerminal(runtime, workflowId, runId, owner ?? principal, result);
2449
4151
  return json(summary);
2450
4152
  });
2451
4153
  }
@@ -2478,7 +4180,7 @@ export class DurableObjectRunner {
2478
4180
  throw new UnknownRunError(workflowId, runId);
2479
4181
  }
2480
4182
  }
2481
- const result = await runtime.timeOutAsPrincipal(workflowId, runId, cas, principal, owner ?? principal);
4183
+ const result = await runtime.timeOutAsPrincipal(workflowId, runId, cas, principal, owner ?? principal, undefined, (status, commitIntent) => this.#cascadeChildren(workflowId, runId, status, commitIntent));
2482
4184
  if (!result.casMatched || result.cleanup.cleanupCompleted) {
2483
4185
  // The only terminal path that returns without finalizing, so it is
2484
4186
  // also the only one that would leave a record armed for a run that
@@ -2491,10 +4193,7 @@ export class DurableObjectRunner {
2491
4193
  await this.#reconcileSuspensionDeadlinesBestEffort(workflowId, runId, result.summary);
2492
4194
  return json(result.summary);
2493
4195
  }
2494
- const summary = await this.#finalizeTerminal(runtime, workflowId, runId, owner ?? principal, result);
2495
- await this.#settleClosedRunInvocationsBestEffort(workflowId, runId);
2496
- await this.#reconcileSuspensionDeadlinesBestEffort(workflowId, runId, summary);
2497
- this.#broadcastRunSummary(summary);
4196
+ const summary = await this.#finalizeAndPublishTerminal(runtime, workflowId, runId, owner ?? principal, result);
2498
4197
  return json(summary);
2499
4198
  });
2500
4199
  }
@@ -2563,6 +4262,40 @@ export function nextDutyAlarmAt(suspensionDueAt, recoveryDueAt, now) {
2563
4262
  function entriesWithoutStep(entries, step) {
2564
4263
  return entries.filter((entry) => entry.step !== step);
2565
4264
  }
4265
+ function hasChildAwait(summary) {
4266
+ return Object.values(suspensionKindsOf(summary, []) ?? {}).includes('children');
4267
+ }
4268
+ function matchesChildLineage(entry, lineage) {
4269
+ return (lineage?.parentWorkflowId === entry.parentWorkflowId &&
4270
+ lineage.parentRunId === entry.parentRunId &&
4271
+ lineage.rootRunId === entry.rootRunId &&
4272
+ lineage.depth === entry.depth &&
4273
+ lineage.childKey === entry.childKey);
4274
+ }
4275
+ function childRunRetryAt(now, attempts, expiresAt) {
4276
+ return Math.min(expiresAt, now + SUSPENSION_DEADLINE_RETRY_MS * 2 ** Math.min(attempts - 1, 3));
4277
+ }
4278
+ function logChildRunRetryAbandoned(workflowId, runId) {
4279
+ console.error(JSON.stringify({ type: 'child-run-retry-abandoned', workflowId, runId }));
4280
+ }
4281
+ async function waitForChildCall(call, signal) {
4282
+ if (!signal)
4283
+ return call;
4284
+ let onAbort = () => { };
4285
+ const aborted = new Promise((_resolve, reject) => {
4286
+ onAbort = () => reject(signal.reason);
4287
+ if (signal.aborted)
4288
+ onAbort();
4289
+ else
4290
+ signal.addEventListener('abort', onAbort, { once: true });
4291
+ });
4292
+ try {
4293
+ return await Promise.race([call, aborted]);
4294
+ }
4295
+ finally {
4296
+ signal.removeEventListener('abort', onAbort);
4297
+ }
4298
+ }
2566
4299
  /** The run-channel wire frame containing the authoritative RunSummary. */
2567
4300
  function runFrame(summary) {
2568
4301
  return JSON.stringify({ type: 'run', summary });