@proofoftech/flowsafe 0.24.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 (45) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +4 -4
  3. package/dist/agent-host/thread-host.d.ts.map +1 -1
  4. package/dist/agent-host/thread-host.js +20 -2
  5. package/dist/agent-host/thread-host.js.map +1 -1
  6. package/dist/agent-runner/durable-agent-runner.d.ts +2 -2
  7. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  8. package/dist/agent-runner/durable-agent-runner.js +63 -4
  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/background-tasks/d1-storage.d.ts.map +1 -1
  16. package/dist/background-tasks/d1-storage.js +5 -2
  17. package/dist/background-tasks/d1-storage.js.map +1 -1
  18. package/dist/do-runner/durable-object.d.ts +26 -9
  19. package/dist/do-runner/durable-object.d.ts.map +1 -1
  20. package/dist/do-runner/durable-object.js +30 -23
  21. package/dist/do-runner/durable-object.js.map +1 -1
  22. package/dist/do-runner/fenced-workflow-capability.d.ts +31 -4
  23. package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -1
  24. package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -1
  25. package/dist/do-runner/fenced-workflows-d1.js +96 -9
  26. package/dist/do-runner/fenced-workflows-d1.js.map +1 -1
  27. package/dist/do-runner/runtime.d.ts +21 -8
  28. package/dist/do-runner/runtime.d.ts.map +1 -1
  29. package/dist/do-runner/runtime.js +207 -74
  30. package/dist/do-runner/runtime.js.map +1 -1
  31. package/dist/do-runner/workflow-snapshot-row.d.ts +4 -5
  32. package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -1
  33. package/dist/do-runner/workflow-snapshot-row.js +14 -18
  34. package/dist/do-runner/workflow-snapshot-row.js.map +1 -1
  35. package/dist/host-kit/approval-bridge.d.ts +14 -1
  36. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  37. package/dist/host-kit/approval-bridge.js +57 -6
  38. package/dist/host-kit/approval-bridge.js.map +1 -1
  39. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  40. package/dist/host-kit/flowsafe-worker.js +2 -2
  41. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  42. package/dist/host-kit/run-router.d.ts +4 -1
  43. package/dist/host-kit/run-router.d.ts.map +1 -1
  44. package/dist/host-kit/run-router.js.map +1 -1
  45. package/package.json +2 -2
@@ -30,11 +30,12 @@ import { FENCED_WORKFLOW_STORAGE, } from './fenced-workflow-capability.js';
30
30
  import { isDefinitiveInitialAdmissionRefusal } from './initial-admission-refusal.js';
31
31
  import { mastraRegistryEntries } from './mastra-registry.js';
32
32
  import { isPathSafeId } from './path-safe-id.js';
33
- import { advanceLifecycle, canonicalEconomicOperations, canonicalReplayPrincipals, canonicalScheduleDispatch, hasDisputedSettlement, lifecycleFromRequestContext, projectTerminalLifecycle, RUN_INTERRUPTED_MESSAGE, RUN_LIFECYCLE_CONTEXT_KEY, RunLifecycleBlockedError, terminalCleanupFor, } from './run-lifecycle.js';
33
+ import { advanceLifecycle, canonicalEconomicOperations, canonicalReplayPrincipals, canonicalScheduleDispatch, hasDisputedSettlement, lifecycleFromRequestContext, projectTerminalLifecycle, RUN_INTERRUPTED_MESSAGE, RUN_LIFECYCLE_CONTEXT_KEY, RunLifecycleBlockedError, RunSettledConflictError, terminalCleanupFor, } from './run-lifecycle.js';
34
34
  import { decodeProgressRunProvenance, decodeResumeCounts, nextResumeCount, runExecutionIdentityFor, } from './run-provenance.js';
35
35
  import { errorText, isDurableRunStatus, isRunStatus, isTerminalRunStatus, terminalStateFields, terminalStateUpdate, } from './run-terminal-state.js';
36
36
  import { captureReservation, } from './start-reservation-contract.js';
37
37
  import { validateTablePrefix } from './table-prefix.js';
38
+ import { parseSnapshotObject, } from './workflow-snapshot-row.js';
38
39
  export { RunLifecycleBlockedError, RunSettledConflictError, } from './run-lifecycle.js';
