@proofoftech/flowsafe 0.36.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 (87) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/agent-runner/durable-agent-runner.d.ts +1 -2
  3. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  4. package/dist/agent-runner/durable-agent-runner.js +1 -1
  5. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  6. package/dist/do-runner/child-run-ledger.d.ts +84 -0
  7. package/dist/do-runner/child-run-ledger.d.ts.map +1 -0
  8. package/dist/do-runner/child-run-ledger.js +272 -0
  9. package/dist/do-runner/child-run-ledger.js.map +1 -0
  10. package/dist/do-runner/child-runs.d.ts +95 -0
  11. package/dist/do-runner/child-runs.d.ts.map +1 -0
  12. package/dist/do-runner/child-runs.js +185 -0
  13. package/dist/do-runner/child-runs.js.map +1 -0
  14. package/dist/do-runner/constants.d.ts +1 -1
  15. package/dist/do-runner/constants.d.ts.map +1 -1
  16. package/dist/do-runner/constants.js +1 -1
  17. package/dist/do-runner/constants.js.map +1 -1
  18. package/dist/do-runner/d1-storage.d.ts +1 -0
  19. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  20. package/dist/do-runner/d1-storage.js +76 -40
  21. package/dist/do-runner/d1-storage.js.map +1 -1
  22. package/dist/do-runner/durable-object.d.ts +16 -2
  23. package/dist/do-runner/durable-object.d.ts.map +1 -1
  24. package/dist/do-runner/durable-object.js +1273 -65
  25. package/dist/do-runner/durable-object.js.map +1 -1
  26. package/dist/do-runner/execution-context.d.ts.map +1 -1
  27. package/dist/do-runner/execution-context.js +2 -0
  28. package/dist/do-runner/execution-context.js.map +1 -1
  29. package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -1
  30. package/dist/do-runner/fenced-workflows-d1.js +4 -1
  31. package/dist/do-runner/fenced-workflows-d1.js.map +1 -1
  32. package/dist/do-runner/index.d.ts +5 -3
  33. package/dist/do-runner/index.d.ts.map +1 -1
  34. package/dist/do-runner/index.js +3 -1
  35. package/dist/do-runner/index.js.map +1 -1
  36. package/dist/do-runner/init.d.ts +2 -1
  37. package/dist/do-runner/init.d.ts.map +1 -1
  38. package/dist/do-runner/init.js +1 -0
  39. package/dist/do-runner/init.js.map +1 -1
  40. package/dist/do-runner/inventory.d.ts +2 -2
  41. package/dist/do-runner/inventory.d.ts.map +1 -1
  42. package/dist/do-runner/inventory.js +55 -4
  43. package/dist/do-runner/inventory.js.map +1 -1
  44. package/dist/do-runner/resume-refusal-codes.d.ts +3 -0
  45. package/dist/do-runner/resume-refusal-codes.d.ts.map +1 -0
  46. package/dist/do-runner/resume-refusal-codes.js +4 -0
  47. package/dist/do-runner/resume-refusal-codes.js.map +1 -0
  48. package/dist/do-runner/run-lifecycle.d.ts +19 -2
  49. package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
  50. package/dist/do-runner/run-lifecycle.js +23 -0
  51. package/dist/do-runner/run-lifecycle.js.map +1 -1
  52. package/dist/do-runner/run-lineage.d.ts +26 -0
  53. package/dist/do-runner/run-lineage.d.ts.map +1 -0
  54. package/dist/do-runner/run-lineage.js +38 -0
  55. package/dist/do-runner/run-lineage.js.map +1 -0
  56. package/dist/do-runner/runtime.d.ts +56 -3
  57. package/dist/do-runner/runtime.d.ts.map +1 -1
  58. package/dist/do-runner/runtime.js +281 -80
  59. package/dist/do-runner/runtime.js.map +1 -1
  60. package/dist/do-runner/suspension-deadline.d.ts +4 -1
  61. package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
  62. package/dist/do-runner/suspension-deadline.js +24 -4
  63. package/dist/do-runner/suspension-deadline.js.map +1 -1
  64. package/dist/do-runner/suspension-kinds.d.ts +9 -0
  65. package/dist/do-runner/suspension-kinds.d.ts.map +1 -1
  66. package/dist/do-runner/suspension-kinds.js +37 -5
  67. package/dist/do-runner/suspension-kinds.js.map +1 -1
  68. package/dist/durable-agent-workflow-id.d.ts +2 -0
  69. package/dist/durable-agent-workflow-id.d.ts.map +1 -0
  70. package/dist/durable-agent-workflow-id.js +3 -0
  71. package/dist/durable-agent-workflow-id.js.map +1 -0
  72. package/dist/host-kit/do-response.d.ts.map +1 -1
  73. package/dist/host-kit/do-response.js +20 -0
  74. package/dist/host-kit/do-response.js.map +1 -1
  75. package/dist/host-kit/do-run-topology.d.ts +3 -1
  76. package/dist/host-kit/do-run-topology.d.ts.map +1 -1
  77. package/dist/host-kit/do-run-topology.js +60 -0
  78. package/dist/host-kit/do-run-topology.js.map +1 -1
  79. package/dist/host-kit/flowsafe-worker.d.ts +7 -3
  80. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  81. package/dist/host-kit/flowsafe-worker.js +48 -6
  82. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  83. package/dist/host-kit/run-router.d.ts +4 -0
  84. package/dist/host-kit/run-router.d.ts.map +1 -1
  85. package/dist/host-kit/run-router.js +17 -15
  86. package/dist/host-kit/run-router.js.map +1 -1
  87. package/package.json +1 -1
