@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.
- package/CHANGELOG.md +135 -0
- package/README.md +59 -9
- package/dist/agent-host/thread-host.d.ts.map +1 -1
- package/dist/agent-host/thread-host.js +26 -2
- package/dist/agent-host/thread-host.js.map +1 -1
- package/dist/agent-runner/durable-agent-runner.d.ts +13 -19
- package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
- package/dist/agent-runner/durable-agent-runner.js +551 -372
- package/dist/agent-runner/durable-agent-runner.js.map +1 -1
- package/dist/approval-api/retention.d.ts.map +1 -1
- package/dist/approval-api/retention.js +6 -5
- package/dist/approval-api/retention.js.map +1 -1
- package/dist/approval-api/service.js +4 -4
- package/dist/approval-api/service.js.map +1 -1
- package/dist/approval-ui/use-approval-dashboard.js +6 -6
- package/dist/approval-ui/use-approval-dashboard.js.map +1 -1
- package/dist/background-tasks/d1-storage.d.ts.map +1 -1
- package/dist/background-tasks/d1-storage.js +7 -5
- package/dist/background-tasks/d1-storage.js.map +1 -1
- package/dist/background-tasks/host.d.ts.map +1 -1
- package/dist/background-tasks/host.js +27 -38
- package/dist/background-tasks/host.js.map +1 -1
- package/dist/do-runner/cause-chain.d.ts +5 -0
- package/dist/do-runner/cause-chain.d.ts.map +1 -1
- package/dist/do-runner/cause-chain.js +12 -0
- package/dist/do-runner/cause-chain.js.map +1 -1
- package/dist/do-runner/cf-types.d.ts +3 -0
- package/dist/do-runner/cf-types.d.ts.map +1 -1
- package/dist/do-runner/cf-types.js.map +1 -1
- package/dist/do-runner/constants.d.ts +1 -1
- package/dist/do-runner/constants.d.ts.map +1 -1
- package/dist/do-runner/constants.js +1 -1
- package/dist/do-runner/constants.js.map +1 -1
- package/dist/do-runner/core-events-nonce.d.ts +2 -0
- package/dist/do-runner/core-events-nonce.d.ts.map +1 -0
- package/dist/do-runner/core-events-nonce.js +16 -0
- package/dist/do-runner/core-events-nonce.js.map +1 -0
- package/dist/do-runner/d1-storage.js +1 -9
- package/dist/do-runner/d1-storage.js.map +1 -1
- package/dist/do-runner/do-error-response.d.ts.map +1 -1
- package/dist/do-runner/do-error-response.js +2 -1
- package/dist/do-runner/do-error-response.js.map +1 -1
- package/dist/do-runner/durable-object.d.ts +34 -2
- package/dist/do-runner/durable-object.d.ts.map +1 -1
- package/dist/do-runner/durable-object.js +447 -53
- package/dist/do-runner/durable-object.js.map +1 -1
- package/dist/do-runner/fenced-workflow-capability.d.ts +51 -0
- package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -1
- package/dist/do-runner/fenced-workflows-d1.d.ts +5 -1
- package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -1
- package/dist/do-runner/fenced-workflows-d1.js +236 -48
- package/dist/do-runner/fenced-workflows-d1.js.map +1 -1
- package/dist/do-runner/index.d.ts +2 -2
- package/dist/do-runner/index.d.ts.map +1 -1
- package/dist/do-runner/index.js +2 -2
- package/dist/do-runner/index.js.map +1 -1
- package/dist/do-runner/init.d.ts +2 -3
- package/dist/do-runner/init.d.ts.map +1 -1
- package/dist/do-runner/init.js.map +1 -1
- package/dist/do-runner/memory-id.js +1 -1
- package/dist/do-runner/memory-id.js.map +1 -1
- package/dist/do-runner/pubsub.d.ts +6 -2
- package/dist/do-runner/pubsub.d.ts.map +1 -1
- package/dist/do-runner/pubsub.js +12 -22
- package/dist/do-runner/pubsub.js.map +1 -1
- package/dist/do-runner/run-lifecycle.d.ts +42 -2
- package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
- package/dist/do-runner/run-lifecycle.js +57 -1
- package/dist/do-runner/run-lifecycle.js.map +1 -1
- package/dist/do-runner/run-terminal-state.d.ts +2 -0
- package/dist/do-runner/run-terminal-state.d.ts.map +1 -1
- package/dist/do-runner/run-terminal-state.js +4 -0
- package/dist/do-runner/run-terminal-state.js.map +1 -1
- package/dist/do-runner/runtime.d.ts +87 -17
- package/dist/do-runner/runtime.d.ts.map +1 -1
- package/dist/do-runner/runtime.js +455 -155
- package/dist/do-runner/runtime.js.map +1 -1
- package/dist/do-runner/suspension-deadline.d.ts +25 -17
- package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
- package/dist/do-runner/suspension-deadline.js +44 -21
- package/dist/do-runner/suspension-deadline.js.map +1 -1
- package/dist/do-runner/workflow-snapshot-row.d.ts +6 -0
- package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -1
- package/dist/do-runner/workflow-snapshot-row.js +17 -0
- package/dist/do-runner/workflow-snapshot-row.js.map +1 -1
- package/dist/host-kit/approval-bridge.d.ts +25 -9
- package/dist/host-kit/approval-bridge.d.ts.map +1 -1
- package/dist/host-kit/approval-bridge.js +72 -15
- package/dist/host-kit/approval-bridge.js.map +1 -1
- package/dist/host-kit/do-response.d.ts.map +1 -1
- package/dist/host-kit/do-response.js +7 -1
- package/dist/host-kit/do-response.js.map +1 -1
- package/dist/host-kit/flowsafe-worker.d.ts +2 -1
- package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
- package/dist/host-kit/flowsafe-worker.js +4 -2
- package/dist/host-kit/flowsafe-worker.js.map +1 -1
- package/dist/host-kit/run-router.d.ts +4 -1
- package/dist/host-kit/run-router.d.ts.map +1 -1
- package/dist/host-kit/run-router.js +3 -2
- package/dist/host-kit/run-router.js.map +1 -1
- package/dist/schedules/schedules-d1.d.ts +1 -0
- package/dist/schedules/schedules-d1.d.ts.map +1 -1
- package/dist/schedules/schedules-d1.js +35 -22
- package/dist/schedules/schedules-d1.js.map +1 -1
- package/dist/schedules/tick.d.ts +17 -2
- package/dist/schedules/tick.d.ts.map +1 -1
- package/dist/schedules/tick.js +63 -44
- package/dist/schedules/tick.js.map +1 -1
- package/dist/signals/d1-shared.js +1 -1
- package/dist/signals/d1-shared.js.map +1 -1
- package/dist/signals/thread-do-routes.d.ts +8 -1
- package/dist/signals/thread-do-routes.d.ts.map +1 -1
- package/dist/signals/thread-do-routes.js +40 -44
- package/dist/signals/thread-do-routes.js.map +1 -1
- package/package.json +10 -7
|
@@ -30,12 +30,13 @@ 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 { canonicalEconomicOperations, canonicalReplayPrincipals, canonicalScheduleDispatch, hasDisputedSettlement, lifecycleFromRequestContext,
|
|
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
|
-
import { errorText, isRunStatus, isTerminalRunStatus, terminalStateFields, terminalStateUpdate, } from './run-terminal-state.js';
|
|
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
|
-
|
|
38
|
+
import { parseSnapshotObject, } from './workflow-snapshot-row.js';
|
|
39
|
+
export { RunLifecycleBlockedError, RunSettledConflictError, } from './run-lifecycle.js';
|
|
39
40
|
export class UnknownWorkflowError extends Error {
|
|
40
41
|
constructor(workflowId) {
|
|
41
42
|
super(`unknown workflow '${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)
|
|
@@ -282,8 +287,14 @@ function summarizeState(runId, state, counts, requestedBy, requestedByKind) {
|
|
|
282
287
|
if (state.status === 'success') {
|
|
283
288
|
summary.result = state.result;
|
|
284
289
|
}
|
|
285
|
-
else if (state.status === 'failed'
|
|
286
|
-
|
|
290
|
+
else if (state.status === 'failed') {
|
|
291
|
+
if (state.error)
|
|
292
|
+
summary.error = errorText(state.error);
|
|
293
|
+
if (lifecycle?.interruptedAt !== undefined)
|
|
294
|
+
summary.errorEnvelope = {
|
|
295
|
+
code: 'INTERRUPTED',
|
|
296
|
+
message: RUN_INTERRUPTED_MESSAGE,
|
|
297
|
+
};
|
|
287
298
|
}
|
|
288
299
|
else if (state.status === 'suspended') {
|
|
289
300
|
const suspendedKeys = Object.keys(state.suspendedPaths ?? {});
|
|
@@ -363,6 +374,39 @@ function orderedRequestContext(runtimeContext, provided, scheduled) {
|
|
|
363
374
|
...identity,
|
|
364
375
|
]);
|
|
365
376
|
}
|
|
377
|
+
/** How often an executing leg marks its run row live. */
|
|
378
|
+
const RUN_LEG_TOUCH_MS = 30_000;
|
|
379
|
+
// Longer than the largest Workers CPU limit (five minutes), which is the most
|
|
380
|
+
// a busy step can delay a touch timer: a row untouched this long has no leg
|
|
381
|
+
// left marking it, on this instance or one being replaced.
|
|
382
|
+
const RUN_LEG_SILENT_MS = 360_000;
|
|
383
|
+
/** Has no leg marked this row live within RUN_LEG_SILENT_MS? */
|
|
384
|
+
function rowSilent(raw, now) {
|
|
385
|
+
const touchedAt = Date.parse(raw.updatedAt);
|
|
386
|
+
if (!Number.isFinite(touchedAt))
|
|
387
|
+
throw new RunStateUnreadableError(raw.workflowId, raw.runId);
|
|
388
|
+
return now - touchedAt >= RUN_LEG_SILENT_MS;
|
|
389
|
+
}
|
|
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;
|
|
409
|
+
}
|
|
366
410
|
const TERMINABLE_RUN_STATUSES = new Set([
|
|
367
411
|
'running',
|
|
368
412
|
'waiting',
|
|
@@ -385,8 +429,13 @@ function relativeDeadline(deadlineMs, now = Date.now()) {
|
|
|
385
429
|
}
|
|
386
430
|
return deadlineAt;
|
|
387
431
|
}
|
|
432
|
+
function assertLegAbort(legAbort) {
|
|
433
|
+
if (legAbort !== undefined && !(legAbort instanceof AbortController))
|
|
434
|
+
throw new InvalidRunRequestError('legAbort is malformed');
|
|
435
|
+
}
|
|
388
436
|
function captureStartRunOptions(source) {
|
|
389
|
-
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);
|
|
390
439
|
if (requestedBy !== undefined && !isExecutionPrincipalId(requestedBy)) {
|
|
391
440
|
throw new InvalidRunRequestError('requestedBy is malformed');
|
|
392
441
|
}
|
|
@@ -504,6 +553,7 @@ function captureStartRunOptions(source) {
|
|
|
504
553
|
onPreparedStartIdentity,
|
|
505
554
|
runOwnerGuard,
|
|
506
555
|
startReservation,
|
|
556
|
+
legAbort,
|
|
507
557
|
};
|
|
508
558
|
return Object.freeze(requestedBy !== undefined && requestedByKind !== undefined
|
|
509
559
|
? { ...captured, requestedBy, requestedByKind }
|
|
@@ -578,8 +628,8 @@ export class RunnerRuntime {
|
|
|
578
628
|
#activeRuns = new Map();
|
|
579
629
|
#terminalAbortIntents = new Map();
|
|
580
630
|
#lifecycleLocks = new Map();
|
|
581
|
-
// The host DO's pubsub identity (RunnerRuntimeOptions.pubsub)
|
|
582
|
-
// createRun so a configured host
|
|
631
|
+
// The host DO's pubsub identity (RunnerRuntimeOptions.pubsub) is passed to
|
|
632
|
+
// Mastra and each createRun so a configured host shares one feed.
|
|
583
633
|
// Undefined ⇒ core defaults a fresh emitter per run.
|
|
584
634
|
#pubsub;
|
|
585
635
|
#executionFence;
|
|
@@ -796,10 +846,12 @@ export class RunnerRuntime {
|
|
|
796
846
|
const proof = await this.#assertStartFence(options.idempotencyKey, options.mutationEpoch);
|
|
797
847
|
return await this.#withRunLock(workflowId, runId, async () => {
|
|
798
848
|
const activeKey = this.#runKey(workflowId, runId);
|
|
799
|
-
const active =
|
|
849
|
+
const active = options.legAbort
|
|
850
|
+
? { legAbort: options.legAbort }
|
|
851
|
+
: {};
|
|
800
852
|
if (this.#activeRuns.has(activeKey))
|
|
801
853
|
throw new RunAlreadyExistsError(workflowId, runId, 'running');
|
|
802
|
-
this.#
|
|
854
|
+
const leaveLeg = this.#registerLeg(activeKey, active, workflowId, runId);
|
|
803
855
|
let execution;
|
|
804
856
|
let engineEntered = false;
|
|
805
857
|
let outcomeReadStarted = false;
|
|
@@ -924,8 +976,7 @@ export class RunnerRuntime {
|
|
|
924
976
|
throw asClientError(error) ?? error;
|
|
925
977
|
}
|
|
926
978
|
finally {
|
|
927
|
-
|
|
928
|
-
this.#activeRuns.delete(activeKey);
|
|
979
|
+
await leaveLeg();
|
|
929
980
|
}
|
|
930
981
|
});
|
|
931
982
|
}
|
|
@@ -940,21 +991,23 @@ export class RunnerRuntime {
|
|
|
940
991
|
* loads it and re-enters the engine at the suspended step.
|
|
941
992
|
*/
|
|
942
993
|
async resume(workflowId, runId, options = {}) {
|
|
994
|
+
const { legAbort } = options;
|
|
995
|
+
assertLegAbort(legAbort);
|
|
943
996
|
this.#getWorkflow(workflowId);
|
|
944
997
|
const proof = await this.#assertResumeFence(workflowId, runId);
|
|
945
998
|
return this.#withRunLock(workflowId, runId, async () => {
|
|
946
999
|
const activeKey = this.#runKey(workflowId, runId);
|
|
947
|
-
const active = {};
|
|
1000
|
+
const active = legAbort ? { legAbort } : {};
|
|
948
1001
|
if (this.#activeRuns.has(activeKey))
|
|
949
1002
|
throw new RunTerminalConflictError(workflowId, runId, 'running');
|
|
950
|
-
this.#
|
|
1003
|
+
const leaveLeg = this.#registerLeg(activeKey, active, workflowId, runId);
|
|
951
1004
|
let provenance;
|
|
952
1005
|
let engineEntered = false;
|
|
953
1006
|
let outcomeReadStarted = false;
|
|
954
1007
|
try {
|
|
955
1008
|
const source = await this.#captureWorkflowStorage(workflowId);
|
|
956
1009
|
active.source = source;
|
|
957
|
-
const state = await this.#workflowState(workflowId, runId, true);
|
|
1010
|
+
const state = await this.#workflowState(workflowId, runId, true, RESUME_STATE_FIELDS);
|
|
958
1011
|
if (!state)
|
|
959
1012
|
throw new UnknownRunError(workflowId, runId);
|
|
960
1013
|
if (state.isFromInMemory)
|
|
@@ -984,7 +1037,7 @@ export class RunnerRuntime {
|
|
|
984
1037
|
await this.#withLifecycleLock(workflowId, runId, check);
|
|
985
1038
|
if (options.prepareExecution) {
|
|
986
1039
|
const values = structuredClone(Object.fromEntries(requestContext.entries()));
|
|
987
|
-
await options.prepareExecution(new RequestContext(Object.entries(values)));
|
|
1040
|
+
await options.prepareExecution(new RequestContext(Object.entries(values)), state.payload);
|
|
988
1041
|
await this.#withLifecycleLock(workflowId, runId, check);
|
|
989
1042
|
}
|
|
990
1043
|
const run = await this.#createRun(workflowId, runId);
|
|
@@ -1020,8 +1073,7 @@ export class RunnerRuntime {
|
|
|
1020
1073
|
throw asClientError(error) ?? error;
|
|
1021
1074
|
}
|
|
1022
1075
|
finally {
|
|
1023
|
-
|
|
1024
|
-
this.#activeRuns.delete(activeKey);
|
|
1076
|
+
await leaveLeg();
|
|
1025
1077
|
}
|
|
1026
1078
|
});
|
|
1027
1079
|
}
|
|
@@ -1036,19 +1088,18 @@ export class RunnerRuntime {
|
|
|
1036
1088
|
*/
|
|
1037
1089
|
async cancelActiveExecution(workflowId, runId, intendedStatus, replayPrincipals, cas, now = Date.now()) {
|
|
1038
1090
|
this.#getWorkflow(workflowId);
|
|
1039
|
-
const prepared = await this.#withLifecycleLock(workflowId, runId, async () => {
|
|
1091
|
+
const prepared = await this.#withLifecycleLock(workflowId, runId, () => this.#retryOnRowChange(workflowId, runId, async () => {
|
|
1040
1092
|
const source = this.#activeRuns.get(this.#runKey(workflowId, runId))?.source ??
|
|
1041
1093
|
(await this.#captureWorkflowStorage(workflowId));
|
|
1042
|
-
const state = await
|
|
1043
|
-
workflowName: workflowId,
|
|
1044
|
-
runId,
|
|
1045
|
-
});
|
|
1046
|
-
if (!state)
|
|
1047
|
-
throw new UnknownRunError(workflowId, runId);
|
|
1048
|
-
if (state.runId !== runId)
|
|
1049
|
-
throw new RunStateUnreadableError(workflowId, runId);
|
|
1094
|
+
const { state, row } = await this.#readForTransition(source, workflowId, runId);
|
|
1050
1095
|
const key = this.#runKey(workflowId, runId);
|
|
1051
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
|
+
};
|
|
1052
1103
|
const lifecycle = effectiveLifecycle(lifecycleFromRequestContext(state.requestContext), active?.lifecycle);
|
|
1053
1104
|
if (lifecycle?.terminal)
|
|
1054
1105
|
return undefined;
|
|
@@ -1063,10 +1114,7 @@ export class RunnerRuntime {
|
|
|
1063
1114
|
(cas === undefined ||
|
|
1064
1115
|
(existingIntent.expectedRevision === cas.expectedRevision &&
|
|
1065
1116
|
existingIntent.expectedDeadlineAt === cas.expectedDeadlineAt))) {
|
|
1066
|
-
|
|
1067
|
-
return undefined;
|
|
1068
|
-
this.#terminalAbortIntents.set(key, intendedStatus);
|
|
1069
|
-
return { run: active.run, key };
|
|
1117
|
+
return cancelTarget();
|
|
1070
1118
|
}
|
|
1071
1119
|
if (cas &&
|
|
1072
1120
|
(lifecycle?.revision !== cas.expectedRevision ||
|
|
@@ -1085,9 +1133,7 @@ export class RunnerRuntime {
|
|
|
1085
1133
|
return undefined;
|
|
1086
1134
|
}
|
|
1087
1135
|
const principals = canonicalReplayPrincipals(replayPrincipals);
|
|
1088
|
-
const intent = {
|
|
1089
|
-
...(lifecycle ?? { version: 1, revision: 0 }),
|
|
1090
|
-
revision: nextLifecycleRevision(lifecycle?.revision ?? 0),
|
|
1136
|
+
const intent = advanceLifecycle(lifecycle, {
|
|
1091
1137
|
transitionIntent: {
|
|
1092
1138
|
status: intendedStatus,
|
|
1093
1139
|
requestedAt: now,
|
|
@@ -1099,17 +1145,14 @@ export class RunnerRuntime {
|
|
|
1099
1145
|
}
|
|
1100
1146
|
: {}),
|
|
1101
1147
|
},
|
|
1102
|
-
};
|
|
1103
|
-
await this.#
|
|
1148
|
+
});
|
|
1149
|
+
await this.#persistIntent(workflowId, runId, state, intent, now, source, row);
|
|
1104
1150
|
if (active) {
|
|
1105
1151
|
active.lifecycle = intent;
|
|
1106
1152
|
active.requestContext?.set(RUN_LIFECYCLE_CONTEXT_KEY, intent);
|
|
1107
1153
|
}
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
this.#terminalAbortIntents.set(key, intendedStatus);
|
|
1111
|
-
return { run: active.run, key };
|
|
1112
|
-
});
|
|
1154
|
+
return cancelTarget();
|
|
1155
|
+
}));
|
|
1113
1156
|
if (!prepared)
|
|
1114
1157
|
return false;
|
|
1115
1158
|
try {
|
|
@@ -1119,6 +1162,9 @@ export class RunnerRuntime {
|
|
|
1119
1162
|
this.#terminalAbortIntents.delete(prepared.key);
|
|
1120
1163
|
throw error;
|
|
1121
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();
|
|
1122
1168
|
return true;
|
|
1123
1169
|
}
|
|
1124
1170
|
/** Trusted host variant that persists the exact identities allowed to retry. */
|
|
@@ -1146,96 +1192,96 @@ export class RunnerRuntime {
|
|
|
1146
1192
|
this.#getWorkflow(workflowId);
|
|
1147
1193
|
return this.#withRunLock(workflowId, runId, async () => {
|
|
1148
1194
|
const source = await this.#captureWorkflowStorage(workflowId);
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1195
|
+
return this.#retryOnRowChange(workflowId, runId, async () => this.#transitionTerminalLocked(workflowId, runId, status, now, { cas, replayPrincipals, replayingPrincipal }, source, await this.#readForTransition(source, workflowId, runId)));
|
|
1196
|
+
});
|
|
1197
|
+
}
|
|
1198
|
+
/**
|
|
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.
|
|
1202
|
+
*/
|
|
1203
|
+
async #transitionTerminalLocked(workflowId, runId, status, now, { cas, replayPrincipals, replayingPrincipal }, source, { state, row }) {
|
|
1204
|
+
const lifecycle = lifecycleFromRequestContext(state.requestContext);
|
|
1205
|
+
if (lifecycle?.terminal) {
|
|
1206
|
+
if (replayingPrincipal &&
|
|
1207
|
+
!lifecycle.terminal.replayPrincipals.some((principal) => principal.kind === replayingPrincipal.kind &&
|
|
1208
|
+
principal.id === replayingPrincipal.id)) {
|
|
1154
1209
|
throw new UnknownRunError(workflowId, runId);
|
|
1155
|
-
if (state.runId !== runId)
|
|
1156
|
-
throw new RunStateUnreadableError(workflowId, runId);
|
|
1157
|
-
const lifecycle = lifecycleFromRequestContext(state.requestContext);
|
|
1158
|
-
if (lifecycle?.terminal) {
|
|
1159
|
-
if (replayingPrincipal &&
|
|
1160
|
-
!lifecycle.terminal.replayPrincipals.some((principal) => principal.kind === replayingPrincipal.kind &&
|
|
1161
|
-
principal.id === replayingPrincipal.id)) {
|
|
1162
|
-
throw new UnknownRunError(workflowId, runId);
|
|
1163
|
-
}
|
|
1164
|
-
return {
|
|
1165
|
-
summary: await this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state)),
|
|
1166
|
-
transitioned: false,
|
|
1167
|
-
casMatched: cas === undefined ||
|
|
1168
|
-
(lifecycle.terminal.status === 'timed_out' &&
|
|
1169
|
-
lifecycle.deadlineAt === cas.expectedDeadlineAt),
|
|
1170
|
-
cleanup: terminalCleanupFor(lifecycle),
|
|
1171
|
-
};
|
|
1172
1210
|
}
|
|
1173
|
-
const transitionIntent = lifecycle?.transitionIntent;
|
|
1174
|
-
const intentMatchesTransition = transitionIntent?.status === status &&
|
|
1175
|
-
(cas === undefined ||
|
|
1176
|
-
(transitionIntent.expectedRevision === cas.expectedRevision &&
|
|
1177
|
-
transitionIntent.expectedDeadlineAt === cas.expectedDeadlineAt));
|
|
1178
|
-
const intentMatchesCas = cas !== undefined && intentMatchesTransition;
|
|
1179
|
-
if (cas !== undefined &&
|
|
1180
|
-
!intentMatchesCas &&
|
|
1181
|
-
(lifecycle?.revision !== cas.expectedRevision ||
|
|
1182
|
-
lifecycle.deadlineAt !== cas.expectedDeadlineAt ||
|
|
1183
|
-
lifecycle.deadlineAt === undefined ||
|
|
1184
|
-
lifecycle.deadlineAt > now)) {
|
|
1185
|
-
return {
|
|
1186
|
-
summary: await this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state)),
|
|
1187
|
-
transitioned: false,
|
|
1188
|
-
casMatched: false,
|
|
1189
|
-
cleanup: {
|
|
1190
|
-
revision: lifecycle?.revision ?? 0,
|
|
1191
|
-
status,
|
|
1192
|
-
cleanupCompleted: false,
|
|
1193
|
-
...(lifecycle?.scheduleDispatch
|
|
1194
|
-
? { scheduleDispatch: lifecycle.scheduleDispatch }
|
|
1195
|
-
: {}),
|
|
1196
|
-
},
|
|
1197
|
-
};
|
|
1198
|
-
}
|
|
1199
|
-
if (hasDisputedSettlement(lifecycle)) {
|
|
1200
|
-
throw new RunLifecycleBlockedError({
|
|
1201
|
-
code: 'DISPUTED_SETTLEMENT',
|
|
1202
|
-
message: 'run termination is blocked while an economic operation is disputed',
|
|
1203
|
-
});
|
|
1204
|
-
}
|
|
1205
|
-
const currentStatus = state.status;
|
|
1206
|
-
const abortIntent = this.#terminalAbortIntents.get(this.#runKey(workflowId, runId));
|
|
1207
|
-
if (!TERMINABLE_RUN_STATUSES.has(currentStatus) &&
|
|
1208
|
-
!intentMatchesTransition &&
|
|
1209
|
-
!(currentStatus === 'canceled' && abortIntent === status)) {
|
|
1210
|
-
throw new RunTerminalConflictError(workflowId, runId, currentStatus);
|
|
1211
|
-
}
|
|
1212
|
-
const provenance = runProvenance(state);
|
|
1213
|
-
const fallbackPrincipal = provenance?.requestedBy && provenance.requestedByKind
|
|
1214
|
-
? {
|
|
1215
|
-
kind: provenance.requestedByKind,
|
|
1216
|
-
id: provenance.requestedBy,
|
|
1217
|
-
}
|
|
1218
|
-
: { kind: 'system', id: 'flowsafe-system' };
|
|
1219
|
-
const principals = canonicalReplayPrincipals(replayPrincipals ??
|
|
1220
|
-
transitionIntent?.replayPrincipals ?? [fallbackPrincipal]);
|
|
1221
|
-
const next = projectTerminalLifecycle(lifecycle, status, now, principals);
|
|
1222
|
-
await this.#persistLifecycle(workflowId, runId, {
|
|
1223
|
-
...state,
|
|
1224
|
-
...terminalStateFields(status),
|
|
1225
|
-
error: {
|
|
1226
|
-
name: status === 'cancelled' ? 'RunCancelledError' : 'RunTimedOutError',
|
|
1227
|
-
message: next.terminal.error.message,
|
|
1228
|
-
},
|
|
1229
|
-
timestamp: now,
|
|
1230
|
-
}, next, now, source);
|
|
1231
|
-
this.#terminalAbortIntents.delete(this.#runKey(workflowId, runId));
|
|
1232
1211
|
return {
|
|
1233
1212
|
summary: await this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state)),
|
|
1234
|
-
transitioned:
|
|
1235
|
-
casMatched:
|
|
1236
|
-
|
|
1213
|
+
transitioned: false,
|
|
1214
|
+
casMatched: cas === undefined ||
|
|
1215
|
+
(lifecycle.terminal.status === 'timed_out' &&
|
|
1216
|
+
lifecycle.deadlineAt === cas.expectedDeadlineAt),
|
|
1217
|
+
cleanup: terminalCleanupFor(lifecycle),
|
|
1237
1218
|
};
|
|
1238
|
-
}
|
|
1219
|
+
}
|
|
1220
|
+
const transitionIntent = lifecycle?.transitionIntent;
|
|
1221
|
+
const intentMatchesTransition = transitionIntent?.status === status &&
|
|
1222
|
+
(cas === undefined ||
|
|
1223
|
+
(transitionIntent.expectedRevision === cas.expectedRevision &&
|
|
1224
|
+
transitionIntent.expectedDeadlineAt === cas.expectedDeadlineAt));
|
|
1225
|
+
const intentMatchesCas = cas !== undefined && intentMatchesTransition;
|
|
1226
|
+
if (cas !== undefined &&
|
|
1227
|
+
!intentMatchesCas &&
|
|
1228
|
+
(lifecycle?.revision !== cas.expectedRevision ||
|
|
1229
|
+
lifecycle.deadlineAt !== cas.expectedDeadlineAt ||
|
|
1230
|
+
lifecycle.deadlineAt === undefined ||
|
|
1231
|
+
lifecycle.deadlineAt > now)) {
|
|
1232
|
+
return {
|
|
1233
|
+
summary: await this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state)),
|
|
1234
|
+
transitioned: false,
|
|
1235
|
+
casMatched: false,
|
|
1236
|
+
cleanup: {
|
|
1237
|
+
revision: lifecycle?.revision ?? 0,
|
|
1238
|
+
status,
|
|
1239
|
+
cleanupCompleted: false,
|
|
1240
|
+
...(lifecycle?.scheduleDispatch
|
|
1241
|
+
? { scheduleDispatch: lifecycle.scheduleDispatch }
|
|
1242
|
+
: {}),
|
|
1243
|
+
},
|
|
1244
|
+
};
|
|
1245
|
+
}
|
|
1246
|
+
if (hasDisputedSettlement(lifecycle)) {
|
|
1247
|
+
throw new RunLifecycleBlockedError({
|
|
1248
|
+
code: 'DISPUTED_SETTLEMENT',
|
|
1249
|
+
message: 'run termination is blocked while an economic operation is disputed',
|
|
1250
|
+
});
|
|
1251
|
+
}
|
|
1252
|
+
const currentStatus = state.status;
|
|
1253
|
+
const abortIntent = this.#terminalAbortIntents.get(this.#runKey(workflowId, runId));
|
|
1254
|
+
if (!TERMINABLE_RUN_STATUSES.has(currentStatus) &&
|
|
1255
|
+
!intentMatchesTransition &&
|
|
1256
|
+
!(currentStatus === 'canceled' && abortIntent === status)) {
|
|
1257
|
+
throw new RunTerminalConflictError(workflowId, runId, currentStatus);
|
|
1258
|
+
}
|
|
1259
|
+
const provenance = runProvenance(state);
|
|
1260
|
+
const fallbackPrincipal = provenance?.requestedBy && provenance.requestedByKind
|
|
1261
|
+
? {
|
|
1262
|
+
kind: provenance.requestedByKind,
|
|
1263
|
+
id: provenance.requestedBy,
|
|
1264
|
+
}
|
|
1265
|
+
: { kind: 'system', id: 'flowsafe-system' };
|
|
1266
|
+
const principals = canonicalReplayPrincipals(replayPrincipals ??
|
|
1267
|
+
transitionIntent?.replayPrincipals ?? [fallbackPrincipal]);
|
|
1268
|
+
const next = projectTerminalLifecycle(lifecycle, status, now, principals);
|
|
1269
|
+
await this.#persistLifecycle(workflowId, runId, {
|
|
1270
|
+
...state,
|
|
1271
|
+
...terminalStateFields(status),
|
|
1272
|
+
error: {
|
|
1273
|
+
name: status === 'cancelled' ? 'RunCancelledError' : 'RunTimedOutError',
|
|
1274
|
+
message: next.terminal.error.message,
|
|
1275
|
+
},
|
|
1276
|
+
timestamp: now,
|
|
1277
|
+
}, next, now, source, row);
|
|
1278
|
+
this.#terminalAbortIntents.delete(this.#runKey(workflowId, runId));
|
|
1279
|
+
return {
|
|
1280
|
+
summary: await this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state)),
|
|
1281
|
+
transitioned: true,
|
|
1282
|
+
casMatched: true,
|
|
1283
|
+
cleanup: terminalCleanupFor(next),
|
|
1284
|
+
};
|
|
1239
1285
|
}
|
|
1240
1286
|
/** Marks idempotent terminal side-effect cleanup after every hook succeeds. */
|
|
1241
1287
|
async completeTerminalCleanup(workflowId, runId, expectedRevision, now = Date.now()) {
|
|
@@ -1260,14 +1306,9 @@ export class RunnerRuntime {
|
|
|
1260
1306
|
if (lifecycle.revision !== expectedRevision) {
|
|
1261
1307
|
throw new Error('run terminal cleanup CAS no longer matches');
|
|
1262
1308
|
}
|
|
1263
|
-
const next = {
|
|
1264
|
-
...lifecycle,
|
|
1265
|
-
|
|
1266
|
-
terminal: {
|
|
1267
|
-
...lifecycle.terminal,
|
|
1268
|
-
cleanupCompletedAt: now,
|
|
1269
|
-
},
|
|
1270
|
-
};
|
|
1309
|
+
const next = advanceLifecycle(lifecycle, {
|
|
1310
|
+
terminal: { ...lifecycle.terminal, cleanupCompletedAt: now },
|
|
1311
|
+
});
|
|
1271
1312
|
await this.#persistLifecycle(workflowId, runId, state, next, now, source);
|
|
1272
1313
|
return this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state));
|
|
1273
1314
|
});
|
|
@@ -1292,16 +1333,11 @@ export class RunnerRuntime {
|
|
|
1292
1333
|
* status() for a caller about to CONCLUDE something irreversible from what it
|
|
1293
1334
|
* reads — delete a wake record, spend an abandonment budget, resume a run.
|
|
1294
1335
|
*
|
|
1295
|
-
*
|
|
1296
|
-
*
|
|
1297
|
-
*
|
|
1298
|
-
*
|
|
1299
|
-
*
|
|
1300
|
-
* about the run. Mastra stamps `isFromInMemory` on it at its single
|
|
1301
|
-
* construction site and the persisted branch builds its result field by
|
|
1302
|
-
* field without ever copying the marker, so this throws on exactly the reads
|
|
1303
|
-
* that did not reach storage. `null` still means the read SUCCEEDED and
|
|
1304
|
-
* found nothing.
|
|
1336
|
+
* Workflow.getInMemoryRunAsWorkflowState reports the retained Run's lifecycle
|
|
1337
|
+
* status with isFromInMemory: true, without suspended paths or requestContext.
|
|
1338
|
+
* Refusing that marker prevents an approximation from authorizing an
|
|
1339
|
+
* irreversible action; after non-suspended completion the Run leaves the
|
|
1340
|
+
* in-memory map, so the fallback is null.
|
|
1305
1341
|
*
|
|
1306
1342
|
* A valid v2 pending row is refused before lifecycle projection; it has no
|
|
1307
1343
|
* durable execution outcome yet.
|
|
@@ -1341,11 +1377,14 @@ export class RunnerRuntime {
|
|
|
1341
1377
|
}
|
|
1342
1378
|
if (capability === null || typeof capability !== 'object')
|
|
1343
1379
|
throw new Error('workflow capability is malformed');
|
|
1344
|
-
const { database, tablePrefix: prefix, readSnapshot, withInitialAdmission: admit, terminalizeInitialAdmission: terminalize, } = capability;
|
|
1380
|
+
const { database, tablePrefix: prefix, readSnapshot, withInitialAdmission: admit, terminalizeInitialAdmission: terminalize, touchRun: touch, replaceSnapshot: replace, patchRunLifecycle: patch, } = capability;
|
|
1345
1381
|
if (typeof prefix !== 'string' ||
|
|
1346
1382
|
typeof readSnapshot !== 'function' ||
|
|
1347
1383
|
typeof admit !== 'function' ||
|
|
1348
1384
|
typeof terminalize !== 'function' ||
|
|
1385
|
+
(touch !== undefined && typeof touch !== 'function') ||
|
|
1386
|
+
(replace !== undefined && typeof replace !== 'function') ||
|
|
1387
|
+
(patch !== undefined && typeof patch !== 'function') ||
|
|
1349
1388
|
!database ||
|
|
1350
1389
|
typeof database.prepare !== 'function' ||
|
|
1351
1390
|
typeof database.batch !== 'function')
|
|
@@ -1363,6 +1402,9 @@ export class RunnerRuntime {
|
|
|
1363
1402
|
readSnapshot,
|
|
1364
1403
|
admit,
|
|
1365
1404
|
terminalize,
|
|
1405
|
+
...(touch === undefined ? {} : { touch }),
|
|
1406
|
+
...(replace === undefined ? {} : { replace }),
|
|
1407
|
+
...(patch === undefined ? {} : { patch }),
|
|
1366
1408
|
};
|
|
1367
1409
|
}
|
|
1368
1410
|
async #observeStartState(workflowId, runId) {
|
|
@@ -1515,7 +1557,7 @@ export class RunnerRuntime {
|
|
|
1515
1557
|
/** @internal Recover only after the exact owning execution has unwound. */
|
|
1516
1558
|
async recoverStartAttempt(value, recovery) {
|
|
1517
1559
|
const execution = normalizeD1RunExecutionIdentity(value);
|
|
1518
|
-
const { attemptToken, isOwnerQuiescent, startReservation: suppliedClaim, expectedTarget: suppliedTarget, } = recovery;
|
|
1560
|
+
const { attemptToken, isOwnerQuiescent, startReservation: suppliedClaim, expectedTarget: suppliedTarget, startLeg, } = recovery;
|
|
1519
1561
|
let expectedTarget;
|
|
1520
1562
|
if (suppliedTarget !== undefined) {
|
|
1521
1563
|
if (suppliedTarget === null ||
|
|
@@ -1565,7 +1607,9 @@ export class RunnerRuntime {
|
|
|
1565
1607
|
const claim = suppliedClaim === undefined
|
|
1566
1608
|
? undefined
|
|
1567
1609
|
: captureReservation(suppliedClaim, 'started');
|
|
1568
|
-
if (!isPathSafeId(attemptToken) ||
|
|
1610
|
+
if (!isPathSafeId(attemptToken) ||
|
|
1611
|
+
typeof isOwnerQuiescent !== 'function' ||
|
|
1612
|
+
(startLeg !== 'unwound' && startLeg !== 'touched'))
|
|
1569
1613
|
throw new InvalidRunRequestError('start recovery authority is malformed');
|
|
1570
1614
|
if (claim && !this.#startIdempotency)
|
|
1571
1615
|
throw new ExecutionFenceUnreadableError('run start recovery is unresolved');
|
|
@@ -1609,11 +1653,19 @@ export class RunnerRuntime {
|
|
|
1609
1653
|
state.provenance.attemptToken !== attemptToken ||
|
|
1610
1654
|
state.provenance.resumeCounts.length !== 0)
|
|
1611
1655
|
throw new RunStartPendingError();
|
|
1656
|
+
const nowMs = Date.now();
|
|
1657
|
+
// A source without the touch keeps no silence evidence: its start
|
|
1658
|
+
// leg may still run, so it is repaired at once and unstamped.
|
|
1659
|
+
const waitsForSilence = startLeg === 'touched' && source.touch !== undefined;
|
|
1660
|
+
if (waitsForSilence && !rowSilent(state.raw, nowMs))
|
|
1661
|
+
throw new RunStartPendingError();
|
|
1662
|
+
const legStopped = startLeg === 'unwound' || waitsForSilence;
|
|
1612
1663
|
const result = await source.terminalize.call(source.capability, {
|
|
1613
1664
|
expected: state.raw,
|
|
1614
1665
|
execution,
|
|
1615
1666
|
attemptToken,
|
|
1616
|
-
nowMs
|
|
1667
|
+
nowMs,
|
|
1668
|
+
...(legStopped ? { markOutcomeUnknown: true } : {}),
|
|
1617
1669
|
});
|
|
1618
1670
|
if (result.kind === 'conflict')
|
|
1619
1671
|
throw new Error('initial terminalization conflicts');
|
|
@@ -1650,6 +1702,216 @@ export class RunnerRuntime {
|
|
|
1650
1702
|
}
|
|
1651
1703
|
}));
|
|
1652
1704
|
}
|
|
1705
|
+
/**
|
|
1706
|
+
* @internal Mark this run's row live for an executing leg, from whichever
|
|
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.
|
|
1712
|
+
*/
|
|
1713
|
+
async touchRun(workflowId, runId, now = Date.now()) {
|
|
1714
|
+
const source = await this.#captureWorkflowStorage(workflowId);
|
|
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);
|
|
1761
|
+
}
|
|
1762
|
+
/**
|
|
1763
|
+
* @internal Settle a run whose execution leg ended without a durable outcome.
|
|
1764
|
+
*
|
|
1765
|
+
* The caller is the run's own Durable Object after it has established that no
|
|
1766
|
+
* leg of its own drives the run; this runtime's `#activeRuns` covers the
|
|
1767
|
+
* in-process drivers. An object can be replaced while its leg keeps running
|
|
1768
|
+
* on the outgoing instance, so a run is written only after its row has gone
|
|
1769
|
+
* untouched for RUN_LEG_SILENT_MS (`live` otherwise).
|
|
1770
|
+
*
|
|
1771
|
+
* `durable` (suspended, or terminal with its cleanup done) and `absent` leave
|
|
1772
|
+
* the snapshot untouched. A recorded cancellation or timeout owns the
|
|
1773
|
+
* outcome: `transition` completes it, or replays a terminal one whose cleanup
|
|
1774
|
+
* is unfinished, and leaves the cleanup to the caller as the terminate and
|
|
1775
|
+
* deadline routes do. The pending initial row stays with start recovery,
|
|
1776
|
+
* which repairs it as an unknown outcome.
|
|
1777
|
+
*
|
|
1778
|
+
* Any other run becomes `failed` (`interrupted`), never re-executed: the step
|
|
1779
|
+
* that was in flight may already have had effects.
|
|
1780
|
+
*/
|
|
1781
|
+
async settleInterruptedRun(workflowId, runId, now = Date.now()) {
|
|
1782
|
+
this.#getWorkflow(workflowId);
|
|
1783
|
+
// Checked before queueing: a live leg holds the run lock for its whole
|
|
1784
|
+
// length, and a caller waiting behind it would learn nothing.
|
|
1785
|
+
if (this.isRunActive(workflowId, runId))
|
|
1786
|
+
return { kind: 'live' };
|
|
1787
|
+
return this.#withRunLock(workflowId, runId, () => this.#withLifecycleLock(workflowId, runId, async () => {
|
|
1788
|
+
const source = await this.#captureWorkflowStorage(workflowId);
|
|
1789
|
+
const state = await source.load.call(source.workflows, {
|
|
1790
|
+
workflowName: workflowId,
|
|
1791
|
+
runId,
|
|
1792
|
+
});
|
|
1793
|
+
if (!state)
|
|
1794
|
+
return { kind: 'absent' };
|
|
1795
|
+
if (state.runId !== runId)
|
|
1796
|
+
throw new RunStateUnreadableError(workflowId, runId);
|
|
1797
|
+
const lifecycle = lifecycleFromRequestContext(state.requestContext);
|
|
1798
|
+
// Ahead of the status checks: a cancel that took effect leaves Mastra's
|
|
1799
|
+
// terminal `canceled` precursor, which only the recorded transition
|
|
1800
|
+
// turns into `cancelled` with its cleanup.
|
|
1801
|
+
const recorded = lifecycle?.terminal ?? lifecycle?.transitionIntent;
|
|
1802
|
+
if (lifecycle?.terminal?.cleanupCompletedAt !== undefined)
|
|
1803
|
+
return { kind: 'durable' };
|
|
1804
|
+
if (!recorded) {
|
|
1805
|
+
if (isDurableRunStatus(state.status))
|
|
1806
|
+
return { kind: 'durable' };
|
|
1807
|
+
if (state.status === 'pending')
|
|
1808
|
+
throw new RunStartPendingError();
|
|
1809
|
+
if (!TERMINABLE_RUN_STATUSES.has(state.status))
|
|
1810
|
+
throw new RunStateUnreadableError(workflowId, runId);
|
|
1811
|
+
}
|
|
1812
|
+
// Every settlement write below is a compare-and-set against this
|
|
1813
|
+
// silent row: a write that lands after the read makes it miss (`live`).
|
|
1814
|
+
const silent = await this.#silentRow(source, workflowId, runId, now);
|
|
1815
|
+
if (!silent)
|
|
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);
|
|
1820
|
+
try {
|
|
1821
|
+
if (recorded)
|
|
1822
|
+
return {
|
|
1823
|
+
kind: 'transition',
|
|
1824
|
+
replayPrincipal: recorded
|
|
1825
|
+
.replayPrincipals[0],
|
|
1826
|
+
transition: await this.#transitionTerminalLocked(workflowId, runId, recorded.status, now, {}, source, { state: current, row: silent }),
|
|
1827
|
+
};
|
|
1828
|
+
const currentLifecycle = lifecycleFromRequestContext(current.requestContext);
|
|
1829
|
+
if (current.status !== state.status ||
|
|
1830
|
+
currentLifecycle?.revision !== lifecycle?.revision ||
|
|
1831
|
+
currentLifecycle?.terminal ||
|
|
1832
|
+
currentLifecycle?.transitionIntent)
|
|
1833
|
+
return { kind: 'live' };
|
|
1834
|
+
await this.#persistLifecycle(workflowId, runId, {
|
|
1835
|
+
...current,
|
|
1836
|
+
...terminalStateFields('failed'),
|
|
1837
|
+
error: {
|
|
1838
|
+
name: 'RunInterruptedError',
|
|
1839
|
+
message: RUN_INTERRUPTED_MESSAGE,
|
|
1840
|
+
},
|
|
1841
|
+
timestamp: now,
|
|
1842
|
+
}, advanceLifecycle(currentLifecycle, { interruptedAt: now }), now, source, silent);
|
|
1843
|
+
}
|
|
1844
|
+
catch (error) {
|
|
1845
|
+
if (error instanceof RowChangedError)
|
|
1846
|
+
return { kind: 'live' };
|
|
1847
|
+
throw error;
|
|
1848
|
+
}
|
|
1849
|
+
return {
|
|
1850
|
+
kind: 'interrupted',
|
|
1851
|
+
summary: await this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state)),
|
|
1852
|
+
};
|
|
1853
|
+
}));
|
|
1854
|
+
}
|
|
1855
|
+
/**
|
|
1856
|
+
* The run's row, when no leg has marked it live within RUN_LEG_SILENT_MS and
|
|
1857
|
+
* the storage can compare-and-set it; `undefined` otherwise.
|
|
1858
|
+
*/
|
|
1859
|
+
async #silentRow(source, workflowId, runId, now) {
|
|
1860
|
+
if (source.storage !== 'd1' || !source.touch || !source.replace)
|
|
1861
|
+
return undefined;
|
|
1862
|
+
const raw = await source.readSnapshot.call(source.capability, {
|
|
1863
|
+
workflowId,
|
|
1864
|
+
runId,
|
|
1865
|
+
});
|
|
1866
|
+
return raw && rowSilent(raw, now) ? raw : undefined;
|
|
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
|
+
}
|
|
1653
1915
|
/** @internal Settle the exact selected terminal generation before managed cleanup. */
|
|
1654
1916
|
async settleStartExecution(state, originalClaim) {
|
|
1655
1917
|
const claim = originalClaim === undefined
|
|
@@ -1769,16 +2031,14 @@ export class RunnerRuntime {
|
|
|
1769
2031
|
const replacementOperations = canonicalEconomicOperations(economicOperations);
|
|
1770
2032
|
const lifecycle = replacementDeadline === undefined && replacementOperations === undefined
|
|
1771
2033
|
? storedLifecycle
|
|
1772
|
-
: {
|
|
1773
|
-
...(storedLifecycle ?? { version: 1, revision: 0 }),
|
|
1774
|
-
revision: nextLifecycleRevision(storedLifecycle?.revision ?? 0),
|
|
2034
|
+
: advanceLifecycle(storedLifecycle, {
|
|
1775
2035
|
...(replacementDeadline === undefined
|
|
1776
2036
|
? {}
|
|
1777
2037
|
: { deadlineAt: replacementDeadline }),
|
|
1778
2038
|
...(replacementOperations === undefined
|
|
1779
2039
|
? {}
|
|
1780
2040
|
: { economicOperations: replacementOperations }),
|
|
1781
|
-
};
|
|
2041
|
+
});
|
|
1782
2042
|
const requestContext = await this.#requestContextFor(workflowId, runId, {
|
|
1783
2043
|
kind: 'resume',
|
|
1784
2044
|
step,
|
|
@@ -1794,13 +2054,17 @@ export class RunnerRuntime {
|
|
|
1794
2054
|
lifecycle,
|
|
1795
2055
|
};
|
|
1796
2056
|
}
|
|
1797
|
-
#workflowState(workflowId, runId, withNestedWorkflows = false) {
|
|
2057
|
+
#workflowState(workflowId, runId, withNestedWorkflows = false, fields = RUN_STATE_FIELDS) {
|
|
1798
2058
|
return this.#getWorkflow(workflowId).getWorkflowRunById(runId, {
|
|
1799
|
-
fields
|
|
2059
|
+
fields,
|
|
1800
2060
|
withNestedWorkflows,
|
|
1801
2061
|
});
|
|
1802
2062
|
}
|
|
1803
|
-
|
|
2063
|
+
/**
|
|
2064
|
+
* With `expected`, a compare-and-set against that exact row, serialized as
|
|
2065
|
+
* Mastra's own persist does; a miss throws RowChangedError.
|
|
2066
|
+
*/
|
|
2067
|
+
async #persistLifecycle(workflowId, runId, state, lifecycle, now, source, expected) {
|
|
1804
2068
|
const workflows = source.workflows;
|
|
1805
2069
|
const persisted = {
|
|
1806
2070
|
...state,
|
|
@@ -1810,6 +2074,17 @@ export class RunnerRuntime {
|
|
|
1810
2074
|
},
|
|
1811
2075
|
timestamp: now,
|
|
1812
2076
|
};
|
|
2077
|
+
if (expected) {
|
|
2078
|
+
if (source.storage !== 'd1' || !source.replace)
|
|
2079
|
+
throw new Error('storage cannot compare-and-set the run row');
|
|
2080
|
+
const replaced = await source.replace.call(source.capability, expected, {
|
|
2081
|
+
snapshot: JSON.stringify(persisted),
|
|
2082
|
+
updatedAt: new Date(now).toISOString(),
|
|
2083
|
+
});
|
|
2084
|
+
if (!replaced)
|
|
2085
|
+
throw new RowChangedError();
|
|
2086
|
+
return persisted;
|
|
2087
|
+
}
|
|
1813
2088
|
await source.persist.call(workflows, {
|
|
1814
2089
|
workflowName: workflowId,
|
|
1815
2090
|
runId,
|
|
@@ -1818,6 +2093,31 @@ export class RunnerRuntime {
|
|
|
1818
2093
|
});
|
|
1819
2094
|
return persisted;
|
|
1820
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
|
+
}
|
|
1821
2121
|
async #summaryAfterPersist(workflowId, runId, source, expected) {
|
|
1822
2122
|
if (expected?.version === 2) {
|
|
1823
2123
|
const selected = await this.#completedStartState(source, runExecutionIdentityFor({ tablePrefix: source.tablePrefix, workflowId, runId }, expected), expected);
|