39
40
  export class UnknownWorkflowError extends Error {
40
41
  constructor(workflowId) {
@@ -113,6 +114,10 @@ const RUN_STATE_FIELDS = [
113
114
  'suspendedPaths',
114
115
  'requestContext',
115
116
  ];
117
+ const RESUME_STATE_FIELDS = [
118
+ ...RUN_STATE_FIELDS,
119
+ 'payload',
120
+ ];
116
121
  function runProvenance(state) {
117
122
  const value = state.requestContext?.[RUN_PROVENANCE_CONTEXT_KEY];
118
123
  if (value === undefined)
@@ -369,8 +374,8 @@ function orderedRequestContext(runtimeContext, provided, scheduled) {
369
374
  ...identity,
370
375
  ]);
371
376
  }
372
- /** @internal How often an executing leg marks its run row live. */
373
- export const RUN_LEG_TOUCH_MS = 30_000;
377
+ /** How often an executing leg marks its run row live. */
378
+ const RUN_LEG_TOUCH_MS = 30_000;
374
379
  // Longer than the largest Workers CPU limit (five minutes), which is the most
375
380
  // a busy step can delay a touch timer: a row untouched this long has no leg
376
381
  // left marking it, on this instance or one being replaced.
@@ -382,8 +387,25 @@ function rowSilent(raw, now) {
382
387
  throw new RunStateUnreadableError(raw.workflowId, raw.runId);
383
388
  return now - touchedAt >= RUN_LEG_SILENT_MS;
384
389
  }
385
- /** A settlement compare-and-set found its row changed since the silence read. */
386
- class SettlementMissError extends Error {
390
+ /** A compare-and-set write found the run's row changed since the read it decided from. */
391
+ class RowChangedError extends Error {
392
+ constructor() {
393
+ super('the run row changed since it was read');
394
+ this.name = 'RowChangedError';
395
+ }
396
+ }
397
+ /**
398
+ * Compare-and-set passes a lifecycle transition makes before it answers that
399
+ * the run's row keeps changing. A touch moves the row at most once per
400
+ * RUN_LEG_TOUCH_MS, so a miss it causes clears on the next pass; only a leg on
401
+ * another instance writing snapshots back to back misses every time.
402
+ */
403
+ const LIFECYCLE_WRITE_ATTEMPTS = 5;
404
+ function snapshotOfRow(row) {
405
+ const state = parseSnapshotObject(row.snapshot);
406
+ if (state === undefined || state.runId !== row.runId)
407
+ throw new RunStateUnreadableError(row.workflowId, row.runId);
408
+ return state;
387
409
  }
388
410
  const TERMINABLE_RUN_STATUSES = new Set([
389
411
  'running',
@@ -407,8 +429,13 @@ function relativeDeadline(deadlineMs, now = Date.now()) {
407
429
  }
408
430
  return deadlineAt;
409
431
  }
432
+ function assertLegAbort(legAbort) {
433
+ if (legAbort !== undefined && !(legAbort instanceof AbortController))
434
+ throw new InvalidRunRequestError('legAbort is malformed');
435
+ }
410
436
  function captureStartRunOptions(source) {
411
- const { runId, inputData, initialState, storedRequestContext, attemptToken, deadlineMs, economicOperations: rawOperations, scheduleDispatch: rawDispatch, idempotencyKey, requestedBy, requestedByKind, mutationEpoch: rawEpoch, startIdentity: rawIdentity, agentStart: rawAgentStart, onPreparedStartIdentity, runOwnerGuard: rawGuard, startReservation: rawReservation, } = source;
437
+ const { runId, inputData, initialState, storedRequestContext, attemptToken, deadlineMs, economicOperations: rawOperations, scheduleDispatch: rawDispatch, idempotencyKey, requestedBy, requestedByKind, mutationEpoch: rawEpoch, startIdentity: rawIdentity, agentStart: rawAgentStart, onPreparedStartIdentity, runOwnerGuard: rawGuard, startReservation: rawReservation, legAbort, } = source;
438
+ assertLegAbort(legAbort);
412
439
  if (requestedBy !== undefined && !isExecutionPrincipalId(requestedBy)) {
413
440
  throw new InvalidRunRequestError('requestedBy is malformed');
414
441
  }
@@ -526,6 +553,7 @@ function captureStartRunOptions(source) {
526
553
  onPreparedStartIdentity,
527
554
  runOwnerGuard,
528
555
  startReservation,
556
+ legAbort,
529
557
  };
530
558
  return Object.freeze(requestedBy !== undefined && requestedByKind !== undefined
531
559
  ? { ...captured, requestedBy, requestedByKind }
@@ -818,10 +846,12 @@ export class RunnerRuntime {
818
846
  const proof = await this.#assertStartFence(options.idempotencyKey, options.mutationEpoch);
819
847
  return await this.#withRunLock(workflowId, runId, async () => {
820
848
  const activeKey = this.#runKey(workflowId, runId);
821
- const active = {};
849
+ const active = options.legAbort
850
+ ? { legAbort: options.legAbort }
851
+ : {};
822
852
  if (this.#activeRuns.has(activeKey))
823
853
  throw new RunAlreadyExistsError(workflowId, runId, 'running');
824
- this.#activeRuns.set(activeKey, active);
854
+ const leaveLeg = this.#registerLeg(activeKey, active, workflowId, runId);
825
855
  let execution;
826
856
  let engineEntered = false;
827
857
  let outcomeReadStarted = false;
@@ -946,8 +976,7 @@ export class RunnerRuntime {
946
976
  throw asClientError(error) ?? error;
947
977
  }
948
978
  finally {
949
- if (this.#activeRuns.get(activeKey) === active)
950
- this.#activeRuns.delete(activeKey);
979
+ await leaveLeg();
951
980
  }
952
981
  });
953
982
  }
@@ -962,21 +991,23 @@ export class RunnerRuntime {
962
991
  * loads it and re-enters the engine at the suspended step.
963
992
  */
964
993
  async resume(workflowId, runId, options = {}) {
994
+ const { legAbort } = options;
995
+ assertLegAbort(legAbort);
965
996
  this.#getWorkflow(workflowId);
966
997
  const proof = await this.#assertResumeFence(workflowId, runId);
967
998
  return this.#withRunLock(workflowId, runId, async () => {
968
999
  const activeKey = this.#runKey(workflowId, runId);
969
- const active = {};
1000
+ const active = legAbort ? { legAbort } : {};
970
1001
  if (this.#activeRuns.has(activeKey))
971
1002
  throw new RunTerminalConflictError(workflowId, runId, 'running');
972
- this.#activeRuns.set(activeKey, active);
1003
+ const leaveLeg = this.#registerLeg(activeKey, active, workflowId, runId);
973
1004
  let provenance;
974
1005
  let engineEntered = false;
975
1006
  let outcomeReadStarted = false;
976
1007
  try {
977
1008
  const source = await this.#captureWorkflowStorage(workflowId);
978
1009
  active.source = source;
979
- const state = await this.#workflowState(workflowId, runId, true);
1010
+ const state = await this.#workflowState(workflowId, runId, true, RESUME_STATE_FIELDS);
980
1011
  if (!state)
981
1012
  throw new UnknownRunError(workflowId, runId);
982
1013
  if (state.isFromInMemory)
@@ -1006,7 +1037,7 @@ export class RunnerRuntime {
1006
1037
  await this.#withLifecycleLock(workflowId, runId, check);
1007
1038
  if (options.prepareExecution) {
1008
1039
  const values = structuredClone(Object.fromEntries(requestContext.entries()));
1009
- await options.prepareExecution(new RequestContext(Object.entries(values)));
1040
+ await options.prepareExecution(new RequestContext(Object.entries(values)), state.payload);
1010
1041
  await this.#withLifecycleLock(workflowId, runId, check);
1011
1042
  }
1012
1043
  const run = await this.#createRun(workflowId, runId);
@@ -1042,8 +1073,7 @@ export class RunnerRuntime {
1042
1073
  throw asClientError(error) ?? error;
1043
1074
  }
1044
1075
  finally {
1045
- if (this.#activeRuns.get(activeKey) === active)
1046
- this.#activeRuns.delete(activeKey);
1076
+ await leaveLeg();
1047
1077
  }
1048
1078
  });
1049
1079
  }
@@ -1058,19 +1088,18 @@ export class RunnerRuntime {
1058
1088
  */
1059
1089
  async cancelActiveExecution(workflowId, runId, intendedStatus, replayPrincipals, cas, now = Date.now()) {
1060
1090
  this.#getWorkflow(workflowId);
1061
- const prepared = await this.#withLifecycleLock(workflowId, runId, async () => {
1091
+ const prepared = await this.#withLifecycleLock(workflowId, runId, () => this.#retryOnRowChange(workflowId, runId, async () => {
1062
1092
  const source = this.#activeRuns.get(this.#runKey(workflowId, runId))?.source ??
1063
1093
  (await this.#captureWorkflowStorage(workflowId));
1064
- const state = await source.load.call(source.workflows, {
1065
- workflowName: workflowId,
1066
- runId,
1067
- });
1068
- if (!state)
1069
- throw new UnknownRunError(workflowId, runId);
1070
- if (state.runId !== runId)
1071
- throw new RunStateUnreadableError(workflowId, runId);
1094
+ const { state, row } = await this.#readForTransition(source, workflowId, runId);
1072
1095
  const key = this.#runKey(workflowId, runId);
1073
1096
  const active = this.#activeRuns.get(key);
1097
+ const cancelTarget = () => {
1098
+ if (!active?.run)
1099
+ return undefined;
1100
+ this.#terminalAbortIntents.set(key, intendedStatus);
1101
+ return { run: active.run, legAbort: active.legAbort, key };
1102
+ };
1074
1103
  const lifecycle = effectiveLifecycle(lifecycleFromRequestContext(state.requestContext), active?.lifecycle);
1075
1104
  if (lifecycle?.terminal)
1076
1105
  return undefined;
@@ -1085,10 +1114,7 @@ export class RunnerRuntime {
1085
1114
  (cas === undefined ||
1086
1115
  (existingIntent.expectedRevision === cas.expectedRevision &&
1087
1116
  existingIntent.expectedDeadlineAt === cas.expectedDeadlineAt))) {
1088
- if (!active?.run)
1089
- return undefined;
1090
- this.#terminalAbortIntents.set(key, intendedStatus);
1091
- return { run: active.run, key };
1117
+ return cancelTarget();
1092
1118
  }
1093
1119
  if (cas &&
1094
1120
  (lifecycle?.revision !== cas.expectedRevision ||
@@ -1120,16 +1146,13 @@ export class RunnerRuntime {
1120
1146
  : {}),
1121
1147
  },
1122
1148
  });
1123
- await this.#persistLifecycle(workflowId, runId, state, intent, now, source);
1149
+ await this.#persistIntent(workflowId, runId, state, intent, now, source, row);
1124
1150
  if (active) {
1125
1151
  active.lifecycle = intent;
1126
1152
  active.requestContext?.set(RUN_LIFECYCLE_CONTEXT_KEY, intent);
1127
1153
  }
1128
- if (!active?.run)
1129
- return undefined;
1130
- this.#terminalAbortIntents.set(key, intendedStatus);
1131
- return { run: active.run, key };
1132
- });
1154
+ return cancelTarget();
1155
+ }));
1133
1156
  if (!prepared)
1134
1157
  return false;
1135
1158
  try {
@@ -1139,6 +1162,9 @@ export class RunnerRuntime {
1139
1162
  this.#terminalAbortIntents.delete(prepared.key);
1140
1163
  throw error;
1141
1164
  }
1165
+ // After `run.cancel()` has aborted the engine run, so the engine's
1166
+ // cancellation precedes any abort error from a call in flight.
1167
+ prepared.legAbort?.abort();
1142
1168
  return true;
1143
1169
  }
1144
1170
  /** Trusted host variant that persists the exact identities allowed to retry. */
@@ -1164,27 +1190,17 @@ export class RunnerRuntime {
1164
1190
  }
1165
1191
  async #transitionTerminal(workflowId, runId, status, now, cas, replayPrincipals, replayingPrincipal) {
1166
1192
  this.#getWorkflow(workflowId);
1167
- return this.#withRunLock(workflowId, runId, () => this.#transitionTerminalLocked(workflowId, runId, status, now, {
1168
- cas,
1169
- replayPrincipals,
1170
- replayingPrincipal,
1171
- }));
1193
+ return this.#withRunLock(workflowId, runId, async () => {
1194
+ const source = await this.#captureWorkflowStorage(workflowId);
1195
+ return this.#retryOnRowChange(workflowId, runId, async () => this.#transitionTerminalLocked(workflowId, runId, status, now, { cas, replayPrincipals, replayingPrincipal }, source, await this.#readForTransition(source, workflowId, runId)));
1196
+ });
1172
1197
  }
