@proofoftech/flowsafe 0.23.0 → 0.25.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 (115) hide show
  1. package/CHANGELOG.md +135 -0
  2. package/README.md +59 -9
  3. package/dist/agent-host/thread-host.d.ts.map +1 -1
  4. package/dist/agent-host/thread-host.js +26 -2
  5. package/dist/agent-host/thread-host.js.map +1 -1
  6. package/dist/agent-runner/durable-agent-runner.d.ts +13 -19
  7. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  8. package/dist/agent-runner/durable-agent-runner.js +551 -372
  9. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  10. package/dist/approval-api/retention.d.ts.map +1 -1
  11. package/dist/approval-api/retention.js +6 -5
  12. package/dist/approval-api/retention.js.map +1 -1
  13. package/dist/approval-api/service.js +4 -4
  14. package/dist/approval-api/service.js.map +1 -1
  15. package/dist/approval-ui/use-approval-dashboard.js +6 -6
  16. package/dist/approval-ui/use-approval-dashboard.js.map +1 -1
  17. package/dist/background-tasks/d1-storage.d.ts.map +1 -1
  18. package/dist/background-tasks/d1-storage.js +7 -5
  19. package/dist/background-tasks/d1-storage.js.map +1 -1
  20. package/dist/background-tasks/host.d.ts.map +1 -1
  21. package/dist/background-tasks/host.js +27 -38
  22. package/dist/background-tasks/host.js.map +1 -1
  23. package/dist/do-runner/cause-chain.d.ts +5 -0
  24. package/dist/do-runner/cause-chain.d.ts.map +1 -1
  25. package/dist/do-runner/cause-chain.js +12 -0
  26. package/dist/do-runner/cause-chain.js.map +1 -1
  27. package/dist/do-runner/cf-types.d.ts +3 -0
  28. package/dist/do-runner/cf-types.d.ts.map +1 -1
  29. package/dist/do-runner/cf-types.js.map +1 -1
  30. package/dist/do-runner/constants.d.ts +1 -1
  31. package/dist/do-runner/constants.d.ts.map +1 -1
  32. package/dist/do-runner/constants.js +1 -1
  33. package/dist/do-runner/constants.js.map +1 -1
  34. package/dist/do-runner/core-events-nonce.d.ts +2 -0
  35. package/dist/do-runner/core-events-nonce.d.ts.map +1 -0
  36. package/dist/do-runner/core-events-nonce.js +16 -0
  37. package/dist/do-runner/core-events-nonce.js.map +1 -0
  38. package/dist/do-runner/d1-storage.js +1 -9
  39. package/dist/do-runner/d1-storage.js.map +1 -1
  40. package/dist/do-runner/do-error-response.d.ts.map +1 -1
  41. package/dist/do-runner/do-error-response.js +2 -1
  42. package/dist/do-runner/do-error-response.js.map +1 -1
  43. package/dist/do-runner/durable-object.d.ts +34 -2
  44. package/dist/do-runner/durable-object.d.ts.map +1 -1
  45. package/dist/do-runner/durable-object.js +447 -53
  46. package/dist/do-runner/durable-object.js.map +1 -1
  47. package/dist/do-runner/fenced-workflow-capability.d.ts +51 -0
  48. package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -1
  49. package/dist/do-runner/fenced-workflows-d1.d.ts +5 -1
  50. package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -1
  51. package/dist/do-runner/fenced-workflows-d1.js +236 -48
  52. package/dist/do-runner/fenced-workflows-d1.js.map +1 -1
  53. package/dist/do-runner/index.d.ts +2 -2
  54. package/dist/do-runner/index.d.ts.map +1 -1
  55. package/dist/do-runner/index.js +2 -2
  56. package/dist/do-runner/index.js.map +1 -1
  57. package/dist/do-runner/init.d.ts +2 -3
  58. package/dist/do-runner/init.d.ts.map +1 -1
  59. package/dist/do-runner/init.js.map +1 -1
  60. package/dist/do-runner/memory-id.js +1 -1
  61. package/dist/do-runner/memory-id.js.map +1 -1
  62. package/dist/do-runner/pubsub.d.ts +6 -2
  63. package/dist/do-runner/pubsub.d.ts.map +1 -1
  64. package/dist/do-runner/pubsub.js +12 -22
  65. package/dist/do-runner/pubsub.js.map +1 -1
  66. package/dist/do-runner/run-lifecycle.d.ts +42 -2
  67. package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
  68. package/dist/do-runner/run-lifecycle.js +57 -1
  69. package/dist/do-runner/run-lifecycle.js.map +1 -1
  70. package/dist/do-runner/run-terminal-state.d.ts +2 -0
  71. package/dist/do-runner/run-terminal-state.d.ts.map +1 -1
  72. package/dist/do-runner/run-terminal-state.js +4 -0
  73. package/dist/do-runner/run-terminal-state.js.map +1 -1
  74. package/dist/do-runner/runtime.d.ts +87 -17
  75. package/dist/do-runner/runtime.d.ts.map +1 -1
  76. package/dist/do-runner/runtime.js +455 -155
  77. package/dist/do-runner/runtime.js.map +1 -1
  78. package/dist/do-runner/suspension-deadline.d.ts +25 -17
  79. package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
  80. package/dist/do-runner/suspension-deadline.js +44 -21
  81. package/dist/do-runner/suspension-deadline.js.map +1 -1
  82. package/dist/do-runner/workflow-snapshot-row.d.ts +6 -0
  83. package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -1
  84. package/dist/do-runner/workflow-snapshot-row.js +17 -0
  85. package/dist/do-runner/workflow-snapshot-row.js.map +1 -1
  86. package/dist/host-kit/approval-bridge.d.ts +25 -9
  87. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  88. package/dist/host-kit/approval-bridge.js +72 -15
  89. package/dist/host-kit/approval-bridge.js.map +1 -1
  90. package/dist/host-kit/do-response.d.ts.map +1 -1
  91. package/dist/host-kit/do-response.js +7 -1
  92. package/dist/host-kit/do-response.js.map +1 -1
  93. package/dist/host-kit/flowsafe-worker.d.ts +2 -1
  94. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  95. package/dist/host-kit/flowsafe-worker.js +4 -2
  96. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  97. package/dist/host-kit/run-router.d.ts +4 -1
  98. package/dist/host-kit/run-router.d.ts.map +1 -1
  99. package/dist/host-kit/run-router.js +3 -2
  100. package/dist/host-kit/run-router.js.map +1 -1
  101. package/dist/schedules/schedules-d1.d.ts +1 -0
  102. package/dist/schedules/schedules-d1.d.ts.map +1 -1
  103. package/dist/schedules/schedules-d1.js +35 -22
  104. package/dist/schedules/schedules-d1.js.map +1 -1
  105. package/dist/schedules/tick.d.ts +17 -2
  106. package/dist/schedules/tick.d.ts.map +1 -1
  107. package/dist/schedules/tick.js +63 -44
  108. package/dist/schedules/tick.js.map +1 -1
  109. package/dist/signals/d1-shared.js +1 -1
  110. package/dist/signals/d1-shared.js.map +1 -1
  111. package/dist/signals/thread-do-routes.d.ts +8 -1
  112. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  113. package/dist/signals/thread-do-routes.js +40 -44
  114. package/dist/signals/thread-do-routes.js.map +1 -1
  115. package/package.json +10 -7