@@ -14,12 +14,16 @@
14
14
  // share one wake, armed at the earliest due time.
15
15
  import { AnswersInvalidError } from '../answer-schema.js';
16
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';
17
18
  import { readBoundedBody } from '../http-body.js';
18
19
  import { errorMessageOf } from './cause-chain.js';
19
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';
20
23
  import { isDatabaseBinding, verifyDurableObjectDeploymentIdentity, verifyDurableObjectDeploymentRequest, } from './deployment-identity.js';
21
24
  import { DoStatusError, doErrorResponse } from './do-error-response.js';
22
25
  import { ExecutionFenceUnreadableError, isRunStartPendingError, MUTATION_EPOCH_HEADER, mutationEpochFromHeader, normalizeD1RunExecutionIdentity, normalizeRunExecutionIdentity, normalizeStartExecutionIdentity, normalizeStartIdentity, RunStartPendingError, } from './execution-admission.js';
26
+ import { assertNoReservedExecutionContext } from './execution-context.js';
23
27
  import { admitsRunStart, ExecutionFencedError, isExecutionFenceRefusal, readExecutionFence, } from './execution-fence.js';
24
28
  import { EXECUTION_PRINCIPAL_HEADER } from './execution-principal-header.js';
25
29
  import { isDefinitiveInitialAdmissionRefusal } from './initial-admission-refusal.js';
@@ -28,15 +32,17 @@ import { isPathSafeId } from './path-safe-id.js';
28
32
  import { answerQuestion, currentQuestions, deleteEarlyAnswer, expireQuestion, getQuestion, isQuestionFingerprint, isQuestionId, listQuestions, openQuestion, QUESTION_ANSWER_RESUME_KEY, QuestionNotOpenError, readEarlyAnswer, retainEarlyAnswer, sameQuestionSuspension, supersedeOpenQuestions, supersedeQuestion, } from './questions.js';
29
33
  import { RemoteStepSettlementFencedError, WORKFLOW_REMOTE_STEP_RESULT_KEY, } from './remote-step-journal.js';
30
34
  import { lifecycleFromRequestContext, terminalCleanupFor, } from './run-lifecycle.js';
31
- 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';
32
37
  import { isDurableRunStatus, isTerminalRunStatus, } from './run-terminal-state.js';
33
- import { InvalidRunRequestError, parsePauseGeneration, parsePauseRunOptions, RunAlreadyExistsError, RunNotSuspendedError, RunnerRuntime, RunStateUnreadableError, RunTerminalConflictError, SuspensionChangedError, UnknownRunError, } from './runtime.js';
38
+ import { assertRunInputDepth, ChildAwaitResumeSchemaError, currentWorkflowLeg, InvalidRunRequestError, parsePauseGeneration, parsePauseRunOptions, RunAlreadyExistsError, RunNotSuspendedError, RunnerRuntime, RunStateUnreadableError, RunTerminalConflictError, SuspensionChangedError, UnknownRunError, } from './runtime.js';
34
39
  import { resolveScheduleStartOwner, } from './schedule-source.js';
35
40
  import { captureReservation, sameReservationIdentity, } from './start-reservation-contract.js';
36
- 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';
37
- import { suspensionKindsOf } from './suspension-kinds.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';
38
43
  const RUN_OWNER_RECOVERY_KEY = 'flowsafe:run-owner-recovery:v1';
39
44
  const START_PRINCIPAL_RECEIPT_KEY = 'flowsafe:start-principal:v1';
45
+ const CHILD_START_RECOVERY_KEY = 'flowsafe:child-start-recovery:v1';
40
46
  export const RUN_OWNER_RECOVERY_DELAY_MS = 60_000;
41
47
  const SUSPENSION_DEADLINE_RETRY_MS = 60_000;
42
48
  // How long a run's state may stay unreadable before the entries due under it
@@ -74,6 +80,9 @@ const SUSPENSION_DEADLINE_ARM_FLOOR_MS = 1_000;
74
80
  // left `running` has nothing driving it.
75
81
  const RUN_LEG_KEY = 'flowsafe:run-leg:v1';
76
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;
77
86
  // Far past the 15 minutes a pending operation keeps a Durable Object running