1173
1198
  /**
1174
- * #transitionTerminal's body, for a caller already holding the run lock.
1175
- * With `expected`, the write is a compare-and-set against that exact row and
1176
- * a miss throws SettlementMissError.
1199
+ * Decide a terminal transition from one read of the run's row and write it,
1200
+ * for a caller holding the run lock. Where the read carries the row, the
1201
+ * write is a compare-and-set against it and a miss throws RowChangedError.
1177
1202
  */
1178
- async #transitionTerminalLocked(workflowId, runId, status, now, { cas, replayPrincipals, replayingPrincipal, expected, } = {}) {
1179
- const source = await this.#captureWorkflowStorage(workflowId);
1180
- const state = await source.load.call(source.workflows, {
1181
- workflowName: workflowId,
1182
- runId,
1183
- });
1184
- if (!state)
1185
- throw new UnknownRunError(workflowId, runId);
1186
- if (state.runId !== runId)
1187
- throw new RunStateUnreadableError(workflowId, runId);
1203
+ async #transitionTerminalLocked(workflowId, runId, status, now, { cas, replayPrincipals, replayingPrincipal }, source, { state, row }) {
1188
1204
  const lifecycle = lifecycleFromRequestContext(state.requestContext);
1189
1205
  if (lifecycle?.terminal) {
1190
1206
  if (replayingPrincipal &&
@@ -1258,7 +1274,7 @@ export class RunnerRuntime {
1258
1274
  message: next.terminal.error.message,
1259
1275
  },
1260
1276
  timestamp: now,
1261
- }, next, now, source, expected);
1277
+ }, next, now, source, row);
1262
1278
  this.#terminalAbortIntents.delete(this.#runKey(workflowId, runId));