@@ -8,10 +8,12 @@
8
8
  // enforced by RunnerRuntime's per-run FIFO locks; routing one DO instance per run
9
9
  // (idFromName(`${workflowId}:${runId}`)) makes those locks authoritative,
10
10
  // since all traffic for a run lands on one instance. The object's alarm is
11
- // reserved for recovering run-owner claims that outlive an interrupted start
12
- // and for the per-suspension deadlines of this run (suspension-deadline.ts);
13
- // both duties share one wake, armed at the earliest of the two due times.
11
+ // reserved for settling a run whose execution leg stopped mid-step, for
12
+ // recovering run-owner claims that outlive an interrupted start, and for the
13
+ // per-suspension deadlines of this run (suspension-deadline.ts); the duties
14
+ // share one wake, armed at the earliest due time.
14
15
  import { decodeExecutionPrincipal, isExecutionPrincipalId, isExecutionPrincipalKind, } from '../approval-api/principal.js';
16
+ import { errorMessageOf } from './cause-chain.js';
15
17
  import { newWebSocketPair, safeSend } from './cf-types.js';
16
18
  import { isDatabaseBinding, verifyDurableObjectDeploymentIdentity, verifyDurableObjectDeploymentRequest, } from './deployment-identity.js';
17
19
  import { DoStatusError, doErrorResponse } from './do-error-response.js';
@@ -21,11 +23,11 @@ import { EXECUTION_PRINCIPAL_HEADER } from './execution-principal-header.js';
21
23
  import { isDefinitiveInitialAdmissionRefusal } from './initial-admission-refusal.js';
22
24
  import { isPathSafeId } from './path-safe-id.js';
23
25
  import { lifecycleFromRequestContext, terminalCleanupFor, } from './run-lifecycle.js';
24
- import { isTerminalRunStatus } from './run-terminal-state.js';
26
+ import { isDurableRunStatus, isTerminalRunStatus, } from './run-terminal-state.js';
25
27
  import { InvalidRunRequestError, RunAlreadyExistsError, RunnerRuntime, RunStateUnreadableError, UnknownRunError, } from './runtime.js';
26
28
  import { resolveScheduleStartOwner, } from './schedule-source.js';
27
29
  import { captureReservation, sameReservationIdentity, } from './start-reservation-contract.js';
28
- import { dueSuspensionDeadline, isReadableRunSummary, isSuspensionDeadlineDue, MAX_SUSPENSION_DEADLINE_ATTEMPTS, MAX_SUSPENSION_DEADLINES_PER_RUN, mergeSuspensionDeadlines, nextSuspensionDeadlineAt, parseSuspensionDeadlineRecord, SUSPENSION_DEADLINE_PRINCIPAL_ID, SUSPENSION_DEADLINE_STORAGE_KEY, SUSPENSION_TIMEOUT_RESUME_KEY, suspensionDeadlinesOf, suspensionTimeoutResumeData, tombstoned, } from './suspension-deadline.js';
30
+ 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';
29
31
  const RUN_OWNER_RECOVERY_KEY = 'flowsafe:run-owner-recovery:v1';
30
32
  export const RUN_OWNER_RECOVERY_DELAY_MS = 60_000;
31
33
  const SUSPENSION_DEADLINE_RETRY_MS = 60_000;
@@ -59,6 +61,20 @@ const SUSPENSION_DEADLINE_UNREADABLE_LIMIT_MS = 86_400_000;
59
61
  // deferred to the watchdog — up to a minute late, and only while the fault
60
62
  // lasts.
61
63
  const SUSPENSION_DEADLINE_ARM_FLOOR_MS = 1_000;
64
+ // The marker of the execution leg this object is driving. It outlives an
65
+ // isolate that dies mid-step, which is how the next wake learns that a run
66
+ // left `running` has nothing driving it.
67
+ const RUN_LEG_KEY = 'flowsafe:run-leg:v1';
68
+ // Far past the 15 minutes a pending operation keeps a Durable Object running
69
+ // without a connected client. A leg frame this old belongs to an invocation
70
+ // that ended without settling the leg's promise — which still holds this
71
+ // object's locks — or to a leg whose client has stayed connected all along.
72
+ // Resetting the object bounds the first and ends the second.
73
+ const RUN_LEG_MAX_AGE_MS = 7_200_000;
74
+ // The bound on a marker whose run cannot be settled, for instance because a
75
+ // deploy unregistered its workflow: the bound the suspension-deadline duty
76
+ // allows an unreadable run.
77
+ const RUN_LEG_UNSETTLED_LIMIT_MS = SUSPENSION_DEADLINE_UNREADABLE_LIMIT_MS;
62
78
  function recoveryObject(value) {
63
79
  if (value === null || typeof value !== 'object' || Array.isArray(value))
64
80
  throw new Error('stored run owner recovery is malformed');
@@ -70,6 +86,32 @@ function recoveryObject(value) {
70
86
  }
71
87
  return copy;
72
88
  }
