@proofoftech/flowsafe 0.20.0 → 0.21.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 +81 -0
- package/README.md +55 -8
- package/deployment-identity-protocol.d.mts +28 -3
- package/deployment-identity-protocol.mjs +275 -21
- package/dist/agent-host/router.d.ts.map +1 -1
- package/dist/agent-host/router.js +11 -2
- package/dist/agent-host/router.js.map +1 -1
- package/dist/agent-host/thread-host.d.ts +3 -1
- package/dist/agent-host/thread-host.d.ts.map +1 -1
- package/dist/agent-host/thread-host.js +837 -332
- package/dist/agent-host/thread-host.js.map +1 -1
- package/dist/agent-host/thread-topology.d.ts +8 -0
- package/dist/agent-host/thread-topology.d.ts.map +1 -1
- package/dist/agent-host/thread-topology.js +239 -62
- package/dist/agent-host/thread-topology.js.map +1 -1
- package/dist/agent-runner/durable-agent-runner.d.ts +90 -6
- package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
- package/dist/agent-runner/durable-agent-runner.js +371 -29
- package/dist/agent-runner/durable-agent-runner.js.map +1 -1
- package/dist/agent-runner/index.d.ts +1 -1
- package/dist/agent-runner/index.d.ts.map +1 -1
- package/dist/agent-runner/index.js.map +1 -1
- package/dist/approval-api/actor-context.d.ts +4 -0
- package/dist/approval-api/actor-context.d.ts.map +1 -1
- package/dist/approval-api/actor-context.js +53 -5
- package/dist/approval-api/actor-context.js.map +1 -1
- package/dist/approval-api/principal.d.ts +1 -1
- package/dist/approval-api/principal.js +1 -1
- package/dist/approval-api/retention.d.ts +1 -2
- package/dist/approval-api/retention.d.ts.map +1 -1
- package/dist/approval-api/retention.js.map +1 -1
- package/dist/approval-api/service.d.ts +10 -14
- package/dist/approval-api/service.d.ts.map +1 -1
- package/dist/approval-api/service.js +49 -22
- package/dist/approval-api/service.js.map +1 -1
- package/dist/audit-export/index.d.ts +2 -2
- package/dist/audit-export/index.js +2 -2
- package/dist/background-tasks/d1-storage.d.ts +4 -3
- package/dist/background-tasks/d1-storage.d.ts.map +1 -1
- package/dist/background-tasks/d1-storage.js +7 -13
- package/dist/background-tasks/d1-storage.js.map +1 -1
- package/dist/do-runner/constants.d.ts +3 -0
- package/dist/do-runner/constants.d.ts.map +1 -0
- package/dist/do-runner/constants.js +3 -0
- package/dist/do-runner/constants.js.map +1 -0
- package/dist/do-runner/d1-storage.d.ts +31 -157
- package/dist/do-runner/d1-storage.d.ts.map +1 -1
- package/dist/do-runner/d1-storage.js +933 -402
- package/dist/do-runner/d1-storage.js.map +1 -1
- package/dist/do-runner/durable-object.d.ts.map +1 -1
- package/dist/do-runner/durable-object.js +462 -175
- package/dist/do-runner/durable-object.js.map +1 -1
- package/dist/do-runner/execution-admission.d.ts +114 -0
- package/dist/do-runner/execution-admission.d.ts.map +1 -0
- package/dist/do-runner/execution-admission.js +206 -0
- package/dist/do-runner/execution-admission.js.map +1 -0
- package/dist/do-runner/execution-context.d.ts.map +1 -1
- package/dist/do-runner/execution-context.js +1 -0
- package/dist/do-runner/execution-context.js.map +1 -1
- package/dist/do-runner/execution-fence.d.ts +74 -30
- package/dist/do-runner/execution-fence.d.ts.map +1 -1
- package/dist/do-runner/execution-fence.js +684 -120
- package/dist/do-runner/execution-fence.js.map +1 -1
- package/dist/do-runner/fenced-workflow-capability.d.ts +64 -0
- package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -0
- package/dist/do-runner/fenced-workflow-capability.js +3 -0
- package/dist/do-runner/fenced-workflow-capability.js.map +1 -0
- package/dist/do-runner/fenced-workflows-d1.d.ts +15 -0
- package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -0
- package/dist/do-runner/fenced-workflows-d1.js +894 -0
- package/dist/do-runner/fenced-workflows-d1.js.map +1 -0
- package/dist/do-runner/index.d.ts +13 -8
- package/dist/do-runner/index.d.ts.map +1 -1
- package/dist/do-runner/index.js +6 -2
- package/dist/do-runner/index.js.map +1 -1
- package/dist/do-runner/initial-admission-refusal.d.ts +7 -0
- package/dist/do-runner/initial-admission-refusal.d.ts.map +1 -0
- package/dist/do-runner/initial-admission-refusal.js +41 -0
- package/dist/do-runner/initial-admission-refusal.js.map +1 -0
- package/dist/do-runner/inventory.d.ts +2 -1
- package/dist/do-runner/inventory.d.ts.map +1 -1
- package/dist/do-runner/inventory.js +28 -39
- package/dist/do-runner/inventory.js.map +1 -1
- package/dist/do-runner/notification-predicate.d.ts +7 -7
- package/dist/do-runner/notification-predicate.d.ts.map +1 -1
- package/dist/do-runner/notification-predicate.js +134 -7
- package/dist/do-runner/notification-predicate.js.map +1 -1
- package/dist/do-runner/run-lifecycle.d.ts +20 -1
- package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
- package/dist/do-runner/run-lifecycle.js +67 -13
- package/dist/do-runner/run-lifecycle.js.map +1 -1
- package/dist/do-runner/run-provenance.d.ts +38 -0
- package/dist/do-runner/run-provenance.d.ts.map +1 -0
- package/dist/do-runner/run-provenance.js +152 -0
- package/dist/do-runner/run-provenance.js.map +1 -0
- package/dist/do-runner/run-storage-tables.d.ts +2 -0
- package/dist/do-runner/run-storage-tables.d.ts.map +1 -0
- package/dist/do-runner/run-storage-tables.js +4 -0
- package/dist/do-runner/run-storage-tables.js.map +1 -0
- package/dist/do-runner/run-terminal-state.d.ts +29 -0
- package/dist/do-runner/run-terminal-state.d.ts.map +1 -0
- package/dist/do-runner/run-terminal-state.js +105 -0
- package/dist/do-runner/run-terminal-state.js.map +1 -0
- package/dist/do-runner/runtime.d.ts +108 -46
- package/dist/do-runner/runtime.d.ts.map +1 -1
- package/dist/do-runner/runtime.js +927 -438
- package/dist/do-runner/runtime.js.map +1 -1
- package/dist/do-runner/start-idempotency.d.ts +35 -258
- package/dist/do-runner/start-idempotency.d.ts.map +1 -1
- package/dist/do-runner/start-idempotency.js +602 -494
- package/dist/do-runner/start-idempotency.js.map +1 -1
- package/dist/do-runner/start-reservation-contract.d.ts +103 -0
- package/dist/do-runner/start-reservation-contract.d.ts.map +1 -0
- package/dist/do-runner/start-reservation-contract.js +338 -0
- package/dist/do-runner/start-reservation-contract.js.map +1 -0
- package/dist/do-runner/suspension-deadline.d.ts +4 -11
- package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
- package/dist/do-runner/suspension-deadline.js +8 -12
- package/dist/do-runner/suspension-deadline.js.map +1 -1
- package/dist/do-runner/table-prefix.d.ts.map +1 -1
- package/dist/do-runner/table-prefix.js +2 -1
- package/dist/do-runner/table-prefix.js.map +1 -1
- package/dist/do-runner/testing.d.ts +3 -0
- package/dist/do-runner/testing.d.ts.map +1 -0
- package/dist/do-runner/testing.js +3 -0
- package/dist/do-runner/testing.js.map +1 -0
- package/dist/do-runner/thread-do.d.ts +2 -1
- package/dist/do-runner/thread-do.d.ts.map +1 -1
- package/dist/do-runner/thread-do.js +14 -10
- package/dist/do-runner/thread-do.js.map +1 -1
- package/dist/do-runner/workflow-snapshot-row.d.ts +49 -0
- package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -0
- package/dist/do-runner/workflow-snapshot-row.js +97 -0
- package/dist/do-runner/workflow-snapshot-row.js.map +1 -0
- package/dist/goals/objective-routes.d.ts +1 -5
- package/dist/goals/objective-routes.d.ts.map +1 -1
- package/dist/goals/objective-routes.js +32 -53
- package/dist/goals/objective-routes.js.map +1 -1
- package/dist/host-kit/approval-bridge.d.ts.map +1 -1
- package/dist/host-kit/approval-bridge.js +10 -7
- package/dist/host-kit/approval-bridge.js.map +1 -1
- package/dist/host-kit/do-response.d.ts +16 -0
- package/dist/host-kit/do-response.d.ts.map +1 -1
- package/dist/host-kit/do-response.js +181 -0
- package/dist/host-kit/do-response.js.map +1 -1
- package/dist/host-kit/do-run-topology.d.ts +2 -14
- package/dist/host-kit/do-run-topology.d.ts.map +1 -1
- package/dist/host-kit/do-run-topology.js +31 -24
- package/dist/host-kit/do-run-topology.js.map +1 -1
- package/dist/host-kit/env-vars.d.ts.map +1 -1
- package/dist/host-kit/env-vars.js +5 -6
- package/dist/host-kit/env-vars.js.map +1 -1
- package/dist/host-kit/flowsafe-worker.d.ts +38 -6
- package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
- package/dist/host-kit/flowsafe-worker.js +110 -93
- package/dist/host-kit/flowsafe-worker.js.map +1 -1
- package/dist/host-kit/host-approval-service.d.ts +4 -14
- package/dist/host-kit/host-approval-service.d.ts.map +1 -1
- package/dist/host-kit/host-approval-service.js +23 -40
- package/dist/host-kit/host-approval-service.js.map +1 -1
- package/dist/host-kit/index.d.ts +7 -1
- package/dist/host-kit/index.d.ts.map +1 -1
- package/dist/host-kit/index.js +4 -0
- package/dist/host-kit/index.js.map +1 -1
- package/dist/host-kit/run-route-error.d.ts +3 -17
- package/dist/host-kit/run-route-error.d.ts.map +1 -1
- package/dist/host-kit/run-route-error.js +4 -24
- package/dist/host-kit/run-route-error.js.map +1 -1
- package/dist/host-kit/run-router.d.ts +6 -2
- package/dist/host-kit/run-router.d.ts.map +1 -1
- package/dist/host-kit/run-router.js +93 -80
- package/dist/host-kit/run-router.js.map +1 -1
- package/dist/host-kit/thread-topology.d.ts +1 -1
- package/dist/host-kit/thread-topology.d.ts.map +1 -1
- package/dist/host-kit/thread-topology.js +7 -3
- package/dist/host-kit/thread-topology.js.map +1 -1
- package/dist/internal-error-response.d.ts.map +1 -1
- package/dist/internal-error-response.js +16 -6
- package/dist/internal-error-response.js.map +1 -1
- package/dist/schedules/index.d.ts +1 -0
- package/dist/schedules/index.d.ts.map +1 -1
- package/dist/schedules/index.js +1 -7
- package/dist/schedules/index.js.map +1 -1
- package/dist/schedules/mutation-contract.d.ts +38 -0
- package/dist/schedules/mutation-contract.d.ts.map +1 -0
- package/dist/schedules/mutation-contract.js +21 -0
- package/dist/schedules/mutation-contract.js.map +1 -0
- package/dist/schedules/router.d.ts +11 -19
- package/dist/schedules/router.d.ts.map +1 -1
- package/dist/schedules/router.js +130 -49
- package/dist/schedules/router.js.map +1 -1
- package/dist/schedules/schedules-d1.d.ts +11 -5
- package/dist/schedules/schedules-d1.d.ts.map +1 -1
- package/dist/schedules/schedules-d1.js +570 -143
- package/dist/schedules/schedules-d1.js.map +1 -1
- package/dist/schedules/storage.d.ts +0 -7
- package/dist/schedules/storage.d.ts.map +1 -1
- package/dist/schedules/storage.js +0 -27
- package/dist/schedules/storage.js.map +1 -1
- package/dist/schedules/tick.d.ts.map +1 -1
- package/dist/schedules/tick.js +7 -1
- package/dist/schedules/tick.js.map +1 -1
- package/dist/signal-providers/webhook-route.d.ts +1 -1
- package/dist/signal-providers/webhook-route.d.ts.map +1 -1
- package/dist/signal-providers/webhook-route.js +99 -109
- package/dist/signal-providers/webhook-route.js.map +1 -1
- package/dist/signals/d1-shared.d.ts +11 -8
- package/dist/signals/d1-shared.d.ts.map +1 -1
- package/dist/signals/d1-shared.js +1 -6
- package/dist/signals/d1-shared.js.map +1 -1
- package/dist/signals/index.d.ts +1 -1
- package/dist/signals/index.d.ts.map +1 -1
- package/dist/signals/index.js +1 -1
- package/dist/signals/index.js.map +1 -1
- package/dist/signals/notification-dispatch.d.ts +96 -5
- package/dist/signals/notification-dispatch.d.ts.map +1 -1
- package/dist/signals/notification-dispatch.js +418 -53
- package/dist/signals/notification-dispatch.js.map +1 -1
- package/dist/signals/notifications-d1.d.ts +6 -1
- package/dist/signals/notifications-d1.d.ts.map +1 -1
- package/dist/signals/notifications-d1.js +215 -10
- package/dist/signals/notifications-d1.js.map +1 -1
- package/dist/signals/router.d.ts +6 -4
- package/dist/signals/router.d.ts.map +1 -1
- package/dist/signals/router.js +49 -84
- package/dist/signals/router.js.map +1 -1
- package/dist/signals/thread-do-routes.d.ts +2 -0
- package/dist/signals/thread-do-routes.d.ts.map +1 -1
- package/dist/signals/thread-do-routes.js +252 -73
- package/dist/signals/thread-do-routes.js.map +1 -1
- package/package.json +6 -3
- package/patches/@mastra__core@1.53.0.patch +54 -0
- package/scripts/seed-deployment-identity.mjs +12 -5
|
@@ -20,13 +20,22 @@
|
|
|
20
20
|
// (see durable-object.ts).
|
|
21
21
|
import { Mastra } from '@mastra/core/mastra';
|
|
22
22
|
import { RequestContext } from '@mastra/core/request-context';
|
|
23
|
+
import { cleanStepResult, } from '@mastra/core/workflows';
|
|
23
24
|
import { isExecutionPrincipalId, isExecutionPrincipalKind, } from '../approval-api/principal.js';
|
|
24
25
|
import { BREAKWATER_ACTOR_KEY, BREAKWATER_CONNECTOR_EXECUTION_KEY, BREAKWATER_ISOLATION_SCOPE_KEY, BREAKWATER_WORKFLOW_SCOPE_KEY, } from './breakwater-keys.js';
|
|
26
|
+
import { assertMutationEpoch, ExecutionFenceUnreadableError, normalizeD1RunExecutionIdentity, normalizeMutationEpoch, normalizeStartIdentity, RunStartPendingError, } from './execution-admission.js';
|
|
25
27
|
import { isReservedExecutionContextKey, RUN_PROVENANCE_CONTEXT_KEY, stripReservedExecutionContext, } from './execution-context.js';
|
|
26
28
|
import { admitsExistingRun, admitsRunStart, ExecutionFencedError, } from './execution-fence.js';
|
|
29
|
+
import { FENCED_WORKFLOW_STORAGE, } from './fenced-workflow-capability.js';
|
|
30
|
+
import { isDefinitiveInitialAdmissionRefusal } from './initial-admission-refusal.js';
|
|
27
31
|
import { mastraRegistryEntries } from './mastra-registry.js';
|
|
28
32
|
import { isPathSafeId } from './path-safe-id.js';
|
|
29
|
-
import { canonicalEconomicOperations, canonicalReplayPrincipals, canonicalScheduleDispatch, hasDisputedSettlement, lifecycleFromRequestContext, RUN_LIFECYCLE_CONTEXT_KEY, } from './run-lifecycle.js';
|
|
33
|
+
import { canonicalEconomicOperations, canonicalReplayPrincipals, canonicalScheduleDispatch, hasDisputedSettlement, lifecycleFromRequestContext, nextLifecycleRevision, projectTerminalLifecycle, RUN_LIFECYCLE_CONTEXT_KEY, RunLifecycleBlockedError, terminalCleanupFor, } from './run-lifecycle.js';
|
|
34
|
+
import { decodeProgressRunProvenance, decodeResumeCounts, nextResumeCount, runExecutionIdentityFor, } from './run-provenance.js';
|
|
35
|
+
import { errorText, isRunStatus, isTerminalRunStatus, terminalStateFields, terminalStateUpdate, } from './run-terminal-state.js';
|
|
36
|
+
import { captureReservation, } from './start-reservation-contract.js';
|
|
37
|
+
import { validateTablePrefix } from './table-prefix.js';
|
|
38
|
+
export { RunLifecycleBlockedError, } from './run-lifecycle.js';
|
|
30
39
|
export class UnknownWorkflowError extends Error {
|
|
31
40
|
constructor(workflowId) {
|
|
32
41
|
super(`unknown workflow '${workflowId}'`);
|
|
@@ -74,14 +83,6 @@ export class RunTerminalConflictError extends Error {
|
|
|
74
83
|
this.name = 'RunTerminalConflictError';
|
|
75
84
|
}
|
|
76
85
|
}
|
|
77
|
-
export class RunLifecycleBlockedError extends Error {
|
|
78
|
-
reason;
|
|
79
|
-
constructor(reason) {
|
|
80
|
-
super(reason.message);
|
|
81
|
-
this.name = 'RunLifecycleBlockedError';
|
|
82
|
-
this.reason = reason;
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
86
|
/** A request the caller can fix: bad input/resume data or step selection. */
|
|
86
87
|
export class InvalidRunRequestError extends Error {
|
|
87
88
|
constructor(message) {
|
|
@@ -124,6 +125,8 @@ function runProvenance(state) {
|
|
|
124
125
|
if (value === null || typeof value !== 'object') {
|
|
125
126
|
throw new Error('stored run provenance is malformed');
|
|
126
127
|
}
|
|
128
|
+
if (value.version === 2)
|
|
129
|
+
return decodeProgressRunProvenance(value);
|
|
127
130
|
const candidate = value;
|
|
128
131
|
if (candidate.version !== 1 ||
|
|
129
132
|
(candidate.requestedBy !== undefined &&
|
|
@@ -138,17 +141,7 @@ function runProvenance(state) {
|
|
|
138
141
|
!Array.isArray(candidate.resumeCounts)) {
|
|
139
142
|
throw new Error('stored run provenance is malformed');
|
|
140
143
|
}
|
|
141
|
-
const counts =
|
|
142
|
-
for (const entry of candidate.resumeCounts) {
|
|
143
|
-
if (!Array.isArray(entry) ||
|
|
144
|
-
entry.length !== 2 ||
|
|
145
|
-
typeof entry[0] !== 'string' ||
|
|
146
|
-
!Number.isSafeInteger(entry[1]) ||
|
|
147
|
-
entry[1] < 1) {
|
|
148
|
-
throw new Error('stored run provenance is malformed');
|
|
149
|
-
}
|
|
150
|
-
counts.push([entry[0], entry[1]]);
|
|
151
|
-
}
|
|
144
|
+
const counts = decodeResumeCounts(candidate.resumeCounts);
|
|
152
145
|
return {
|
|
153
146
|
version: 1,
|
|
154
147
|
...(candidate.requestedBy === undefined
|
|
@@ -162,78 +155,6 @@ function runProvenance(state) {
|
|
|
162
155
|
resumeCounts: counts,
|
|
163
156
|
};
|
|
164
157
|
}
|
|
165
|
-
const NONTERMINAL_RUN_STATUSES = new Set([
|
|
166
|
-
'running',
|
|
167
|
-
'suspended',
|
|
168
|
-
'waiting',
|
|
169
|
-
'pending',
|
|
170
|
-
'paused',
|
|
171
|
-
]);
|
|
172
|
-
function terminalStateUpdate(result) {
|
|
173
|
-
if (NONTERMINAL_RUN_STATUSES.has(result.status))
|
|
174
|
-
return undefined;
|
|
175
|
-
const common = {
|
|
176
|
-
status: result.status,
|
|
177
|
-
result: undefined,
|
|
178
|
-
error: undefined,
|
|
179
|
-
suspendedPaths: {},
|
|
180
|
-
waitingPaths: {},
|
|
181
|
-
resumeLabels: {},
|
|
182
|
-
activePaths: [],
|
|
183
|
-
activeStepsPath: {},
|
|
184
|
-
};
|
|
185
|
-
if (result.status === 'success') {
|
|
186
|
-
return {
|
|
187
|
-
...common,
|
|
188
|
-
result: result.result,
|
|
189
|
-
};
|
|
190
|
-
}
|
|
191
|
-
if (result.status === 'failed') {
|
|
192
|
-
const error = result.error;
|
|
193
|
-
const name = error instanceof Error
|
|
194
|
-
? error.name
|
|
195
|
-
: error !== null &&
|
|
196
|
-
typeof error === 'object' &&
|
|
197
|
-
'name' in error &&
|
|
198
|
-
typeof error.name === 'string'
|
|
199
|
-
? error.name
|
|
200
|
-
: 'Error';
|
|
201
|
-
const stack = error instanceof Error
|
|
202
|
-
? error.stack
|
|
203
|
-
: error !== null &&
|
|
204
|
-
typeof error === 'object' &&
|
|
205
|
-
'stack' in error &&
|
|
206
|
-
typeof error.stack === 'string'
|
|
207
|
-
? error.stack
|
|
208
|
-
: undefined;
|
|
209
|
-
return {
|
|
210
|
-
...common,
|
|
211
|
-
error: {
|
|
212
|
-
name,
|
|
213
|
-
message: errorText(error),
|
|
214
|
-
...(stack !== undefined ? { stack } : {}),
|
|
215
|
-
},
|
|
216
|
-
};
|
|
217
|
-
}
|
|
218
|
-
return common;
|
|
219
|
-
}
|
|
220
|
-
// Failed runs carry the step's thrown error as an Error instance, a string,
|
|
221
|
-
// or — once it crossed an engine/persistence boundary — a serialized
|
|
222
|
-
// { name, message, stack } object; String() on the last reads
|
|
223
|
-
// '[object Object]', so extract the message wherever it lives.
|
|
224
|
-
function errorText(error) {
|
|
225
|
-
if (error instanceof Error)
|
|
226
|
-
return error.message;
|
|
227
|
-
if (typeof error === 'string')
|
|
228
|
-
return error;
|
|
229
|
-
if (error !== null &&
|
|
230
|
-
typeof error === 'object' &&
|
|
231
|
-
'message' in error &&
|
|
232
|
-
typeof error.message === 'string') {
|
|
233
|
-
return error.message;
|
|
234
|
-
}
|
|
235
|
-
return String(error);
|
|
236
|
-
}
|
|
237
158
|
function summarize(runId, result, counts, requestedBy, requestedByKind, deadlineAt) {
|
|
238
159
|
let summary;
|
|
239
160
|
switch (result.status) {
|
|
@@ -349,15 +270,6 @@ function byStep(suspendedKeys, lookup) {
|
|
|
349
270
|
}
|
|
350
271
|
return size > 0 ? map : undefined;
|
|
351
272
|
}
|
|
352
|
-
// Projection of the persisted WorkflowState for status(). Unlike summarize()
|
|
353
|
-
// (which shapes a just-finished WorkflowResult), this reads the stored
|
|
354
|
-
// snapshot: suspended paths come from suspendedPaths keys (dot-joined for
|
|
355
|
-
// nested steps) and suspend payloads from per-step results — the same keyed
|
|
356
|
-
// shape start/resume return. A tripwire status carries no reason here (the
|
|
357
|
-
// snapshot does not persist it). When the state is an in-memory approximation
|
|
358
|
-
// (isFromInMemory), steps are empty and timestamps are current-time; the
|
|
359
|
-
// projection truthfully degrades to status-only rather than fabricating
|
|
360
|
-
// detail.
|
|
361
273
|
function summarizeState(runId, state, counts, requestedBy, requestedByKind) {
|
|
362
274
|
const lifecycle = lifecycleFromRequestContext(state.requestContext);
|
|
363
275
|
const summary = {
|
|
@@ -399,6 +311,20 @@ function summarizeState(runId, state, counts, requestedBy, requestedByKind) {
|
|
|
399
311
|
}
|
|
400
312
|
return summary;
|
|
401
313
|
}
|
|
314
|
+
function summaryFromSelectedSnapshot(runId, snapshot, timestamps, provenance) {
|
|
315
|
+
const steps = Object.fromEntries(Object.entries(snapshot.context ?? {})
|
|
316
|
+
.filter(([key]) => key !== 'input' && key !== '__state')
|
|
317
|
+
.map(([key, value]) => [key, cleanStepResult(value)]));
|
|
318
|
+
return summarizeState(runId, {
|
|
319
|
+
status: snapshot.status,
|
|
320
|
+
result: snapshot.result,
|
|
321
|
+
error: snapshot.error,
|
|
322
|
+
requestContext: snapshot.requestContext,
|
|
323
|
+
suspendedPaths: snapshot.suspendedPaths,
|
|
324
|
+
steps,
|
|
325
|
+
...timestamps,
|
|
326
|
+
}, provenance ? new Map(provenance.resumeCounts) : undefined, provenance?.requestedBy, provenance?.requestedByKind);
|
|
327
|
+
}
|
|
402
328
|
function summaryWithRequester(summary, requestedBy, requestedByKind) {
|
|
403
329
|
if (requestedBy !== undefined)
|
|
404
330
|
summary.requestedBy = requestedBy;
|
|
@@ -466,6 +392,130 @@ function relativeDeadline(deadlineMs, now = Date.now()) {
|
|
|
466
392
|
}
|
|
467
393
|
return deadlineAt;
|
|
468
394
|
}
|
|
395
|
+
function captureStartRunOptions(source) {
|
|
396
|
+
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;
|
|
397
|
+
if (requestedBy !== undefined && !isExecutionPrincipalId(requestedBy)) {
|
|
398
|
+
throw new InvalidRunRequestError('requestedBy is malformed');
|
|
399
|
+
}
|
|
400
|
+
if (requestedByKind !== undefined &&
|
|
401
|
+
!isExecutionPrincipalKind(requestedByKind)) {
|
|
402
|
+
throw new InvalidRunRequestError('requestedByKind is malformed');
|
|
403
|
+
}
|
|
404
|
+
if ((requestedBy === undefined) !== (requestedByKind === undefined)) {
|
|
405
|
+
throw new InvalidRunRequestError('requestedBy and requestedByKind must be provided together');
|
|
406
|
+
}
|
|
407
|
+
const mutationEpoch = normalizeMutationEpoch(rawEpoch);
|
|
408
|
+
const startIdentity = rawIdentity === undefined ? undefined : normalizeStartIdentity(rawIdentity);
|
|
409
|
+
const startReservation = rawReservation === undefined
|
|
410
|
+
? undefined
|
|
411
|
+
: captureReservation(rawReservation, 'started');
|
|
412
|
+
let agentStart;
|
|
413
|
+
if (rawAgentStart !== undefined) {
|
|
414
|
+
if (rawAgentStart === null ||
|
|
415
|
+
typeof rawAgentStart !== 'object' ||
|
|
416
|
+
Array.isArray(rawAgentStart)) {
|
|
417
|
+
throw new InvalidRunRequestError('agentStart is malformed');
|
|
418
|
+
}
|
|
419
|
+
const { threaded } = rawAgentStart;
|
|
420
|
+
if (typeof threaded !== 'boolean') {
|
|
421
|
+
throw new InvalidRunRequestError('agentStart is malformed');
|
|
422
|
+
}
|
|
423
|
+
agentStart = Object.freeze({ threaded });
|
|
424
|
+
}
|
|
425
|
+
if (agentStart !== undefined && startIdentity?.target.kind !== 'agent')
|
|
426
|
+
throw new InvalidRunRequestError('agentStart has no agent target');
|
|
427
|
+
if (startIdentity?.target.kind === 'agent' && agentStart === undefined) {
|
|
428
|
+
throw new InvalidRunRequestError('agentStart is required for an agent target');
|
|
429
|
+
}
|
|
430
|
+
if (startIdentity &&
|
|
431
|
+
(startIdentity.owner.id !== requestedBy ||
|
|
432
|
+
startIdentity.owner.kind !== requestedByKind)) {
|
|
433
|
+
throw new InvalidRunRequestError('startIdentity owner does not match requester');
|
|
434
|
+
}
|
|
435
|
+
if (onPreparedStartIdentity !== undefined &&
|
|
436
|
+
typeof onPreparedStartIdentity !== 'function') {
|
|
437
|
+
throw new InvalidRunRequestError('onPreparedStartIdentity is malformed');
|
|
438
|
+
}
|
|
439
|
+
let runOwnerGuard;
|
|
440
|
+
if (rawGuard !== undefined) {
|
|
441
|
+
if (rawGuard === null ||
|
|
442
|
+
typeof rawGuard !== 'object' ||
|
|
443
|
+
Array.isArray(rawGuard)) {
|
|
444
|
+
throw new InvalidRunRequestError('runOwnerGuard is malformed');
|
|
445
|
+
}
|
|
446
|
+
const { owner: rawOwner, reservationToken } = rawGuard;
|
|
447
|
+
if (rawOwner === null ||
|
|
448
|
+
typeof rawOwner !== 'object' ||
|
|
449
|
+
Array.isArray(rawOwner)) {
|
|
450
|
+
throw new InvalidRunRequestError('runOwnerGuard is malformed');
|
|
451
|
+
}
|
|
452
|
+
const { kind, id } = rawOwner;
|
|
453
|
+
if (!isExecutionPrincipalKind(kind) ||
|
|
454
|
+
!isExecutionPrincipalId(id) ||
|
|
455
|
+
!isPathSafeId(reservationToken)) {
|
|
456
|
+
throw new InvalidRunRequestError('runOwnerGuard is malformed');
|
|
457
|
+
}
|
|
458
|
+
runOwnerGuard = Object.freeze({
|
|
459
|
+
owner: Object.freeze({ kind, id }),
|
|
460
|
+
reservationToken,
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
if (deadlineMs !== undefined &&
|
|
464
|
+
(!Number.isSafeInteger(deadlineMs) || deadlineMs < 0)) {
|
|
465
|
+
throw new InvalidRunRequestError('deadlineMs must be a nonnegative safe integer');
|
|
466
|
+
}
|
|
467
|
+
let dispatch;
|
|
468
|
+
if (rawDispatch !== undefined) {
|
|
469
|
+
if (rawDispatch === null ||
|
|
470
|
+
typeof rawDispatch !== 'object' ||
|
|
471
|
+
Array.isArray(rawDispatch)) {
|
|
472
|
+
throw new Error('stored run lifecycle is malformed');
|
|
473
|
+
}
|
|
474
|
+
const { scheduleId, dispatchId } = rawDispatch;
|
|
475
|
+
dispatch = { scheduleId, dispatchId };
|
|
476
|
+
}
|
|
477
|
+
let operations;
|
|
478
|
+
if (rawOperations !== undefined) {
|
|
479
|
+
if (!Array.isArray(rawOperations)) {
|
|
480
|
+
throw new Error('stored run lifecycle is malformed');
|
|
481
|
+
}
|
|
482
|
+
const length = rawOperations.length;
|
|
483
|
+
if (!Number.isSafeInteger(length) || length < 0 || length > 0xffff_ffff) {
|
|
484
|
+
throw new Error('stored run lifecycle is malformed');
|
|
485
|
+
}
|
|
486
|
+
operations = new Array(length);
|
|
487
|
+
for (let index = 0; index < length; index++) {
|
|
488
|
+
if (!(index in rawOperations))
|
|
489
|
+
throw new Error('stored run lifecycle is malformed');
|
|
490
|
+
const entry = rawOperations[index];
|
|
491
|
+
if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) {
|
|
492
|
+
throw new Error('stored run lifecycle is malformed');
|
|
493
|
+
}
|
|
494
|
+
const { id, settlementState } = entry;
|
|
495
|
+
operations[index] = { id, settlementState };
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
const captured = {
|
|
499
|
+
runId,
|
|
500
|
+
inputData,
|
|
501
|
+
initialState,
|
|
502
|
+
storedRequestContext,
|
|
503
|
+
attemptToken,
|
|
504
|
+
deadlineMs,
|
|
505
|
+
economicOperations: canonicalEconomicOperations(operations),
|
|
506
|
+
scheduleDispatch: canonicalScheduleDispatch(dispatch),
|
|
507
|
+
idempotencyKey,
|
|
508
|
+
mutationEpoch,
|
|
509
|
+
startIdentity,
|
|
510
|
+
agentStart,
|
|
511
|
+
onPreparedStartIdentity,
|
|
512
|
+
runOwnerGuard,
|
|
513
|
+
startReservation,
|
|
514
|
+
};
|
|
515
|
+
return Object.freeze(requestedBy !== undefined && requestedByKind !== undefined
|
|
516
|
+
? { ...captured, requestedBy, requestedByKind }
|
|
517
|
+
: captured);
|
|
518
|
+
}
|
|
469
519
|
function lifecycleForStart(options) {
|
|
470
520
|
const deadlineAt = relativeDeadline(options.deadlineMs);
|
|
471
521
|
const economicOperations = canonicalEconomicOperations(options.economicOperations);
|
|
@@ -505,6 +555,26 @@ function effectiveLifecycle(persisted, active) {
|
|
|
505
555
|
: {}),
|
|
506
556
|
};
|
|
507
557
|
}
|
|
558
|
+
function sameExecution(a, b) {
|
|
559
|
+
return (a.tablePrefix === b.tablePrefix &&
|
|
560
|
+
a.workflowId === b.workflowId &&
|
|
561
|
+
a.runId === b.runId &&
|
|
562
|
+
a.startToken === b.startToken);
|
|
563
|
+
}
|
|
564
|
+
function assertClaimIdentity(claim, execution, key = claim.key) {
|
|
565
|
+
if (claim.key !== key ||
|
|
566
|
+
claim.runId !== execution.runId ||
|
|
567
|
+
claim.owner.id !== execution.owner.id ||
|
|
568
|
+
claim.owner.kind !== execution.owner.kind ||
|
|
569
|
+
claim.targetKind !== execution.target.kind ||
|
|
570
|
+
claim.targetId !== execution.target.id ||
|
|
571
|
+
claim.threadId !==
|
|
572
|
+
(execution.target.kind === 'agent'
|
|
573
|
+
? execution.target.threadId
|
|
574
|
+
: undefined)) {
|
|
575
|
+
throw new InvalidRunRequestError('start reservation disagrees with execution identity');
|
|
576
|
+
}
|
|
577
|
+
}
|
|
508
578
|
export class RunnerRuntime {
|
|
509
579
|
#storage;
|
|
510
580
|
#logger;
|
|
@@ -611,171 +681,269 @@ export class RunnerRuntime {
|
|
|
611
681
|
workflowIds() {
|
|
612
682
|
return [...this.#workflows.keys()];
|
|
613
683
|
}
|
|
614
|
-
|
|
615
|
-
* The fence check every mint passes. In proof-only the admitted start also
|
|
616
|
-
* BINDS the proof to its run id, and that write-back is conditional: between
|
|
617
|
-
* the read that admitted it and the write another start may have claimed the
|
|
618
|
-
* proof, or the operator may have moved the fence on. Zero rows changed
|
|
619
|
-
* therefore refuses the start — the deployment is no longer the one this
|
|
620
|
-
* start read.
|
|
621
|
-
*/
|
|
622
|
-
async #assertStartFence(runId, idempotencyKey) {
|
|
684
|
+
async #assertStartFence(idempotencyKey, mutationEpoch) {
|
|
623
685
|
const fence = this.#executionFence;
|
|
624
686
|
if (!fence)
|
|
625
687
|
return;
|
|
626
688
|
const reading = await fence.read();
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
}
|
|
630
|
-
if (reading.state !== 'proof-only' || reading.proofKey === undefined) {
|
|
631
|
-
return;
|
|
632
|
-
}
|
|
633
|
-
if (!(await fence.recordProofRun(reading.proofKey, runId))) {
|
|
689
|
+
assertMutationEpoch(reading, mutationEpoch);
|
|
690
|
+
if (!admitsRunStart(reading, idempotencyKey))
|
|
634
691
|
throw new ExecutionFencedError(reading.state, 'run start');
|
|
635
|
-
|
|
692
|
+
if (reading.state === 'proof-only' && reading.proofKey !== undefined)
|
|
693
|
+
return Object.freeze({
|
|
694
|
+
key: reading.proofKey,
|
|
695
|
+
mutationEpoch: reading.mutationEpoch,
|
|
696
|
+
transitionRevision: reading.transitionRevision,
|
|
697
|
+
});
|
|
636
698
|
}
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
*
|
|
640
|
-
* BEST EFFORT, and deliberately so: the run has already reached a terminal
|
|
641
|
-
* state and its snapshot is already persisted, so failing the caller here
|
|
642
|
-
* would turn a completed run into an error response — while the reconcile it
|
|
643
|
-
* failed to make costs only the LATER answer's precision (a purged run
|
|
644
|
-
* replays as UNRESOLVABLE rather than ALREADY_SETTLED, which refuses either
|
|
645
|
-
* way). The retention purge marks any reservation this missed, so a swallowed
|
|
646
|
-
* failure heals rather than accumulating.
|
|
647
|
-
*/
|
|
648
|
-
async #settleStartReservation(runId) {
|
|
649
|
-
const store = this.#startIdempotency;
|
|
650
|
-
if (!store)
|
|
699
|
+
async #settleStartReservation(state) {
|
|
700
|
+
if (state.kind !== 'result' || !isTerminalRunStatus(state.summary.status))
|
|
651
701
|
return;
|
|
652
702
|
try {
|
|
653
|
-
await
|
|
703
|
+
await this.settleStartExecution(state);
|
|
654
704
|
}
|
|
655
705
|
catch (error) {
|
|
656
706
|
console.error(JSON.stringify({
|
|
657
707
|
type: 'start-reservation-settle-failed',
|
|
658
|
-
runId,
|
|
708
|
+
runId: state.execution.runId,
|
|
659
709
|
error: error instanceof Error ? error.message : String(error),
|
|
660
710
|
}));
|
|
661
711
|
}
|
|
662
712
|
}
|
|
663
|
-
|
|
664
|
-
async #assertResumeFence(runId) {
|
|
713
|
+
async #assertResumeFence(workflowId, runId) {
|
|
665
714
|
const fence = this.#executionFence;
|
|
666
715
|
if (!fence)
|
|
667
716
|
return;
|
|
668
717
|
const reading = await fence.read();
|
|
669
|
-
if (
|
|
718
|
+
if (reading.state === 'open' || reading.state === 'draining')
|
|
719
|
+
return;
|
|
720
|
+
if (reading.state === 'migration-locked')
|
|
670
721
|
throw new ExecutionFencedError(reading.state, 'run resume');
|
|
671
|
-
|
|
722
|
+
const state = await this.authoritativeStartState(workflowId, runId);
|
|
723
|
+
if (state?.storage !== 'd1' || !admitsExistingRun(reading, state.execution))
|
|
724
|
+
throw new ExecutionFencedError(reading.state, 'run resume');
|
|
725
|
+
return state.execution;
|
|
672
726
|
}
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
if (!
|
|
686
|
-
throw new
|
|
727
|
+
/** @internal Retain this physical proof expectation across preparation waits. */
|
|
728
|
+
assertExistingRunAllowed(workflowId, runId) {
|
|
729
|
+
return this.#assertResumeFence(workflowId, runId);
|
|
730
|
+
}
|
|
731
|
+
async #assertRetainedResume(source, workflowId, runId, expected, proof) {
|
|
732
|
+
const reading = this.#executionFence
|
|
733
|
+
? await this.#executionFence.read()
|
|
734
|
+
: undefined;
|
|
735
|
+
const snapshot = await source.load.call(source.workflows, {
|
|
736
|
+
workflowName: workflowId,
|
|
737
|
+
runId,
|
|
738
|
+
});
|
|
739
|
+
if (!snapshot)
|
|
740
|
+
throw new UnknownRunError(workflowId, runId);
|
|
741
|
+
if (snapshot.runId !== runId)
|
|
742
|
+
throw new RunStateUnreadableError(workflowId, runId);
|
|
743
|
+
const current = runProvenance(snapshot);
|
|
744
|
+
if (expected?.version === 2 &&
|
|
745
|
+
(current?.version !== 2 || current.startToken !== expected.startToken))
|
|
746
|
+
throw new RunStateUnreadableError(workflowId, runId);
|
|
747
|
+
if (proof &&
|
|
748
|
+
(source.tablePrefix !== proof.tablePrefix ||
|
|
749
|
+
current?.version !== 2 ||
|
|
750
|
+
current.startToken !== proof.startToken))
|
|
751
|
+
throw new RunStateUnreadableError(workflowId, runId);
|
|
752
|
+
if (reading) {
|
|
753
|
+
const execution = current?.version === 2
|
|
754
|
+
? runExecutionIdentityFor({ tablePrefix: source.tablePrefix, workflowId, runId }, current)
|
|
755
|
+
: undefined;
|
|
756
|
+
if (!admitsExistingRun(reading, execution) ||
|
|
757
|
+
(proof && (!execution || !sameExecution(proof, execution))))
|
|
758
|
+
throw new ExecutionFencedError(reading.state, 'run resume');
|
|
687
759
|
}
|
|
760
|
+
return snapshot;
|
|
761
|
+
}
|
|
762
|
+
async #completedStartState(source, execution, expected) {
|
|
763
|
+
const state = await this.#readStartState(source, execution.workflowId, execution.runId);
|
|
764
|
+
if (!state ||
|
|
765
|
+
state.kind === 'legacy' ||
|
|
766
|
+
!sameExecution(state.execution, execution) ||
|
|
767
|
+
state.provenance.version !== expected.version ||
|
|
768
|
+
state.provenance.attemptToken !== expected.attemptToken)
|
|
769
|
+
throw new RunStateUnreadableError(execution.workflowId, execution.runId);
|
|
770
|
+
if (state.kind === 'initial')
|
|
771
|
+
throw new RunStartPendingError();
|
|
772
|
+
return state;
|
|
773
|
+
}
|
|
774
|
+
async start(workflowId, sourceOptions) {
|
|
775
|
+
const options = captureStartRunOptions(sourceOptions);
|
|
688
776
|
const runId = options.runId;
|
|
689
|
-
if (
|
|
690
|
-
|
|
691
|
-
throw new InvalidRunRequestError('requestedBy is malformed');
|
|
692
|
-
}
|
|
693
|
-
if (options.requestedByKind !== undefined &&
|
|
694
|
-
!isExecutionPrincipalKind(options.requestedByKind)) {
|
|
695
|
-
throw new InvalidRunRequestError('requestedByKind is malformed');
|
|
696
|
-
}
|
|
697
|
-
if ((options.requestedBy === undefined) !==
|
|
698
|
-
(options.requestedByKind === undefined)) {
|
|
699
|
-
throw new InvalidRunRequestError('requestedBy and requestedByKind must be provided together');
|
|
700
|
-
}
|
|
777
|
+
if (!isPathSafeId(runId))
|
|
778
|
+
throw new InvalidRunRequestError('runId is required and must be URL-path-safe');
|
|
701
779
|
if (options.attemptToken !== undefined &&
|
|
702
|
-
!isPathSafeId(options.attemptToken))
|
|
780
|
+
!isPathSafeId(options.attemptToken))
|
|
703
781
|
throw new InvalidRunRequestError('attemptToken is malformed');
|
|
782
|
+
const startIdentity = options.startIdentity ??
|
|
783
|
+
(options.requestedBy === undefined
|
|
784
|
+
? undefined
|
|
785
|
+
: normalizeStartIdentity({
|
|
786
|
+
owner: { id: options.requestedBy, kind: options.requestedByKind },
|
|
787
|
+
target: { kind: 'workflow', id: workflowId },
|
|
788
|
+
}));
|
|
789
|
+
const claim = options.startReservation;
|
|
790
|
+
if (claim) {
|
|
791
|
+
if (!startIdentity || !this.#startIdempotency)
|
|
792
|
+
throw new InvalidRunRequestError('start reservation requires configured store and identity');
|
|
793
|
+
if (options.idempotencyKey !== claim.key)
|
|
794
|
+
throw new InvalidRunRequestError('start reservation key disagrees with execution');
|
|
795
|
+
assertClaimIdentity(claim, { ...startIdentity, runId }, options.idempotencyKey);
|
|
704
796
|
}
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
797
|
+
let preflight = true;
|
|
798
|
+
const releasePreflight = async () => {
|
|
799
|
+
if (preflight && claim && this.#startIdempotency)
|
|
800
|
+
await this.#startIdempotency.releaseReservation(claim);
|
|
801
|
+
};
|
|
802
|
+
try {
|
|
803
|
+
const workflow = this.#getWorkflow(workflowId);
|
|
804
|
+
if (startIdentity?.target.kind === 'workflow' &&
|
|
805
|
+
startIdentity.target.id !== workflow.id)
|
|
806
|
+
throw new InvalidRunRequestError('startIdentity target does not match workflow');
|
|
807
|
+
const proof = await this.#assertStartFence(options.idempotencyKey, options.mutationEpoch);
|
|
808
|
+
return await this.#withRunLock(workflowId, runId, async () => {
|
|
809
|
+
const activeKey = this.#runKey(workflowId, runId);
|
|
810
|
+
const active = {};
|
|
811
|
+
if (this.#activeRuns.has(activeKey))
|
|
812
|
+
throw new RunAlreadyExistsError(workflowId, runId, 'running');
|
|
813
|
+
this.#activeRuns.set(activeKey, active);
|
|
814
|
+
let execution;
|
|
815
|
+
let engineEntered = false;
|
|
816
|
+
let outcomeReadStarted = false;
|
|
817
|
+
let admissionEntered = false;
|
|
818
|
+
let candidate;
|
|
819
|
+
const originalCached = workflow.runs.get(runId);
|
|
820
|
+
let provenance;
|
|
821
|
+
try {
|
|
822
|
+
const existing = await workflow.getWorkflowRunById(runId);
|
|
823
|
+
if (existing || originalCached)
|
|
824
|
+
throw new RunAlreadyExistsError(workflowId, runId, existing?.status ?? 'pending');
|
|
825
|
+
const source = await this.#captureWorkflowStorage(workflow);
|
|
826
|
+
active.source = source;
|
|
827
|
+
provenance = {
|
|
828
|
+
version: 2,
|
|
829
|
+
startToken: crypto.randomUUID(),
|
|
830
|
+
attemptToken: options.attemptToken ?? crypto.randomUUID(),
|
|
831
|
+
resumeCounts: [],
|
|
832
|
+
...(options.requestedBy === undefined
|
|
833
|
+
? {}
|
|
834
|
+
: {
|
|
835
|
+
requestedBy: options.requestedBy,
|
|
836
|
+
requestedByKind: options.requestedByKind,
|
|
837
|
+
}),
|
|
838
|
+
...(startIdentity ? { startIdentity } : {}),
|
|
839
|
+
...(options.agentStart ? { agentStart: options.agentStart } : {}),
|
|
840
|
+
...(options.mutationEpoch === undefined
|
|
841
|
+
? {}
|
|
842
|
+
: { mutationEpoch: options.mutationEpoch }),
|
|
843
|
+
};
|
|
844
|
+
execution = runExecutionIdentityFor({ tablePrefix: source.tablePrefix, workflowId, runId }, provenance);
|
|
845
|
+
const lifecycle = lifecycleForStart(options);
|
|
846
|
+
active.lifecycle = lifecycle;
|
|
847
|
+
preflight = false;
|
|
848
|
+
const requestContext = await this.#requestContextFor(workflowId, runId, { kind: 'start' }, provenance, options.storedRequestContext, lifecycle);
|
|
849
|
+
active.requestContext = requestContext;
|
|
850
|
+
if (options.onPreparedStartIdentity)
|
|
851
|
+
await Reflect.apply(options.onPreparedStartIdentity, undefined, [
|
|
852
|
+
execution,
|
|
853
|
+
]);
|
|
854
|
+
const capturedExecution = execution;
|
|
855
|
+
const capturedProvenance = provenance;
|
|
856
|
+
const { executionPromise } = await this.#withLifecycleLock(workflowId, runId, async () => {
|
|
857
|
+
let run;
|
|
858
|
+
if (this.#executionFence) {
|
|
859
|
+
if (source.storage !== 'd1')
|
|
860
|
+
throw new Error('fenced workflow storage capability is unavailable');
|
|
861
|
+
const d1Execution = normalizeD1RunExecutionIdentity(capturedExecution);
|
|
862
|
+
admissionEntered = true;
|
|
863
|
+
const admitted = await source.admit.call(source.capability, {
|
|
864
|
+
execution: d1Execution,
|
|
865
|
+
attemptToken: capturedProvenance.attemptToken,
|
|
866
|
+
mutationEpoch: options.mutationEpoch,
|
|
867
|
+
startIdentity,
|
|
868
|
+
requestContext: Object.fromEntries(requestContext.entries()),
|
|
869
|
+
fence: this.#executionFence,
|
|
870
|
+
reservationStore: claim
|
|
871
|
+
? this.#startIdempotency
|
|
872
|
+
: undefined,
|
|
873
|
+
reservation: claim,
|
|
874
|
+
proof,
|
|
875
|
+
runOwnerGuard: options.runOwnerGuard,
|
|
876
|
+
onInitialWriteAttempt: () => {
|
|
877
|
+
candidate = workflow.runs.get(runId);
|
|
878
|
+
},
|
|
879
|
+
}, () => workflow.createRun({ runId, pubsub: this.#pubsub }));
|
|
880
|
+
if (!admitted?.witness ||
|
|
881
|
+
!sameExecution(admitted.witness.execution, d1Execution))
|
|
882
|
+
throw new RunStateUnreadableError(workflowId, runId);
|
|
883
|
+
const witnessed = this.#projectD1StartState(source, workflowId, runId, admitted.witness.row);
|
|
884
|
+
if (witnessed.kind !== 'initial' ||
|
|
885
|
+
!sameExecution(witnessed.execution, d1Execution) ||
|
|
886
|
+
witnessed.provenance.initialAdmission !== true ||
|
|
887
|
+
witnessed.provenance.attemptToken !==
|
|
888
|
+
capturedProvenance.attemptToken)
|
|
889
|
+
throw new RunStateUnreadableError(workflowId, runId);
|
|
890
|
+
run = admitted.value;
|
|
891
|
+
}
|
|
892
|
+
else {
|
|
893
|
+
if (claim && startIdentity && this.#startIdempotency)
|
|
894
|
+
await this.#startIdempotency.bindPreparedStart(claim, {
|
|
895
|
+
...capturedExecution,
|
|
896
|
+
...startIdentity,
|
|
897
|
+
});
|
|
898
|
+
run = await workflow.createRun({ runId, pubsub: this.#pubsub });
|
|
899
|
+
}
|
|
900
|
+
active.run = run;
|
|
901
|
+
engineEntered = true;
|
|
902
|
+
return {
|
|
903
|
+
executionPromise: run.start({
|
|
904
|
+
inputData: options.inputData,
|
|
905
|
+
initialState: options.initialState,
|
|
906
|
+
requestContext,
|
|
907
|
+
}),
|
|
908
|
+
};
|
|
909
|
+
});
|
|
910
|
+
const result = await executionPromise;
|
|
911
|
+
await this.#reconcileTerminalState(workflowId, runId, result, requestContext, source);
|
|
912
|
+
outcomeReadStarted = true;
|
|
913
|
+
const selected = await this.#completedStartState(source, capturedExecution, provenance);
|
|
914
|
+
await this.#settleStartReservation(selected);
|
|
915
|
+
return selected.summary;
|
|
766
916
|
}
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
917
|
+
catch (error) {
|
|
918
|
+
if (admissionEntered &&
|
|
919
|
+
!engineEntered &&
|
|
920
|
+
execution?.tablePrefix !== null &&
|
|
921
|
+
execution !== undefined &&
|
|
922
|
+
isDefinitiveInitialAdmissionRefusal(error, normalizeD1RunExecutionIdentity(execution))) {
|
|
923
|
+
if (candidate &&
|
|
924
|
+
candidate !== originalCached &&
|
|
925
|
+
workflow.runs.get(runId) === candidate)
|
|
926
|
+
workflow.runs.delete(runId);
|
|
927
|
+
if (claim && this.#startIdempotency)
|
|
928
|
+
await this.#startIdempotency.releaseReservation(claim);
|
|
929
|
+
}
|
|
930
|
+
if (engineEntered && provenance && !outcomeReadStarted) {
|
|
931
|
+
const recovered = await this.#summaryForAttempt(workflow, runId, provenance);
|
|
932
|
+
if (recovered)
|
|
933
|
+
return recovered;
|
|
934
|
+
}
|
|
935
|
+
throw asClientError(error) ?? error;
|
|
936
|
+
}
|
|
937
|
+
finally {
|
|
938
|
+
if (this.#activeRuns.get(activeKey) === active)
|
|
939
|
+
this.#activeRuns.delete(activeKey);
|
|
940
|
+
}
|
|
941
|
+
});
|
|
942
|
+
}
|
|
943
|
+
catch (error) {
|
|
944
|
+
await releasePreflight();
|
|
945
|
+
throw error;
|
|
946
|
+
}
|
|
779
947
|
}
|
|
780
948
|
/**
|
|
781
949
|
* Reattach to a suspended run — the designed fresh-process pattern:
|
|
@@ -784,89 +952,88 @@ export class RunnerRuntime {
|
|
|
784
952
|
*/
|
|
785
953
|
async resume(workflowId, runId, options = {}) {
|
|
786
954
|
const workflow = this.#getWorkflow(workflowId);
|
|
787
|
-
|
|
788
|
-
// waiting for exactly these — so only migration-locked and proof-only
|
|
789
|
-
// block here, and proof-only admits its one nominated run.
|
|
790
|
-
await this.#assertResumeFence(runId);
|
|
955
|
+
const proof = await this.#assertResumeFence(workflowId, runId);
|
|
791
956
|
return this.#withRunLock(workflowId, runId, async () => {
|
|
792
|
-
const state = await this.#workflowState(workflow, runId);
|
|
793
|
-
if (!state)
|
|
794
|
-
throw new UnknownRunError(workflowId, runId);
|
|
795
|
-
if (state.status !== 'suspended') {
|
|
796
|
-
throw new RunNotSuspendedError(workflowId, runId, state.status);
|
|
797
|
-
}
|
|
798
|
-
// Provider before createRun for symmetry with start(): a resume-time
|
|
799
|
-
// createRun only reattaches (no snapshot write), but failing before it
|
|
800
|
-
// still does the least work and keeps the ordering invariant uniform.
|
|
801
|
-
const { nextCounts, provenance, requestContext, lifecycle } = await this.#trustedResumePreparation(workflowId, runId, state, options.step, options.requestedBy, options.requestedByKind, options.deadlineMs, options.economicOperations);
|
|
802
957
|
const activeKey = this.#runKey(workflowId, runId);
|
|
803
|
-
const active = {
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
throw new RunTerminalConflictError(workflowId, runId, current.status);
|
|
811
|
-
}
|
|
812
|
-
active.lifecycle = effectiveLifecycle(currentLifecycle, lifecycle);
|
|
813
|
-
this.#activeRuns.set(activeKey, active);
|
|
814
|
-
});
|
|
815
|
-
let run;
|
|
816
|
-
let result;
|
|
958
|
+
const active = {};
|
|
959
|
+
if (this.#activeRuns.has(activeKey))
|
|
960
|
+
throw new RunTerminalConflictError(workflowId, runId, 'running');
|
|
961
|
+
this.#activeRuns.set(activeKey, active);
|
|
962
|
+
let provenance;
|
|
963
|
+
let engineEntered = false;
|
|
964
|
+
let outcomeReadStarted = false;
|
|
817
965
|
try {
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
966
|
+
const source = await this.#captureWorkflowStorage(workflow);
|
|
967
|
+
active.source = source;
|
|
968
|
+
const state = await this.#workflowState(workflow, runId, true);
|
|
969
|
+
if (!state)
|
|
970
|
+
throw new UnknownRunError(workflowId, runId);
|
|
971
|
+
if (state.isFromInMemory)
|
|
972
|
+
throw new RunStateUnreadableError(workflowId, runId);
|
|
973
|
+
const prior = runProvenance(state);
|
|
974
|
+
if (proof &&
|
|
975
|
+
(prior?.version !== 2 ||
|
|
976
|
+
prior.startToken !== proof.startToken ||
|
|
977
|
+
source.tablePrefix !== proof.tablePrefix))
|
|
978
|
+
throw new RunStateUnreadableError(workflowId, runId);
|
|
979
|
+
if (state.status !== 'suspended')
|
|
980
|
+
throw new RunNotSuspendedError(workflowId, runId, state.status);
|
|
981
|
+
const prepared = await this.#trustedResumePreparation(workflowId, runId, state, options.step, options.requestedBy, options.requestedByKind, options.deadlineMs, options.economicOperations);
|
|
982
|
+
provenance = prepared.provenance;
|
|
983
|
+
const { requestContext, lifecycle, nextCounts } = prepared;
|
|
984
|
+
active.requestContext = requestContext;
|
|
985
|
+
active.lifecycle = lifecycle;
|
|
986
|
+
const check = async () => {
|
|
987
|
+
const current = await this.#assertRetainedResume(source, workflowId, runId, prior, proof);
|
|
829
988
|
const currentLifecycle = lifecycleFromRequestContext(current.requestContext);
|
|
830
989
|
if (currentLifecycle?.terminal ||
|
|
831
990
|
currentLifecycle?.transitionIntent ||
|
|
832
|
-
this.#activeRuns.get(activeKey) !== active)
|
|
991
|
+
this.#activeRuns.get(activeKey) !== active)
|
|
833
992
|
throw new RunTerminalConflictError(workflowId, runId, current.status);
|
|
834
|
-
}
|
|
835
993
|
active.lifecycle = effectiveLifecycle(currentLifecycle, active.lifecycle);
|
|
994
|
+
};
|
|
995
|
+
await this.#withLifecycleLock(workflowId, runId, check);
|
|
996
|
+
if (options.prepareExecution) {
|
|
997
|
+
const values = structuredClone(Object.fromEntries(requestContext.entries()));
|
|
998
|
+
await options.prepareExecution(new RequestContext(Object.entries(values)));
|
|
999
|
+
await this.#withLifecycleLock(workflowId, runId, check);
|
|
1000
|
+
}
|
|
1001
|
+
const run = await workflow.createRun({ runId, pubsub: this.#pubsub });
|
|
1002
|
+
const { executionPromise } = await this.#withLifecycleLock(workflowId, runId, async () => {
|
|
1003
|
+
await check();
|
|
836
1004
|
active.run = run;
|
|
1005
|
+
engineEntered = true;
|
|
1006
|
+
return {
|
|
1007
|
+
executionPromise: run.resume({
|
|
1008
|
+
step: options.step,
|
|
1009
|
+
resumeData: options.resumeData,
|
|
1010
|
+
requestContext,
|
|
1011
|
+
}),
|
|
1012
|
+
};
|
|
837
1013
|
});
|
|
838
|
-
result = await
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
1014
|
+
const result = await executionPromise;
|
|
1015
|
+
await this.#reconcileTerminalState(workflowId, runId, result, requestContext, source, proof);
|
|
1016
|
+
if (provenance.version === 2) {
|
|
1017
|
+
const execution = runExecutionIdentityFor({ tablePrefix: source.tablePrefix, workflowId, runId }, provenance);
|
|
1018
|
+
outcomeReadStarted = true;
|
|
1019
|
+
const selected = await this.#completedStartState(source, execution, provenance);
|
|
1020
|
+
await this.#settleStartReservation(selected);
|
|
1021
|
+
return selected.summary;
|
|
1022
|
+
}
|
|
1023
|
+
return summarize(runId, result, nextCounts, provenance.requestedBy, provenance.requestedByKind, lifecycle?.deadlineAt);
|
|
843
1024
|
}
|
|
844
1025
|
catch (error) {
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
1026
|
+
if (engineEntered && provenance && !outcomeReadStarted) {
|
|
1027
|
+
const recovered = await this.#summaryForAttempt(workflow, runId, provenance);
|
|
1028
|
+
if (recovered)
|
|
1029
|
+
return recovered;
|
|
1030
|
+
}
|
|
850
1031
|
throw asClientError(error) ?? error;
|
|
851
1032
|
}
|
|
852
1033
|
finally {
|
|
853
|
-
if (this.#activeRuns.get(activeKey) === active)
|
|
1034
|
+
if (this.#activeRuns.get(activeKey) === active)
|
|
854
1035
|
this.#activeRuns.delete(activeKey);
|
|
855
|
-
}
|
|
856
1036
|
}
|
|
857
|
-
// A re-suspension produced by this resume carries the incremented ordinal
|
|
858
|
-
// in the same authoritative snapshot as the new workflow state.
|
|
859
|
-
const summary = summarize(run.runId, result, nextCounts, provenance.requestedBy, provenance.requestedByKind, lifecycle?.deadlineAt);
|
|
860
|
-
try {
|
|
861
|
-
await this.#reconcileTerminalState(workflowId, run.runId, result, requestContext);
|
|
862
|
-
}
|
|
863
|
-
catch (error) {
|
|
864
|
-
const recovered = await this.#summaryForAttempt(workflow, runId, provenance.attemptToken);
|
|
865
|
-
if (recovered)
|
|
866
|
-
return recovered;
|
|
867
|
-
throw error;
|
|
868
|
-
}
|
|
869
|
-
return summary;
|
|
870
1037
|
});
|
|
871
1038
|
}
|
|
872
1039
|
/** Idempotently cancel a live run from its persisted snapshot. */
|
|
@@ -881,9 +1048,16 @@ export class RunnerRuntime {
|
|
|
881
1048
|
async cancelActiveExecution(workflowId, runId, intendedStatus, replayPrincipals, cas, now = Date.now()) {
|
|
882
1049
|
this.#getWorkflow(workflowId);
|
|
883
1050
|
const prepared = await this.#withLifecycleLock(workflowId, runId, async () => {
|
|
884
|
-
const
|
|
1051
|
+
const source = this.#activeRuns.get(this.#runKey(workflowId, runId))?.source ??
|
|
1052
|
+
(await this.#captureWorkflowStorage(this.#getWorkflow(workflowId)));
|
|
1053
|
+
const state = await source.load.call(source.workflows, {
|
|
1054
|
+
workflowName: workflowId,
|
|
1055
|
+
runId,
|
|
1056
|
+
});
|
|
885
1057
|
if (!state)
|
|
886
1058
|
throw new UnknownRunError(workflowId, runId);
|
|
1059
|
+
if (state.runId !== runId)
|
|
1060
|
+
throw new RunStateUnreadableError(workflowId, runId);
|
|
887
1061
|
const key = this.#runKey(workflowId, runId);
|
|
888
1062
|
const active = this.#activeRuns.get(key);
|
|
889
1063
|
const lifecycle = effectiveLifecycle(lifecycleFromRequestContext(state.requestContext), active?.lifecycle);
|
|
@@ -924,7 +1098,7 @@ export class RunnerRuntime {
|
|
|
924
1098
|
const principals = canonicalReplayPrincipals(replayPrincipals);
|
|
925
1099
|
const intent = {
|
|
926
1100
|
...(lifecycle ?? { version: 1, revision: 0 }),
|
|
927
|
-
revision: (lifecycle?.revision ?? 0)
|
|
1101
|
+
revision: nextLifecycleRevision(lifecycle?.revision ?? 0),
|
|
928
1102
|
transitionIntent: {
|
|
929
1103
|
status: intendedStatus,
|
|
930
1104
|
requestedAt: now,
|
|
@@ -937,7 +1111,7 @@ export class RunnerRuntime {
|
|
|
937
1111
|
: {}),
|
|
938
1112
|
},
|
|
939
1113
|
};
|
|
940
|
-
await this.#persistLifecycle(workflowId, runId, state, intent, now);
|
|
1114
|
+
await this.#persistLifecycle(workflowId, runId, state, intent, now, source);
|
|
941
1115
|
if (active) {
|
|
942
1116
|
active.lifecycle = intent;
|
|
943
1117
|
active.requestContext?.set(RUN_LIFECYCLE_CONTEXT_KEY, intent);
|
|
@@ -982,9 +1156,15 @@ export class RunnerRuntime {
|
|
|
982
1156
|
async #transitionTerminal(workflowId, runId, status, now, cas, replayPrincipals, replayingPrincipal) {
|
|
983
1157
|
this.#getWorkflow(workflowId);
|
|
984
1158
|
return this.#withRunLock(workflowId, runId, async () => {
|
|
985
|
-
const
|
|
1159
|
+
const source = await this.#captureWorkflowStorage(this.#getWorkflow(workflowId));
|
|
1160
|
+
const state = await source.load.call(source.workflows, {
|
|
1161
|
+
workflowName: workflowId,
|
|
1162
|
+
runId,
|
|
1163
|
+
});
|
|
986
1164
|
if (!state)
|
|
987
1165
|
throw new UnknownRunError(workflowId, runId);
|
|
1166
|
+
if (state.runId !== runId)
|
|
1167
|
+
throw new RunStateUnreadableError(workflowId, runId);
|
|
988
1168
|
const lifecycle = lifecycleFromRequestContext(state.requestContext);
|
|
989
1169
|
if (lifecycle?.terminal) {
|
|
990
1170
|
if (replayingPrincipal &&
|
|
@@ -992,24 +1172,13 @@ export class RunnerRuntime {
|
|
|
992
1172
|
principal.id === replayingPrincipal.id)) {
|
|
993
1173
|
throw new UnknownRunError(workflowId, runId);
|
|
994
1174
|
}
|
|
995
|
-
// A re-entry onto an already-terminal run heals a reconcile that an
|
|
996
|
-
// earlier crash lost. The CAS is `state <> 'terminal'`, so this is a
|
|
997
|
-
// no-op for the reservations that settled the first time.
|
|
998
|
-
await this.#settleStartReservation(runId);
|
|
999
1175
|
return {
|
|
1000
|
-
summary: await this.#summaryAfterPersist(workflowId, runId),
|
|
1176
|
+
summary: await this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state)),
|
|
1001
1177
|
transitioned: false,
|
|
1002
1178
|
casMatched: cas === undefined ||
|
|
1003
1179
|
(lifecycle.terminal.status === 'timed_out' &&
|
|
1004
1180
|
lifecycle.deadlineAt === cas.expectedDeadlineAt),
|
|
1005
|
-
cleanup:
|
|
1006
|
-
revision: lifecycle.revision,
|
|
1007
|
-
status: lifecycle.terminal.status,
|
|
1008
|
-
cleanupCompleted: lifecycle.terminal.cleanupCompletedAt !== undefined,
|
|
1009
|
-
...(lifecycle.scheduleDispatch
|
|
1010
|
-
? { scheduleDispatch: lifecycle.scheduleDispatch }
|
|
1011
|
-
: {}),
|
|
1012
|
-
},
|
|
1181
|
+
cleanup: terminalCleanupFor(lifecycle),
|
|
1013
1182
|
};
|
|
1014
1183
|
}
|
|
1015
1184
|
const transitionIntent = lifecycle?.transitionIntent;
|
|
@@ -1025,7 +1194,7 @@ export class RunnerRuntime {
|
|
|
1025
1194
|
lifecycle.deadlineAt === undefined ||
|
|
1026
1195
|
lifecycle.deadlineAt > now)) {
|
|
1027
1196
|
return {
|
|
1028
|
-
summary: await this.#summaryAfterPersist(workflowId, runId),
|
|
1197
|
+
summary: await this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state)),
|
|
1029
1198
|
transitioned: false,
|
|
1030
1199
|
casMatched: false,
|
|
1031
1200
|
cleanup: {
|
|
@@ -1051,9 +1220,6 @@ export class RunnerRuntime {
|
|
|
1051
1220
|
!(currentStatus === 'canceled' && abortIntent === status)) {
|
|
1052
1221
|
throw new RunTerminalConflictError(workflowId, runId, currentStatus);
|
|
1053
1222
|
}
|
|
1054
|
-
const error = status === 'cancelled'
|
|
1055
|
-
? { code: 'CANCELLED', message: 'run was cancelled' }
|
|
1056
|
-
: { code: 'TIMED_OUT', message: 'run deadline expired' };
|
|
1057
1223
|
const provenance = runProvenance(state);
|
|
1058
1224
|
const fallbackPrincipal = provenance?.requestedBy && provenance.requestedByKind
|
|
1059
1225
|
? {
|
|
@@ -1063,53 +1229,22 @@ export class RunnerRuntime {
|
|
|
1063
1229
|
: { kind: 'system', id: 'flowsafe-system' };
|
|
1064
1230
|
const principals = canonicalReplayPrincipals(replayPrincipals ??
|
|
1065
1231
|
transitionIntent?.replayPrincipals ?? [fallbackPrincipal]);
|
|
1066
|
-
const
|
|
1067
|
-
? Object.fromEntries(Object.entries(lifecycle).filter(([key]) => key !== 'transitionIntent'))
|
|
1068
|
-
: { version: 1, revision: 0 };
|
|
1069
|
-
const next = {
|
|
1070
|
-
...lifecycleBase,
|
|
1071
|
-
version: 1,
|
|
1072
|
-
revision: (lifecycle?.revision ?? 0) + 1,
|
|
1073
|
-
terminal: {
|
|
1074
|
-
status,
|
|
1075
|
-
error,
|
|
1076
|
-
transitionedAt: now,
|
|
1077
|
-
replayPrincipals: principals,
|
|
1078
|
-
},
|
|
1079
|
-
};
|
|
1232
|
+
const next = projectTerminalLifecycle(lifecycle, status, now, principals);
|
|
1080
1233
|
await this.#persistLifecycle(workflowId, runId, {
|
|
1081
1234
|
...state,
|
|
1082
|
-
status
|
|
1083
|
-
result: undefined,
|
|
1235
|
+
...terminalStateFields(status),
|
|
1084
1236
|
error: {
|
|
1085
1237
|
name: status === 'cancelled' ? 'RunCancelledError' : 'RunTimedOutError',
|
|
1086
|
-
message: error.message,
|
|
1238
|
+
message: next.terminal.error.message,
|
|
1087
1239
|
},
|
|
1088
|
-
suspendedPaths: {},
|
|
1089
|
-
waitingPaths: {},
|
|
1090
|
-
resumeLabels: {},
|
|
1091
|
-
activePaths: [],
|
|
1092
|
-
activeStepsPath: {},
|
|
1093
1240
|
timestamp: now,
|
|
1094
|
-
}, next, now);
|
|
1241
|
+
}, next, now, source);
|
|
1095
1242
|
this.#terminalAbortIntents.delete(this.#runKey(workflowId, runId));
|
|
1096
|
-
// Cancel and timeout are terminal too: a run killed by an operator or by
|
|
1097
|
-
// its deadline spends its idempotency key exactly as a completed one does,
|
|
1098
|
-
// and a key left unspent here would keep a dead run in the drain
|
|
1099
|
-
// inventory forever.
|
|
1100
|
-
await this.#settleStartReservation(runId);
|
|
1101
1243
|
return {
|
|
1102
|
-
summary: await this.#summaryAfterPersist(workflowId, runId),
|
|
1244
|
+
summary: await this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state)),
|
|
1103
1245
|
transitioned: true,
|
|
1104
1246
|
casMatched: true,
|
|
1105
|
-
cleanup:
|
|
1106
|
-
revision: next.revision,
|
|
1107
|
-
status,
|
|
1108
|
-
cleanupCompleted: false,
|
|
1109
|
-
...(next.scheduleDispatch
|
|
1110
|
-
? { scheduleDispatch: next.scheduleDispatch }
|
|
1111
|
-
: {}),
|
|
1112
|
-
},
|
|
1247
|
+
cleanup: terminalCleanupFor(next),
|
|
1113
1248
|
};
|
|
1114
1249
|
});
|
|
1115
1250
|
}
|
|
@@ -1117,29 +1252,35 @@ export class RunnerRuntime {
|
|
|
1117
1252
|
async completeTerminalCleanup(workflowId, runId, expectedRevision, now = Date.now()) {
|
|
1118
1253
|
this.#getWorkflow(workflowId);
|
|
1119
1254
|
return this.#withRunLock(workflowId, runId, async () => {
|
|
1120
|
-
const
|
|
1255
|
+
const source = await this.#captureWorkflowStorage(this.#getWorkflow(workflowId));
|
|
1256
|
+
const state = await source.load.call(source.workflows, {
|
|
1257
|
+
workflowName: workflowId,
|
|
1258
|
+
runId,
|
|
1259
|
+
});
|
|
1121
1260
|
if (!state)
|
|
1122
1261
|
throw new UnknownRunError(workflowId, runId);
|
|
1262
|
+
if (state.runId !== runId)
|
|
1263
|
+
throw new RunStateUnreadableError(workflowId, runId);
|
|
1123
1264
|
const lifecycle = lifecycleFromRequestContext(state.requestContext);
|
|
1124
1265
|
if (!lifecycle?.terminal) {
|
|
1125
1266
|
throw new RunTerminalConflictError(workflowId, runId, state.status);
|
|
1126
1267
|
}
|
|
1127
1268
|
if (lifecycle.terminal.cleanupCompletedAt !== undefined) {
|
|
1128
|
-
return this.#summaryAfterPersist(workflowId, runId);
|
|
1269
|
+
return this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state));
|
|
1129
1270
|
}
|
|
1130
1271
|
if (lifecycle.revision !== expectedRevision) {
|
|
1131
1272
|
throw new Error('run terminal cleanup CAS no longer matches');
|
|
1132
1273
|
}
|
|
1133
1274
|
const next = {
|
|
1134
1275
|
...lifecycle,
|
|
1135
|
-
revision: lifecycle.revision
|
|
1276
|
+
revision: nextLifecycleRevision(lifecycle.revision),
|
|
1136
1277
|
terminal: {
|
|
1137
1278
|
...lifecycle.terminal,
|
|
1138
1279
|
cleanupCompletedAt: now,
|
|
1139
1280
|
},
|
|
1140
1281
|
};
|
|
1141
|
-
await this.#persistLifecycle(workflowId, runId, state, next, now);
|
|
1142
|
-
return this.#summaryAfterPersist(workflowId, runId);
|
|
1282
|
+
await this.#persistLifecycle(workflowId, runId, state, next, now, source);
|
|
1283
|
+
return this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state));
|
|
1143
1284
|
});
|
|
1144
1285
|
}
|
|
1145
1286
|
/**
|
|
@@ -1174,8 +1315,8 @@ export class RunnerRuntime {
|
|
|
1174
1315
|
* that did not reach storage. `null` still means the read SUCCEEDED and
|
|
1175
1316
|
* found nothing.
|
|
1176
1317
|
*
|
|
1177
|
-
* status
|
|
1178
|
-
*
|
|
1318
|
+
* Both status readers refuse a valid v2 pending row before lifecycle
|
|
1319
|
+
* projection; it has no durable execution outcome yet.
|
|
1179
1320
|
*/
|
|
1180
1321
|
async authoritativeStatus(workflowId, runId) {
|
|
1181
1322
|
const workflow = this.#getWorkflow(workflowId);
|
|
@@ -1187,42 +1328,360 @@ export class RunnerRuntime {
|
|
|
1187
1328
|
}
|
|
1188
1329
|
return this.#summaryFromState(runId, state);
|
|
1189
1330
|
}
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1331
|
+
async authoritativeStartState(workflowId, runId, options) {
|
|
1332
|
+
const includeLegacy = options?.includeLegacy === true;
|
|
1333
|
+
const { state } = await this.#observeStartState(workflowId, runId);
|
|
1334
|
+
if (state?.kind === 'legacy' && !includeLegacy)
|
|
1335
|
+
throw new RunStateUnreadableError(workflowId, runId);
|
|
1336
|
+
return state;
|
|
1337
|
+
}
|
|
1338
|
+
async #captureWorkflowStorage(workflow) {
|
|
1339
|
+
const workflows = await workflow.mastra
|
|
1340
|
+
?.getStorage()
|
|
1341
|
+
?.getStore('workflows');
|
|
1342
|
+
if (!workflows)
|
|
1343
|
+
throw new Error('workflow storage is unavailable');
|
|
1344
|
+
const methods = {
|
|
1345
|
+
workflows,
|
|
1346
|
+
read: workflows.getWorkflowRunById,
|
|
1347
|
+
load: workflows.loadWorkflowSnapshot,
|
|
1348
|
+
persist: workflows.persistWorkflowSnapshot,
|
|
1349
|
+
};
|
|
1350
|
+
const capability = workflows[FENCED_WORKFLOW_STORAGE];
|
|
1351
|
+
if (capability === undefined) {
|
|
1352
|
+
if (this.#executionFence)
|
|
1353
|
+
throw new Error('fenced workflow storage capability is unavailable');
|
|
1354
|
+
return { ...methods, storage: 'unfenced', tablePrefix: null };
|
|
1199
1355
|
}
|
|
1356
|
+
if (capability === null || typeof capability !== 'object')
|
|
1357
|
+
throw new Error('workflow capability is malformed');
|
|
1358
|
+
const { database, tablePrefix: prefix, readSnapshot, withInitialAdmission: admit, terminalizeInitialAdmission: terminalize, } = capability;
|
|
1359
|
+
if (typeof prefix !== 'string' ||
|
|
1360
|
+
typeof readSnapshot !== 'function' ||
|
|
1361
|
+
typeof admit !== 'function' ||
|
|
1362
|
+
typeof terminalize !== 'function' ||
|
|
1363
|
+
!database ||
|
|
1364
|
+
typeof database.prepare !== 'function' ||
|
|
1365
|
+
typeof database.batch !== 'function')
|
|
1366
|
+
throw new Error('workflow capability is malformed');
|
|
1367
|
+
validateTablePrefix(prefix);
|
|
1368
|
+
if ((this.#executionFence && !this.#executionFence.usesDatabase(database)) ||
|
|
1369
|
+
(this.#startIdempotency && !this.#startIdempotency.usesDatabase(database)))
|
|
1370
|
+
throw new Error('workflow storage binding disagrees with runtime stores');
|
|
1371
|
+
return {
|
|
1372
|
+
...methods,
|
|
1373
|
+
storage: 'd1',
|
|
1374
|
+
tablePrefix: prefix.toLowerCase(),
|
|
1375
|
+
capability,
|
|
1376
|
+
database,
|
|
1377
|
+
readSnapshot,
|
|
1378
|
+
admit,
|
|
1379
|
+
terminalize,
|
|
1380
|
+
};
|
|
1381
|
+
}
|
|
1382
|
+
async #observeStartState(workflowId, runId) {
|
|
1383
|
+
if (!isPathSafeId(workflowId))
|
|
1384
|
+
throw new InvalidRunRequestError('workflowId is malformed');
|
|
1385
|
+
if (!isPathSafeId(runId))
|
|
1386
|
+
throw new InvalidRunRequestError('runId is malformed');
|
|
1200
1387
|
const workflow = this.#getWorkflow(workflowId);
|
|
1201
|
-
|
|
1202
|
-
const
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1388
|
+
try {
|
|
1389
|
+
const source = await this.#captureWorkflowStorage(workflow);
|
|
1390
|
+
return {
|
|
1391
|
+
source,
|
|
1392
|
+
state: await this.#readStartState(source, workflowId, runId),
|
|
1393
|
+
};
|
|
1394
|
+
}
|
|
1395
|
+
catch (cause) {
|
|
1396
|
+
if (cause instanceof RunStateUnreadableError)
|
|
1397
|
+
throw cause;
|
|
1398
|
+
throw new RunStateUnreadableError(workflowId, runId, { cause });
|
|
1399
|
+
}
|
|
1400
|
+
}
|
|
1401
|
+
#projectD1StartState(source, workflowId, runId, observed) {
|
|
1402
|
+
for (const key of [
|
|
1403
|
+
'tablePrefix',
|
|
1404
|
+
'workflowId',
|
|
1405
|
+
'runId',
|
|
1406
|
+
'resourceId',
|
|
1407
|
+
'snapshot',
|
|
1408
|
+
'createdAt',
|
|
1409
|
+
'updatedAt',
|
|
1410
|
+
]) {
|
|
1411
|
+
if (!Object.hasOwn(observed, key))
|
|
1412
|
+
throw new Error('workflow snapshot field is missing');
|
|
1413
|
+
}
|
|
1414
|
+
const { tablePrefix, workflowId: storedWorkflow, runId: storedRun, resourceId, snapshot, createdAt, updatedAt, } = observed;
|
|
1415
|
+
if (tablePrefix !== source.tablePrefix ||
|
|
1416
|
+
storedWorkflow !== workflowId ||
|
|
1417
|
+
storedRun !== runId ||
|
|
1418
|
+
(resourceId !== null && typeof resourceId !== 'string') ||
|
|
1419
|
+
typeof snapshot !== 'string' ||
|
|
1420
|
+
typeof createdAt !== 'string' ||
|
|
1421
|
+
typeof updatedAt !== 'string')
|
|
1422
|
+
throw new Error('workflow snapshot fields are malformed');
|
|
1423
|
+
const raw = Object.freeze({
|
|
1424
|
+
tablePrefix,
|
|
1425
|
+
workflowId,
|
|
1426
|
+
runId,
|
|
1427
|
+
resourceId,
|
|
1428
|
+
snapshot,
|
|
1429
|
+
createdAt,
|
|
1430
|
+
updatedAt,
|
|
1431
|
+
});
|
|
1432
|
+
return this.#projectStartState({ storage: 'd1', tablePrefix, raw }, workflowId, runId, JSON.parse(snapshot), createdAt, updatedAt);
|
|
1433
|
+
}
|
|
1434
|
+
async #readStartState(source, workflowId, runId) {
|
|
1435
|
+
try {
|
|
1436
|
+
let state;
|
|
1437
|
+
if (source.storage === 'd1') {
|
|
1438
|
+
const row = await source.readSnapshot.call(source.capability, {
|
|
1439
|
+
workflowId,
|
|
1440
|
+
runId,
|
|
1441
|
+
});
|
|
1442
|
+
state =
|
|
1443
|
+
row === undefined
|
|
1444
|
+
? null
|
|
1445
|
+
: this.#projectD1StartState(source, workflowId, runId, row);
|
|
1216
1446
|
}
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1447
|
+
else {
|
|
1448
|
+
const row = await source.read.call(source.workflows, {
|
|
1449
|
+
workflowName: workflowId,
|
|
1450
|
+
runId,
|
|
1451
|
+
});
|
|
1452
|
+
if (row === null)
|
|
1453
|
+
return null;
|
|
1454
|
+
const { workflowName, runId: storedRun, snapshot, createdAt, updatedAt, } = row;
|
|
1455
|
+
if (workflowName !== workflowId || storedRun !== runId)
|
|
1456
|
+
throw new Error('workflow snapshot selector disagrees with the request');
|
|
1457
|
+
state = this.#projectStartState(source, workflowId, runId, typeof snapshot === 'string'
|
|
1458
|
+
? JSON.parse(snapshot)
|
|
1459
|
+
: structuredClone(snapshot), createdAt, updatedAt);
|
|
1220
1460
|
}
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1461
|
+
return state;
|
|
1462
|
+
}
|
|
1463
|
+
catch (cause) {
|
|
1464
|
+
throw new RunStateUnreadableError(workflowId, runId, { cause });
|
|
1465
|
+
}
|
|
1466
|
+
}
|
|
1467
|
+
#projectStartState(physical, workflowId, runId, decoded, createdAt, updatedAt) {
|
|
1468
|
+
if (decoded === null ||
|
|
1469
|
+
typeof decoded !== 'object' ||
|
|
1470
|
+
Array.isArray(decoded))
|
|
1471
|
+
throw new Error('workflow snapshot is malformed');
|
|
1472
|
+
const snapshot = decoded;
|
|
1473
|
+
if (snapshot.runId !== runId || !isRunStatus(snapshot.status))
|
|
1474
|
+
throw new Error('workflow snapshot identity or status is malformed');
|
|
1475
|
+
for (const value of [
|
|
1476
|
+
snapshot.requestContext,
|
|
1477
|
+
snapshot.context,
|
|
1478
|
+
snapshot.suspendedPaths,
|
|
1479
|
+
]) {
|
|
1480
|
+
if (value !== undefined &&
|
|
1481
|
+
(value === null || typeof value !== 'object' || Array.isArray(value)))
|
|
1482
|
+
throw new Error('workflow snapshot container is malformed');
|
|
1483
|
+
}
|
|
1484
|
+
const provenance = runProvenance(snapshot);
|
|
1485
|
+
lifecycleFromRequestContext(snapshot.requestContext);
|
|
1486
|
+
for (const value of [createdAt, updatedAt]) {
|
|
1487
|
+
if (!(value instanceof Date) && typeof value !== 'string')
|
|
1488
|
+
throw new Error('workflow snapshot timestamp is malformed');
|
|
1489
|
+
if (!Number.isFinite(new Date(value).getTime()))
|
|
1490
|
+
throw new Error('workflow snapshot timestamp is malformed');
|
|
1491
|
+
}
|
|
1492
|
+
if (provenance?.version !== 2)
|
|
1493
|
+
return {
|
|
1494
|
+
kind: 'legacy',
|
|
1495
|
+
provenanceVersion: provenance?.version,
|
|
1496
|
+
address: Object.freeze({
|
|
1497
|
+
tablePrefix: physical.tablePrefix,
|
|
1498
|
+
workflowId,
|
|
1499
|
+
runId,
|
|
1500
|
+
}),
|
|
1501
|
+
snapshot,
|
|
1502
|
+
summary: summaryFromSelectedSnapshot(runId, snapshot, { createdAt: toIso(createdAt), updatedAt: toIso(updatedAt) }, provenance),
|
|
1503
|
+
};
|
|
1504
|
+
const execution = runExecutionIdentityFor({ tablePrefix: physical.tablePrefix, workflowId, runId }, provenance);
|
|
1505
|
+
const state = snapshot.status === 'pending'
|
|
1506
|
+
? { kind: 'initial', snapshot, provenance }
|
|
1507
|
+
: {
|
|
1508
|
+
kind: 'result',
|
|
1509
|
+
snapshot,
|
|
1510
|
+
provenance,
|
|
1511
|
+
summary: summaryFromSelectedSnapshot(runId, snapshot, { createdAt: toIso(createdAt), updatedAt: toIso(updatedAt) }, provenance),
|
|
1512
|
+
};
|
|
1513
|
+
return physical.storage === 'd1'
|
|
1514
|
+
? {
|
|
1515
|
+
...state,
|
|
1516
|
+
storage: 'd1',
|
|
1517
|
+
execution: Object.freeze({
|
|
1518
|
+
...execution,
|
|
1519
|
+
tablePrefix: physical.tablePrefix,
|
|
1520
|
+
}),
|
|
1521
|
+
raw: physical.raw,
|
|
1522
|
+
}
|
|
1523
|
+
: {
|
|
1524
|
+
...state,
|
|
1525
|
+
storage: 'unfenced',
|
|
1526
|
+
execution: Object.freeze({ ...execution, tablePrefix: null }),
|
|
1527
|
+
};
|
|
1528
|
+
}
|
|
1529
|
+
/** @internal Recover only after the exact owning execution has unwound. */
|
|
1530
|
+
async recoverStartAttempt(value, recovery) {
|
|
1531
|
+
const execution = normalizeD1RunExecutionIdentity(value);
|
|
1532
|
+
const { attemptToken, isOwnerQuiescent, startReservation: suppliedClaim, expectedTarget: suppliedTarget, } = recovery;
|
|
1533
|
+
let expectedTarget;
|
|
1534
|
+
if (suppliedTarget !== undefined) {
|
|
1535
|
+
if (suppliedTarget === null ||
|
|
1536
|
+
typeof suppliedTarget !== 'object' ||
|
|
1537
|
+
Array.isArray(suppliedTarget))
|
|
1538
|
+
throw new InvalidRunRequestError('start recovery target is malformed');
|
|
1539
|
+
const { kind } = suppliedTarget;
|
|
1540
|
+
if (kind === 'workflow')
|
|
1541
|
+
expectedTarget = Object.freeze({ kind });
|
|
1542
|
+
else if (kind === 'agent') {
|
|
1543
|
+
const { owner, id, threadId, threaded } = suppliedTarget;
|
|
1544
|
+
const identity = normalizeStartIdentity({
|
|
1545
|
+
owner,
|
|
1546
|
+
target: { kind, id, threadId },
|
|
1547
|
+
});
|
|
1548
|
+
if (typeof threaded !== 'boolean')
|
|
1549
|
+
throw new InvalidRunRequestError('start recovery target is malformed');
|
|
1550
|
+
expectedTarget = Object.freeze({
|
|
1551
|
+
kind,
|
|
1552
|
+
id: identity.target.id,
|
|
1553
|
+
threadId,
|
|
1554
|
+
owner: identity.owner,
|
|
1555
|
+
threaded,
|
|
1556
|
+
});
|
|
1224
1557
|
}
|
|
1225
|
-
|
|
1558
|
+
else
|
|
1559
|
+
throw new InvalidRunRequestError('start recovery target is malformed');
|
|
1560
|
+
}
|
|
1561
|
+
const assertExpectedTarget = (state) => {
|
|
1562
|
+
if (!expectedTarget)
|
|
1563
|
+
return;
|
|
1564
|
+
const { startIdentity, agentStart } = state.provenance;
|
|
1565
|
+
if (expectedTarget.kind === 'workflow') {
|
|
1566
|
+
if (startIdentity?.target.kind !== 'workflow' ||
|
|
1567
|
+
startIdentity.target.id !== state.execution.workflowId ||
|
|
1568
|
+
agentStart !== undefined)
|
|
1569
|
+
throw new Error('recovery workflow target disagrees with execution');
|
|
1570
|
+
}
|
|
1571
|
+
else if (startIdentity?.target.kind !== 'agent' ||
|
|
1572
|
+
startIdentity.target.id !== expectedTarget.id ||
|
|
1573
|
+
startIdentity.target.threadId !== expectedTarget.threadId ||
|
|
1574
|
+
startIdentity.owner.kind !== expectedTarget.owner.kind ||
|
|
1575
|
+
startIdentity.owner.id !== expectedTarget.owner.id ||
|
|
1576
|
+
agentStart?.threaded !== expectedTarget.threaded)
|
|
1577
|
+
throw new Error('recovery agent target disagrees with execution');
|
|
1578
|
+
};
|
|
1579
|
+
const claim = suppliedClaim === undefined
|
|
1580
|
+
? undefined
|
|
1581
|
+
: captureReservation(suppliedClaim, 'started');
|
|
1582
|
+
if (!isPathSafeId(attemptToken) || typeof isOwnerQuiescent !== 'function')
|
|
1583
|
+
throw new InvalidRunRequestError('start recovery authority is malformed');
|
|
1584
|
+
if (claim && !this.#startIdempotency)
|
|
1585
|
+
throw new ExecutionFenceUnreadableError('run start recovery is unresolved');
|
|
1586
|
+
const { workflowId, runId } = execution;
|
|
1587
|
+
const workflow = this.#getWorkflow(workflowId);
|
|
1588
|
+
return this.#withRunLock(workflowId, runId, () => this.#withLifecycleLock(workflowId, runId, async () => {
|
|
1589
|
+
try {
|
|
1590
|
+
if (this.isRunActive(workflowId, runId))
|
|
1591
|
+
throw new Error('run owner is not quiescent');
|
|
1592
|
+
const source = await this.#captureWorkflowStorage(workflow);
|
|
1593
|
+
if (this.isRunActive(workflowId, runId) ||
|
|
1594
|
+
(await Reflect.apply(isOwnerQuiescent, undefined, [])) !== true ||
|
|
1595
|
+
this.isRunActive(workflowId, runId))
|
|
1596
|
+
throw new Error('run owner is not quiescent');
|
|
1597
|
+
const state = await this.#readStartState(source, workflowId, runId);
|
|
1598
|
+
if (state?.kind === 'legacy')
|
|
1599
|
+
throw new RunStateUnreadableError(workflowId, runId);
|
|
1600
|
+
if (source.storage !== 'd1' ||
|
|
1601
|
+
source.tablePrefix !== execution.tablePrefix)
|
|
1602
|
+
throw new Error('recovery source disagrees with execution');
|
|
1603
|
+
if (!state)
|
|
1604
|
+
return null;
|
|
1605
|
+
if (!sameExecution(state.execution, execution))
|
|
1606
|
+
throw new Error('recovery generation disagrees with execution');
|
|
1607
|
+
assertExpectedTarget(state);
|
|
1608
|
+
if (claim) {
|
|
1609
|
+
if (!state.provenance.startIdentity)
|
|
1610
|
+
throw new Error('recovery lacks logical identity');
|
|
1611
|
+
assertClaimIdentity(claim, {
|
|
1612
|
+
...state.provenance.startIdentity,
|
|
1613
|
+
runId,
|
|
1614
|
+
});
|
|
1615
|
+
}
|
|
1616
|
+
let selected = state;
|
|
1617
|
+
let transitioned = false;
|
|
1618
|
+
let cleanup = terminalCleanupFor(lifecycleFromRequestContext(state.snapshot.requestContext));
|
|
1619
|
+
if (state.kind === 'initial') {
|
|
1620
|
+
if (!this.#executionFence ||
|
|
1621
|
+
state.storage !== 'd1' ||
|
|
1622
|
+
state.provenance.initialAdmission !== true ||
|
|
1623
|
+
state.provenance.attemptToken !== attemptToken ||
|
|
1624
|
+
state.provenance.resumeCounts.length !== 0)
|
|
1625
|
+
throw new RunStartPendingError();
|
|
1626
|
+
const result = await source.terminalize.call(source.capability, {
|
|
1627
|
+
expected: state.raw,
|
|
1628
|
+
execution,
|
|
1629
|
+
attemptToken,
|
|
1630
|
+
nowMs: Date.now(),
|
|
1631
|
+
});
|
|
1632
|
+
if (result.kind === 'conflict')
|
|
1633
|
+
throw new Error('initial terminalization conflicts');
|
|
1634
|
+
const projected = this.#projectD1StartState(source, workflowId, runId, result.row);
|
|
1635
|
+
if (projected.kind !== 'result' ||
|
|
1636
|
+
!sameExecution(projected.execution, execution))
|
|
1637
|
+
throw new Error('terminalization result is unresolved');
|
|
1638
|
+
selected = projected;
|
|
1639
|
+
assertExpectedTarget(selected);
|
|
1640
|
+
transitioned = result.kind === 'terminalized';
|
|
1641
|
+
cleanup = result.cleanup;
|
|
1642
|
+
}
|
|
1643
|
+
if (selected.kind !== 'result')
|
|
1644
|
+
throw new RunStartPendingError();
|
|
1645
|
+
if (isTerminalRunStatus(selected.summary.status))
|
|
1646
|
+
await this.settleStartExecution(selected, claim);
|
|
1647
|
+
return cleanup
|
|
1648
|
+
? {
|
|
1649
|
+
kind: 'lifecycle',
|
|
1650
|
+
transition: {
|
|
1651
|
+
summary: selected.summary,
|
|
1652
|
+
transitioned,
|
|
1653
|
+
casMatched: true,
|
|
1654
|
+
cleanup,
|
|
1655
|
+
},
|
|
1656
|
+
}
|
|
1657
|
+
: { kind: 'ordinary', summary: selected.summary };
|
|
1658
|
+
}
|
|
1659
|
+
catch (cause) {
|
|
1660
|
+
if (cause instanceof RunStartPendingError ||
|
|
1661
|
+
cause instanceof RunStateUnreadableError)
|
|
1662
|
+
throw cause;
|
|
1663
|
+
throw new ExecutionFenceUnreadableError('run start recovery is unresolved', { cause });
|
|
1664
|
+
}
|
|
1665
|
+
}));
|
|
1666
|
+
}
|
|
1667
|
+
/** @internal Settle the exact selected terminal generation before managed cleanup. */
|
|
1668
|
+
async settleStartExecution(state, originalClaim) {
|
|
1669
|
+
const claim = originalClaim === undefined
|
|
1670
|
+
? undefined
|
|
1671
|
+
: captureReservation(originalClaim, 'started');
|
|
1672
|
+
if (state.kind !== 'result' || !isTerminalRunStatus(state.summary.status))
|
|
1673
|
+
throw new RunStartPendingError();
|
|
1674
|
+
const identity = state.provenance.startIdentity;
|
|
1675
|
+
if (claim) {
|
|
1676
|
+
if (!identity || !this.#startIdempotency)
|
|
1677
|
+
throw new ExecutionFenceUnreadableError('run start settlement is unresolved');
|
|
1678
|
+
assertClaimIdentity(claim, { ...identity, runId: state.execution.runId });
|
|
1679
|
+
}
|
|
1680
|
+
if (!identity || !this.#startIdempotency)
|
|
1681
|
+
return;
|
|
1682
|
+
await this.#startIdempotency.settleExecution({
|
|
1683
|
+
...state.execution,
|
|
1684
|
+
...identity,
|
|
1226
1685
|
});
|
|
1227
1686
|
}
|
|
1228
1687
|
// A provider crash propagates (fail loud): silently starting the leg with
|
|
@@ -1312,10 +1771,12 @@ export class RunnerRuntime {
|
|
|
1312
1771
|
const priorCounts = new Map(storedProvenance?.resumeCounts ?? []);
|
|
1313
1772
|
const nextCounts = new Map(priorCounts);
|
|
1314
1773
|
if (stepKey !== undefined) {
|
|
1315
|
-
nextCounts.set(stepKey, (nextCounts.get(stepKey) ?? 0)
|
|
1774
|
+
nextCounts.set(stepKey, nextResumeCount(nextCounts.get(stepKey) ?? 0));
|
|
1316
1775
|
}
|
|
1317
1776
|
const provenance = {
|
|
1318
|
-
version
|
|
1777
|
+
...(storedProvenance?.version === 2
|
|
1778
|
+
? storedProvenance
|
|
1779
|
+
: { version: 1 }),
|
|
1319
1780
|
...(requester === undefined
|
|
1320
1781
|
? {}
|
|
1321
1782
|
: { requestedBy: requester, requestedByKind: requesterKind }),
|
|
@@ -1330,7 +1791,7 @@ export class RunnerRuntime {
|
|
|
1330
1791
|
? storedLifecycle
|
|
1331
1792
|
: {
|
|
1332
1793
|
...(storedLifecycle ?? { version: 1, revision: 0 }),
|
|
1333
|
-
revision: (storedLifecycle?.revision ?? 0)
|
|
1794
|
+
revision: nextLifecycleRevision(storedLifecycle?.revision ?? 0),
|
|
1334
1795
|
...(replacementDeadline === undefined
|
|
1335
1796
|
? {}
|
|
1336
1797
|
: { deadlineAt: replacementDeadline }),
|
|
@@ -1353,21 +1814,14 @@ export class RunnerRuntime {
|
|
|
1353
1814
|
lifecycle,
|
|
1354
1815
|
};
|
|
1355
1816
|
}
|
|
1356
|
-
#workflowState(workflow, runId) {
|
|
1357
|
-
return workflow.getWorkflowRunById(runId, {
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
if (!workflows) {
|
|
1362
|
-
throw new Error('RunnerRuntime: workflows storage is unavailable');
|
|
1363
|
-
}
|
|
1364
|
-
return workflows.loadWorkflowSnapshot({ workflowName: workflowId, runId });
|
|
1817
|
+
#workflowState(workflow, runId, withNestedWorkflows = false) {
|
|
1818
|
+
return workflow.getWorkflowRunById(runId, {
|
|
1819
|
+
fields: RUN_STATE_FIELDS,
|
|
1820
|
+
withNestedWorkflows,
|
|
1821
|
+
});
|
|
1365
1822
|
}
|
|
1366
|
-
async #persistLifecycle(workflowId, runId, state, lifecycle, now) {
|
|
1367
|
-
const workflows =
|
|
1368
|
-
if (!workflows) {
|
|
1369
|
-
throw new Error('RunnerRuntime: workflows storage is unavailable');
|
|
1370
|
-
}
|
|
1823
|
+
async #persistLifecycle(workflowId, runId, state, lifecycle, now, source) {
|
|
1824
|
+
const workflows = source.workflows;
|
|
1371
1825
|
const persisted = {
|
|
1372
1826
|
...state,
|
|
1373
1827
|
requestContext: {
|
|
@@ -1376,7 +1830,7 @@ export class RunnerRuntime {
|
|
|
1376
1830
|
},
|
|
1377
1831
|
timestamp: now,
|
|
1378
1832
|
};
|
|
1379
|
-
await
|
|
1833
|
+
await source.persist.call(workflows, {
|
|
1380
1834
|
workflowName: workflowId,
|
|
1381
1835
|
runId,
|
|
1382
1836
|
snapshot: persisted,
|
|
@@ -1384,7 +1838,13 @@ export class RunnerRuntime {
|
|
|
1384
1838
|
});
|
|
1385
1839
|
return persisted;
|
|
1386
1840
|
}
|
|
1387
|
-
async #summaryAfterPersist(workflowId, runId) {
|
|
1841
|
+
async #summaryAfterPersist(workflowId, runId, source, expected) {
|
|
1842
|
+
if (expected?.version === 2) {
|
|
1843
|
+
const selected = await this.#completedStartState(source, runExecutionIdentityFor({ tablePrefix: source.tablePrefix, workflowId, runId }, expected), expected);
|
|
1844
|
+
if (isTerminalRunStatus(selected.summary.status))
|
|
1845
|
+
await this.settleStartExecution(selected);
|
|
1846
|
+
return selected.summary;
|
|
1847
|
+
}
|
|
1388
1848
|
const state = await this.#workflowState(this.#getWorkflow(workflowId), runId);
|
|
1389
1849
|
if (!state)
|
|
1390
1850
|
throw new UnknownRunError(workflowId, runId);
|
|
@@ -1392,33 +1852,67 @@ export class RunnerRuntime {
|
|
|
1392
1852
|
}
|
|
1393
1853
|
#summaryFromState(runId, state) {
|
|
1394
1854
|
const provenance = runProvenance(state);
|
|
1855
|
+
if (state.status === 'pending' && provenance?.version === 2)
|
|
1856
|
+
throw new RunStartPendingError();
|
|
1395
1857
|
return summarizeState(runId, state, provenance ? new Map(provenance.resumeCounts) : undefined, provenance?.requestedBy, provenance?.requestedByKind);
|
|
1396
1858
|
}
|
|
1397
|
-
async #summaryForAttempt(workflow, runId,
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1859
|
+
async #summaryForAttempt(workflow, runId, expected) {
|
|
1860
|
+
try {
|
|
1861
|
+
if (expected.version === 2) {
|
|
1862
|
+
const source = this.#activeRuns.get(this.#runKey(workflow.id, runId))?.source;
|
|
1863
|
+
if (!source)
|
|
1864
|
+
return undefined;
|
|
1865
|
+
const state = await this.#completedStartState(source, {
|
|
1866
|
+
tablePrefix: source.tablePrefix,
|
|
1867
|
+
workflowId: workflow.id,
|
|
1868
|
+
runId,
|
|
1869
|
+
startToken: expected.startToken,
|
|
1870
|
+
}, expected);
|
|
1871
|
+
await this.#settleStartReservation(state);
|
|
1872
|
+
return state.summary;
|
|
1873
|
+
}
|
|
1874
|
+
const persisted = await this.#workflowState(workflow, runId);
|
|
1875
|
+
if (!persisted ||
|
|
1876
|
+
persisted.isFromInMemory ||
|
|
1877
|
+
persisted.status === 'pending')
|
|
1878
|
+
return undefined;
|
|
1879
|
+
const provenance = runProvenance(persisted);
|
|
1880
|
+
if (provenance?.version !== expected.version ||
|
|
1881
|
+
provenance.attemptToken !== expected.attemptToken)
|
|
1882
|
+
return undefined;
|
|
1883
|
+
return summarizeState(runId, persisted, new Map(provenance.resumeCounts), provenance.requestedBy, provenance.requestedByKind);
|
|
1884
|
+
}
|
|
1885
|
+
catch {
|
|
1403
1886
|
return undefined;
|
|
1404
|
-
|
|
1887
|
+
}
|
|
1405
1888
|
}
|
|
1406
|
-
async #reconcileTerminalState(workflowId, runId, result, requestContext) {
|
|
1889
|
+
async #reconcileTerminalState(workflowId, runId, result, requestContext, source, proof) {
|
|
1407
1890
|
const opts = terminalStateUpdate(result);
|
|
1408
1891
|
if (!opts)
|
|
1409
1892
|
return;
|
|
1410
1893
|
await this.#withLifecycleLock(workflowId, runId, async () => {
|
|
1411
|
-
const workflows =
|
|
1412
|
-
|
|
1413
|
-
throw new Error('RunnerRuntime: workflows storage is unavailable while persisting terminal state');
|
|
1414
|
-
}
|
|
1415
|
-
const snapshot = await workflows.loadWorkflowSnapshot({
|
|
1894
|
+
const workflows = source.workflows;
|
|
1895
|
+
const snapshot = await source.load.call(workflows, {
|
|
1416
1896
|
workflowName: workflowId,
|
|
1417
1897
|
runId,
|
|
1418
1898
|
});
|
|
1419
1899
|
if (!snapshot) {
|
|
1420
1900
|
throw new Error(`RunnerRuntime: run '${runId}' of workflow '${workflowId}' completed without a durable snapshot`);
|
|
1421
1901
|
}
|
|
1902
|
+
if (snapshot.runId !== runId)
|
|
1903
|
+
throw new RunStateUnreadableError(workflowId, runId);
|
|
1904
|
+
const expected = runProvenance({
|
|
1905
|
+
requestContext: Object.fromEntries(requestContext.entries()),
|
|
1906
|
+
});
|
|
1907
|
+
const persisted = runProvenance(snapshot);
|
|
1908
|
+
if (expected?.version === 2 &&
|
|
1909
|
+
((persisted !== undefined &&
|
|
1910
|
+
(persisted.version !== 2 ||
|
|
1911
|
+
persisted.startToken !== expected.startToken)) ||
|
|
1912
|
+
(this.#executionFence && persisted?.version !== 2)))
|
|
1913
|
+
throw new RunStateUnreadableError(workflowId, runId);
|
|
1914
|
+
if (proof)
|
|
1915
|
+
await this.#assertRetainedResume(source, workflowId, runId, expected, proof);
|
|
1422
1916
|
const persistedContext = snapshot.requestContext !== null &&
|
|
1423
1917
|
typeof snapshot.requestContext === 'object' &&
|
|
1424
1918
|
!Array.isArray(snapshot.requestContext)
|
|
@@ -1451,7 +1945,7 @@ export class RunnerRuntime {
|
|
|
1451
1945
|
persistedCoversLifecycle) {
|
|
1452
1946
|
return;
|
|
1453
1947
|
}
|
|
1454
|
-
await
|
|
1948
|
+
await source.persist.call(workflows, {
|
|
1455
1949
|
workflowName: workflowId,
|
|
1456
1950
|
runId,
|
|
1457
1951
|
snapshot: {
|
|
@@ -1462,11 +1956,6 @@ export class RunnerRuntime {
|
|
|
1462
1956
|
},
|
|
1463
1957
|
});
|
|
1464
1958
|
});
|
|
1465
|
-
// The run is terminal and its snapshot now says so, so any idempotency key
|
|
1466
|
-
// that named it is spent. AFTER the persist, never before: a reservation
|
|
1467
|
-
// marked terminal ahead of a persist that then failed would answer a retry
|
|
1468
|
-
// with ALREADY_SETTLED for a run whose settled state exists nowhere.
|
|
1469
|
-
await this.#settleStartReservation(runId);
|
|
1470
1959
|
}
|
|
1471
1960
|
#getWorkflow(workflowId) {
|
|
1472
1961
|
this.#ensureMastra();
|