1263
1279
  return {
1264
1280
  summary: await this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state)),
@@ -1361,13 +1377,14 @@ export class RunnerRuntime {
1361
1377
  }
1362
1378
  if (capability === null || typeof capability !== 'object')
1363
1379
  throw new Error('workflow capability is malformed');
1364
- const { database, tablePrefix: prefix, readSnapshot, withInitialAdmission: admit, terminalizeInitialAdmission: terminalize, touchRun: touch, replaceSnapshot: replace, } = capability;
1380
+ const { database, tablePrefix: prefix, readSnapshot, withInitialAdmission: admit, terminalizeInitialAdmission: terminalize, touchRun: touch, replaceSnapshot: replace, patchRunLifecycle: patch, } = capability;
1365
1381
  if (typeof prefix !== 'string' ||
1366
1382
  typeof readSnapshot !== 'function' ||
1367
1383
  typeof admit !== 'function' ||
1368
1384
  typeof terminalize !== 'function' ||
1369
1385
  (touch !== undefined && typeof touch !== 'function') ||
1370
1386
  (replace !== undefined && typeof replace !== 'function') ||
1387
+ (patch !== undefined && typeof patch !== 'function') ||
1371
1388
  !database ||
1372
1389
  typeof database.prepare !== 'function' ||
1373
1390
  typeof database.batch !== 'function')