89
+ function runLegMarker(value) {
90
+ let stored;
91
+ try {
92
+ stored = recoveryObject(value);
93
+ }
94
+ catch {
95
+ throw new Error('stored run leg marker is malformed');
96
+ }
97
+ if (stored.version !== 1 ||
98
+ !isPathSafeId(stored.workflowId) ||
99
+ !isPathSafeId(stored.runId) ||
100
+ !isPathSafeId(stored.token) ||
101
+ (stored.trigger !== 'start' &&
102
+ stored.trigger !== 'resume' &&
103
+ stored.trigger !== 'deadline') ||
104
+ !Number.isSafeInteger(stored.startedAt))
105
+ throw new Error('stored run leg marker is malformed');
106
+ return {
107
+ version: 1,
108
+ workflowId: stored.workflowId,
109
+ runId: stored.runId,
110
+ token: stored.token,
111
+ trigger: stored.trigger,
112
+ startedAt: stored.startedAt,
113
+ };
114
+ }
73
115
  function sameRunRecovery(actual, expected) {
74
116
  const claim = actual.startReservation;
75
117
  const wantedClaim = expected.startReservation;
@@ -150,6 +192,8 @@ export class DurableObjectRunner {
150
192
  #reportedSuspensionRejections = new Set();
151
193
  /** Persisted claims outlive an isolate and cannot establish run liveness. */
152
194
  #startsInFlight = new Map();
195
+ /** Execution legs running in this isolate. */
196
+ #legs = new Set();
153
197
  constructor(state, env) {
154
198
  this.state = state;
155
199
  this.env = env;
@@ -158,7 +202,11 @@ export class DurableObjectRunner {
158
202
  scheduleSource(_env) {
159
203
  return undefined;
160
204
  }
161
- /** Required when the host exposes terminate or deadline lifecycle routes. */
205
+ /**
206
+ * Required when the host exposes terminate or deadline lifecycle routes.
207
+ * Its optional `reconcileApprovals` files the approvals the object reaches
208
+ * from its alarm.
209
+ */
162
210
  runLifecycle(_env) {
163
211
  return undefined;
164
212
  }
@@ -205,11 +253,14 @@ export class DurableObjectRunner {
205
253
  // populated for idFromName-created ids; it is absent under node tests
206
254
  // (state undefined / minimal stubs), where the runtime's own validation
207
255
  // still applies.
256
+ /** Does `workflowId:runId` name this object's run (or does it carry no name)? */
257
+ #isOwnRun(workflowId, runId) {
258
+ const name = this.state?.id?.name;
259
+ return name === undefined || name === `${workflowId}:${runId}`;
260
+ }
208
261
  #assertRunIdentity(workflowId, runId) {
209
262
  const name = this.state?.id?.name;
210
- if (name === undefined)
211
- return;
212
- if (name !== `${workflowId}:${runId}`) {
263
+ if (!this.#isOwnRun(workflowId, runId)) {
213
264
  throw new Error(`DO identity mismatch: instance is '${name}' but the request names '${workflowId}:${runId}' — refusing`);
214
265
  }
215
266
  }
@@ -416,8 +467,9 @@ export class DurableObjectRunner {
416
467
  }
417
468
  }
418
469
  /**
419
- * The arming path for this object's one alarm, which two independent duties
420
- * share: run-owner recovery and the run's suspension deadlines. Every arm
470
+ * The arming path for this object's one alarm, which independent duties
471
+ * share: run-owner recovery and leg settlement (one cadence, kept while
472
+ * either record exists) and the run's suspension deadlines. Every arm
421
473
  * that reflects CONVERGED state routes through here, or through the
422
474
  * #armAlarmFor it delegates to, because an alarm set for one duty from a
423
475
  * site that cannot see the other would silently drop the other's wake — a
@@ -448,8 +500,11 @@ export class DurableObjectRunner {
448
500
  throw new Error('run owner recovery and suspension deadlines require Durable Object alarms');
449
501
  }
450
502
  const suspensionDueAt = nextSuspensionDeadlineAt(stored);
503
+ // A leg marker keeps the recovery cadence: it is the wake that finds a
504
+ // leg which stopped without reaching a durable state.
451
505
  const recoveryDue = recoveryDueAt ??
452
- ((await storage.get(RUN_OWNER_RECOVERY_KEY)) !== undefined
506
+ ((await storage.get(RUN_OWNER_RECOVERY_KEY)) !== undefined ||
507
+ (await storage.get(RUN_LEG_KEY)) !== undefined
453
508
  ? Date.now() + RUN_OWNER_RECOVERY_DELAY_MS
454
509
  : undefined);
455
510
  // `now` is sampled AFTER the awaited recovery-key read above. Hoisting it
@@ -685,10 +740,7 @@ export class DurableObjectRunner {
685
740
  // born abandoned. `previous` still reaches the write below, whose
686
741
  // write-or-skip decision is about the key that is stored, not about whose
687
742
  // run it names.
688
- const inherited = previous?.workflowId === workflowId && previous.runId === runId
689
- ? previous
690
- : undefined;
691
- await this.#writeSuspensionDeadlines(workflowId, runId, previous, mergeSuspensionDeadlines(inherited, derived));
743
+ await this.#writeSuspensionDeadlines(workflowId, runId, previous, mergeSuspensionDeadlines(ownSuspensionDeadlines(previous, workflowId, runId), derived));
692
744
  }
693
745
  /**
694
746
  * Report a deadline the run asked for and did not get, once. Derivation runs
@@ -708,6 +760,32 @@ export class DurableObjectRunner {
708
760
  this.#reportedSuspensionRejections.add(seen);
709
761
  console.error(`suspension deadline not armed for step '${rejection.step}' of run '${runId}': ${rejection.reason}`);
710
762
  }
763
+ /**
764
+ * The summary with its timer steps listed, so approval bridges file nothing
765
+ * for a step this object will resume itself. It never throws and never
766
+ * deletes: the lifecycle change behind the response has already persisted,
767
+ * and the status and replay routes run outside the operation lock. Without a
768
+ * scheduled wake nothing would resume a timer, so a step this read cannot
769
+ * vouch for is left out and gets an approval a person can resume.
770
+ */
771
+ async #withSuspensionTimers(workflowId, summary) {
772
+ try {
773
+ // Most suspensions ask for no timer; they pay no storage read.
774
+ if (suspensionTimerSteps(summary, undefined).length === 0)
775
+ return summary;
776
+ const storage = this.state?.storage;
777
+ if (!storage?.getAlarm || (await storage.getAlarm()) === null)
778
+ return summary;
779
+ const steps = suspensionTimerSteps(summary, ownSuspensionDeadlines(parseSuspensionDeadlineRecord(await storage.get(SUSPENSION_DEADLINE_STORAGE_KEY)), workflowId, summary.runId));
780
+ return steps.length === 0
781
+ ? summary
782
+ : { ...summary, suspensionTimers: steps };
783
+ }
784
+ catch (error) {
785
+ console.error('suspension timer read failed', error);
786
+ return summary;
787
+ }
788
+ }
711
789
  /**
712
790
  * Reconciliation is bookkeeping ABOUT a transition that has already been
713
791
  * persisted by the runtime. Failing the caller's start, resume, or
@@ -745,6 +823,43 @@ export class DurableObjectRunner {
745
823
  return false;
746
824
  }
747
825
  }
826
+ /**
827
+ * Reconcile the approvals of this object's run, at a boundary the object
828
+ * reached on its own, through the lifecycle's `reconcileApprovals`.
829
+ * `known` is an authoritative summary already in hand; without one the run
830
+ * is read. `ended` is the suspension a timeout resume just ended; the hook
831
+ * then hears of it whatever the run did next. Never throws: the boundary has
832
+ * already happened, and a host read with reconciliation files what a failure
833
+ * here misses.
834
+ */
835
+ async #reconcileApprovalsBestEffort(workflowId, runId, known, ended) {
836
+ // A foreign record names another object's run: nothing here to file.
837
+ if (!this.#isOwnRun(workflowId, runId))
838
+ return;
839
+ try {
840
+ const hooks = this.runLifecycle(this.env);
841
+ if (!hooks?.reconcileApprovals)
842
+ return;
843
+ const summary = known ??
844
+ (await this.#authoritativeStatusOrUnreadable(this.#ensureRuntime(), workflowId, runId));
845
+ if (!summary || !isReadableRunSummary(summary))
846
+ return;
847
+ // A run that is not suspended has nothing to file; the hook still hears
848
+ // of a suspension a timeout resume just ended, so it can close that
849
+ // approval.
850
+ if (summary.status !== 'suspended' && ended === undefined)
851
+ return;
852
+ await hooks.reconcileApprovals(workflowId, await this.#withSuspensionTimers(workflowId, summary), ended);
853
+ }
854
+ catch (error) {
855
+ console.error(JSON.stringify({
856
+ type: 'reconcile-error',
857
+ workflowId,
858
+ runId,
859
+ error: errorMessageOf(error),
860
+ }));
861
+ }
862
+ }
748
863
  // An entry is keyed by the DOT-JOINED suspended path, exactly as the summary
749
864
  // keys the two fence fields read below, so the path is joined here too. The
750
865
  // wake reads the rehydrated projection, which splits a stored key on every
@@ -776,6 +891,7 @@ export class DurableObjectRunner {
776
891
  * and the budget would bound one burst instead of the suspension. The merge
777
892
  * carries the tombstone while the fence is unchanged and drops it when the
778
893
  * suspension moves on, so a later suspension of the same step starts fresh.
894
+ * Answers whether this charge abandoned the entry.
779
895
  */
780
896
  async #chargeSuspensionDeadlineAttempt(stored, entry, now, error) {
781
897
  const { workflowId, runId } = stored;
@@ -787,7 +903,7 @@ export class DurableObjectRunner {
787
903
  ...remaining,
788
904
  tombstoned(entry),
789
905
  ]);
790
- return;
906
+ return true;
791
907
  }
792
908
  console.error(`suspension deadline wake for step '${entry.step}' of run '${runId}' failed (attempt ${attempts})`, error);
793
909
  // Rebuilt field by field rather than spread from `entry`: the REBUILD is
@@ -811,6 +927,7 @@ export class DurableObjectRunner {
811
927
  nextAttemptAt: now + SUSPENSION_DEADLINE_RETRY_MS * 2 ** (attempts - 1),
812
928
  },
813
929
  ]);
930
+ return false;
814
931
  }