78
87
  // without a connected client. A leg frame this old belongs to an invocation
79
88
  // that ended without settling the leg's promise — which still holds this
@@ -141,7 +150,7 @@ function sameRunRecovery(actual, expected) {
141
150
  claim.binding.kind === wantedClaim.binding.kind));
142
151
  }
143
152
  function preparedRunExecution(recovery) {
144
- return recovery.phase === 'preparing' ? undefined : recovery.execution;
153
+ return recovery.execution;
145
154
  }
146
155
  class DurableObjectRunIdentityError extends DoStatusError {
147
156
  status = 403;
@@ -196,6 +205,8 @@ export class DurableObjectRunner {
196
205
  /** Absent in Node tests; present under workerd for storage and the alarm. */
197
206
  state;
198
207
  #runtime;
208
+ #childStartsInFlight = new Map();
209
+ #childLedger;
199
210
  #workflowRemoteReader;
200
211
  #operationTail = Promise.resolve();
201
212
  /** `step\0reason` of every suspension deadline this object has reported. */
@@ -211,6 +222,15 @@ export class DurableObjectRunner {
211
222
  async workflowRemoteSteps(_env, _runtime) {
212
223
  return undefined;
213
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
+ }
214
234
  /** Existing schedules domain used only for target-verifiable schedule fires. */
215
235
  scheduleSource(_env) {
216
236
  return undefined;
@@ -334,6 +354,7 @@ export class DurableObjectRunner {
334
354
  SUSPENSION_TIMEOUT_RESUME_KEY,
335
355
  WORKFLOW_REMOTE_STEP_RESULT_KEY,
336
356
  QUESTION_ANSWER_RESUME_KEY,
357
+ CHILDREN_RESUME_KEY,
337
358
  ]) {
338
359
  if (key in value) {
339
360
  throw new InvalidRunRequestError(`resume data must not carry the reserved '${key}' key`);
@@ -346,6 +367,913 @@ export class DurableObjectRunner {
346
367
  const db = this.env?.DB;
347
368
  return isDatabaseBinding(db) ? db : undefined;
348
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
+ }
349
1277
  async #reconcileQuestions(workflowId, summary) {
350
1278
  const questions = currentQuestions(workflowId, summary);
351
1279
  if (questions.length === 0 && !isTerminalRunStatus(summary.status))
@@ -527,6 +1455,7 @@ export class DurableObjectRunner {
527
1455
  const failed = await runtime.failQuestionResume(workflowId, runId, question);
528
1456
  if (failed) {
529
1457
  await this.#reconcileQuestions(workflowId, failed);
1458
+ await this.#recordRunEnd(workflowId, failed);
530
1459
  await this.#finishQuestionResume(workflowId, failed);
531
1460
  }
532
1461
  return failed;
@@ -766,6 +1695,13 @@ export class DurableObjectRunner {
766
1695
  };
767
1696
  return this.#completeTerminalEffects(runtime, workflowId, runId, owner, { ...result, summary: state.summary, cleanup }, assertNoJournal);
768
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
+ }
769
1705
  async #resolveWorkflowRemoteReader(runtime) {
770
1706
  this.#workflowRemoteReader ??= await this.workflowRemoteSteps(this.env, runtime);
771
1707
  return this.#workflowRemoteReader;
@@ -794,8 +1730,11 @@ export class DurableObjectRunner {
794
1730
  if (validate)
795
1731
  await validate();
796
1732
  await this.#reconcileQuestions(workflowId, result.summary);
797
- if (result.cleanup.cleanupCompleted)
1733
+ if (result.cleanup.cleanupCompleted) {
1734
+ await this.#recordRunEnd(workflowId, result.summary);
1735
+ await this.#completeChildCascade();
798
1736
  return result.summary;
1737
+ }
799
1738
  const hooks = this.runLifecycle(this.env);
800
1739
  if (!hooks) {
801
1740
  throw new Error('run termination requires lifecycle cleanup hooks');
@@ -826,9 +1765,13 @@ export class DurableObjectRunner {
826
1765
  throw new Error(`run '${runId}' ownership could not be released`);
827
1766
  }
828
1767
  }
1768
+ if (result.summary.parentRunId)
1769
+ await this.#stageParentNotice(workflowId, runId, result.cleanup.revision);
829
1770
  const summary = await runtime.completeTerminalCleanup(workflowId, runId, result.cleanup.revision);
830
1771
  if (validate)
831
1772
  await validate();
1773
+ await this.#recordRunEnd(workflowId, summary);
1774
+ await this.#completeChildCascade();
832
1775
  return summary;
833
1776
  }
834
1777
  async #startSource(principal, workflowId, runId, scheduleId, dispatchId) {
@@ -910,13 +1853,19 @@ export class DurableObjectRunner {
910
1853
  const recoveryDue = recoveryDueAt ??
911
1854
  ((await storage.get(RUN_OWNER_RECOVERY_KEY)) !== undefined ||
912
1855
  (await storage.get(RUN_LEG_KEY)) !== undefined ||
1856
+ (await storage.get(CHILD_START_RECOVERY_KEY)) !== undefined ||
913
1857
  (await storage.get(QUESTION_RECOVERY_KEY)) !== undefined
914
1858
  ? Date.now() + RUN_OWNER_RECOVERY_DELAY_MS
915
1859
  : undefined);
916
1860
  // `now` is sampled AFTER the awaited recovery-key read above. Hoisting it
917
1861
  // before the read would shrink the floor by the read's latency, and the
918
1862
  // floor is the anti-spin guarantee for an entry that is already due.
919
- 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());
920
1869
  if (due === undefined) {
921
1870
  await storage.deleteAlarm?.();
922
1871
  return;
@@ -1066,20 +2015,19 @@ export class DurableObjectRunner {
1066
2015
  console.error('start principal receipt could not be verified', error);
1067
2016
  }
1068
2017
  }
1069
- async #startPrincipalReceipt(workflowId, runId) {
1070
- const unavailable = () => json({ error: 'run not found' }, 404);
2018
+ async #readStartPrincipalReceipt(workflowId, runId) {
1071
2019
  const storage = this.state?.storage;
1072
2020
  if (!storage || this.state?.id?.name !== `${workflowId}:${runId}`)
1073
- return unavailable();
2021
+ return undefined;
1074
2022
  try {
1075
2023
  const raw = await storage.get(START_PRINCIPAL_RECEIPT_KEY);
1076
2024
  if (typeof raw !== 'string')
1077
- return unavailable();
2025
+ return undefined;
1078
2026
  const parsed = JSON.parse(raw);
1079
2027
  if (parsed === null ||
1080
2028
  typeof parsed !== 'object' ||
1081
2029
  Array.isArray(parsed))
1082
- return unavailable();
2030
+ return undefined;
1083
2031
  const receipt = parsed;
1084
2032
  if (receipt.version !== 1 ||
1085
2033
  receipt.owner === null ||
@@ -1088,7 +2036,7 @@ export class DurableObjectRunner {
1088
2036
  receipt.principal === null ||
1089
2037
  typeof receipt.principal !== 'object' ||
1090
2038
  Array.isArray(receipt.principal))
1091
- return unavailable();
2039
+ return undefined;
1092
2040
  const execution = normalizeD1RunExecutionIdentity(receipt.execution);
1093
2041
  const owner = receipt.owner;
1094
2042
  const principal = decodeExecutionPrincipal(JSON.stringify(receipt.principal));
@@ -1099,7 +2047,7 @@ export class DurableObjectRunner {
1099
2047
  execution.runId !== runId ||
1100
2048
  owner.kind !== principal.kind ||
1101
2049
  owner.id !== principal.id)
1102
- return unavailable();
2050
+ return undefined;
1103
2051
  const canonical = {
1104
2052
  version: 1,
1105
2053
  execution,
@@ -1107,7 +2055,7 @@ export class DurableObjectRunner {
1107
2055
  principal,
1108
2056
  };
1109
2057
  if (JSON.stringify(canonical) !== raw)
1110
- return unavailable();
2058
+ return undefined;
1111
2059
  const state = await this.#ensureRuntime().authoritativeStartState(workflowId, runId);
1112
2060
  const identity = state?.provenance.startIdentity;
1113
2061
  if (state?.storage !== 'd1' ||
@@ -1121,11 +2069,11 @@ export class DurableObjectRunner {
1121
2069
  identity.owner.kind !== owner.kind ||
1122
2070
  identity.owner.id !== owner.id ||
1123
2071
  state.provenance.agentStart !== undefined)
1124
- return unavailable();
1125
- return json(canonical);
2072
+ return undefined;
2073
+ return canonical;
1126
2074
  }
1127
2075
  catch {
1128
- return unavailable();
2076
+ return undefined;
1129
2077
  }
1130
2078
  }
1131
2079
  #matchingRunState(recovery, state) {
@@ -1170,6 +2118,8 @@ export class DurableObjectRunner {
1170
2118
  casMatched: true,
1171
2119
  cleanup,
1172
2120
  });
2121
+ else
2122
+ await this.#recordRunEnd(recovery.workflowId, state.summary);
1173
2123
  const reconciled = await this.#reconcileSuspensionDeadlinesBestEffort(recovery.workflowId, recovery.runId, summary);
1174
2124
  await this.#clearRunOwnerRecovery(recovery, !reconciled);
1175
2125
  return summary;
@@ -1655,6 +2605,21 @@ export class DurableObjectRunner {
1655
2605
  await this.#reconcileApprovalsBestEffort(workflowId, runId, summary);
1656
2606
  return;
1657
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
+ }
1658
2623
  const next = await this.#withLeg(workflowId, runId, 'deadline', () => runtime.resume(workflowId, runId, {
1659
2624
  step: [entry.step],
1660
2625
  resumeData: suspensionTimeoutResumeData(entry, now),
@@ -1780,8 +2745,19 @@ export class DurableObjectRunner {
1780
2745
  console.error(`run '${runId}' of workflow '${workflowId}' state read back self-inconsistent; keeping the record`);
1781
2746
  return;
1782
2747
  }
1783
- const recovered = await this.#recoverQuestionResumes(runtime, workflowId, summary, true);
1784
- await this.#reconcileSuspensionDeadlines(workflowId, runId, recovered, 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);
1785
2761
  }
1786
2762
  /**
1787
2763
  * Never rethrows. workerd retries a thrown alarm(), which would re-run this
@@ -1954,6 +2930,9 @@ export class DurableObjectRunner {
1954
2930
  : await this.#completeTerminalEffects(runtime, recovery.workflowId, recovery.runId, recovery.owner, recovered.transition);
1955
2931
  if (recovered.kind === 'lifecycle')
1956
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);
1957
2936
  const reconciled = await this.#reconcileSuspensionDeadlinesBestEffort(recovery.workflowId, recovery.runId, completed);
1958
2937
  await this.#clearRunOwnerRecovery(recovery, !reconciled);
1959
2938
  return completed;
@@ -2067,23 +3046,27 @@ export class DurableObjectRunner {
2067
3046
  * Clearing never arms: each caller's own boundary re-arms from what is left.
2068
3047
  * Everything after `body` is best effort, because the leg has already run.
2069
3048
  */
2070
- async #withLeg(workflowId, runId, trigger, body, armed) {
3049
+ async #withLeg(workflowId, runId, trigger, body, armed, queueChildAwait = true) {
2071
3050
  const runtime = this.#ensureRuntime();
2072
3051
  const frame = {
2073
3052
  token: crypto.randomUUID(),
2074
3053
  startedAt: Date.now(),
2075
3054
  };
2076
3055
  this.#legs.add(frame);
2077
- const clearIfDurable = async (summary) => {
3056
+ const clearIfDurable = async (summary, completed) => {
2078
3057
  try {
2079
3058
  if (summary && isDurableRunStatus(summary.status)) {
2080
3059
  const current = currentQuestions(workflowId, summary).length > 0
2081
3060
  ? await runtime.authoritativeStatus(workflowId, runId)
2082
3061
  : summary;
2083
- if (!current)
3062
+ if (!current || (!completed && hasInvalidChildAwait(current)))
2084
3063
  return;
2085
3064
  await this.#reconcileQuestions(workflowId, current);
3065
+ if (trigger !== 'start')
3066
+ await this.#recordRunEnd(workflowId, current);
2086
3067
  await this.#clearLegMarker(frame.token);
3068
+ if (completed && queueChildAwait && hasChildAwait(current))
3069
+ this.#queueChildAwait(workflowId, runId);
2087
3070
  }
2088
3071
  }
2089
3072
  catch (error) {
@@ -2104,9 +3087,21 @@ export class DurableObjectRunner {
2104
3087
  startedAt: frame.startedAt,
2105
3088
  });
2106
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
+ }
2107
3098
  let summary;
2108
3099
  try {
2109
- 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);
2110
3105
  }
2111
3106
  catch (error) {
2112
3107
  let current = null;
@@ -2116,10 +3111,10 @@ export class DurableObjectRunner {
2116
3111
  catch {
2117
3112
  // Unreadable: the marker stays for the next wake.
2118
3113
  }
2119
- await clearIfDurable(current);
3114
+ await clearIfDurable(current, false);
2120
3115
  throw error;
2121
3116
  }
2122
- await clearIfDurable(summary);
3117
+ await clearIfDurable(summary, true);
2123
3118
  return summary;
2124
3119
  }
2125
3120
  finally {
@@ -2222,7 +3217,7 @@ export class DurableObjectRunner {
2222
3217
  try {
2223
3218
  this.#assertRunIdentity(workflowId, runId);
2224
3219
  runtime = this.#ensureRuntime();
2225
- settled = await runtime.settleInterruptedRun(workflowId, runId);
3220
+ settled = await runtime.settleInterruptedRun(workflowId, runId, undefined, (status, commitIntent) => this.#cascadeChildren(workflowId, runId, status, commitIntent));
2226
3221
  }
2227
3222
  catch (error) {
2228
3223
  if (await dropIfStale(error))
@@ -2253,6 +3248,10 @@ export class DurableObjectRunner {
2253
3248
  }
2254
3249
  if (summary) {
2255
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);
2256
3255
  try {
2257
3256
  this.#broadcastRunSummary(summary);
2258
3257
  }
@@ -2263,8 +3262,13 @@ export class DurableObjectRunner {
2263
3262
  }
2264
3263
  else if (settled.kind === 'durable') {
2265
3264
  const current = await this.#authoritativeStatusOrUnreadable(runtime, workflowId, runId);
2266
- if (current)
3265
+ if (current) {
2267
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
+ }
2268
3272
  // A leg that stopped after persisting a suspension reached it with no
2269
3273
  // host request to file its approval.
2270
3274
  await this.#reconcileApprovalsBestEffort(workflowId, runId, current ?? undefined);
@@ -2284,6 +3288,15 @@ export class DurableObjectRunner {
2284
3288
  // long as the misbinding lasts. Failing with the watchdog in place keeps
2285
3289
  // the recovery cadence this object woke at before it served deadlines.
2286
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
+ }
2287
3300
  // The duties are failure-isolated: none that throws may skip the
2288
3301
  // others (or their re-arm), and none may leave the object with no wake.
2289
3302
  // A leg settlement that fails keeps its marker, which the final arm
@@ -2295,6 +3308,12 @@ export class DurableObjectRunner {
2295
3308
  catch (error) {
2296
3309
  console.error('interrupted run leg settlement failed', error);
2297
3310
  }
3311
+ try {
3312
+ await this.#retryChildCascade();
3313
+ }
3314
+ catch (error) {
3315
+ console.error('child cascade recovery failed', error);
3316
+ }
2298
3317
  let recoveryError;
2299
3318
  try {
2300
3319
  const recovered = await this.#recoverPendingRunOwner();
@@ -2305,6 +3324,12 @@ export class DurableObjectRunner {
2305
3324
  catch (error) {
2306
3325
  recoveryError = error;
2307
3326
  }
3327
+ try {
3328
+ await this.#sendParentNotice();
3329
+ }
3330
+ catch (error) {
3331
+ console.error('child settlement notice recovery failed', error);
3332
+ }
2308
3333
  const converged = await this.#runDueSuspensionDeadline(Date.now());
2309
3334
  // A duty that converged nothing has no arm to compute: the watchdog set
2310
3335
  // at the top of this body IS the cadence it falls back to, and re-arming
@@ -2343,16 +3368,31 @@ export class DurableObjectRunner {
2343
3368
  if (segments[0] !== 'runs')
2344
3369
  return json({ error: 'not found' }, 404);
2345
3370
  const [, workflowId, runId, action] = segments;
2346
- if (request.method === 'POST' && segments.length === 1) {
2347
- const principal = this.#trustedExecutionPrincipal(encodedPrincipal);
2348
- 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);
2349
3379
  const runRequester = encodedRequester === null
2350
3380
  ? undefined
2351
3381
  : decodeRunRequester(encodedRequester);
2352
3382
  if (encodedRequester !== null && runRequester === undefined)
2353
3383
  throw new InvalidRunRequestError('runRequester is malformed');
2354
3384
  const body = await readJson(request);
2355
- 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 () => {
2356
3396
  if (body &&
2357
3397
  [
2358
3398
  'mutationEpoch',
@@ -2364,16 +3404,17 @@ export class DurableObjectRunner {
2364
3404
  'attemptToken',
2365
3405
  'runOwnerGuard',
2366
3406
  'onPreparedStartIdentity',
3407
+ 'onAdmittedStartIdentity',
2367
3408
  ].some((key) => Object.hasOwn(body, key))) {
2368
3409
  throw new InvalidRunRequestError('start authority is derived from trusted provenance');
2369
3410
  }
2370
- 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;
2371
3414
  if (typeof startWorkflowId !== 'string') {
2372
3415
  return json({ error: 'workflowId is required' }, 400);
2373
3416
  }
2374
- // The DO never generates a runId: the trusted Worker mints the id and
2375
- // addresses this instance with it. A start without one is a caller bug,
2376
- // not a request for generation.
3417
+ // The caller supplies the ID it used to address this object.
2377
3418
  if (typeof startRunId !== 'string') {
2378
3419
  return json({ error: 'runId is required (server-minted by the run router)' }, 400);
2379
3420
  }
@@ -2381,6 +3422,55 @@ export class DurableObjectRunner {
2381
3422
  throw new InvalidRunRequestError('workflowId and runId must be URL-path-safe identifiers');
2382
3423
  }
2383
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');
2384
3474
  // The key rides the internal channel and nothing else. Validated here
2385
3475
  // rather than trusted because this body is JSON: an unvalidated value
2386
3476
  // would reach the fence's proof-only comparison and the runtime's
@@ -2395,20 +3485,23 @@ export class DurableObjectRunner {
2395
3485
  startReservation.targetKind !== 'workflow' ||
2396
3486
  startReservation.targetId !== startWorkflowId ||
2397
3487
  startReservation.threadId !== undefined ||
2398
- startReservation.owner.kind !== principal.kind ||
2399
- startReservation.owner.id !== principal.id ||
3488
+ startReservation.owner.kind !== requester.kind ||
3489
+ startReservation.owner.id !== requester.id ||
2400
3490
  !this.#ensureRuntime().startIdempotency))
2401
3491
  throw new InvalidRunRequestError('start reservation does not match the trusted start');
2402
3492
  const startIdentity = normalizeStartIdentity({
2403
- owner: { kind: principal.kind, id: principal.id },
3493
+ owner: { kind: requester.kind, id: requester.id },
2404
3494
  target: { kind: 'workflow', id: startWorkflowId },
2405
3495
  });
2406
3496
  // Only this local preflight can release the captured claim. Admission
2407
3497
  // and proof binding belong to Runtime after durable preparation.
3498
+ let startEpoch = mutationEpoch;
2408
3499
  try {
2409
3500
  const startFence = await this.#readExecutionFence();
2410
3501
  if (!admitsRunStart(startFence, idempotencyKey))
2411
3502
  throw new ExecutionFencedError(startFence.state, 'run start');
3503
+ if (childStart)
3504
+ startEpoch = startFence.mutationEpoch;
2412
3505
  }
2413
3506
  catch (error) {
2414
3507
  if (startReservation) {
@@ -2421,7 +3514,9 @@ export class DurableObjectRunner {
2421
3514
  }
2422
3515
  throw error;
2423
3516
  }
2424
- 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 };
2425
3520
  const rawOwner = source.owner;
2426
3521
  const owner = Object.freeze({ kind: rawOwner.kind, id: rawOwner.id });
2427
3522
  const target = source.target;
@@ -2431,7 +3526,8 @@ export class DurableObjectRunner {
2431
3526
  ? target.requestContext
2432
3527
  : requestContext;
2433
3528
  const runtime = this.#ensureRuntime();
2434
- await this.#recoverPendingRunOwner();
3529
+ if (!childEntry)
3530
+ await this.#recoverPendingRunOwner();
2435
3531
  const existing = await runtime.status(startWorkflowId, startRunId);
2436
3532
  if (existing) {
2437
3533
  const registered = await this.runOwnership(this.env).owner('run', startRunId);
@@ -2455,9 +3551,20 @@ export class DurableObjectRunner {
2455
3551
  token: recovery.token,
2456
3552
  owner,
2457
3553
  unwound: false,
3554
+ childLineage: child?.lineage,
2458
3555
  };
2459
3556
  const frameKey = this.#inFlightKey(startWorkflowId, startRunId);
2460
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
+ };
2461
3568
  try {
2462
3569
  await this.#armRunOwnerRecovery(recovery);
2463
3570
  await this.#reserveRunOwner(startRunId, owner, recovery.token);
@@ -2470,20 +3577,48 @@ export class DurableObjectRunner {
2470
3577
  ...(storedRequestContext !== undefined
2471
3578
  ? { storedRequestContext }
2472
3579
  : {}),
2473
- requestedBy: principal.id,
2474
- requestedByKind: principal.kind,
2475
- ...(runRequester === undefined || scheduleId !== undefined
3580
+ requestedBy: requester.id,
3581
+ requestedByKind: requester.kind,
3582
+ ...(startRunRequester === undefined ||
3583
+ scheduleId !== undefined
2476
3584
  ? {}
2477
- : { runRequester }),
3585
+ : { runRequester: startRunRequester }),
2478
3586
  attemptToken: recovery.token,
2479
- ...(mutationEpoch === undefined ? {} : { mutationEpoch }),
3587
+ ...(startEpoch === undefined
3588
+ ? {}
3589
+ : { mutationEpoch: startEpoch }),
2480
3590
  startIdentity,
3591
+ ...(childOptions === undefined
3592
+ ? {}
3593
+ : { child: childOptions }),
2481
3594
  startReservation,
2482
3595
  runOwnerGuard: { owner, reservationToken: recovery.token },
2483
3596
  pendingTerminal: () => frame.pendingTerminal,
2484
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
+ }
2485
3608
  recovery = await this.#prepareRunOwner(recovery, execution);
2486
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
+ },
2487
3622
  ...(idempotencyKey === undefined ? {} : { idempotencyKey }),
2488
3623
  ...(deadlineMs === undefined
2489
3624
  ? {}
@@ -2495,9 +3630,14 @@ export class DurableObjectRunner {
2495
3630
  }
2496
3631
  summary = await this.#finishRunOwner(recovery, summary);
2497
3632
  const preparedExecution = preparedRunExecution(recovery);
2498
- if (scheduleId === undefined && preparedExecution)
2499
- await this.#recordStartPrincipal(preparedExecution, owner, principal);
3633
+ if (preparedExecution)
3634
+ await recordStartReceipt(preparedExecution);
3635
+ if (childEntry) {
3636
+ await this.#reconcileApprovalsBestEffort(startWorkflowId, startRunId, summary);
3637
+ }
2500
3638
  this.#broadcastRunSummary(summary);
3639
+ if (childEntry)
3640
+ return new Response(null, { status: 202 });
2501
3641
  return json(await this.#withSuspensionTimers(startWorkflowId, summary));
2502
3642
  }
2503
3643
  catch (error) {
@@ -2509,8 +3649,13 @@ export class DurableObjectRunner {
2509
3649
  if (!sameRunRecovery(current, recovery))
2510
3650
  throw new Error('run owner recovery changed');
2511
3651
  const recovered = await this.#recoverRunOwner(current, frame, error);
2512
- if (recovered)
3652
+ if (recovered) {
3653
+ if (childEntry) {
3654
+ await this.#reconcileApprovalsBestEffort(startWorkflowId, startRunId, recovered);
3655
+ return new Response(null, { status: 202 });
3656
+ }
2513
3657
  return json(await this.#withSuspensionTimers(startWorkflowId, recovered));
3658
+ }
2514
3659
  }
2515
3660
  }
2516
3661
  catch (recoveryError) {
@@ -2524,6 +3669,34 @@ export class DurableObjectRunner {
2524
3669
  this.#startsInFlight.delete(frameKey);
2525
3670
  }
2526
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 });
2527
3700
  }
2528
3701
  // The liveness probe, answered OUTSIDE #withOperationLock on purpose: the
2529
3702
  // start it is asking about holds that lock for the whole first leg, so a
@@ -2544,7 +3717,17 @@ export class DurableObjectRunner {
2544
3717
  runId) {
2545
3718
  if (!isPathSafeId(workflowId) || !isPathSafeId(runId))
2546
3719
  return json({ error: 'run not found' }, 404);
2547
- 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 });
2548
3731
  }
2549
3732
  if (request.method === 'GET' &&
2550
3733
  segments.length === 3 &&
@@ -2709,11 +3892,8 @@ export class DurableObjectRunner {
2709
3892
  if (invocation.status === 'settled' &&
2710
3893
  invocation.settlementOutcome === 'applied') {
2711
3894
  if (!owner) {
2712
- const receipt = await this.#startPrincipalReceipt(workflowId, runId);
2713
- if (receipt.status !== 200)
2714
- return json({ error: 'run not found' }, 404);
2715
- const value = (await receipt.json());
2716
- if (!samePrincipal(value.principal, principal))
3895
+ const receipt = await this.#readStartPrincipalReceipt(workflowId, runId);
3896
+ if (!receipt || !samePrincipal(receipt.principal, principal))
2717
3897
  return json({ error: 'run not found' }, 404);
2718
3898
  }
2719
3899
  return json({ kind: 'already-applied', invocationId });
@@ -2966,11 +4146,8 @@ export class DurableObjectRunner {
2966
4146
  throw new UnknownRunError(workflowId, runId);
2967
4147
  }
2968
4148
  }
2969
- const result = await runtime.terminateAsPrincipal(workflowId, runId, principal, owner ?? principal);
2970
- const summary = await this.#finalizeTerminal(runtime, workflowId, runId, owner ?? principal, result);
2971
- await this.#settleClosedRunInvocationsBestEffort(workflowId, runId);
2972
- await this.#reconcileSuspensionDeadlinesBestEffort(workflowId, runId, summary);
2973
- 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);
2974
4151
  return json(summary);
2975
4152
  });
2976
4153
  }
@@ -3003,7 +4180,7 @@ export class DurableObjectRunner {
3003
4180
  throw new UnknownRunError(workflowId, runId);
3004
4181
  }
3005
4182
  }
3006
- 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));
3007
4184
  if (!result.casMatched || result.cleanup.cleanupCompleted) {
3008
4185
  // The only terminal path that returns without finalizing, so it is
3009
4186
  // also the only one that would leave a record armed for a run that
@@ -3016,10 +4193,7 @@ export class DurableObjectRunner {
3016
4193
  await this.#reconcileSuspensionDeadlinesBestEffort(workflowId, runId, result.summary);
3017
4194
  return json(result.summary);
3018
4195
  }
3019
- const summary = await this.#finalizeTerminal(runtime, workflowId, runId, owner ?? principal, result);
3020
- await this.#settleClosedRunInvocationsBestEffort(workflowId, runId);
3021
- await this.#reconcileSuspensionDeadlinesBestEffort(workflowId, runId, summary);
3022
- this.#broadcastRunSummary(summary);
4196
+ const summary = await this.#finalizeAndPublishTerminal(runtime, workflowId, runId, owner ?? principal, result);
3023
4197
  return json(summary);
3024
4198
  });
3025
4199
  }
@@ -3088,6 +4262,40 @@ export function nextDutyAlarmAt(suspensionDueAt, recoveryDueAt, now) {
3088
4262
  function entriesWithoutStep(entries, step) {
3089
4263
  return entries.filter((entry) => entry.step !== step);
3090
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
+ }
3091
4299
  /** The run-channel wire frame containing the authoritative RunSummary. */
3092
4300
  function runFrame(summary) {
3093
4301
  return JSON.stringify({ type: 'run', summary });