@@ -1387,6 +1404,7 @@ export class RunnerRuntime {
1387
1404
  terminalize,
1388
1405
  ...(touch === undefined ? {} : { touch }),
1389
1406
  ...(replace === undefined ? {} : { replace }),
1407
+ ...(patch === undefined ? {} : { patch }),
1390
1408
  };
1391
1409
  }
1392
1410
  async #observeStartState(workflowId, runId) {
@@ -1591,9 +1609,7 @@ export class RunnerRuntime {
1591
1609
  : captureReservation(suppliedClaim, 'started');
1592
1610
  if (!isPathSafeId(attemptToken) ||
1593
1611
  typeof isOwnerQuiescent !== 'function' ||
1594
- (startLeg !== undefined &&
1595
- startLeg !== 'unwound' &&
1596
- startLeg !== 'touched'))
1612
+ (startLeg !== 'unwound' && startLeg !== 'touched'))
1597
1613
  throw new InvalidRunRequestError('start recovery authority is malformed');
1598
1614
  if (claim && !this.#startIdempotency)
1599
1615
  throw new ExecutionFenceUnreadableError('run start recovery is unresolved');
@@ -1688,13 +1704,60 @@ export class RunnerRuntime {
1688
1704
  }
1689
1705
  /**
1690
1706
  * @internal Mark this run's row live for an executing leg, from whichever
1691
- * instance runs it; the evidence #silentRow reads. A storage source without
1692
- * the touch leaves nothing to read, so its runs are never settled here.
1707
+ * instance runs it; the evidence #silentRow reads. When the row reads
1708
+ * settled, the leg this runtime drives for the run is aborted: its engine
1709
+ * starts no further step, and its step in flight sees its `abortSignal`
1710
+ * aborted. A storage source without the touch leaves nothing to read, so its
1711
+ * runs are never settled here.
1693
1712
  */
1694
1713
  async touchRun(workflowId, runId, now = Date.now()) {
1695
1714
  const source = await this.#captureWorkflowStorage(workflowId);
1696
- if (source.storage === 'd1' && source.touch)
1697
- await source.touch.call(source.capability, { workflowId, runId }, now);
1715
+ if (source.storage !== 'd1' || !source.touch)
1716
+ return;
1717
+ const touched = await source.touch.call(source.capability, { workflowId, runId }, now);
1718
+ if (touched === 'settled')
1719
+ this.#abortSettledLeg(workflowId, runId);
1720
+ }
1721
+ /**
1722
+ * A leg's registration and its touch share one span, because recovery reads a
1723
+ * row nobody touches as abandoned. The release waits for a touch in flight:
1724
+ * its late write would make a following repair's exact-row compare-and-set
1725
+ * miss.
1726
+ */
1727
+ #registerLeg(activeKey, active, workflowId, runId) {
1728
+ this.#activeRuns.set(activeKey, active);
1729
+ const touches = new Set();
1730
+ const timer = setInterval(() => {
1731
+ const touch = this.touchRun(workflowId, runId)
1732
+ .catch((error) => console.error('run leg liveness touch failed', error))
1733
+ .finally(() => touches.delete(touch));
1734
+ touches.add(touch);
1735
+ }, RUN_LEG_TOUCH_MS);
1736
+ return async () => {
1737
+ clearInterval(timer);
1738
+ await Promise.all(touches);
1739
+ if (this.#activeRuns.get(activeKey) === active)
1740
+ this.#activeRuns.delete(activeKey);
1741
+ };
1742
+ }
1743
+ /**
1744
+ * Abort the leg this runtime drives for a run another instance settled.
1745
+ * Never `run.cancel()`: it reads the stored status first and returns without
1746
+ * aborting on `failed`, which an interruption or a start repair writes. The
1747
+ * reason is named `AbortError`, which Mastra and the AI SDK read as an abort,
1748
+ * and carries the settlement as its cause. The leg's `legAbort` takes the
1749
+ * same reason, so a model or tool call in flight stops with the engine.
1750
+ */
1751
+ #abortSettledLeg(workflowId, runId) {
1752
+ const active = this.#activeRuns.get(this.#runKey(workflowId, runId));
1753
+ const unaborted = [active?.run?.abortController, active?.legAbort].filter((controller) => controller !== undefined && !controller.signal.aborted);
1754
+ if (unaborted.length === 0)
1755
+ return;
1756
+ console.error(JSON.stringify({ type: 'run-leg-settled-abort', workflowId, runId }));
1757
+ const conflict = new RunSettledConflictError(workflowId, runId);
1758
+ const reason = Object.assign(new Error(conflict.message, { cause: conflict }), { name: 'AbortError' });
1759
+ for (const controller of unaborted)
1760
+ controller.abort(reason);
1698
1761
  }