815
932
  /**
816
933
  * Record that this wake could not read the run's authoritative state, and
@@ -972,14 +1089,31 @@ export class DurableObjectRunner {
972
1089
  // record this wake read goes with it: re-reading it would be the second
973
1090
  // storage read #armAlarmFor's JSDoc refuses to pay.
974
1091
  await this.#reconcileSuspensionDeadlines(workflowId, runId, summary, stored);
1092
+ // A timeout resume that stopped after persisting the next suspension
1093
+ // reaches here with no host request to file its approval.
1094
+ await this.#reconcileApprovalsBestEffort(workflowId, runId, summary);
975
1095
  return;
976
1096
  }
977
- const next = await runtime.resume(workflowId, runId, {
1097
+ const next = await this.#withLeg(workflowId, runId, 'deadline', () => runtime.resume(workflowId, runId, {
978
1098
  step: [entry.step],
979
1099
  resumeData: suspensionTimeoutResumeData(entry, now),
980
- requestedBy: SUSPENSION_DEADLINE_PRINCIPAL_ID,
981
- requestedByKind: 'system',
982
- });
1100
+ // A timeout is no principal's action, so the run keeps its recorded
1101
+ // requester and the next gate is filed against them: the runtime
1102
+ // inherits a complete pair. Legacy provenance without a kind takes
1103
+ // the approval bridge's legacy default, which the runtime will not
1104
+ // infer, and a run without a requester resumes under the reserved id.
1105
+ ...(summary.requestedBy === undefined
1106
+ ? {
1107
+ requestedBy: SUSPENSION_DEADLINE_PRINCIPAL_ID,
1108
+ requestedByKind: 'system',
1109
+ }
1110
+ : summary.requestedByKind === undefined
1111
+ ? {
1112
+ requestedBy: summary.requestedBy,
1113
+ requestedByKind: 'human',
1114
+ }
1115
+ : {}),
1116
+ }), true);
983
1117
  // EVERYTHING after this point is best effort, because the resume has
984
1118
  // already run the step: charging a bookkeeping failure to the retry ledger
985
1119
  // would record a failed resume that in fact succeeded, and could resume the
@@ -994,6 +1128,15 @@ export class DurableObjectRunner {
994
1128
  console.error('suspension deadline broadcast failed', error);
995
1129
  }
996
1130
  await this.#reconcileSuspensionDeadlinesBestEffort(workflowId, runId, next);
1131
+ // From a fresh authoritative read, not `next`: a host status read files
1132
+ // against the stored projection, so filing from it keys a gate the way that
1133
+ // read does. The hook also receives the suspension this resume ended,
1134
+ // whatever the run did next, so it can close an approval still open for it.
1135
+ await this.#reconcileApprovalsBestEffort(workflowId, runId, undefined, {
1136
+ step: entry.step,
1137
+ suspendedAt: entry.suspendedAt,
1138
+ resumeCount: entry.resumeCount,
1139
+ });
997
1140
  }
998
1141
  /**
999
1142
  * The shared end of every wake that will not resume AND holds no
@@ -1001,9 +1144,8 @@ export class DurableObjectRunner {
1001
1144
  * directly from the one it read): re-derive this run's deadlines from
1002
1145
  * authoritative state. The set of wakes that land here with nothing due is
1003
1146
  * ordinary, not anomalous — the watchdog survivor whose duty already ran,
1004
- * H1's retry wake after a failed reconcile, a recovery-armed wake whose
1005
- * start body outlived the 60 s recovery delay (a healthy slow workflow), a
1006
- * workerd alarm redelivery or at-least-once retry after a rethrown recovery
1147
+ * H1's retry wake after a failed reconcile, a recovery-armed wake that fell
1148
+ * due after its start leg returned, a workerd alarm redelivery or at-least-once retry after a rethrown recovery
1007
1149
  * error (up to 6 retries), and an entry still inside the 1 s arm floor. The
1008
1150
  * `authoritativeStatus()` read lands off the lifecycle hot path on exactly
1009
1151
  * those wakes — and it is the authoritative read, not `status()`, because
@@ -1187,14 +1329,19 @@ export class DurableObjectRunner {
1187
1329
  // above — has nothing to charge, so it keeps the watchdog cadence.
1188
1330
  if (!stored || !entry)
1189
1331
  return false;
1332
+ let abandoned;
1190
1333
  try {
1191
- await this.#chargeSuspensionDeadlineAttempt(stored, entry, now, error);
1192
- return true;
1334
+ abandoned = await this.#chargeSuspensionDeadlineAttempt(stored, entry, now, error);
1193
1335
  }
1194
1336
  catch (ledgerError) {
1195
1337
  console.error('suspension deadline ledger update failed', ledgerError);
1196
1338
  return false;
1197
1339
  }
1340
+ // A step whose timer this object gave up on gets the approval a person
1341
+ // can resume it with.
1342
+ if (abandoned)
1343
+ await this.#reconcileApprovalsBestEffort(stored.workflowId, stored.runId);
1344
+ return true;
1198
1345
  }
1199
1346
  }
1200
1347
  async #recoverRunOwner(recovery, ownFrame, ownFailure) {
@@ -1221,6 +1368,7 @@ export class DurableObjectRunner {
1221
1368
  isOwnerQuiescent: quiescent,
1222
1369
  startReservation: recovery.startReservation,
1223
1370
  expectedTarget: { kind: 'workflow' },
1371
+ startLeg: ownFrame?.unwound === true ? 'unwound' : 'touched',
1224
1372
  });
1225
1373
  }
1226
1374
  else if (recovery.phase === 'prepared-unfenced') {
@@ -1320,13 +1468,230 @@ export class DurableObjectRunner {
1320
1468
  }
1321
1469
  : { ...base, phase: 'prepared-unfenced', execution };
1322
1470
  }
1471
+ /** The recovered run's summary, or undefined when none was recovered. */
1323
1472
  async #recoverPendingRunOwner() {
