@proofoftech/flowsafe 0.24.0 → 0.26.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 +45 -0
- package/README.md +6 -4
- package/dist/agent-host/thread-host.d.ts.map +1 -1
- package/dist/agent-host/thread-host.js +64 -3
- package/dist/agent-host/thread-host.js.map +1 -1
- package/dist/agent-host/thread-topology.d.ts.map +1 -1
- package/dist/agent-host/thread-topology.js +2 -1
- package/dist/agent-host/thread-topology.js.map +1 -1
- package/dist/agent-runner/durable-agent-runner.d.ts +12 -3
- package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
- package/dist/agent-runner/durable-agent-runner.js +217 -102
- package/dist/agent-runner/durable-agent-runner.js.map +1 -1
- package/dist/approval-api/grants.d.ts +11 -1
- package/dist/approval-api/grants.d.ts.map +1 -1
- package/dist/approval-api/grants.js +20 -0
- package/dist/approval-api/grants.js.map +1 -1
- package/dist/approval-api/index.d.ts +1 -1
- package/dist/approval-api/index.d.ts.map +1 -1
- package/dist/approval-api/index.js +1 -1
- package/dist/approval-api/index.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.d.ts +4 -1
- package/dist/approval-api/service.d.ts.map +1 -1
- package/dist/approval-api/service.js +12 -5
- package/dist/approval-api/service.js.map +1 -1
- package/dist/approval-api/types.d.ts +8 -1
- package/dist/approval-api/types.d.ts.map +1 -1
- package/dist/background-tasks/d1-storage.d.ts.map +1 -1
- package/dist/background-tasks/d1-storage.js +7 -12
- package/dist/background-tasks/d1-storage.js.map +1 -1
- package/dist/do-runner/durable-object.d.ts +29 -10
- package/dist/do-runner/durable-object.d.ts.map +1 -1
- package/dist/do-runner/durable-object.js +56 -33
- package/dist/do-runner/durable-object.js.map +1 -1
- package/dist/do-runner/fenced-workflow-capability.d.ts +35 -5
- package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -1
- package/dist/do-runner/fenced-workflows-d1.d.ts +8 -0
- package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -1
- package/dist/do-runner/fenced-workflows-d1.js +402 -39
- package/dist/do-runner/fenced-workflows-d1.js.map +1 -1
- package/dist/do-runner/index.d.ts +1 -1
- package/dist/do-runner/index.d.ts.map +1 -1
- package/dist/do-runner/index.js +1 -1
- package/dist/do-runner/index.js.map +1 -1
- package/dist/do-runner/run-input-depth.d.ts +15 -0
- package/dist/do-runner/run-input-depth.d.ts.map +1 -0
- package/dist/do-runner/run-input-depth.js +32 -0
- package/dist/do-runner/run-input-depth.js.map +1 -0
- package/dist/do-runner/run-lifecycle.d.ts +68 -3
- package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
- package/dist/do-runner/run-lifecycle.js +76 -12
- package/dist/do-runner/run-lifecycle.js.map +1 -1
- package/dist/do-runner/runtime.d.ts +46 -9
- package/dist/do-runner/runtime.d.ts.map +1 -1
- package/dist/do-runner/runtime.js +361 -115
- package/dist/do-runner/runtime.js.map +1 -1
- package/dist/do-runner/workflow-snapshot-row.d.ts +4 -5
- package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -1
- package/dist/do-runner/workflow-snapshot-row.js +14 -18
- package/dist/do-runner/workflow-snapshot-row.js.map +1 -1
- package/dist/host-kit/approval-bridge.d.ts +20 -2
- package/dist/host-kit/approval-bridge.d.ts.map +1 -1
- package/dist/host-kit/approval-bridge.js +66 -7
- package/dist/host-kit/approval-bridge.js.map +1 -1
- package/dist/host-kit/do-run-topology.d.ts +3 -1
- package/dist/host-kit/do-run-topology.d.ts.map +1 -1
- package/dist/host-kit/do-run-topology.js +2 -1
- package/dist/host-kit/do-run-topology.js.map +1 -1
- package/dist/host-kit/flowsafe-worker.d.ts +6 -1
- package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
- package/dist/host-kit/flowsafe-worker.js +2 -2
- package/dist/host-kit/flowsafe-worker.js.map +1 -1
- package/dist/host-kit/host-approval-service.d.ts +3 -1
- package/dist/host-kit/host-approval-service.d.ts.map +1 -1
- package/dist/host-kit/host-approval-service.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 +14 -0
- package/dist/host-kit/run-router.js.map +1 -1
- package/dist/schedules/tick.d.ts +28 -2
- package/dist/schedules/tick.d.ts.map +1 -1
- package/dist/schedules/tick.js +35 -11
- package/dist/schedules/tick.js.map +1 -1
- package/package.json +2 -2
|
@@ -23,6 +23,8 @@ import { RequestContext } from '@mastra/core/request-context';
|
|
|
23
23
|
import { cleanStepResult, } from '@mastra/core/workflows';
|
|
24
24
|
import { isExecutionPrincipalId, isExecutionPrincipalKind, } from '../approval-api/principal.js';
|
|
25
25
|
import { BREAKWATER_ACTOR_KEY, BREAKWATER_CONNECTOR_EXECUTION_KEY, BREAKWATER_ISOLATION_SCOPE_KEY, BREAKWATER_WORKFLOW_SCOPE_KEY, } from './breakwater-keys.js';
|
|
26
|
+
import { errorMessageOf, findInCauseChain } from './cause-chain.js';
|
|
27
|
+
import { DoStatusError } from './do-status-error.js';
|
|
26
28
|
import { assertMutationEpoch, ExecutionFenceUnreadableError, normalizeD1RunExecutionIdentity, normalizeMutationEpoch, normalizeStartIdentity, RunStartPendingError, } from './execution-admission.js';
|
|
27
29
|
import { isReservedExecutionContextKey, RUN_PROVENANCE_CONTEXT_KEY, stripReservedExecutionContext, } from './execution-context.js';
|
|
28
30
|
import { admitsExistingRun, admitsRunStart, ExecutionFencedError, } from './execution-fence.js';
|
|
@@ -30,12 +32,14 @@ import { FENCED_WORKFLOW_STORAGE, } from './fenced-workflow-capability.js';
|
|
|
30
32
|
import { isDefinitiveInitialAdmissionRefusal } from './initial-admission-refusal.js';
|
|
31
33
|
import { mastraRegistryEntries } from './mastra-registry.js';
|
|
32
34
|
import { isPathSafeId } from './path-safe-id.js';
|
|
33
|
-
import {
|
|
35
|
+
import { exceedsRunInputDepth, runInputDepthMessage, } from './run-input-depth.js';
|
|
36
|
+
import { advanceLifecycle, canonicalEconomicOperations, canonicalReplayPrincipals, canonicalScheduleDispatch, failureEnvelope, hasDisputedSettlement, legAbortReason, lifecycleFromRequestContext, projectTerminalLifecycle, RUN_FAILURE_MARKERS, RUN_LIFECYCLE_CONTEXT_KEY, RUN_SETTLING_MARKERS, RunLifecycleBlockedError, RunSettledConflictError, RunStateNotStorableError, runTerminalError, terminalCleanupFor, terminalLegAbortReason, } from './run-lifecycle.js';
|
|
34
37
|
import { decodeProgressRunProvenance, decodeResumeCounts, nextResumeCount, runExecutionIdentityFor, } from './run-provenance.js';
|
|
35
38
|
import { errorText, isDurableRunStatus, isRunStatus, isTerminalRunStatus, terminalStateFields, terminalStateUpdate, } from './run-terminal-state.js';
|
|
36
39
|
import { captureReservation, } from './start-reservation-contract.js';
|
|
37
40
|
import { validateTablePrefix } from './table-prefix.js';
|
|
38
|
-
|
|
41
|
+
import { parseSnapshotObject, } from './workflow-snapshot-row.js';
|
|
42
|
+
export { RunLifecycleBlockedError, RunSettledConflictError, RunStateNotStorableError, } from './run-lifecycle.js';
|
|
39
43
|
export class UnknownWorkflowError extends Error {
|
|
40
44
|
constructor(workflowId) {
|
|
41
45
|
super(`unknown workflow '${workflowId}'`);
|
|
@@ -54,6 +58,18 @@ export class RunNotSuspendedError extends Error {
|
|
|
54
58
|
this.name = 'RunNotSuspendedError';
|
|
55
59
|
}
|
|
56
60
|
}
|
|
61
|
+
/**
|
|
62
|
+
* A resume that names the suspension it is for, of a step that has since left
|
|
63
|
+
* it: resumed and suspended again, or no longer suspended at all.
|
|
64
|
+
*/
|
|
65
|
+
export class SuspensionChangedError extends DoStatusError {
|
|
66
|
+
status = 409;
|
|
67
|
+
reason = { code: 'SUSPENSION_CHANGED' };
|
|
68
|
+
constructor(workflowId, runId, step) {
|
|
69
|
+
super(`step '${step}' of run '${runId}' of workflow '${workflowId}' is no longer at the suspension the resume names`);
|
|
70
|
+
this.name = 'SuspensionChangedError';
|
|
71
|
+
}
|
|
72
|
+
}
|
|
57
73
|
/**
|
|
58
74
|
* An authoritative run-state read did not succeed, so nothing that read
|
|
59
75
|
* returned is evidence about the run. One cause is Mastra answering from its
|
|
@@ -113,6 +129,10 @@ const RUN_STATE_FIELDS = [
|
|
|
113
129
|
'suspendedPaths',
|
|
114
130
|
'requestContext',
|
|
115
131
|
];
|
|
132
|
+
const RESUME_STATE_FIELDS = [
|
|
133
|
+
...RUN_STATE_FIELDS,
|
|
134
|
+
'payload',
|
|
135
|
+
];
|
|
116
136
|
function runProvenance(state) {
|
|
117
137
|
const value = state.requestContext?.[RUN_PROVENANCE_CONTEXT_KEY];
|
|
118
138
|
if (value === undefined)
|
|
@@ -285,11 +305,9 @@ function summarizeState(runId, state, counts, requestedBy, requestedByKind) {
|
|
|
285
305
|
else if (state.status === 'failed') {
|
|
286
306
|
if (state.error)
|
|
287
307
|
summary.error = errorText(state.error);
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
message: RUN_INTERRUPTED_MESSAGE,
|
|
292
|
-
};
|
|
308
|
+
const envelope = failureEnvelope(lifecycle);
|
|
309
|
+
if (envelope)
|
|
310
|
+
summary.errorEnvelope = envelope;
|
|
293
311
|
}
|
|
294
312
|
else if (state.status === 'suspended') {
|
|
295
313
|
const suspendedKeys = Object.keys(state.suspendedPaths ?? {});
|
|
@@ -369,8 +387,8 @@ function orderedRequestContext(runtimeContext, provided, scheduled) {
|
|
|
369
387
|
...identity,
|
|
370
388
|
]);
|
|
371
389
|
}
|
|
372
|
-
/**
|
|
373
|
-
|
|
390
|
+
/** How often an executing leg marks its run row live. */
|
|
391
|
+
const RUN_LEG_TOUCH_MS = 30_000;
|
|
374
392
|
// Longer than the largest Workers CPU limit (five minutes), which is the most
|
|
375
393
|
// a busy step can delay a touch timer: a row untouched this long has no leg
|
|
376
394
|
// left marking it, on this instance or one being replaced.
|
|
@@ -382,8 +400,25 @@ function rowSilent(raw, now) {
|
|
|
382
400
|
throw new RunStateUnreadableError(raw.workflowId, raw.runId);
|
|
383
401
|
return now - touchedAt >= RUN_LEG_SILENT_MS;
|
|
384
402
|
}
|
|
385
|
-
/** A
|
|
386
|
-
class
|
|
403
|
+
/** A compare-and-set write found the run's row changed since the read it decided from. */
|
|
404
|
+
class RowChangedError extends Error {
|
|
405
|
+
constructor() {
|
|
406
|
+
super('the run row changed since it was read');
|
|
407
|
+
this.name = 'RowChangedError';
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Compare-and-set passes a lifecycle transition makes before it answers that
|
|
412
|
+
* the run's row keeps changing. A touch moves the row at most once per
|
|
413
|
+
* RUN_LEG_TOUCH_MS, so a miss it causes clears on the next pass; only a leg on
|
|
414
|
+
* another instance writing snapshots back to back misses every time.
|
|
415
|
+
*/
|
|
416
|
+
const LIFECYCLE_WRITE_ATTEMPTS = 5;
|
|
417
|
+
function snapshotOfRow(row) {
|
|
418
|
+
const state = parseSnapshotObject(row.snapshot);
|
|
419
|
+
if (state === undefined || state.runId !== row.runId)
|
|
420
|
+
throw new RunStateUnreadableError(row.workflowId, row.runId);
|
|
421
|
+
return state;
|
|
387
422
|
}
|
|
388
423
|
const TERMINABLE_RUN_STATUSES = new Set([
|
|
389
424
|
'running',
|
|
@@ -407,8 +442,42 @@ function relativeDeadline(deadlineMs, now = Date.now()) {
|
|
|
407
442
|
}
|
|
408
443
|
return deadlineAt;
|
|
409
444
|
}
|
|
445
|
+
function assertLegAbort(legAbort) {
|
|
446
|
+
if (legAbort !== undefined && !(legAbort instanceof AbortController))
|
|
447
|
+
throw new InvalidRunRequestError('legAbort is malformed');
|
|
448
|
+
}
|
|
449
|
+
function assertRunInputDepth(field, value) {
|
|
450
|
+
if (exceedsRunInputDepth(value))
|
|
451
|
+
throw new InvalidRunRequestError(runInputDepthMessage(field));
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* `resumeCount` is absent on a first suspension and 1, 2, … after it, so 0 is
|
|
455
|
+
* malformed rather than a suspension the step can be at.
|
|
456
|
+
*/
|
|
457
|
+
function captureExpectedSuspension(value) {
|
|
458
|
+
if (value === undefined)
|
|
459
|
+
return undefined;
|
|
460
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
461
|
+
throw new InvalidRunRequestError('expectedSuspension is malformed');
|
|
462
|
+
const { suspendedAt, resumeCount } = value;
|
|
463
|
+
if (!Number.isSafeInteger(suspendedAt) ||
|
|
464
|
+
suspendedAt < 0 ||
|
|
465
|
+
(resumeCount !== undefined &&
|
|
466
|
+
(!Number.isSafeInteger(resumeCount) || resumeCount < 1)))
|
|
467
|
+
throw new InvalidRunRequestError('expectedSuspension is malformed');
|
|
468
|
+
return Object.freeze({
|
|
469
|
+
suspendedAt: suspendedAt,
|
|
470
|
+
...(resumeCount === undefined
|
|
471
|
+
? {}
|
|
472
|
+
: { resumeCount: resumeCount }),
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
function isRunStateNotStorable(error) {
|
|
476
|
+
return findInCauseChain(error, (link) => link instanceof RunStateNotStorableError, { rootOnly: false });
|
|
477
|
+
}
|
|
410
478
|
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;
|
|
479
|
+
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;
|
|
480
|
+
assertLegAbort(legAbort);
|
|
412
481
|
if (requestedBy !== undefined && !isExecutionPrincipalId(requestedBy)) {
|
|
413
482
|
throw new InvalidRunRequestError('requestedBy is malformed');
|
|
414
483
|
}
|
|
@@ -526,6 +595,7 @@ function captureStartRunOptions(source) {
|
|
|
526
595
|
onPreparedStartIdentity,
|
|
527
596
|
runOwnerGuard,
|
|
528
597
|
startReservation,
|
|
598
|
+
legAbort,
|
|
529
599
|
};
|
|
530
600
|
return Object.freeze(requestedBy !== undefined && requestedByKind !== undefined
|
|
531
601
|
? { ...captured, requestedBy, requestedByKind }
|
|
@@ -570,6 +640,37 @@ function effectiveLifecycle(persisted, active) {
|
|
|
570
640
|
: {}),
|
|
571
641
|
};
|
|
572
642
|
}
|
|
643
|
+
/**
|
|
644
|
+
* A stored request context with a leg's values laid over it, and the lifecycle
|
|
645
|
+
* that results. Summary selection reads the attempt token in the context that
|
|
646
|
+
* results, so every writer of a leg's outcome builds it here.
|
|
647
|
+
*/
|
|
648
|
+
function overlayLegContext(stored, overlay) {
|
|
649
|
+
const persisted = stored !== null && typeof stored === 'object' && !Array.isArray(stored)
|
|
650
|
+
? stored
|
|
651
|
+
: {};
|
|
652
|
+
const context = { ...persisted, ...overlay };
|
|
653
|
+
const persistedLifecycle = lifecycleFromRequestContext(persisted);
|
|
654
|
+
return {
|
|
655
|
+
context,
|
|
656
|
+
persistedLifecycle,
|
|
657
|
+
lifecycle: effectiveLifecycle(persistedLifecycle, lifecycleFromRequestContext(context)),
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
/** The request-context keys summary selection reads from a run's stored context. */
|
|
661
|
+
const SELECTION_CONTEXT_KEYS = [
|
|
662
|
+
RUN_PROVENANCE_CONTEXT_KEY,
|
|
663
|
+
RUN_LIFECYCLE_CONTEXT_KEY,
|
|
664
|
+
];
|
|
665
|
+
/** The state with which the runtime fails a run by one of its failure markers. */
|
|
666
|
+
function failedByMarker(marker, now) {
|
|
667
|
+
const { errorName, envelope } = RUN_FAILURE_MARKERS[marker];
|
|
668
|
+
return {
|
|
669
|
+
...terminalStateFields('failed'),
|
|
670
|
+
error: { name: errorName, message: envelope.message },
|
|
671
|
+
timestamp: now,
|
|
672
|
+
};
|
|
673
|
+
}
|
|
573
674
|
function sameExecution(a, b) {
|
|
574
675
|
return (a.tablePrefix === b.tablePrefix &&
|
|
575
676
|
a.workflowId === b.workflowId &&
|
|
@@ -811,6 +912,13 @@ export class RunnerRuntime {
|
|
|
811
912
|
await this.#startIdempotency.releaseReservation(claim);
|
|
812
913
|
};
|
|
813
914
|
try {
|
|
915
|
+
// An agent's loop input also carries the thread history memory recalls,
|
|
916
|
+
// which the caller did not send; the agent host bounds the caller's part.
|
|
917
|
+
if (options.agentStart === undefined)
|
|
918
|
+
assertRunInputDepth('inputData', options.inputData);
|
|
919
|
+
assertRunInputDepth('initialState', options.initialState);
|
|
920
|
+
for (const value of Object.values(options.storedRequestContext ?? {}))
|
|
921
|
+
assertRunInputDepth('a requestContext value', value);
|
|
814
922
|
const workflow = this.#getWorkflow(workflowId);
|
|
815
923
|
if (startIdentity?.target.kind === 'workflow' &&
|
|
816
924
|
startIdentity.target.id !== workflow.id)
|
|
@@ -818,10 +926,12 @@ export class RunnerRuntime {
|
|
|
818
926
|
const proof = await this.#assertStartFence(options.idempotencyKey, options.mutationEpoch);
|
|
819
927
|
return await this.#withRunLock(workflowId, runId, async () => {
|
|
820
928
|
const activeKey = this.#runKey(workflowId, runId);
|
|
821
|
-
const active =
|
|
929
|
+
const active = options.legAbort
|
|
930
|
+
? { legAbort: options.legAbort }
|
|
931
|
+
: {};
|
|
822
932
|
if (this.#activeRuns.has(activeKey))
|
|
823
933
|
throw new RunAlreadyExistsError(workflowId, runId, 'running');
|
|
824
|
-
this.#
|
|
934
|
+
const leaveLeg = this.#registerLeg(activeKey, active, workflowId, runId);
|
|
825
935
|
let execution;
|
|
826
936
|
let engineEntered = false;
|
|
827
937
|
let outcomeReadStarted = false;
|
|
@@ -939,6 +1049,7 @@ export class RunnerRuntime {
|
|
|
939
1049
|
await this.#startIdempotency.releaseReservation(claim);
|
|
940
1050
|
}
|
|
941
1051
|
if (engineEntered && provenance && !outcomeReadStarted) {
|
|
1052
|
+
await this.#failUnstorableLeg(workflowId, runId, active, error);
|
|
942
1053
|
const recovered = await this.#summaryForAttempt(workflowId, runId, provenance);
|
|
943
1054
|
if (recovered)
|
|
944
1055
|
return recovered;
|
|
@@ -946,8 +1057,7 @@ export class RunnerRuntime {
|
|
|
946
1057
|
throw asClientError(error) ?? error;
|
|
947
1058
|
}
|
|
948
1059
|
finally {
|
|
949
|
-
|
|
950
|
-
this.#activeRuns.delete(activeKey);
|
|
1060
|
+
await leaveLeg();
|
|
951
1061
|
}
|
|
952
1062
|
});
|
|
953
1063
|
}
|
|
@@ -962,21 +1072,25 @@ export class RunnerRuntime {
|
|
|
962
1072
|
* loads it and re-enters the engine at the suspended step.
|
|
963
1073
|
*/
|
|
964
1074
|
async resume(workflowId, runId, options = {}) {
|
|
1075
|
+
const { legAbort } = options;
|
|
1076
|
+
assertLegAbort(legAbort);
|
|
1077
|
+
assertRunInputDepth('resumeData', options.resumeData);
|
|
1078
|
+
const expectedSuspension = captureExpectedSuspension(options.expectedSuspension);
|
|
965
1079
|
this.#getWorkflow(workflowId);
|
|
966
1080
|
const proof = await this.#assertResumeFence(workflowId, runId);
|
|
967
1081
|
return this.#withRunLock(workflowId, runId, async () => {
|
|
968
1082
|
const activeKey = this.#runKey(workflowId, runId);
|
|
969
|
-
const active = {};
|
|
1083
|
+
const active = legAbort ? { legAbort } : {};
|
|
970
1084
|
if (this.#activeRuns.has(activeKey))
|
|
971
1085
|
throw new RunTerminalConflictError(workflowId, runId, 'running');
|
|
972
|
-
this.#
|
|
1086
|
+
const leaveLeg = this.#registerLeg(activeKey, active, workflowId, runId);
|
|
973
1087
|
let provenance;
|
|
974
1088
|
let engineEntered = false;
|
|
975
1089
|
let outcomeReadStarted = false;
|
|
976
1090
|
try {
|
|
977
1091
|
const source = await this.#captureWorkflowStorage(workflowId);
|
|
978
1092
|
active.source = source;
|
|
979
|
-
const state = await this.#workflowState(workflowId, runId, true);
|
|
1093
|
+
const state = await this.#workflowState(workflowId, runId, true, RESUME_STATE_FIELDS);
|
|
980
1094
|
if (!state)
|
|
981
1095
|
throw new UnknownRunError(workflowId, runId);
|
|
982
1096
|
if (state.isFromInMemory)
|
|
@@ -989,7 +1103,7 @@ export class RunnerRuntime {
|
|
|
989
1103
|
throw new RunStateUnreadableError(workflowId, runId);
|
|
990
1104
|
if (state.status !== 'suspended')
|
|
991
1105
|
throw new RunNotSuspendedError(workflowId, runId, state.status);
|
|
992
|
-
const prepared = await this.#trustedResumePreparation(workflowId, runId, state,
|
|
1106
|
+
const prepared = await this.#trustedResumePreparation(workflowId, runId, state, { ...options, expectedSuspension });
|
|
993
1107
|
provenance = prepared.provenance;
|
|
994
1108
|
const { requestContext, lifecycle, nextCounts } = prepared;
|
|
995
1109
|
active.requestContext = requestContext;
|
|
@@ -1006,7 +1120,7 @@ export class RunnerRuntime {
|
|
|
1006
1120
|
await this.#withLifecycleLock(workflowId, runId, check);
|
|
1007
1121
|
if (options.prepareExecution) {
|
|
1008
1122
|
const values = structuredClone(Object.fromEntries(requestContext.entries()));
|
|
1009
|
-
await options.prepareExecution(new RequestContext(Object.entries(values)));
|
|
1123
|
+
await options.prepareExecution(new RequestContext(Object.entries(values)), state.payload);
|
|
1010
1124
|
await this.#withLifecycleLock(workflowId, runId, check);
|
|
1011
1125
|
}
|
|
1012
1126
|
const run = await this.#createRun(workflowId, runId);
|
|
@@ -1035,6 +1149,7 @@ export class RunnerRuntime {
|
|
|
1035
1149
|
}
|
|
1036
1150
|
catch (error) {
|
|
1037
1151
|
if (engineEntered && provenance && !outcomeReadStarted) {
|
|
1152
|
+
await this.#failUnstorableLeg(workflowId, runId, active, error);
|
|
1038
1153
|
const recovered = await this.#summaryForAttempt(workflowId, runId, provenance);
|
|
1039
1154
|
if (recovered)
|
|
1040
1155
|
return recovered;
|
|
@@ -1042,8 +1157,7 @@ export class RunnerRuntime {
|
|
|
1042
1157
|
throw asClientError(error) ?? error;
|
|
1043
1158
|
}
|
|
1044
1159
|
finally {
|
|
1045
|
-
|
|
1046
|
-
this.#activeRuns.delete(activeKey);
|
|
1160
|
+
await leaveLeg();
|
|
1047
1161
|
}
|
|
1048
1162
|
});
|
|
1049
1163
|
}
|
|
@@ -1058,19 +1172,18 @@ export class RunnerRuntime {
|
|
|
1058
1172
|
*/
|
|
1059
1173
|
async cancelActiveExecution(workflowId, runId, intendedStatus, replayPrincipals, cas, now = Date.now()) {
|
|
1060
1174
|
this.#getWorkflow(workflowId);
|
|
1061
|
-
const prepared = await this.#withLifecycleLock(workflowId, runId, async () => {
|
|
1175
|
+
const prepared = await this.#withLifecycleLock(workflowId, runId, () => this.#retryOnRowChange(workflowId, runId, async () => {
|
|
1062
1176
|
const source = this.#activeRuns.get(this.#runKey(workflowId, runId))?.source ??
|
|
1063
1177
|
(await this.#captureWorkflowStorage(workflowId));
|
|
1064
|
-
const state = await
|
|
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);
|
|
1178
|
+
const { state, row } = await this.#readForTransition(source, workflowId, runId);
|
|
1072
1179
|
const key = this.#runKey(workflowId, runId);
|
|
1073
1180
|
const active = this.#activeRuns.get(key);
|
|
1181
|
+
const cancelTarget = () => {
|
|
1182
|
+
if (!active?.run)
|
|
1183
|
+
return undefined;
|
|
1184
|
+
this.#terminalAbortIntents.set(key, intendedStatus);
|
|
1185
|
+
return { run: active.run, legAbort: active.legAbort, key };
|
|
1186
|
+
};
|
|
1074
1187
|
const lifecycle = effectiveLifecycle(lifecycleFromRequestContext(state.requestContext), active?.lifecycle);
|
|
1075
1188
|
if (lifecycle?.terminal)
|
|
1076
1189
|
return undefined;
|
|
@@ -1085,10 +1198,7 @@ export class RunnerRuntime {
|
|
|
1085
1198
|
(cas === undefined ||
|
|
1086
1199
|
(existingIntent.expectedRevision === cas.expectedRevision &&
|
|
1087
1200
|
existingIntent.expectedDeadlineAt === cas.expectedDeadlineAt))) {
|
|
1088
|
-
|
|
1089
|
-
return undefined;
|
|
1090
|
-
this.#terminalAbortIntents.set(key, intendedStatus);
|
|
1091
|
-
return { run: active.run, key };
|
|
1201
|
+
return cancelTarget();
|
|
1092
1202
|
}
|
|
1093
1203
|
if (cas &&
|
|
1094
1204
|
(lifecycle?.revision !== cas.expectedRevision ||
|
|
@@ -1120,16 +1230,13 @@ export class RunnerRuntime {
|
|
|
1120
1230
|
: {}),
|
|
1121
1231
|
},
|
|
1122
1232
|
});
|
|
1123
|
-
await this.#
|
|
1233
|
+
await this.#persistIntent(workflowId, runId, state, intent, now, source, row);
|
|
1124
1234
|
if (active) {
|
|
1125
1235
|
active.lifecycle = intent;
|
|
1126
1236
|
active.requestContext?.set(RUN_LIFECYCLE_CONTEXT_KEY, intent);
|
|
1127
1237
|
}
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
this.#terminalAbortIntents.set(key, intendedStatus);
|
|
1131
|
-
return { run: active.run, key };
|
|
1132
|
-
});
|
|
1238
|
+
return cancelTarget();
|
|
1239
|
+
}));
|
|
1133
1240
|
if (!prepared)
|
|
1134
1241
|
return false;
|
|
1135
1242
|
try {
|
|
@@ -1139,6 +1246,9 @@ export class RunnerRuntime {
|
|
|
1139
1246
|
this.#terminalAbortIntents.delete(prepared.key);
|
|
1140
1247
|
throw error;
|
|
1141
1248
|
}
|
|
1249
|
+
// After `run.cancel()` has aborted the engine run, so the engine's
|
|
1250
|
+
// cancellation precedes any abort error from a call in flight.
|
|
1251
|
+
prepared.legAbort?.abort(terminalLegAbortReason(intendedStatus));
|
|
1142
1252
|
return true;
|
|
1143
1253
|
}
|
|
1144
1254
|
/** Trusted host variant that persists the exact identities allowed to retry. */
|
|
@@ -1164,27 +1274,17 @@ export class RunnerRuntime {
|
|
|
1164
1274
|
}
|
|
1165
1275
|
async #transitionTerminal(workflowId, runId, status, now, cas, replayPrincipals, replayingPrincipal) {
|
|
1166
1276
|
this.#getWorkflow(workflowId);
|
|
1167
|
-
return this.#withRunLock(workflowId, runId, () =>
|
|
1168
|
-
|
|
1169
|
-
replayPrincipals,
|
|
1170
|
-
|
|
1171
|
-
}));
|
|
1277
|
+
return this.#withRunLock(workflowId, runId, async () => {
|
|
1278
|
+
const source = await this.#captureWorkflowStorage(workflowId);
|
|
1279
|
+
return this.#retryOnRowChange(workflowId, runId, async () => this.#transitionTerminalLocked(workflowId, runId, status, now, { cas, replayPrincipals, replayingPrincipal }, source, await this.#readForTransition(source, workflowId, runId)));
|
|
1280
|
+
});
|
|
1172
1281
|
}
|
|
1173
1282
|
/**
|
|
1174
|
-
*
|
|
1175
|
-
*
|
|
1176
|
-
* a miss throws
|
|
1283
|
+
* Decide a terminal transition from one read of the run's row and write it,
|
|
1284
|
+
* for a caller holding the run lock. Where the read carries the row, the
|
|
1285
|
+
* write is a compare-and-set against it and a miss throws RowChangedError.
|
|
1177
1286
|
*/
|
|
1178
|
-
async #transitionTerminalLocked(workflowId, runId, status, now, { cas, replayPrincipals, replayingPrincipal,
|
|
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);
|
|
1287
|
+
async #transitionTerminalLocked(workflowId, runId, status, now, { cas, replayPrincipals, replayingPrincipal }, source, { state, row }) {
|
|
1188
1288
|
const lifecycle = lifecycleFromRequestContext(state.requestContext);
|
|
1189
1289
|
if (lifecycle?.terminal) {
|
|
1190
1290
|
if (replayingPrincipal &&
|
|
@@ -1253,12 +1353,9 @@ export class RunnerRuntime {
|
|
|
1253
1353
|
await this.#persistLifecycle(workflowId, runId, {
|
|
1254
1354
|
...state,
|
|
1255
1355
|
...terminalStateFields(status),
|
|
1256
|
-
error:
|
|
1257
|
-
name: status === 'cancelled' ? 'RunCancelledError' : 'RunTimedOutError',
|
|
1258
|
-
message: next.terminal.error.message,
|
|
1259
|
-
},
|
|
1356
|
+
error: runTerminalError(status),
|
|
1260
1357
|
timestamp: now,
|
|
1261
|
-
}, next, now, source,
|
|
1358
|
+
}, next, now, source, row);
|
|
1262
1359
|
this.#terminalAbortIntents.delete(this.#runKey(workflowId, runId));
|
|
1263
1360
|
return {
|
|
1264
1361
|
summary: await this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state)),
|
|
@@ -1361,13 +1458,14 @@ export class RunnerRuntime {
|
|
|
1361
1458
|
}
|
|
1362
1459
|
if (capability === null || typeof capability !== 'object')
|
|
1363
1460
|
throw new Error('workflow capability is malformed');
|
|
1364
|
-
const { database, tablePrefix: prefix, readSnapshot, withInitialAdmission: admit, terminalizeInitialAdmission: terminalize, touchRun: touch, replaceSnapshot: replace, } = capability;
|
|
1461
|
+
const { database, tablePrefix: prefix, readSnapshot, withInitialAdmission: admit, terminalizeInitialAdmission: terminalize, touchRun: touch, replaceSnapshot: replace, patchRunLifecycle: patch, } = capability;
|
|
1365
1462
|
if (typeof prefix !== 'string' ||
|
|
1366
1463
|
typeof readSnapshot !== 'function' ||
|
|
1367
1464
|
typeof admit !== 'function' ||
|
|
1368
1465
|
typeof terminalize !== 'function' ||
|
|
1369
1466
|
(touch !== undefined && typeof touch !== 'function') ||
|
|
1370
1467
|
(replace !== undefined && typeof replace !== 'function') ||
|
|
1468
|
+
(patch !== undefined && typeof patch !== 'function') ||
|
|
1371
1469
|
!database ||
|
|
1372
1470
|
typeof database.prepare !== 'function' ||
|
|
1373
1471
|
typeof database.batch !== 'function')
|
|
@@ -1387,6 +1485,7 @@ export class RunnerRuntime {
|
|
|
1387
1485
|
terminalize,
|
|
1388
1486
|
...(touch === undefined ? {} : { touch }),
|
|
1389
1487
|
...(replace === undefined ? {} : { replace }),
|
|
1488
|
+
...(patch === undefined ? {} : { patch }),
|
|
1390
1489
|
};
|
|
1391
1490
|
}
|
|
1392
1491
|
async #observeStartState(workflowId, runId) {
|
|
@@ -1591,9 +1690,7 @@ export class RunnerRuntime {
|
|
|
1591
1690
|
: captureReservation(suppliedClaim, 'started');
|
|
1592
1691
|
if (!isPathSafeId(attemptToken) ||
|
|
1593
1692
|
typeof isOwnerQuiescent !== 'function' ||
|
|
1594
|
-
(startLeg !==
|
|
1595
|
-
startLeg !== 'unwound' &&
|
|
1596
|
-
startLeg !== 'touched'))
|
|
1693
|
+
(startLeg !== 'unwound' && startLeg !== 'touched'))
|
|
1597
1694
|
throw new InvalidRunRequestError('start recovery authority is malformed');
|
|
1598
1695
|
if (claim && !this.#startIdempotency)
|
|
1599
1696
|
throw new ExecutionFenceUnreadableError('run start recovery is unresolved');
|
|
@@ -1688,13 +1785,57 @@ export class RunnerRuntime {
|
|
|
1688
1785
|
}
|
|
1689
1786
|
/**
|
|
1690
1787
|
* @internal Mark this run's row live for an executing leg, from whichever
|
|
1691
|
-
* instance runs it; the evidence #silentRow reads.
|
|
1692
|
-
* the
|
|
1788
|
+
* instance runs it; the evidence #silentRow reads. When the row reads
|
|
1789
|
+
* settled, the leg this runtime drives for the run is aborted: its engine
|
|
1790
|
+
* starts no further step, and its step in flight sees its `abortSignal`
|
|
1791
|
+
* aborted. A storage source without the touch leaves nothing to read, so its
|
|
1792
|
+
* runs are never settled here.
|
|
1693
1793
|
*/
|
|
1694
1794
|
async touchRun(workflowId, runId, now = Date.now()) {
|
|
1695
1795
|
const source = await this.#captureWorkflowStorage(workflowId);
|
|
1696
|
-
if (source.storage
|
|
1697
|
-
|
|
1796
|
+
if (source.storage !== 'd1' || !source.touch)
|
|
1797
|
+
return;
|
|
1798
|
+
const touched = await source.touch.call(source.capability, { workflowId, runId }, now);
|
|
1799
|
+
if (touched === 'settled')
|
|
1800
|
+
this.#abortLeg(this.#activeRuns.get(this.#runKey(workflowId, runId)), new RunSettledConflictError(workflowId, runId), 'run-leg-settled-abort', workflowId, runId);
|
|
1801
|
+
}
|
|
1802
|
+
/**
|
|
1803
|
+
* A leg's registration and its touch share one span, because recovery reads a
|
|
1804
|
+
* row nobody touches as abandoned. The release waits for a touch in flight:
|
|
1805
|
+
* its late write would make a following repair's exact-row compare-and-set
|
|
1806
|
+
* miss.
|
|
1807
|
+
*/
|
|
1808
|
+
#registerLeg(activeKey, active, workflowId, runId) {
|
|
1809
|
+
this.#activeRuns.set(activeKey, active);
|
|
1810
|
+
const touches = new Set();
|
|
1811
|
+
const timer = setInterval(() => {
|
|
1812
|
+
const touch = this.touchRun(workflowId, runId)
|
|
1813
|
+
.catch((error) => console.error('run leg liveness touch failed', error))
|
|
1814
|
+
.finally(() => touches.delete(touch));
|
|
1815
|
+
touches.add(touch);
|
|
1816
|
+
}, RUN_LEG_TOUCH_MS);
|
|
1817
|
+
return async () => {
|
|
1818
|
+
clearInterval(timer);
|
|
1819
|
+
await Promise.all(touches);
|
|
1820
|
+
if (this.#activeRuns.get(activeKey) === active)
|
|
1821
|
+
this.#activeRuns.delete(activeKey);
|
|
1822
|
+
};
|
|
1823
|
+
}
|
|
1824
|
+
/**
|
|
1825
|
+
* Abort the engine and the `legAbort` of a leg this runtime drives, with
|
|
1826
|
+
* `cause` as the cause of one shared reason, so a model or tool call in
|
|
1827
|
+
* flight stops with the engine. Never `run.cancel()`: it reads the stored
|
|
1828
|
+
* status first and returns without aborting on `failed`, which an
|
|
1829
|
+
* interruption or a start repair writes.
|
|
1830
|
+
*/
|
|
1831
|
+
#abortLeg(active, cause, logType, workflowId, runId) {
|
|
1832
|
+
const unaborted = [active?.run?.abortController, active?.legAbort].filter((controller) => controller !== undefined && !controller.signal.aborted);
|
|
1833
|
+
if (unaborted.length === 0)
|
|
1834
|
+
return;
|
|
1835
|
+
console.error(JSON.stringify({ type: logType, workflowId, runId }));
|
|
1836
|
+
const reason = legAbortReason(cause);
|
|
1837
|
+
for (const controller of unaborted)
|
|
1838
|
+
controller.abort(reason);
|
|
1698
1839
|
}
|
|
1699
1840
|
/**
|
|
1700
1841
|
* @internal Settle a run whose execution leg ended without a durable outcome.
|
|
@@ -1751,37 +1892,27 @@ export class RunnerRuntime {
|
|
|
1751
1892
|
const silent = await this.#silentRow(source, workflowId, runId, now);
|
|
1752
1893
|
if (!silent)
|
|
1753
1894
|
return { kind: 'live' };
|
|
1895
|
+
// The write replaces the silent row, so it is built from that row; one
|
|
1896
|
+
// that moved since the decision above waits for the next wake.
|
|
1897
|
+
const current = snapshotOfRow(silent);
|
|
1754
1898
|
try {
|
|
1755
1899
|
if (recorded)
|
|
1756
1900
|
return {
|
|
1757
1901
|
kind: 'transition',
|
|
1758
1902
|
replayPrincipal: recorded
|
|
1759
1903
|
.replayPrincipals[0],
|
|
1760
|
-
transition: await this.#transitionTerminalLocked(workflowId, runId, recorded.status, now, {
|
|
1904
|
+
transition: await this.#transitionTerminalLocked(workflowId, runId, recorded.status, now, {}, source, { state: current, row: silent }),
|
|
1761
1905
|
};
|
|
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
1906
|
const currentLifecycle = lifecycleFromRequestContext(current.requestContext);
|
|
1768
1907
|
if (current.status !== state.status ||
|
|
1769
1908
|
currentLifecycle?.revision !== lifecycle?.revision ||
|
|
1770
1909
|
currentLifecycle?.terminal ||
|
|
1771
1910
|
currentLifecycle?.transitionIntent)
|
|
1772
1911
|
return { kind: 'live' };
|
|
1773
|
-
await this.#persistLifecycle(workflowId, runId, {
|
|
1774
|
-
...current,
|
|
1775
|
-
...terminalStateFields('failed'),
|
|
1776
|
-
error: {
|
|
1777
|
-
name: 'RunInterruptedError',
|
|
1778
|
-
message: RUN_INTERRUPTED_MESSAGE,
|
|
1779
|
-
},
|
|
1780
|
-
timestamp: now,
|
|
1781
|
-
}, advanceLifecycle(currentLifecycle, { interruptedAt: now }), now, source, silent);
|
|
1912
|
+
await this.#persistLifecycle(workflowId, runId, { ...current, ...failedByMarker('interruptedAt', now) }, advanceLifecycle(currentLifecycle, { interruptedAt: now }), now, source, silent);
|
|
1782
1913
|
}
|
|
1783
1914
|
catch (error) {
|
|
1784
|
-
if (error instanceof
|
|
1915
|
+
if (error instanceof RowChangedError)
|
|
1785
1916
|
return { kind: 'live' };
|
|
1786
1917
|
throw error;
|
|
1787
1918
|
}
|
|
@@ -1804,6 +1935,53 @@ export class RunnerRuntime {
|
|
|
1804
1935
|
});
|
|
1805
1936
|
return raw && rowSilent(raw, now) ? raw : undefined;
|
|
1806
1937
|
}
|
|
1938
|
+
/**
|
|
1939
|
+
* The run's snapshot for a lifecycle transition, with the exact row it was
|
|
1940
|
+
* parsed from where the storage can compare-and-set that row, so the write
|
|
1941
|
+
* lands only on the row the decision read. Other storage answers the
|
|
1942
|
+
* snapshot alone and keeps its unconditional write.
|
|
1943
|
+
*/
|
|
1944
|
+
async #readForTransition(source, workflowId, runId) {
|
|
1945
|
+
if (source.storage === 'd1' && source.replace) {
|
|
1946
|
+
const row = await source.readSnapshot.call(source.capability, {
|
|
1947
|
+
workflowId,
|
|
1948
|
+
runId,
|
|
1949
|
+
});
|
|
1950
|
+
if (!row)
|
|
1951
|
+
throw new UnknownRunError(workflowId, runId);
|
|
1952
|
+
return { state: snapshotOfRow(row), row };
|
|
1953
|
+
}
|
|
1954
|
+
const state = await source.load.call(source.workflows, {
|
|
1955
|
+
workflowName: workflowId,
|
|
1956
|
+
runId,
|
|
1957
|
+
});
|
|
1958
|
+
if (!state)
|
|
1959
|
+
throw new UnknownRunError(workflowId, runId);
|
|
1960
|
+
if (state.runId !== runId)
|
|
1961
|
+
throw new RunStateUnreadableError(workflowId, runId);
|
|
1962
|
+
return { state };
|
|
1963
|
+
}
|
|
1964
|
+
/**
|
|
1965
|
+
* Repeat one read-decide-write pass until its compare-and-set lands or it
|
|
1966
|
+
* decides without writing, for at most LIFECYCLE_WRITE_ATTEMPTS passes. A
|
|
1967
|
+
* miss means the row changed after the read, so the next pass decides again
|
|
1968
|
+
* from the row as it now stands.
|
|
1969
|
+
*/
|
|
1970
|
+
async #retryOnRowChange(workflowId, runId, pass) {
|
|
1971
|
+
for (let attempt = 1;; attempt++) {
|
|
1972
|
+
try {
|
|
1973
|
+
return await pass();
|
|
1974
|
+
}
|
|
1975
|
+
catch (error) {
|
|
1976
|
+
if (!(error instanceof RowChangedError))
|
|
1977
|
+
throw error;
|
|
1978
|
+
if (attempt >= LIFECYCLE_WRITE_ATTEMPTS)
|
|
1979
|
+
throw new RunStateUnreadableError(workflowId, runId, {
|
|
1980
|
+
cause: new Error(`the run row changed on each of ${LIFECYCLE_WRITE_ATTEMPTS} compare-and-set attempts`, { cause: error }),
|
|
1981
|
+
});
|
|
1982
|
+
}
|
|
1983
|
+
}
|
|
1984
|
+
}
|
|
1807
1985
|
/** @internal Settle the exact selected terminal generation before managed cleanup. */
|
|
1808
1986
|
async settleStartExecution(state, originalClaim) {
|
|
1809
1987
|
const claim = originalClaim === undefined
|
|
@@ -1876,7 +2054,8 @@ export class RunnerRuntime {
|
|
|
1876
2054
|
: undefined;
|
|
1877
2055
|
return orderedRequestContext(base, values, storedRequestContext);
|
|
1878
2056
|
}
|
|
1879
|
-
async #trustedResumePreparation(workflowId, runId, state,
|
|
2057
|
+
async #trustedResumePreparation(workflowId, runId, state, options) {
|
|
2058
|
+
const { step: selectedStep, requestedBy, requestedByKind, deadlineMs, economicOperations, expectedSuspension, } = options;
|
|
1880
2059
|
if (requestedBy !== undefined && !isExecutionPrincipalId(requestedBy)) {
|
|
1881
2060
|
throw new InvalidRunRequestError('requestedBy is malformed');
|
|
1882
2061
|
}
|
|
@@ -1903,6 +2082,21 @@ export class RunnerRuntime {
|
|
|
1903
2082
|
? storedProvenance?.requestedByKind
|
|
1904
2083
|
: requestedByKind;
|
|
1905
2084
|
const priorCounts = new Map(storedProvenance?.resumeCounts ?? []);
|
|
2085
|
+
const leg = {
|
|
2086
|
+
kind: 'resume',
|
|
2087
|
+
step,
|
|
2088
|
+
suspendedAt: stepKey !== undefined ? suspendedAtOf(state.steps, stepKey) : undefined,
|
|
2089
|
+
resumeCount: stepKey !== undefined ? priorCounts.get(stepKey) : undefined,
|
|
2090
|
+
};
|
|
2091
|
+
// The pair the leg's grant minting reads, compared as
|
|
2092
|
+
// boundToCurrentSuspension compares it.
|
|
2093
|
+
if (expectedSuspension !== undefined) {
|
|
2094
|
+
if (stepKey === undefined)
|
|
2095
|
+
throw new InvalidRunRequestError('expectedSuspension requires a resolvable resumed step');
|
|
2096
|
+
if (leg.suspendedAt !== expectedSuspension.suspendedAt ||
|
|
2097
|
+
leg.resumeCount !== expectedSuspension.resumeCount)
|
|
2098
|
+
throw new SuspensionChangedError(workflowId, runId, stepKey);
|
|
2099
|
+
}
|
|
1906
2100
|
const nextCounts = new Map(priorCounts);
|
|
1907
2101
|
if (stepKey !== undefined) {
|
|
1908
2102
|
nextCounts.set(stepKey, nextResumeCount(nextCounts.get(stepKey) ?? 0));
|
|
@@ -1931,14 +2125,7 @@ export class RunnerRuntime {
|
|
|
1931
2125
|
? {}
|
|
1932
2126
|
: { economicOperations: replacementOperations }),
|
|
1933
2127
|
});
|
|
1934
|
-
const requestContext = await this.#requestContextFor(workflowId, runId,
|
|
1935
|
-
kind: 'resume',
|
|
1936
|
-
step,
|
|
1937
|
-
suspendedAt: stepKey !== undefined
|
|
1938
|
-
? suspendedAtOf(state.steps, stepKey)
|
|
1939
|
-
: undefined,
|
|
1940
|
-
resumeCount: stepKey !== undefined ? priorCounts?.get(stepKey) : undefined,
|
|
1941
|
-
}, provenance, undefined, lifecycle);
|
|
2128
|
+
const requestContext = await this.#requestContextFor(workflowId, runId, leg, provenance, undefined, lifecycle);
|
|
1942
2129
|
return {
|
|
1943
2130
|
nextCounts,
|
|
1944
2131
|
provenance,
|
|
@@ -1946,15 +2133,15 @@ export class RunnerRuntime {
|
|
|
1946
2133
|
lifecycle,
|
|
1947
2134
|
};
|
|
1948
2135
|
}
|
|
1949
|
-
#workflowState(workflowId, runId, withNestedWorkflows = false) {
|
|
2136
|
+
#workflowState(workflowId, runId, withNestedWorkflows = false, fields = RUN_STATE_FIELDS) {
|
|
1950
2137
|
return this.#getWorkflow(workflowId).getWorkflowRunById(runId, {
|
|
1951
|
-
fields
|
|
2138
|
+
fields,
|
|
1952
2139
|
withNestedWorkflows,
|
|
1953
2140
|
});
|
|
1954
2141
|
}
|
|
1955
2142
|
/**
|
|
1956
2143
|
* With `expected`, a compare-and-set against that exact row, serialized as
|
|
1957
|
-
* Mastra's own persist does; a miss throws
|
|
2144
|
+
* Mastra's own persist does; a miss throws RowChangedError.
|
|
1958
2145
|
*/
|
|
1959
2146
|
async #persistLifecycle(workflowId, runId, state, lifecycle, now, source, expected) {
|
|
1960
2147
|
const workflows = source.workflows;
|
|
@@ -1968,13 +2155,13 @@ export class RunnerRuntime {
|
|
|
1968
2155
|
};
|
|
1969
2156
|
if (expected) {
|
|
1970
2157
|
if (source.storage !== 'd1' || !source.replace)
|
|
1971
|
-
throw new Error('
|
|
2158
|
+
throw new Error('storage cannot compare-and-set the run row');
|
|
1972
2159
|
const replaced = await source.replace.call(source.capability, expected, {
|
|
1973
2160
|
snapshot: JSON.stringify(persisted),
|
|
1974
2161
|
updatedAt: new Date(now).toISOString(),
|
|
1975
2162
|
});
|
|
1976
2163
|
if (!replaced)
|
|
1977
|
-
throw new
|
|
2164
|
+
throw new RowChangedError();
|
|
1978
2165
|
return persisted;
|
|
1979
2166
|
}
|
|
1980
2167
|
await source.persist.call(workflows, {
|
|
@@ -1985,6 +2172,31 @@ export class RunnerRuntime {
|
|
|
1985
2172
|
});
|
|
1986
2173
|
return persisted;
|
|
1987
2174
|
}
|
|
2175
|
+
/**
|
|
2176
|
+
* Persist a cancellation intent through `patchRunLifecycle` where the storage
|
|
2177
|
+
* has it, otherwise as #persistLifecycle does; a miss throws RowChangedError.
|
|
2178
|
+
* The patch also misses on a snapshot SQLite cannot parse, which the
|
|
2179
|
+
* whole-row compare-and-set still replaces, so that write is tried before
|
|
2180
|
+
* the miss counts as a row change.
|
|
2181
|
+
*/
|
|
2182
|
+
async #persistIntent(workflowId, runId, state, intent, now, source, row) {
|
|
2183
|
+
if (source.storage === 'd1' && source.patch) {
|
|
2184
|
+
const patched = await source.patch.call(source.capability, { workflowId, runId }, {
|
|
2185
|
+
status: state.status,
|
|
2186
|
+
lifecycleRevision: lifecycleFromRequestContext(state.requestContext)
|
|
2187
|
+
?.revision,
|
|
2188
|
+
}, {
|
|
2189
|
+
lifecycle: intent,
|
|
2190
|
+
timestamp: now,
|
|
2191
|
+
updatedAt: new Date(now).toISOString(),
|
|
2192
|
+
});
|
|
2193
|
+
if (patched)
|
|
2194
|
+
return;
|
|
2195
|
+
if (!row)
|
|
2196
|
+
throw new RowChangedError();
|
|
2197
|
+
}
|
|
2198
|
+
await this.#persistLifecycle(workflowId, runId, state, intent, now, source, row);
|
|
2199
|
+
}
|
|
1988
2200
|
async #summaryAfterPersist(workflowId, runId, source, expected) {
|
|
1989
2201
|
if (expected?.version === 2) {
|
|
1990
2202
|
const selected = await this.#completedStartState(source, runExecutionIdentityFor({ tablePrefix: source.tablePrefix, workflowId, runId }, expected), expected);
|
|
@@ -2033,6 +2245,51 @@ export class RunnerRuntime {
|
|
|
2033
2245
|
return undefined;
|
|
2034
2246
|
}
|
|
2035
2247
|
}
|
|
2248
|
+
/**
|
|
2249
|
+
* When `error` is a storage refusal of state that cannot be stored, record
|
|
2250
|
+
* the leg's run as failed and stop the leg. The row still holds the last
|
|
2251
|
+
* state the run stored, and only the keys summary selection reads are laid
|
|
2252
|
+
* over it from the leg's context: the other values may be the ones SQLite
|
|
2253
|
+
* cannot parse. The marker makes the settled-row guard refuse the leg's later
|
|
2254
|
+
* writes. Never throws: the caller's summary read follows.
|
|
2255
|
+
*/
|
|
2256
|
+
async #failUnstorableLeg(workflowId, runId, active, error) {
|
|
2257
|
+
if (!isRunStateNotStorable(error))
|
|
2258
|
+
return;
|
|
2259
|
+
const { source, requestContext } = active;
|
|
2260
|
+
if (source?.storage === 'd1' && source.replace && requestContext) {
|
|
2261
|
+
const live = Object.fromEntries(requestContext.entries());
|
|
2262
|
+
const overlay = Object.fromEntries(SELECTION_CONTEXT_KEYS.filter((key) => key in live).map((key) => [
|
|
2263
|
+
key,
|
|
2264
|
+
live[key],
|
|
2265
|
+
]));
|
|
2266
|
+
try {
|
|
2267
|
+
await this.#withLifecycleLock(workflowId, runId, () => this.#retryOnRowChange(workflowId, runId, async () => {
|
|
2268
|
+
const { state, row } = await this.#readForTransition(source, workflowId, runId);
|
|
2269
|
+
const { context, lifecycle } = overlayLegContext(state.requestContext, overlay);
|
|
2270
|
+
if (!TERMINABLE_RUN_STATUSES.has(state.status) ||
|
|
2271
|
+
lifecycle?.transitionIntent !== undefined ||
|
|
2272
|
+
RUN_SETTLING_MARKERS.some((marker) => lifecycle?.[marker] !== undefined))
|
|
2273
|
+
return;
|
|
2274
|
+
const now = Date.now();
|
|
2275
|
+
await this.#persistLifecycle(workflowId, runId, {
|
|
2276
|
+
...state,
|
|
2277
|
+
...failedByMarker('stateNotStorableAt', now),
|
|
2278
|
+
requestContext: context,
|
|
2279
|
+
}, advanceLifecycle(lifecycle, { stateNotStorableAt: now }), now, source, row);
|
|
2280
|
+
}));
|
|
2281
|
+
}
|
|
2282
|
+
catch (settleError) {
|
|
2283
|
+
console.error(JSON.stringify({
|
|
2284
|
+
type: 'run-state-not-storable-settle-failed',
|
|
2285
|
+
workflowId,
|
|
2286
|
+
runId,
|
|
2287
|
+
error: errorMessageOf(settleError),
|
|
2288
|
+
}));
|
|
2289
|
+
}
|
|
2290
|
+
}
|
|
2291
|
+
this.#abortLeg(active, new RunStateNotStorableError(workflowId, runId), 'run-leg-state-not-storable-abort', workflowId, runId);
|
|
2292
|
+
}
|
|
2036
2293
|
async #reconcileTerminalState(workflowId, runId, result, requestContext, source, proof) {
|
|
2037
2294
|
const opts = terminalStateUpdate(result);
|
|
2038
2295
|
if (!opts)
|
|
@@ -2060,21 +2317,10 @@ export class RunnerRuntime {
|
|
|
2060
2317
|
throw new RunStateUnreadableError(workflowId, runId);
|
|
2061
2318
|
if (proof)
|
|
2062
2319
|
await this.#assertRetainedResume(source, workflowId, runId, expected, proof);
|
|
2063
|
-
const persistedContext = snapshot.requestContext !== null &&
|
|
2064
|
-
typeof snapshot.requestContext === 'object' &&
|
|
2065
|
-
!Array.isArray(snapshot.requestContext)
|
|
2066
|
-
? snapshot.requestContext
|
|
2067
|
-
: {};
|
|
2068
2320
|
// Core merges resume context over the prior snapshot. Terminal-only
|
|
2069
2321
|
// repair must persist that same effective context, including application
|
|
2070
2322
|
// keys the current provider intentionally omitted.
|
|
2071
|
-
const authoritativeContext =
|
|
2072
|
-
...persistedContext,
|
|
2073
|
-
...Object.fromEntries(requestContext.entries()),
|
|
2074
|
-
};
|
|
2075
|
-
const persistedLifecycle = lifecycleFromRequestContext(persistedContext);
|
|
2076
|
-
const authoritativeLifecycle = lifecycleFromRequestContext(authoritativeContext);
|
|
2077
|
-
const reconciledLifecycle = effectiveLifecycle(persistedLifecycle, authoritativeLifecycle);
|
|
2323
|
+
const { context: authoritativeContext, persistedLifecycle, lifecycle: reconciledLifecycle, } = overlayLegContext(snapshot.requestContext, Object.fromEntries(requestContext.entries()));
|
|
2078
2324
|
if (reconciledLifecycle) {
|
|
2079
2325
|
authoritativeContext[RUN_LIFECYCLE_CONTEXT_KEY] = reconciledLifecycle;
|
|
2080
2326
|
}
|