1699
1762
  /**
1700
1763
  * @internal Settle a run whose execution leg ended without a durable outcome.
@@ -1751,19 +1814,17 @@ export class RunnerRuntime {
1751
1814
  const silent = await this.#silentRow(source, workflowId, runId, now);
1752
1815
  if (!silent)
1753
1816
  return { kind: 'live' };
1817
+ // The write replaces the silent row, so it is built from that row; one
1818
+ // that moved since the decision above waits for the next wake.
1819
+ const current = snapshotOfRow(silent);
1754
1820
  try {
1755
1821
  if (recorded)
1756
1822
  return {
1757
1823
  kind: 'transition',
1758
1824
  replayPrincipal: recorded
1759
1825
  .replayPrincipals[0],
1760
- transition: await this.#transitionTerminalLocked(workflowId, runId, recorded.status, now, { expected: silent }),
1826
+ transition: await this.#transitionTerminalLocked(workflowId, runId, recorded.status, now, {}, source, { state: current, row: silent }),
1761
1827
  };
1762
- // The write replaces the silent row, so it is built from that row;
1763
- // one that moved since the decision above waits for the next wake.
1764
- const current = JSON.parse(silent.snapshot);
1765
- if (current.runId !== runId)
1766
- throw new RunStateUnreadableError(workflowId, runId);
1767
1828
  const currentLifecycle = lifecycleFromRequestContext(current.requestContext);
1768
1829
  if (current.status !== state.status ||
1769
1830
  currentLifecycle?.revision !== lifecycle?.revision ||
@@ -1781,7 +1842,7 @@ export class RunnerRuntime {
1781
1842
  }, advanceLifecycle(currentLifecycle, { interruptedAt: now }), now, source, silent);
1782
1843
  }
1783
1844
  catch (error) {
1784
- if (error instanceof SettlementMissError)
1845
+ if (error instanceof RowChangedError)
1785
1846
  return { kind: 'live' };
1786
1847
  throw error;
1787
1848
  }
@@ -1804,6 +1865,53 @@ export class RunnerRuntime {
1804
1865
  });
1805
1866
  return raw && rowSilent(raw, now) ? raw : undefined;
1806
1867
  }
1868
+ /**
1869
+ * The run's snapshot for a lifecycle transition, with the exact row it was
1870
+ * parsed from where the storage can compare-and-set that row, so the write
1871
+ * lands only on the row the decision read. Other storage answers the
1872
+ * snapshot alone and keeps its unconditional write.
1873
+ */
1874
+ async #readForTransition(source, workflowId, runId) {
1875
+ if (source.storage === 'd1' && source.replace) {
1876
+ const row = await source.readSnapshot.call(source.capability, {
1877
+ workflowId,
1878
+ runId,
1879
+ });
1880
+ if (!row)
1881
+ throw new UnknownRunError(workflowId, runId);
1882
+ return { state: snapshotOfRow(row), row };
1883
+ }
1884
+ const state = await source.load.call(source.workflows, {
1885
+ workflowName: workflowId,
1886
+ runId,
1887
+ });
1888
+ if (!state)
1889
+ throw new UnknownRunError(workflowId, runId);
1890
+ if (state.runId !== runId)
1891
+ throw new RunStateUnreadableError(workflowId, runId);
1892
+ return { state };
1893
+ }
1894
+ /**
1895
+ * Repeat one read-decide-write pass until its compare-and-set lands or it
1896
+ * decides without writing, for at most LIFECYCLE_WRITE_ATTEMPTS passes. A
1897
+ * miss means the row changed after the read, so the next pass decides again
1898
+ * from the row as it now stands.
1899
+ */
1900
+ async #retryOnRowChange(workflowId, runId, pass) {
1901
+ for (let attempt = 1;; attempt++) {
1902
+ try {
1903
+ return await pass();
1904
+ }
1905
+ catch (error) {
1906
+ if (!(error instanceof RowChangedError))
1907
+ throw error;
1908
+ if (attempt >= LIFECYCLE_WRITE_ATTEMPTS)
1909
+ throw new RunStateUnreadableError(workflowId, runId, {
1910
+ cause: new Error(`the run row changed on each of ${LIFECYCLE_WRITE_ATTEMPTS} compare-and-set attempts`, { cause: error }),
1911
+ });
1912
+ }
1913
+ }
1914
+ }
1807
1915
  /** @internal Settle the exact selected terminal generation before managed cleanup. */