1324
1473
  const stored = await this.state?.storage?.get(RUN_OWNER_RECOVERY_KEY);
1325
- if (stored !== undefined) {
1326
- await this.#recoverRunOwner(this.#runOwnerRecovery(stored));
1474
+ if (stored === undefined)
1475
+ return undefined;
1476
+ const recovery = this.#runOwnerRecovery(stored);
1477
+ const summary = await this.#recoverRunOwner(recovery);
1478
+ return summary ? { workflowId: recovery.workflowId, summary } : undefined;
1479
+ }
1480
+ /**
1481
+ * Drive one execution leg under a durable marker and an in-memory frame.
1482
+ *
1483
+ * The marker is written before the engine runs and removed once the leg is
1484
+ * known to have left the run in a durable state (suspended or terminal). A
1485
+ * leg that throws is not such evidence: when a platform limit cancels the
1486
+ * invocation, the engine's promise rejects mid-step and this frame still
1487
+ * unwinds, so a throw clears the marker only when an authoritative read then
1488
+ * shows a durable run — the read a cancelled invocation cannot make. A kept
1489
+ * marker is the next wake's to settle.
1490
+ *
1491
+ * While the leg runs, the runtime marks its run row live in D1 every
1492
+ * RUN_LEG_TOUCH_MS (RunnerRuntime.start and resume). The marker says a leg
1493
+ * began; the touch says one is still running, from whichever instance runs
1494
+ * it — during a deploy an outgoing instance keeps executing a leg that never
1495
+ * touches this object's storage, while the next wake already runs on the new
1496
+ * instance.
1497
+ *
1498
+ * `armed` is true where the caller already holds a wake within the recovery
1499
+ * delay: the start journal's, or the watchdog an alarm body opens with.
1500
+ * Clearing never arms: each caller's own boundary re-arms from what is left.
1501
+ * Everything after `body` is best effort, because the leg has already run.
1502
+ */
1503
+ async #withLeg(workflowId, runId, trigger, body, armed) {
1504
+ const runtime = this.#ensureRuntime();
1505
+ const frame = {
1506
+ token: crypto.randomUUID(),
1507
+ startedAt: Date.now(),
1508
+ };
1509
+ this.#legs.add(frame);
1510
+ const clearIfDurable = async (summary) => {
1511
+ try {
1512
+ if (summary && isDurableRunStatus(summary.status))
1513
+ await this.#clearLegMarker(frame.token);
1514
+ }
1515
+ catch (error) {
1516
+ console.error('run leg marker clear failed', error);
1517
+ }
1518
+ };
1519
+ try {
1520
+ const storage = this.state?.storage;
1521
+ if (storage) {
1522
+ if (!armed)
1523
+ await this.#armNextAlarm(Date.now() + RUN_OWNER_RECOVERY_DELAY_MS);
1524
+ await storage.put(RUN_LEG_KEY, {
1525
+ version: 1,
1526
+ workflowId,
1527
+ runId,
1528
+ token: frame.token,
1529
+ trigger,
1530
+ startedAt: frame.startedAt,
1531
+ });
1532
+ }
1533
+ let summary;
1534
+ try {
1535
+ summary = await body();
1536
+ }
1537
+ catch (error) {
1538
+ let current = null;
1539
+ try {
1540
+ current = await runtime.authoritativeStatus(workflowId, runId);
1541
+ }
1542
+ catch {
1543
+ // Unreadable: the marker stays for the next wake.
1544
+ }
1545
+ await clearIfDurable(current);
1546
+ throw error;
1547
+ }
1548
+ await clearIfDurable(summary);
1549
+ return summary;
1550
+ }
1551
+ finally {
1552
+ this.#legs.delete(frame);
1327
1553
  }