1808
1916
  async settleStartExecution(state, originalClaim) {
1809
1917
  const claim = originalClaim === undefined
@@ -1946,15 +2054,15 @@ export class RunnerRuntime {
1946
2054
  lifecycle,
1947
2055
  };
1948
2056
  }
1949
- #workflowState(workflowId, runId, withNestedWorkflows = false) {
2057
+ #workflowState(workflowId, runId, withNestedWorkflows = false, fields = RUN_STATE_FIELDS) {
1950
2058
  return this.#getWorkflow(workflowId).getWorkflowRunById(runId, {
1951
- fields: RUN_STATE_FIELDS,
2059
+ fields,
1952
2060
  withNestedWorkflows,
1953
2061
  });
1954
2062
  }
1955
2063
  /**
1956
2064
  * With `expected`, a compare-and-set against that exact row, serialized as
1957
- * Mastra's own persist does; a miss throws SettlementMissError.
2065
+ * Mastra's own persist does; a miss throws RowChangedError.
1958
2066
  */
1959
2067
  async #persistLifecycle(workflowId, runId, state, lifecycle, now, source, expected) {
1960
2068
  const workflows = source.workflows;
@@ -1968,13 +2076,13 @@ export class RunnerRuntime {
1968
2076
  };
1969
2077
  if (expected) {
1970
2078
  if (source.storage !== 'd1' || !source.replace)
1971
- throw new Error('settlement storage cannot compare-and-set');
2079
+ throw new Error('storage cannot compare-and-set the run row');
1972
2080
  const replaced = await source.replace.call(source.capability, expected, {
1973
2081
  snapshot: JSON.stringify(persisted),
1974
2082
  updatedAt: new Date(now).toISOString(),
1975
2083
  });
1976
2084
  if (!replaced)
1977
- throw new SettlementMissError();
2085
+ throw new RowChangedError();
1978
2086
  return persisted;
1979
2087
  }