1328
1554
  }
1555
+ /** Remove the leg marker unless a later leg has replaced it. */
1556
+ async #clearLegMarker(token) {
1557
+ const storage = this.state?.storage;
1558
+ if (!storage)
1559
+ return;
1560
+ const stored = await storage.get(RUN_LEG_KEY);
1561
+ if (stored === undefined)
1562
+ return;
1563
+ let current;
1564
+ try {
1565
+ current = runLegMarker(stored);
1566
+ }
1567
+ catch {
1568
+ current = undefined;
1569
+ }
1570
+ if (current !== undefined && current.token !== token)
1571
+ return;
1572
+ await storage.delete(RUN_LEG_KEY);
1573
+ }
1574
+ /**
1575
+ * The alarm's check before it queues behind the operation lock, which a leg
1576
+ * holds for its whole run. It reads only this isolate's frames, so the
1577
+ * watchdog it may arm is still the wake's first storage operation.
1578
+ *
1579
+ * A leg in this isolate is executing as far as the isolate can tell: the
1580
+ * wake has nothing to do while it runs (the run is not suspended, and its
1581
+ * start journal cannot be recovered while it is live), so it keeps the
1582
+ * recovery cadence instead of waiting out the leg — which can outlast the
1583
+ * alarm's own wall-time limit.
1584
+ *
1585
+ * A frame older than RUN_LEG_MAX_AGE_MS is reset instead. Its promise still
1586
+ * holds the operation and run locks, so nothing in this isolate can settle
1587
+ * the run; the interrupted alarm retries on a fresh instance, which settles
1588
+ * through #settleInterruptedLeg. Writing the snapshot from here would race a
1589
+ * promise that could still write it. Returns whether this wake stops here.
1590
+ */
1591
+ async #deferToLiveLeg() {
1592
+ const frames = [...this.#legs];
1593
+ if (frames.length === 0)
1594
+ return false;
1595
+ const now = Date.now();
1596
+ if (frames.some((frame) => now - frame.startedAt >= RUN_LEG_MAX_AGE_MS)) {
1597
+ console.error(JSON.stringify({ type: 'run-leg-reset', legs: frames.length }));
1598
+ this.state?.abort?.('flowsafe: run leg outlived its invocation');
1599
+ }
1600
+ await this.#armAlarmWatchdog();
1601
+ return true;
1602
+ }
1603
+ /**
1604
+ * Settle the run a leg marker names once no leg of this object drives it.
1605
+ *
1606
+ * The first duty of every alarm body, ahead of start recovery: a stranded
1607
+ * start settled here reaches the journal duty as a terminal run, whose
1608
+ * terminal branch settles the start reservation and clears the journal.
1609
+ *
1610
+ * The marker is this object's own record, written only after its run's
1611
+ * identity was asserted, so its ids are asserted against `id.name` like the
1612
+ * start journal's. No leg of this object can be executing here: each one
1613
+ * drops its frame before it releases the operation lock this duty runs
1614
+ * under. A leg on an instance being replaced still touches the run row, and
1615
+ * the runtime settles nothing while it does (`live`).
1616
+ *
1617
+ * A refused or `live` settlement keeps the marker, so the recovery cadence
1618
+ * retries it, for at most RUN_LEG_UNSETTLED_LIMIT_MS after the leg began;
1619
+ * past that the marker is dropped with a log line rather than waking the
1620
+ * object forever.
1621
+ */
1622
+ async #settleInterruptedLeg() {
1623
+ const storage = this.state?.storage;
1624
+ if (!storage)
1625
+ return;
1626
+ const stored = await storage.get(RUN_LEG_KEY);
1627
+ if (stored === undefined)
1628
+ return;
1629
+ let marker;
1630
+ try {
1631
+ marker = runLegMarker(stored);
1632
+ }
1633
+ catch (error) {
1634
+ console.error('stored run leg marker discarded', error);
1635
+ await storage.delete(RUN_LEG_KEY);
1636
+ return;
1637
+ }
1638
+ const { workflowId, runId } = marker;
1639
+ const dropIfStale = async (cause) => {
1640
+ if (Date.now() - marker.startedAt < RUN_LEG_UNSETTLED_LIMIT_MS)
1641
+ return false;
1642
+ console.error(`run leg marker for run '${runId}' of workflow '${workflowId}' dropped without settlement`, cause);
1643
+ await this.#clearLegMarker(marker.token);
1644
+ return true;
1645
+ };
1646
+ let settled;
1647
+ let runtime;
1648
+ try {
1649
+ this.#assertRunIdentity(workflowId, runId);
1650
+ runtime = this.#ensureRuntime();
1651
+ settled = await runtime.settleInterruptedRun(workflowId, runId);
1652
+ }
1653
+ catch (error) {
1654
+ if (await dropIfStale(error))
1655
+ return;
1656
+ throw error;
1657
+ }
1658
+ if (settled.kind === 'live') {
1659
+ await dropIfStale();
1660
+ return;
1661
+ }
1662
+ let summary;
1663
+ if (settled.kind === 'interrupted') {
1664
+ summary = settled.summary;
1665
+ console.error(JSON.stringify({
1666
+ type: 'run-leg-interrupted',
1667
+ workflowId,
1668
+ runId,
1669
+ trigger: marker.trigger,
1670
+ }));
1671
+ }
1672
+ else if (settled.kind === 'transition') {
1673
+ const owner = await this.runOwnership(this.env).owner('run', runId);
1674
+ summary = await this.#finalizeTerminal(runtime, workflowId, runId, owner ?? settled.replayPrincipal, settled.transition);
1675
+ }
1676
+ if (summary) {
1677
+ try {
1678
+ this.#broadcastRunSummary(summary);
1679
+ }
1680
+ catch (error) {
1681
+ console.error('interrupted run broadcast failed', error);
1682
+ }
1683
+ await this.#reconcileSuspensionDeadlinesBestEffort(workflowId, runId, summary);
1684
+ }
1685
+ else if (settled.kind === 'durable') {
1686
+ // A leg that stopped after persisting a suspension reached it with no
1687
+ // host request to file its approval.
1688
+ await this.#reconcileApprovalsBestEffort(workflowId, runId);
1689
+ }
1690
+ await this.#clearLegMarker(marker.token);
1691
+ }
1329
1692
  async alarm() {
1693
+ if (await this.#deferToLiveLeg())
1694
+ return;
1330
1695
  await this.#withOperationLock(async () => {
1331
1696
  await this.#armAlarmWatchdog();
1332
1697
  // The watchdog arm above is deliberately the ONLY arm on the path where
@@ -1337,12 +1702,23 @@ export class DurableObjectRunner {
1337
1702
  // long as the misbinding lasts. Failing with the watchdog in place keeps
1338
1703
  // the recovery cadence this object woke at before it served deadlines.
1339
1704
  await verifyDurableObjectDeploymentIdentity(this.state, this.env);
1340
- // The two duties are failure-isolated: a run-owner recovery that throws
1341
- // must not skip a due suspension deadline (and its re-arm), and neither
1342
- // must be able to leave the object with no wake at all.
1705
+ // The duties are failure-isolated: none that throws may skip the
1706
+ // others (or their re-arm), and none may leave the object with no wake.
1707
+ // A leg settlement that fails keeps its marker, which the final arm
1708
+ // reads back into the recovery cadence; it is never rethrown, because a
1709
+ // retried alarm would repeat the other duties' work.
1710
+ try {
1711
+ await this.#settleInterruptedLeg();
1712
+ }
1713
+ catch (error) {
1714
+ console.error('interrupted run leg settlement failed', error);
1715
+ }
1343
1716
  let recoveryError;
1344
1717
  try {
1345
- await this.#recoverPendingRunOwner();
1718
+ const recovered = await this.#recoverPendingRunOwner();
1719
+ // Only the alarm files: its recovery has no host request behind it.
1720
+ if (recovered)
1721
+ await this.#reconcileApprovalsBestEffort(recovered.workflowId, recovered.summary.runId, recovered.summary);
1346
1722
  }
1347
1723
  catch (error) {
1348
1724
  recoveryError = error;
@@ -1364,6 +1740,12 @@ export class DurableObjectRunner {
1364
1740
  // comes from.
1365
1741
  console.error('run owner recovery could not read authoritative state', recoveryError);
1366
1742
  }
1743
+ else if (isRunStartPendingError(recoveryError)) {
1744
+ // Not rethrown either: a start whose leg may still run, or whose
1745
+ // row the touch rule does not yet read as silent, settled nothing.
1746
+ // The journal survives, and the arm below keeps the 60 s cadence
1747
+ // without workerd's immediate retries.
1748
+ }
1367
1749
  else {
1368
1750
  if (converged)
1369
1751
  await this.#rearmRunOwnerRecovery();
@@ -1489,7 +1871,7 @@ export class DurableObjectRunner {
1489
1871
  await this.#reserveRunOwner(startRunId, owner, recovery.token);
1490
1872
  let summary;
1491
1873
  try {
1492
- summary = await runtime.start(startWorkflowId, {
1874
+ summary = await this.#withLeg(startWorkflowId, startRunId, 'start', () => runtime.start(startWorkflowId, {
1493
1875
  runId: startRunId,
1494
1876
  inputData: resolvedInput,
1495
1877
  initialState: resolvedState,
@@ -1510,14 +1892,14 @@ export class DurableObjectRunner {
1510
1892
  ...(deadlineMs === undefined
1511
1893
  ? {}
1512
1894
  : { deadlineMs: deadlineMs }),
1513
- });
1895
+ }), true);
1514
1896
  }
1515
1897
  finally {
1516
1898
  frame.unwound = true;
1517
1899
  }
1518
1900
  summary = await this.#finishRunOwner(recovery, summary);
1519
1901
  this.#broadcastRunSummary(summary);
1520
- return json(summary);
1902
+ return json(await this.#withSuspensionTimers(startWorkflowId, summary));
1521
1903
  }
1522
1904
  catch (error) {
1523
1905
  frame.unwound = true;
@@ -1529,7 +1911,7 @@ export class DurableObjectRunner {
1529
1911
  throw new Error('run owner recovery changed');
1530
1912
  const recovered = await this.#recoverRunOwner(current, frame, error);
1531
1913
  if (recovered)
1532
- return json(recovered);
1914
+ return json(await this.#withSuspensionTimers(startWorkflowId, recovered));
1533
1915
  }
1534
1916
  }
1535
1917
  catch (recoveryError) {
@@ -1576,12 +1958,16 @@ export class DurableObjectRunner {
1576
1958
  });
1577
1959
  return json(state.kind === 'initial'
1578
1960
  ? { kind: 'initial', execution }
1579
- : { kind: 'result', execution, value: state.summary });
1961
+ : {
1962
+ kind: 'result',
1963
+ execution,
1964
+ value: await this.#withSuspensionTimers(workflowId, state.summary),
1965
+ });
1580
1966
  }
1581
1967
  const summary = await runtime.status(workflowId, runId);
1582
1968
  if (!summary)
1583
1969
  return json({ error: 'run not found' }, 404);
1584
- return json(summary);
1970
+ return json(await this.#withSuspensionTimers(workflowId, summary));
1585
1971
  }
1586
1972
  if (request.method === 'GET' &&
1587
1973
  segments.length === 4 &&
@@ -1595,7 +1981,7 @@ export class DurableObjectRunner {
1595
1981
  const summary = await runtime.status(workflowId, runId);
1596
1982
  if (!summary)
1597
1983
  return json({ error: 'run not found' }, 404);
1598
- return json(summary);
1984
+ return json(await this.#withSuspensionTimers(workflowId, summary));
1599
1985
  });
1600
1986
  }
1601
1987
  if (request.method === 'GET' &&
@@ -1650,7 +2036,7 @@ export class DurableObjectRunner {
1650
2036
  // resumes — the suspended runs it is draining are waiting for exactly
1651
2037
  // these — and proof-only admits its one nominated run.
1652
2038
  await runtime.assertExistingRunAllowed(workflowId, runId);
1653
- const summary = await runtime.resume(workflowId, runId, {
2039
+ const summary = await this.#withLeg(workflowId, runId, 'resume', () => runtime.resume(workflowId, runId, {
1654
2040
  step: body.step,
1655
2041
  resumeData,
1656
2042
  requestedBy,
@@ -1658,11 +2044,21 @@ export class DurableObjectRunner {
1658
2044
  ...(body.deadlineMs === undefined
1659
2045
  ? {}
1660
2046
  : { deadlineMs: body.deadlineMs }),
1661
- });
1662
- await this.#reconcileSuspensionDeadlinesBestEffort(workflowId, runId, summary);
2047
+ }), false);
2048
+ // The leg armed a recovery-cadence wake for its marker. A boundary
2049
+ // that converged re-arms from what is left, which drops that wake
2050
+ // when nothing is pending; one that did not keeps its retry wake.
2051
+ if (await this.#reconcileSuspensionDeadlinesBestEffort(workflowId, runId, summary)) {
2052
+ try {
2053
+ await this.#armNextAlarm();
2054
+ }
2055
+ catch (error) {
2056
+ console.error('resume boundary re-arm failed', error);
2057
+ }
2058
+ }
1663
2059
  // Broadcast the post-resume authoritative summary.
1664
2060
  this.#broadcastRunSummary(summary);
1665
- return json(summary);
2061
+ return json(await this.#withSuspensionTimers(workflowId, summary));
1666
2062
  });
1667
2063
  }
1668
2064
  if (request.method === 'POST' &&
@@ -1683,10 +2079,10 @@ export class DurableObjectRunner {
1683
2079
  return this.#withOperationLock(async () => {
1684
2080
  const owner = await this.runOwnership(this.env).owner('run', runId);
1685
2081
  if (action === 'terminate-replay') {
1686
- // Degrades CLOSED: the in-memory fallback reports 'pending', which
1687
- // is neither terminal status, so a replay during a degraded read is
1688
- // refused with UnknownRunError rather than replayed against a run
1689
- // whose terminal state could not be read.
2082
+ // The in-memory fallback has no requestContext for lifecycle
2083
+ // projection, and core's statuses include neither cancelled nor
2084
+ // timed_out. It cannot authorize a terminal replay during a degraded
2085
+ // read.
1690
2086
  const summary = await runtime.status(workflowId, runId);
1691
2087
  if (summary?.status !== 'cancelled' &&
1692
2088
  summary?.status !== 'timed_out') {
@@ -1720,12 +2116,10 @@ export class DurableObjectRunner {
1720
2116
  return this.#withOperationLock(async () => {
1721
2117
  const owner = await this.runOwnership(this.env).owner('run', runId);
1722
2118
  if (!owner) {
1723
- // Degrades CLOSED, same as the replay guard: 'pending' is not
1724
- // 'timed_out', so the throw stands. It costs more here — this route
1725
- // is driven by the maintenance sweep, and the throw fails the whole
1726
- // sweep pass for that interval — but the next pass retries it, so a
1727
- // degraded read delays the sweep rather than timing out a run whose
1728
- // state nothing could read.
2119
+ // The in-memory fallback has no lifecycle requestContext and core
2120
+ // has no timed_out status, so it cannot authorize this ownerless
2121
+ // deadline route. A degraded read fails the maintenance sweep pass,
2122
+ // which retries on the next interval.
1729
2123
  const summary = await runtime.status(workflowId, runId);
1730
2124
  if (summary?.status !== 'timed_out') {
1731
2125
  throw new UnknownRunError(workflowId, runId);