1980
2088
  await source.persist.call(workflows, {
@@ -1985,6 +2093,31 @@ export class RunnerRuntime {
1985
2093
  });
1986
2094
  return persisted;
1987
2095
  }
2096
+ /**
2097
+ * Persist a cancellation intent through `patchRunLifecycle` where the storage
2098
+ * has it, otherwise as #persistLifecycle does; a miss throws RowChangedError.
2099
+ * The patch also misses on a snapshot SQLite cannot parse, which the
2100
+ * whole-row compare-and-set still replaces, so that write is tried before
2101
+ * the miss counts as a row change.
2102
+ */
2103
+ async #persistIntent(workflowId, runId, state, intent, now, source, row) {
2104
+ if (source.storage === 'd1' && source.patch) {
2105
+ const patched = await source.patch.call(source.capability, { workflowId, runId }, {
2106
+ status: state.status,
2107
+ lifecycleRevision: lifecycleFromRequestContext(state.requestContext)
2108
+ ?.revision,
2109
+ }, {
2110
+ lifecycle: intent,
2111
+ timestamp: now,
2112
+ updatedAt: new Date(now).toISOString(),
2113
+ });
2114
+ if (patched)
2115
+ return;
2116
+ if (!row)
2117
+ throw new RowChangedError();
2118
+ }
2119
+ await this.#persistLifecycle(workflowId, runId, state, intent, now, source, row);
2120
+ }
1988
2121
  async #summaryAfterPersist(workflowId, runId, source, expected) {
1989
2122
  if (expected?.version === 2) {
1990
2123
  const selected = await this.#completedStartState(source, runExecutionIdentityFor({ tablePrefix: source.tablePrefix, workflowId, runId }, expected), expected);