@proofoftech/flowsafe 0.35.0 → 0.37.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 +70 -0
- package/README.md +14 -2
- package/dist/agent-runner/durable-agent-runner.d.ts +1 -2
- package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
- package/dist/agent-runner/durable-agent-runner.js +1 -1
- package/dist/agent-runner/durable-agent-runner.js.map +1 -1
- package/dist/answer-schema.d.ts +30 -0
- package/dist/answer-schema.d.ts.map +1 -0
- package/dist/answer-schema.js +311 -0
- package/dist/answer-schema.js.map +1 -0
- package/dist/approval-api/answer-schema.d.ts +2 -0
- package/dist/approval-api/answer-schema.d.ts.map +1 -0
- package/dist/approval-api/answer-schema.js +3 -0
- package/dist/approval-api/answer-schema.js.map +1 -0
- package/dist/approval-api/d1-store.d.ts +3 -16
- package/dist/approval-api/d1-store.d.ts.map +1 -1
- package/dist/approval-api/d1-store.js +117 -33
- package/dist/approval-api/d1-store.js.map +1 -1
- package/dist/approval-api/grants.d.ts +2 -3
- package/dist/approval-api/grants.d.ts.map +1 -1
- package/dist/approval-api/grants.js +5 -3
- package/dist/approval-api/grants.js.map +1 -1
- package/dist/approval-api/human-notifications.d.ts +34 -0
- package/dist/approval-api/human-notifications.d.ts.map +1 -0
- package/dist/approval-api/human-notifications.js +160 -0
- package/dist/approval-api/human-notifications.js.map +1 -0
- package/dist/approval-api/index.d.ts +3 -1
- package/dist/approval-api/index.d.ts.map +1 -1
- package/dist/approval-api/index.js +1 -0
- package/dist/approval-api/index.js.map +1 -1
- package/dist/approval-api/retention.d.ts +3 -1
- package/dist/approval-api/retention.d.ts.map +1 -1
- package/dist/approval-api/retention.js +21 -1
- package/dist/approval-api/retention.js.map +1 -1
- package/dist/approval-api/router.d.ts +1 -1
- package/dist/approval-api/router.d.ts.map +1 -1
- package/dist/approval-api/router.js +7 -0
- package/dist/approval-api/router.js.map +1 -1
- package/dist/approval-api/service.d.ts +6 -1
- package/dist/approval-api/service.d.ts.map +1 -1
- package/dist/approval-api/service.js +55 -10
- package/dist/approval-api/service.js.map +1 -1
- package/dist/approval-api/store-factory.d.ts +2 -0
- package/dist/approval-api/store-factory.d.ts.map +1 -1
- package/dist/approval-api/store-factory.js.map +1 -1
- package/dist/approval-api/store.d.ts +3 -0
- package/dist/approval-api/store.d.ts.map +1 -1
- package/dist/approval-api/store.js +2 -1
- package/dist/approval-api/store.js.map +1 -1
- package/dist/approval-api/types.d.ts +78 -4
- package/dist/approval-api/types.d.ts.map +1 -1
- package/dist/approval-api/types.js +1 -0
- package/dist/approval-api/types.js.map +1 -1
- package/dist/do-runner/child-run-ledger.d.ts +84 -0
- package/dist/do-runner/child-run-ledger.d.ts.map +1 -0
- package/dist/do-runner/child-run-ledger.js +272 -0
- package/dist/do-runner/child-run-ledger.js.map +1 -0
- package/dist/do-runner/child-runs.d.ts +95 -0
- package/dist/do-runner/child-runs.d.ts.map +1 -0
- package/dist/do-runner/child-runs.js +185 -0
- package/dist/do-runner/child-runs.js.map +1 -0
- package/dist/do-runner/constants.d.ts +3 -0
- package/dist/do-runner/constants.d.ts.map +1 -1
- package/dist/do-runner/constants.js +3 -0
- package/dist/do-runner/constants.js.map +1 -1
- package/dist/do-runner/d1-storage.d.ts +1 -0
- package/dist/do-runner/d1-storage.d.ts.map +1 -1
- package/dist/do-runner/d1-storage.js +108 -39
- package/dist/do-runner/d1-storage.js.map +1 -1
- package/dist/do-runner/durable-object.d.ts +26 -5
- package/dist/do-runner/durable-object.d.ts.map +1 -1
- package/dist/do-runner/durable-object.js +1857 -124
- package/dist/do-runner/durable-object.js.map +1 -1
- package/dist/do-runner/execution-context.d.ts +6 -0
- package/dist/do-runner/execution-context.d.ts.map +1 -1
- package/dist/do-runner/execution-context.js +10 -0
- package/dist/do-runner/execution-context.js.map +1 -1
- package/dist/do-runner/fenced-workflow-capability.d.ts +12 -1
- package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -1
- package/dist/do-runner/fenced-workflow-capability.js +17 -0
- package/dist/do-runner/fenced-workflow-capability.js.map +1 -1
- package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -1
- package/dist/do-runner/fenced-workflows-d1.js +169 -22
- package/dist/do-runner/fenced-workflows-d1.js.map +1 -1
- package/dist/do-runner/index.d.ts +9 -5
- 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/init.d.ts +4 -3
- package/dist/do-runner/init.d.ts.map +1 -1
- package/dist/do-runner/init.js +1 -0
- package/dist/do-runner/init.js.map +1 -1
- package/dist/do-runner/inventory.d.ts +2 -2
- package/dist/do-runner/inventory.d.ts.map +1 -1
- package/dist/do-runner/inventory.js +112 -5
- package/dist/do-runner/inventory.js.map +1 -1
- package/dist/do-runner/questions.d.ts +70 -0
- package/dist/do-runner/questions.d.ts.map +1 -0
- package/dist/do-runner/questions.js +440 -0
- package/dist/do-runner/questions.js.map +1 -0
- package/dist/do-runner/resume-refusal-codes.d.ts +3 -0
- package/dist/do-runner/resume-refusal-codes.d.ts.map +1 -0
- package/dist/do-runner/resume-refusal-codes.js +4 -0
- package/dist/do-runner/resume-refusal-codes.js.map +1 -0
- package/dist/do-runner/run-lifecycle.d.ts +42 -7
- package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
- package/dist/do-runner/run-lifecycle.js +77 -1
- package/dist/do-runner/run-lifecycle.js.map +1 -1
- package/dist/do-runner/run-lineage.d.ts +26 -0
- package/dist/do-runner/run-lineage.d.ts.map +1 -0
- package/dist/do-runner/run-lineage.js +38 -0
- package/dist/do-runner/run-lineage.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 -1
- package/dist/do-runner/run-storage-tables.js +2 -0
- package/dist/do-runner/run-storage-tables.js.map +1 -1
- package/dist/do-runner/run-terminal-state.d.ts +1 -1
- package/dist/do-runner/run-terminal-state.d.ts.map +1 -1
- package/dist/do-runner/run-terminal-state.js +2 -2
- package/dist/do-runner/run-terminal-state.js.map +1 -1
- package/dist/do-runner/runtime.d.ts +148 -20
- package/dist/do-runner/runtime.d.ts.map +1 -1
- package/dist/do-runner/runtime.js +726 -99
- package/dist/do-runner/runtime.js.map +1 -1
- package/dist/do-runner/suspension-deadline.d.ts +4 -1
- package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
- package/dist/do-runner/suspension-deadline.js +32 -7
- package/dist/do-runner/suspension-deadline.js.map +1 -1
- package/dist/do-runner/suspension-kinds.d.ts +15 -0
- package/dist/do-runner/suspension-kinds.d.ts.map +1 -0
- package/dist/do-runner/suspension-kinds.js +65 -0
- package/dist/do-runner/suspension-kinds.js.map +1 -0
- package/dist/durable-agent-workflow-id.d.ts +2 -0
- package/dist/durable-agent-workflow-id.d.ts.map +1 -0
- package/dist/durable-agent-workflow-id.js +3 -0
- package/dist/durable-agent-workflow-id.js.map +1 -0
- package/dist/host-kit/approval-bridge.d.ts +12 -14
- package/dist/host-kit/approval-bridge.d.ts.map +1 -1
- package/dist/host-kit/approval-bridge.js +40 -18
- package/dist/host-kit/approval-bridge.js.map +1 -1
- package/dist/host-kit/do-response.d.ts.map +1 -1
- package/dist/host-kit/do-response.js +50 -1
- package/dist/host-kit/do-response.js.map +1 -1
- package/dist/host-kit/do-run-topology.d.ts +10 -3
- package/dist/host-kit/do-run-topology.d.ts.map +1 -1
- package/dist/host-kit/do-run-topology.js +124 -1
- package/dist/host-kit/do-run-topology.js.map +1 -1
- package/dist/host-kit/flowsafe-worker.d.ts +30 -9
- package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
- package/dist/host-kit/flowsafe-worker.js +168 -21
- package/dist/host-kit/flowsafe-worker.js.map +1 -1
- package/dist/host-kit/host-approval-service.d.ts +1 -1
- package/dist/host-kit/host-approval-service.d.ts.map +1 -1
- package/dist/host-kit/host-approval-service.js +10 -4
- package/dist/host-kit/host-approval-service.js.map +1 -1
- package/dist/host-kit/index.d.ts +3 -1
- package/dist/host-kit/index.d.ts.map +1 -1
- package/dist/host-kit/index.js +1 -0
- package/dist/host-kit/index.js.map +1 -1
- package/dist/host-kit/run-router.d.ts +39 -3
- package/dist/host-kit/run-router.d.ts.map +1 -1
- package/dist/host-kit/run-router.js +136 -21
- package/dist/host-kit/run-router.js.map +1 -1
- package/dist/human-notification-storage.d.ts +5 -0
- package/dist/human-notification-storage.d.ts.map +1 -0
- package/dist/human-notification-storage.js +57 -0
- package/dist/human-notification-storage.js.map +1 -0
- package/dist/notification-retry.d.ts +3 -0
- package/dist/notification-retry.d.ts.map +1 -0
- package/dist/notification-retry.js +6 -0
- package/dist/notification-retry.js.map +1 -0
- package/dist/signals/notification-dispatch.d.ts +1 -1
- package/dist/signals/notification-dispatch.d.ts.map +1 -1
- package/dist/signals/notification-dispatch.js +3 -4
- package/dist/signals/notification-dispatch.js.map +1 -1
- package/package.json +1 -1
|
@@ -18,23 +18,26 @@
|
|
|
18
18
|
// exact failure an approval product must not have. Both locks are per runtime instance;
|
|
19
19
|
// cross-instance serialization comes from routing one DO instance per run
|
|
20
20
|
// (see durable-object.ts).
|
|
21
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
21
22
|
import { Mastra } from '@mastra/core/mastra';
|
|
22
23
|
import { RequestContext } from '@mastra/core/request-context';
|
|
23
24
|
import { createEmptyWorkflowSnapshot, } from '@mastra/core/storage';
|
|
24
25
|
import { cleanStepResult, } from '@mastra/core/workflows';
|
|
25
26
|
import { isExecutionPrincipalId, isExecutionPrincipalKind, } from '../approval-api/principal.js';
|
|
26
|
-
import { BREAKWATER_ACTOR_KEY, BREAKWATER_CONNECTOR_EXECUTION_KEY, BREAKWATER_ISOLATION_SCOPE_KEY, BREAKWATER_WORKFLOW_SCOPE_KEY, } from './breakwater-keys.js';
|
|
27
|
+
import { BREAKWATER_ACTOR_KEY, BREAKWATER_CONNECTOR_EXECUTION_KEY, BREAKWATER_CONNECTOR_GRANTS_KEY, BREAKWATER_ISOLATION_SCOPE_KEY, BREAKWATER_WORKFLOW_SCOPE_KEY, } from './breakwater-keys.js';
|
|
27
28
|
import { errorMessageOf, findInCauseChain } from './cause-chain.js';
|
|
28
29
|
import { DoStatusError } from './do-status-error.js';
|
|
29
30
|
import { assertMutationEpoch, ExecutionFenceUnreadableError, normalizeD1RunExecutionIdentity, normalizeMutationEpoch, normalizeStartIdentity, RunStartPendingError, } from './execution-admission.js';
|
|
30
|
-
import { isReservedExecutionContextKey, RUN_PROVENANCE_CONTEXT_KEY, stripReservedExecutionContext, } from './execution-context.js';
|
|
31
|
+
import { isReservedExecutionContextKey, LEG_OUTCOME_CONTEXT_KEY, RUN_PROVENANCE_CONTEXT_KEY, stripReservedExecutionContext, } from './execution-context.js';
|
|
31
32
|
import { admitsExistingRun, admitsRunStart, ExecutionFencedError, } from './execution-fence.js';
|
|
32
|
-
import { FENCED_WORKFLOW_STORAGE, } from './fenced-workflow-capability.js';
|
|
33
|
+
import { FENCED_WORKFLOW_STORAGE, isEntryBoundarySnapshot, } from './fenced-workflow-capability.js';
|
|
33
34
|
import { isDefinitiveInitialAdmissionRefusal } from './initial-admission-refusal.js';
|
|
34
35
|
import { mastraRegistryEntries } from './mastra-registry.js';
|
|
35
36
|
import { isPathSafeId } from './path-safe-id.js';
|
|
37
|
+
import { RUN_NOT_SUSPENDED, SUSPENSION_CHANGED, } from './resume-refusal-codes.js';
|
|
36
38
|
import { exceedsRunInputDepth, runInputDepthMessage, } from './run-input-depth.js';
|
|
37
|
-
import { advanceLifecycle, canonicalEconomicOperations, canonicalReplayPrincipals, canonicalScheduleDispatch, failureEnvelope, hasDisputedSettlement, isSettledLegAbort, legAbortReason, lifecycleFromRequestContext, projectTerminalLifecycle, RUN_FAILURE_MARKERS, RUN_LIFECYCLE_CONTEXT_KEY, RUN_SETTLING_MARKERS, RunLifecycleBlockedError, RunSettledConflictError, RunStateNotStorableError, runTerminalError, terminalCleanupFor, terminalLegAbortReason, } from './run-lifecycle.js';
|
|
39
|
+
import { advanceLifecycle, canonicalEconomicOperations, canonicalReplayPrincipals, canonicalScheduleDispatch, failureEnvelope, hasDisputedSettlement, isPauseLegAbort, isPauseReason, isSettledLegAbort, legAbortReason, lifecycleFromRequestContext, nextLifecycleRevision, pauseLegAbortReason, projectTerminalLifecycle, RUN_FAILURE_MARKERS, RUN_LIFECYCLE_CONTEXT_KEY, RUN_SETTLING_MARKERS, RunLifecycleBlockedError, RunSettledConflictError, RunStateNotStorableError, runTerminalError, terminalCleanupFor, terminalLegAbortReason, } from './run-lifecycle.js';
|
|
40
|
+
import { parseRunLineage, projectRunLineage, RUN_LINEAGE_CONTEXT_KEY, } from './run-lineage.js';
|
|
38
41
|
import { decodeProgressRunProvenance, decodeResumeCounts, nextResumeCount, runExecutionIdentityFor, } from './run-provenance.js';
|
|
39
42
|
import { captureRunRequester } from './run-requester.js';
|
|
40
43
|
import { errorText, isDurableRunStatus, isRunStatus, isTerminalRunStatus, terminalStateFields, terminalStateUpdate, } from './run-terminal-state.js';
|
|
@@ -68,7 +71,7 @@ export class UnknownRunError extends Error {
|
|
|
68
71
|
*/
|
|
69
72
|
export class RunNotSuspendedError extends DoStatusError {
|
|
70
73
|
status = 409;
|
|
71
|
-
reason = { code:
|
|
74
|
+
reason = { code: RUN_NOT_SUSPENDED };
|
|
72
75
|
constructor(workflowId, runId, runStatus) {
|
|
73
76
|
super(`run '${runId}' of workflow '${workflowId}' is '${runStatus}', not 'suspended'`);
|
|
74
77
|
this.name = 'RunNotSuspendedError';
|
|
@@ -80,7 +83,7 @@ export class RunNotSuspendedError extends DoStatusError {
|
|
|
80
83
|
*/
|
|
81
84
|
export class SuspensionChangedError extends DoStatusError {
|
|
82
85
|
status = 409;
|
|
83
|
-
reason = { code:
|
|
86
|
+
reason = { code: SUSPENSION_CHANGED };
|
|
84
87
|
constructor(workflowId, runId, step) {
|
|
85
88
|
super(`step '${step}' of run '${runId}' of workflow '${workflowId}' is no longer at the suspension the resume names`);
|
|
86
89
|
this.name = 'SuspensionChangedError';
|
|
@@ -145,6 +148,87 @@ export class InvalidRunRequestError extends Error {
|
|
|
145
148
|
this.name = 'InvalidRunRequestError';
|
|
146
149
|
}
|
|
147
150
|
}
|
|
151
|
+
/** @internal The step's resume schema rejected the internally built envelope. */
|
|
152
|
+
export class ChildAwaitResumeSchemaError extends InvalidRunRequestError {
|
|
153
|
+
}
|
|
154
|
+
export class PauseConflictError extends DoStatusError {
|
|
155
|
+
status = 409;
|
|
156
|
+
reason = { code: 'PAUSE_CONFLICT' };
|
|
157
|
+
constructor() {
|
|
158
|
+
super('a different pause request is already recorded for this run');
|
|
159
|
+
this.name = 'PauseConflictError';
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
export class PauseUnsupportedError extends DoStatusError {
|
|
163
|
+
status = 409;
|
|
164
|
+
reason = { code: 'PAUSE_UNSUPPORTED' };
|
|
165
|
+
constructor(message) {
|
|
166
|
+
super(message);
|
|
167
|
+
this.name = 'PauseUnsupportedError';
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
export class PauseHoldsScheduleError extends DoStatusError {
|
|
171
|
+
status = 409;
|
|
172
|
+
reason = { code: 'PAUSE_HOLDS_SCHEDULE' };
|
|
173
|
+
constructor() {
|
|
174
|
+
super('the schedule overlap policy skip or queue_one will skip or hold fires while the run is paused');
|
|
175
|
+
this.name = 'PauseHoldsScheduleError';
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
export class RunNotPausedError extends DoStatusError {
|
|
179
|
+
status = 409;
|
|
180
|
+
reason = { code: 'RUN_NOT_PAUSED' };
|
|
181
|
+
constructor() {
|
|
182
|
+
super('the run has no resumable pause');
|
|
183
|
+
this.name = 'RunNotPausedError';
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
export class PauseGenerationStaleError extends DoStatusError {
|
|
187
|
+
status = 409;
|
|
188
|
+
reason = { code: 'PAUSE_GENERATION_STALE' };
|
|
189
|
+
constructor() {
|
|
190
|
+
super('the run has a different pause generation');
|
|
191
|
+
this.name = 'PauseGenerationStaleError';
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
export class PauseInProgressError extends DoStatusError {
|
|
195
|
+
status = 409;
|
|
196
|
+
reason = { code: 'PAUSE_IN_PROGRESS' };
|
|
197
|
+
constructor() {
|
|
198
|
+
super('the run is honoring a pause');
|
|
199
|
+
this.name = 'PauseInProgressError';
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
/** @internal Validate the pause request before passing it across a host boundary. */
|
|
203
|
+
export function parsePauseRunOptions(value) {
|
|
204
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
205
|
+
throw new InvalidRunRequestError('pause body must be an object');
|
|
206
|
+
const { reason, holdsSchedule } = value;
|
|
207
|
+
if (!isPauseReason(reason))
|
|
208
|
+
throw new InvalidRunRequestError('pause requires a reason of 1 to 500 characters');
|
|
209
|
+
if (holdsSchedule !== undefined && typeof holdsSchedule !== 'boolean')
|
|
210
|
+
throw new InvalidRunRequestError('holdsSchedule must be a boolean');
|
|
211
|
+
return { reason, ...(holdsSchedule === undefined ? {} : { holdsSchedule }) };
|
|
212
|
+
}
|
|
213
|
+
/** @internal Validate the generation before forwarding or resuming a pause. */
|
|
214
|
+
export function parsePauseGeneration(value) {
|
|
215
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1)
|
|
216
|
+
throw new InvalidRunRequestError('expectedGeneration must be a positive safe integer');
|
|
217
|
+
return value;
|
|
218
|
+
}
|
|
219
|
+
function pauseForResume(state, expectedGeneration) {
|
|
220
|
+
const lifecycle = lifecycleFromRequestContext(state.requestContext);
|
|
221
|
+
const pause = lifecycle?.pause;
|
|
222
|
+
if (!lifecycle ||
|
|
223
|
+
!pause ||
|
|
224
|
+
(state.status === 'paused') !== (pause.pausedAt !== undefined))
|
|
225
|
+
throw new RunNotPausedError();
|
|
226
|
+
if (pause.honoringAt !== undefined)
|
|
227
|
+
throw new PauseInProgressError();
|
|
228
|
+
if (pause.generation !== expectedGeneration)
|
|
229
|
+
throw new PauseGenerationStaleError();
|
|
230
|
+
return { lifecycle, pause };
|
|
231
|
+
}
|
|
148
232
|
// Only core's own shapes of a caller-fixable refusal answer 400: anchored
|
|
149
233
|
// leading text, never a substring a foreign error can carry. The schema
|
|
150
234
|
// violation is read by id and category because `instanceof` fails across
|
|
@@ -180,6 +264,7 @@ const RUN_STATE_FIELDS = [
|
|
|
180
264
|
const RESUME_STATE_FIELDS = [
|
|
181
265
|
...RUN_STATE_FIELDS,
|
|
182
266
|
'payload',
|
|
267
|
+
'serializedStepGraph',
|
|
183
268
|
];
|
|
184
269
|
function runProvenance(state) {
|
|
185
270
|
const value = state.requestContext?.[RUN_PROVENANCE_CONTEXT_KEY];
|
|
@@ -218,7 +303,7 @@ function runProvenance(state) {
|
|
|
218
303
|
resumeCounts: counts,
|
|
219
304
|
};
|
|
220
305
|
}
|
|
221
|
-
function summarize(runId, result, counts, requestedBy, requestedByKind, deadlineAt) {
|
|
306
|
+
function summarize(workflowId, runId, result, lineage, counts, requestedBy, requestedByKind, deadlineAt) {
|
|
222
307
|
let summary;
|
|
223
308
|
switch (result.status) {
|
|
224
309
|
case 'success':
|
|
@@ -268,7 +353,7 @@ function summarize(runId, result, counts, requestedBy, requestedByKind, deadline
|
|
|
268
353
|
}
|
|
269
354
|
if (deadlineAt !== undefined)
|
|
270
355
|
summary.deadlineAt = deadlineAt;
|
|
271
|
-
return summary;
|
|
356
|
+
return { ...summary, ...projectRunLineage(workflowId, runId, lineage) };
|
|
272
357
|
}
|
|
273
358
|
// Storage may hand timestamps back as Date or as a serialized string
|
|
274
359
|
// depending on the adapter's snapshot round-trip; normalize defensively.
|
|
@@ -290,6 +375,14 @@ function resolveResumeStep(step, state) {
|
|
|
290
375
|
const suspended = Object.keys(state.suspendedPaths ?? {});
|
|
291
376
|
return suspended.length === 1 ? suspended[0]?.split('.') : undefined;
|
|
292
377
|
}
|
|
378
|
+
function suspendedInsideForeach(state, step) {
|
|
379
|
+
const paths = state.suspendedPaths ?? {};
|
|
380
|
+
const candidates = step
|
|
381
|
+
? [paths[step.join('.')] ?? paths[step[0] ?? '']]
|
|
382
|
+
: Object.values(paths);
|
|
383
|
+
return candidates.some(([entry] = []) => entry !== undefined &&
|
|
384
|
+
state.serializedStepGraph?.[entry]?.type === 'foreach');
|
|
385
|
+
}
|
|
293
386
|
// The live attempt for a step. Repeated steps (foreach) store an array of
|
|
294
387
|
// attempts, so the current suspension/resume is the latest; a single-run step
|
|
295
388
|
// stores one entry.
|
|
@@ -331,11 +424,14 @@ function byStep(suspendedKeys, lookup) {
|
|
|
331
424
|
}
|
|
332
425
|
return size > 0 ? map : undefined;
|
|
333
426
|
}
|
|
334
|
-
function summarizeState(runId, state, provenance) {
|
|
427
|
+
function summarizeState(workflowId, runId, state, provenance) {
|
|
335
428
|
const lifecycle = lifecycleFromRequestContext(state.requestContext);
|
|
336
429
|
const summary = {
|
|
337
430
|
runId,
|
|
338
431
|
status: lifecycle?.terminal?.status ?? state.status,
|
|
432
|
+
...(state.isFromInMemory
|
|
433
|
+
? {}
|
|
434
|
+
: projectRunLineage(workflowId, runId, parseRunLineage(state.requestContext?.[RUN_LINEAGE_CONTEXT_KEY]))),
|
|
339
435
|
createdAt: toIso(state.createdAt),
|
|
340
436
|
updatedAt: toIso(state.updatedAt),
|
|
341
437
|
};
|
|
@@ -347,6 +443,17 @@ function summarizeState(runId, state, provenance) {
|
|
|
347
443
|
return summaryWithRequester(summary, provenance);
|
|
348
444
|
}
|
|
349
445
|
summaryWithRequester(summary, provenance);
|
|
446
|
+
const pause = lifecycle?.pause;
|
|
447
|
+
if (pause &&
|
|
448
|
+
pause.restartAttemptToken === undefined &&
|
|
449
|
+
!isTerminalRunStatus(state.status)) {
|
|
450
|
+
summary.pauseRequestedAt = pause.requestedAt;
|
|
451
|
+
summary.pausedBy = pause.requestedBy;
|
|
452
|
+
summary.pauseReason = pause.reason;
|
|
453
|
+
summary.pauseGeneration = pause.generation;
|
|
454
|
+
if (pause.pausedAt !== undefined)
|
|
455
|
+
summary.pausedAt = pause.pausedAt;
|
|
456
|
+
}
|
|
350
457
|
if (state.status === 'success') {
|
|
351
458
|
summary.result = state.result;
|
|
352
459
|
}
|
|
@@ -377,11 +484,11 @@ function summarizeState(runId, state, provenance) {
|
|
|
377
484
|
}
|
|
378
485
|
return summary;
|
|
379
486
|
}
|
|
380
|
-
function summaryFromSelectedSnapshot(runId, snapshot, timestamps, provenance) {
|
|
487
|
+
function summaryFromSelectedSnapshot(workflowId, runId, snapshot, timestamps, provenance) {
|
|
381
488
|
const steps = Object.fromEntries(Object.entries(snapshot.context ?? {})
|
|
382
489
|
.filter(([key]) => key !== 'input' && key !== '__state')
|
|
383
490
|
.map(([key, value]) => [key, cleanStepResult(value)]));
|
|
384
|
-
return summarizeState(runId, {
|
|
491
|
+
return summarizeState(workflowId, runId, {
|
|
385
492
|
status: snapshot.status,
|
|
386
493
|
result: snapshot.result,
|
|
387
494
|
error: snapshot.error,
|
|
@@ -417,6 +524,7 @@ function orderedRequestContext(runtimeContext, provided, scheduled) {
|
|
|
417
524
|
key === BREAKWATER_CONNECTOR_EXECUTION_KEY ||
|
|
418
525
|
key === RUN_PROVENANCE_CONTEXT_KEY ||
|
|
419
526
|
key === RUN_LIFECYCLE_CONTEXT_KEY ||
|
|
527
|
+
key === RUN_LINEAGE_CONTEXT_KEY ||
|
|
420
528
|
key === 'runId') {
|
|
421
529
|
continue;
|
|
422
530
|
}
|
|
@@ -507,33 +615,30 @@ export function assertRunInputDepth(field, value) {
|
|
|
507
615
|
if (exceedsRunInputDepth(value))
|
|
508
616
|
throw new InvalidRunRequestError(runInputDepthMessage(field));
|
|
509
617
|
}
|
|
510
|
-
/**
|
|
511
|
-
* `resumeCount` is absent on a first suspension and 1, 2, … after it, so 0 is
|
|
512
|
-
* malformed rather than a suspension the step can be at.
|
|
513
|
-
*/
|
|
514
618
|
function captureExpectedSuspension(value) {
|
|
515
619
|
if (value === undefined)
|
|
516
620
|
return undefined;
|
|
517
621
|
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
518
622
|
throw new InvalidRunRequestError('expectedSuspension is malformed');
|
|
519
623
|
const { suspendedAt, resumeCount } = value;
|
|
520
|
-
if (
|
|
624
|
+
if (typeof suspendedAt !== 'number' ||
|
|
625
|
+
!Number.isSafeInteger(suspendedAt) ||
|
|
521
626
|
suspendedAt < 0 ||
|
|
522
627
|
(resumeCount !== undefined &&
|
|
523
|
-
(
|
|
628
|
+
(typeof resumeCount !== 'number' ||
|
|
629
|
+
!Number.isSafeInteger(resumeCount) ||
|
|
630
|
+
resumeCount < 0)))
|
|
524
631
|
throw new InvalidRunRequestError('expectedSuspension is malformed');
|
|
525
632
|
return Object.freeze({
|
|
526
|
-
suspendedAt
|
|
527
|
-
...(resumeCount === undefined
|
|
528
|
-
? {}
|
|
529
|
-
: { resumeCount: resumeCount }),
|
|
633
|
+
suspendedAt,
|
|
634
|
+
...(resumeCount === undefined ? {} : { resumeCount }),
|
|
530
635
|
});
|
|
531
636
|
}
|
|
532
637
|
function isRunStateNotStorable(error) {
|
|
533
638
|
return findInCauseChain(error, (link) => link instanceof RunStateNotStorableError, { rootOnly: false });
|
|
534
639
|
}
|
|
535
640
|
function captureStartRunOptions(source) {
|
|
536
|
-
const { runId, inputData, initialState, storedRequestContext, attemptToken, deadlineMs, economicOperations: rawOperations, scheduleDispatch: rawDispatch, idempotencyKey, requestedBy, requestedByKind, runRequester: rawRequester, mutationEpoch: rawEpoch, startIdentity: rawIdentity, agentStart: rawAgentStart, onPreparedStartIdentity, pendingTerminal, runOwnerGuard: rawGuard, startReservation: rawReservation, legAbort, } = source;
|
|
641
|
+
const { runId, inputData, initialState, storedRequestContext, attemptToken, deadlineMs, economicOperations: rawOperations, scheduleDispatch: rawDispatch, idempotencyKey, requestedBy, requestedByKind, runRequester: rawRequester, mutationEpoch: rawEpoch, startIdentity: rawIdentity, child: rawChild, agentStart: rawAgentStart, onPreparedStartIdentity, onAdmittedStartIdentity, pendingTerminal, runOwnerGuard: rawGuard, startReservation: rawReservation, legAbort, } = source;
|
|
537
642
|
assertLegAbort(legAbort);
|
|
538
643
|
if (requestedBy !== undefined && !isExecutionPrincipalId(requestedBy)) {
|
|
539
644
|
throw new InvalidRunRequestError('requestedBy is malformed');
|
|
@@ -550,6 +655,17 @@ function captureStartRunOptions(source) {
|
|
|
550
655
|
throw new InvalidRunRequestError('runRequester is malformed');
|
|
551
656
|
const mutationEpoch = normalizeMutationEpoch(rawEpoch);
|
|
552
657
|
const startIdentity = rawIdentity === undefined ? undefined : normalizeStartIdentity(rawIdentity);
|
|
658
|
+
let child;
|
|
659
|
+
if (rawChild !== undefined) {
|
|
660
|
+
const lineage = parseRunLineage(rawChild.lineage);
|
|
661
|
+
const { parentDeadlineAt } = rawChild;
|
|
662
|
+
if (!lineage ||
|
|
663
|
+
(parentDeadlineAt !== undefined &&
|
|
664
|
+
(!Number.isSafeInteger(parentDeadlineAt) || parentDeadlineAt < 0))) {
|
|
665
|
+
throw new InvalidRunRequestError('child start authority is malformed');
|
|
666
|
+
}
|
|
667
|
+
child = Object.freeze({ lineage, parentDeadlineAt });
|
|
668
|
+
}
|
|
553
669
|
const startReservation = rawReservation === undefined
|
|
554
670
|
? undefined
|
|
555
671
|
: captureReservation(rawReservation, 'started');
|
|
@@ -580,6 +696,9 @@ function captureStartRunOptions(source) {
|
|
|
580
696
|
typeof onPreparedStartIdentity !== 'function') {
|
|
581
697
|
throw new InvalidRunRequestError('onPreparedStartIdentity is malformed');
|
|
582
698
|
}
|
|
699
|
+
if (onAdmittedStartIdentity !== undefined &&
|
|
700
|
+
typeof onAdmittedStartIdentity !== 'function')
|
|
701
|
+
throw new InvalidRunRequestError('onAdmittedStartIdentity is malformed');
|
|
583
702
|
if (pendingTerminal !== undefined && typeof pendingTerminal !== 'function')
|
|
584
703
|
throw new InvalidRunRequestError('pendingTerminal is malformed');
|
|
585
704
|
let runOwnerGuard;
|
|
@@ -654,8 +773,10 @@ function captureStartRunOptions(source) {
|
|
|
654
773
|
idempotencyKey,
|
|
655
774
|
mutationEpoch,
|
|
656
775
|
startIdentity,
|
|
776
|
+
child,
|
|
657
777
|
agentStart,
|
|
658
778
|
onPreparedStartIdentity,
|
|
779
|
+
onAdmittedStartIdentity,
|
|
659
780
|
pendingTerminal,
|
|
660
781
|
runOwnerGuard,
|
|
661
782
|
startReservation,
|
|
@@ -666,7 +787,11 @@ function captureStartRunOptions(source) {
|
|
|
666
787
|
: captured);
|
|
667
788
|
}
|
|
668
789
|
function lifecycleForStart(options) {
|
|
669
|
-
const
|
|
790
|
+
const requestedDeadlineAt = relativeDeadline(options.deadlineMs);
|
|
791
|
+
const parentDeadlineAt = options.child?.parentDeadlineAt;
|
|
792
|
+
const deadlineAt = requestedDeadlineAt === undefined || parentDeadlineAt === undefined
|
|
793
|
+
? (requestedDeadlineAt ?? parentDeadlineAt)
|
|
794
|
+
: Math.min(requestedDeadlineAt, parentDeadlineAt);
|
|
670
795
|
const economicOperations = canonicalEconomicOperations(options.economicOperations);
|
|
671
796
|
const scheduleDispatch = canonicalScheduleDispatch(options.scheduleDispatch);
|
|
672
797
|
if (deadlineAt === undefined &&
|
|
@@ -687,6 +812,8 @@ function effectiveLifecycle(persisted, active) {
|
|
|
687
812
|
return active;
|
|
688
813
|
if (!active)
|
|
689
814
|
return persisted;
|
|
815
|
+
if (persisted.transitionIntent?.childCascadeStarted)
|
|
816
|
+
return persisted;
|
|
690
817
|
// As lifecycleMergeSql decides: a stored intent never joins a lifecycle it
|
|
691
818
|
// was not checked against.
|
|
692
819
|
if (persisted.transitionIntent && hasDisputedSettlement(active))
|
|
@@ -741,6 +868,23 @@ function failedByMarker(marker, now) {
|
|
|
741
868
|
timestamp: now,
|
|
742
869
|
};
|
|
743
870
|
}
|
|
871
|
+
const activeWorkflowLeg = new AsyncLocalStorage();
|
|
872
|
+
/** @internal The engine leg whose step is executing in this async context. */
|
|
873
|
+
export function currentWorkflowLeg() {
|
|
874
|
+
return activeWorkflowLeg.getStore();
|
|
875
|
+
}
|
|
876
|
+
function matchesSuspension(step, suspendedAt, resumeCount) {
|
|
877
|
+
return ({ state }, provenance) => {
|
|
878
|
+
const result = state.context?.[step];
|
|
879
|
+
const attempt = Array.isArray(result) ? result.at(-1) : result;
|
|
880
|
+
return (Object.hasOwn(state.suspendedPaths ?? {}, step) &&
|
|
881
|
+
attempt !== null &&
|
|
882
|
+
typeof attempt === 'object' &&
|
|
883
|
+
'suspendedAt' in attempt &&
|
|
884
|
+
attempt.suspendedAt === suspendedAt &&
|
|
885
|
+
(new Map(provenance?.resumeCounts).get(step) ?? 0) === resumeCount);
|
|
886
|
+
};
|
|
887
|
+
}
|
|
744
888
|
function sameExecution(a, b) {
|
|
745
889
|
return (a.tablePrefix === b.tablePrefix &&
|
|
746
890
|
a.workflowId === b.workflowId &&
|
|
@@ -762,6 +906,7 @@ function assertClaimIdentity(claim, execution, key = claim.key) {
|
|
|
762
906
|
}
|
|
763
907
|
}
|
|
764
908
|
export class RunnerRuntime {
|
|
909
|
+
#childRunLimits;
|
|
765
910
|
#storage;
|
|
766
911
|
#logger;
|
|
767
912
|
#requestContextForRun;
|
|
@@ -779,6 +924,14 @@ export class RunnerRuntime {
|
|
|
779
924
|
#startIdempotency;
|
|
780
925
|
#mastra;
|
|
781
926
|
constructor(options) {
|
|
927
|
+
const { maxDepth = 4, maxChildrenPerRun = 16 } = options.childRuns ?? {};
|
|
928
|
+
if (!Number.isSafeInteger(maxDepth) ||
|
|
929
|
+
maxDepth < 0 ||
|
|
930
|
+
!Number.isSafeInteger(maxChildrenPerRun) ||
|
|
931
|
+
maxChildrenPerRun < 0) {
|
|
932
|
+
throw new Error('child run limits must be nonnegative safe integers');
|
|
933
|
+
}
|
|
934
|
+
this.#childRunLimits = Object.freeze({ maxDepth, maxChildrenPerRun });
|
|
782
935
|
this.#storage = options.storage;
|
|
783
936
|
this.#logger = options.logger ?? false;
|
|
784
937
|
this.#requestContextForRun = options.requestContextForRun;
|
|
@@ -786,6 +939,10 @@ export class RunnerRuntime {
|
|
|
786
939
|
this.#executionFence = options.executionFence;
|
|
787
940
|
this.#startIdempotency = options.startIdempotency;
|
|
788
941
|
}
|
|
942
|
+
/** @internal Limits used by the run object when reserving children. */
|
|
943
|
+
get childRunLimits() {
|
|
944
|
+
return this.#childRunLimits;
|
|
945
|
+
}
|
|
789
946
|
/**
|
|
790
947
|
* The deployment execution fence this runtime enforces, or undefined when
|
|
791
948
|
* the host built an unfenced runtime. Exposed so the surfaces ABOVE the
|
|
@@ -1042,8 +1199,24 @@ export class RunnerRuntime {
|
|
|
1042
1199
|
const lifecycle = lifecycleForStart(options);
|
|
1043
1200
|
active.lifecycle = lifecycle;
|
|
1044
1201
|
preflight = false;
|
|
1045
|
-
const
|
|
1202
|
+
const lineage = options.child?.lineage;
|
|
1203
|
+
const requestContext = await this.#requestContextFor(workflowId, runId, lineage === undefined
|
|
1204
|
+
? { kind: 'start' }
|
|
1205
|
+
: {
|
|
1206
|
+
kind: 'start',
|
|
1207
|
+
parent: Object.freeze({
|
|
1208
|
+
workflowId: lineage.parentWorkflowId,
|
|
1209
|
+
runId: lineage.parentRunId,
|
|
1210
|
+
rootRunId: lineage.rootRunId,
|
|
1211
|
+
depth: lineage.depth - 1,
|
|
1212
|
+
key: lineage.childKey,
|
|
1213
|
+
...(options.runRequester === undefined
|
|
1214
|
+
? {}
|
|
1215
|
+
: { runRequester: options.runRequester }),
|
|
1216
|
+
}),
|
|
1217
|
+
}, provenance, options.storedRequestContext, lifecycle, lineage);
|
|
1046
1218
|
active.requestContext = requestContext;
|
|
1219
|
+
this.#enablePauseBoundary(active);
|
|
1047
1220
|
if (options.onPreparedStartIdentity)
|
|
1048
1221
|
await Reflect.apply(options.onPreparedStartIdentity, undefined, [
|
|
1049
1222
|
execution,
|
|
@@ -1118,13 +1291,16 @@ export class RunnerRuntime {
|
|
|
1118
1291
|
active.lifecycle = intent;
|
|
1119
1292
|
requestContext.set(RUN_LIFECYCLE_CONTEXT_KEY, intent);
|
|
1120
1293
|
}
|
|
1294
|
+
if (initial && options.onAdmittedStartIdentity)
|
|
1295
|
+
await Reflect.apply(options.onAdmittedStartIdentity, undefined, [capturedExecution]);
|
|
1121
1296
|
active.run = run;
|
|
1122
1297
|
engineEntered = true;
|
|
1123
|
-
|
|
1298
|
+
// Mastra's WorkflowResult omits the engine's 'canceled' status.
|
|
1299
|
+
const startPromise = this.#inWorkflowLeg(workflowId, runId, active, () => run.start({
|
|
1124
1300
|
inputData: options.inputData,
|
|
1125
1301
|
initialState: options.initialState,
|
|
1126
1302
|
requestContext,
|
|
1127
|
-
});
|
|
1303
|
+
}));
|
|
1128
1304
|
if (pending && !hasDisputedSettlement(active.lifecycle)) {
|
|
1129
1305
|
this.#terminalAbortIntents.set(activeKey, pending.status);
|
|
1130
1306
|
// Run.cancel reads storage before aborting, while start
|
|
@@ -1138,6 +1314,10 @@ export class RunnerRuntime {
|
|
|
1138
1314
|
});
|
|
1139
1315
|
const result = await executionPromise;
|
|
1140
1316
|
this.#throwIfSettledLeg(active, workflowId, runId);
|
|
1317
|
+
if (result.status === 'canceled' &&
|
|
1318
|
+
isPauseLegAbort(active.run?.abortController.signal.reason) &&
|
|
1319
|
+
(await this.#commitPause(workflowId, runId, active)))
|
|
1320
|
+
return;
|
|
1141
1321
|
await this.#reconcileTerminalState(workflowId, runId, result, requestContext, source,
|
|
1142
1322
|
// A fenced start's admission witnessed the row it stored.
|
|
1143
1323
|
admissionEntered || active.storedRunScope?.rowStored === true);
|
|
@@ -1184,9 +1364,78 @@ export class RunnerRuntime {
|
|
|
1184
1364
|
* loads it and re-enters the engine at the suspended step.
|
|
1185
1365
|
*/
|
|
1186
1366
|
async resume(workflowId, runId, options = {}) {
|
|
1367
|
+
return this.#resume(workflowId, runId, options);
|
|
1368
|
+
}
|
|
1369
|
+
/** @internal Resume from persisted child outcomes under a suspension fingerprint. */
|
|
1370
|
+
resumeChildAwait(workflowId, runId, options) {
|
|
1371
|
+
return this.#resume(workflowId, runId, options, { kind: 'child-await' });
|
|
1372
|
+
}
|
|
1373
|
+
async resumePaused(workflowId, runId, principal, options) {
|
|
1374
|
+
const { expectedGeneration, legAbort } = options;
|
|
1375
|
+
assertLegAbort(legAbort);
|
|
1376
|
+
if (!isExecutionPrincipalKind(principal?.kind) ||
|
|
1377
|
+
!isExecutionPrincipalId(principal?.id))
|
|
1378
|
+
throw new InvalidRunRequestError('resume principal is malformed');
|
|
1379
|
+
const restartPrincipal = { id: principal.id, kind: principal.kind };
|
|
1380
|
+
const cleared = await this.clearPendingPause(workflowId, runId, expectedGeneration);
|
|
1381
|
+
if (cleared)
|
|
1382
|
+
return cleared;
|
|
1383
|
+
return this.restartPaused(workflowId, runId, restartPrincipal, {
|
|
1384
|
+
expectedGeneration,
|
|
1385
|
+
legAbort,
|
|
1386
|
+
});
|
|
1387
|
+
}
|
|
1388
|
+
/** @internal Clear a pending pause without waiting for the active leg. */
|
|
1389
|
+
async clearPendingPause(workflowId, runId, generation) {
|
|
1390
|
+
const expectedGeneration = parsePauseGeneration(generation);
|
|
1391
|
+
this.#getWorkflow(workflowId);
|
|
1392
|
+
const proof = await this.#assertResumeFence(workflowId, runId);
|
|
1393
|
+
return this.#withLifecycleLock(workflowId, runId, () => this.#retryOnRowChange(workflowId, runId, async () => {
|
|
1394
|
+
const active = this.#activeRuns.get(this.#runKey(workflowId, runId));
|
|
1395
|
+
const source = active?.source ?? (await this.#captureWorkflowStorage(workflowId));
|
|
1396
|
+
const { state, row } = await this.#readForTransition(source, workflowId, runId);
|
|
1397
|
+
const { lifecycle, pause } = pauseForResume(state, expectedGeneration);
|
|
1398
|
+
if (pause.pausedAt !== undefined)
|
|
1399
|
+
return;
|
|
1400
|
+
if (!row)
|
|
1401
|
+
throw new RunStateUnreadableError(workflowId, runId);
|
|
1402
|
+
if (lifecycle.transitionIntent ||
|
|
1403
|
+
lifecycle.terminal ||
|
|
1404
|
+
!TERMINABLE_RUN_STATUSES.has(state.status))
|
|
1405
|
+
throw new RunTerminalConflictError(workflowId, runId, state.status, lifecycle.transitionIntent ? 'ending' : 'terminal');
|
|
1406
|
+
const provenance = runProvenance(state);
|
|
1407
|
+
await this.#assertRetainedResume(source, workflowId, runId, provenance, proof);
|
|
1408
|
+
const now = Date.now();
|
|
1409
|
+
const next = advanceLifecycle(lifecycle, {});
|
|
1410
|
+
delete next.pause;
|
|
1411
|
+
await this.#persistIntent(workflowId, runId, state, next, now, source, row);
|
|
1412
|
+
return summaryFromSelectedSnapshot(workflowId, runId, {
|
|
1413
|
+
...state,
|
|
1414
|
+
requestContext: {
|
|
1415
|
+
...state.requestContext,
|
|
1416
|
+
[RUN_LIFECYCLE_CONTEXT_KEY]: next,
|
|
1417
|
+
},
|
|
1418
|
+
}, { ...row, updatedAt: new Date(now).toISOString() }, provenance);
|
|
1419
|
+
}));
|
|
1420
|
+
}
|
|
1421
|
+
/** @internal Start a leg for a committed pause after checking for a pending pause. */
|
|
1422
|
+
restartPaused(workflowId, runId, principal, options, onRestartState) {
|
|
1423
|
+
return this.#resume(workflowId, runId, {
|
|
1424
|
+
requestedBy: principal.id,
|
|
1425
|
+
requestedByKind: principal.kind,
|
|
1426
|
+
legAbort: options.legAbort,
|
|
1427
|
+
}, {
|
|
1428
|
+
kind: 'restart',
|
|
1429
|
+
generation: options.expectedGeneration,
|
|
1430
|
+
onRestartState,
|
|
1431
|
+
});
|
|
1432
|
+
}
|
|
1433
|
+
async #resume(workflowId, runId, options, mode) {
|
|
1434
|
+
const restart = mode?.kind === 'restart' ? mode : undefined;
|
|
1187
1435
|
const { legAbort } = options;
|
|
1188
1436
|
assertLegAbort(legAbort);
|
|
1189
|
-
|
|
1437
|
+
if (mode?.kind !== 'child-await')
|
|
1438
|
+
assertRunInputDepth('resumeData', options.resumeData);
|
|
1190
1439
|
const expectedSuspension = captureExpectedSuspension(options.expectedSuspension);
|
|
1191
1440
|
this.#getWorkflow(workflowId);
|
|
1192
1441
|
const proof = await this.#assertResumeFence(workflowId, runId);
|
|
@@ -1199,6 +1448,7 @@ export class RunnerRuntime {
|
|
|
1199
1448
|
let provenance;
|
|
1200
1449
|
let engineEntered = false;
|
|
1201
1450
|
let outcomeReadStarted = false;
|
|
1451
|
+
let restorePersistenceOverride;
|
|
1202
1452
|
try {
|
|
1203
1453
|
const source = await this.#captureWorkflowStorage(workflowId);
|
|
1204
1454
|
active.source = source;
|
|
@@ -1215,13 +1465,21 @@ export class RunnerRuntime {
|
|
|
1215
1465
|
prior.startToken !== proof.startToken ||
|
|
1216
1466
|
source.tablePrefix !== proof.tablePrefix))
|
|
1217
1467
|
throw new RunStateUnreadableError(workflowId, runId);
|
|
1218
|
-
if (
|
|
1468
|
+
if (restart) {
|
|
1469
|
+
pauseForResume(state, restart.generation);
|
|
1470
|
+
if (state.status !== 'paused')
|
|
1471
|
+
throw new RunNotPausedError();
|
|
1472
|
+
}
|
|
1473
|
+
else if (state.status !== 'suspended')
|
|
1219
1474
|
throw new RunNotSuspendedError(workflowId, runId, state.status);
|
|
1220
|
-
const prepared = await this.#trustedResumePreparation(workflowId, runId, state, { ...options, expectedSuspension });
|
|
1475
|
+
const prepared = await this.#trustedResumePreparation(workflowId, runId, state, { ...options, expectedSuspension }, restart !== undefined);
|
|
1221
1476
|
provenance = prepared.provenance;
|
|
1222
1477
|
const { requestContext, lifecycle, nextCounts } = prepared;
|
|
1223
1478
|
active.requestContext = requestContext;
|
|
1224
1479
|
active.lifecycle = lifecycle;
|
|
1480
|
+
if (restart ||
|
|
1481
|
+
!suspendedInsideForeach(state, resolveResumeStep(options.step, state)))
|
|
1482
|
+
this.#enablePauseBoundary(active);
|
|
1225
1483
|
const check = async () => {
|
|
1226
1484
|
const current = await this.#assertRetainedResume(source, workflowId, runId, prior, proof);
|
|
1227
1485
|
const currentLifecycle = lifecycleFromRequestContext(current.requestContext);
|
|
@@ -1250,18 +1508,53 @@ export class RunnerRuntime {
|
|
|
1250
1508
|
const run = await this.#createRun(workflowId, runId);
|
|
1251
1509
|
const { executionPromise } = await this.#withLifecycleLock(workflowId, runId, async () => {
|
|
1252
1510
|
await check();
|
|
1511
|
+
if (restart) {
|
|
1512
|
+
const { storedRunScope } = active;
|
|
1513
|
+
if (!storedRunScope)
|
|
1514
|
+
throw new PauseUnsupportedError('storage cannot restart a pause');
|
|
1515
|
+
const claimedLifecycle = await this.#claimPausedRun(source, workflowId, runId, restart.generation, prior?.startToken, prepared.provenance.attemptToken, restart.onRestartState);
|
|
1516
|
+
active.lifecycle = claimedLifecycle;
|
|
1517
|
+
requestContext.set(RUN_LIFECYCLE_CONTEXT_KEY, claimedLifecycle);
|
|
1518
|
+
// The restart must record step entry before the step runs,
|
|
1519
|
+
// even when the workflow normally filters running snapshots.
|
|
1520
|
+
const engine = run.executionEngine;
|
|
1521
|
+
const override = engine.getRunPersistenceOverride(runId);
|
|
1522
|
+
const persistFirstWrite = () => true;
|
|
1523
|
+
const restore = () => {
|
|
1524
|
+
const currentOverride = engine.getRunPersistenceOverride(runId);
|
|
1525
|
+
if (currentOverride !== persistFirstWrite)
|
|
1526
|
+
return;
|
|
1527
|
+
if (override) {
|
|
1528
|
+
engine.setRunPersistenceOverride(runId, override);
|
|
1529
|
+
}
|
|
1530
|
+
else {
|
|
1531
|
+
engine.clearRunPersistenceOverride(runId);
|
|
1532
|
+
}
|
|
1533
|
+
};
|
|
1534
|
+
storedRunScope.restart = {
|
|
1535
|
+
attemptToken: prepared.provenance.attemptToken,
|
|
1536
|
+
onFirstWrite: restore,
|
|
1537
|
+
};
|
|
1538
|
+
restorePersistenceOverride = restore;
|
|
1539
|
+
engine.setRunPersistenceOverride(runId, persistFirstWrite);
|
|
1540
|
+
}
|
|
1253
1541
|
active.run = run;
|
|
1254
1542
|
engineEntered = true;
|
|
1255
|
-
|
|
1256
|
-
|
|
1543
|
+
const legPromise = this.#inWorkflowLeg(workflowId, runId, active, () => restart === undefined
|
|
1544
|
+
? run.resume({
|
|
1257
1545
|
step: options.step,
|
|
1258
1546
|
resumeData: options.resumeData,
|
|
1259
1547
|
requestContext,
|
|
1260
|
-
})
|
|
1261
|
-
|
|
1548
|
+
})
|
|
1549
|
+
: run.restart({ requestContext }));
|
|
1550
|
+
return { executionPromise: legPromise };
|
|
1262
1551
|
});
|
|
1263
1552
|
const resumed = await executionPromise;
|
|
1264
1553
|
this.#throwIfSettledLeg(active, workflowId, runId);
|
|
1554
|
+
if (resumed.status === 'canceled' &&
|
|
1555
|
+
isPauseLegAbort(active.run?.abortController.signal.reason) &&
|
|
1556
|
+
(await this.#commitPause(workflowId, runId, active)))
|
|
1557
|
+
return resumed;
|
|
1265
1558
|
await this.#reconcileTerminalState(workflowId, runId, resumed, requestContext, source,
|
|
1266
1559
|
// A resume begins from the row it read.
|
|
1267
1560
|
true, proof);
|
|
@@ -1274,22 +1567,151 @@ export class RunnerRuntime {
|
|
|
1274
1567
|
await this.#settleStartReservation(selected);
|
|
1275
1568
|
return selected.summary;
|
|
1276
1569
|
}
|
|
1277
|
-
|
|
1570
|
+
if (source.storage === 'd1' &&
|
|
1571
|
+
source.capability.supportsPause &&
|
|
1572
|
+
(result.status === 'suspended' ||
|
|
1573
|
+
isPauseLegAbort(active.run?.abortController.signal.reason))) {
|
|
1574
|
+
const summary = await this.#summaryAfterPersist(workflowId, runId, source, provenance);
|
|
1575
|
+
if (summary.pauseGeneration !== undefined)
|
|
1576
|
+
return summary;
|
|
1577
|
+
}
|
|
1578
|
+
return summarize(workflowId, runId, result, parseRunLineage(state.requestContext?.[RUN_LINEAGE_CONTEXT_KEY]), nextCounts, provenance.requestedBy, provenance.requestedByKind, lifecycle?.deadlineAt);
|
|
1278
1579
|
}
|
|
1279
1580
|
catch (error) {
|
|
1280
|
-
|
|
1581
|
+
const claim = active.storedRunScope?.restart;
|
|
1582
|
+
const source = active.source;
|
|
1583
|
+
if (claim?.onFirstWrite && source) {
|
|
1584
|
+
try {
|
|
1585
|
+
const restored = await this.#withLifecycleLock(workflowId, runId, () => this.#retryOnRowChange(workflowId, runId, async () => {
|
|
1586
|
+
const { state, row } = await this.#readForTransition(source, workflowId, runId);
|
|
1587
|
+
return row
|
|
1588
|
+
? this.#restorePausedRestart(source, state, row, Date.now(), claim.attemptToken)
|
|
1589
|
+
: undefined;
|
|
1590
|
+
}));
|
|
1591
|
+
if (restored)
|
|
1592
|
+
restart?.onRestartState?.(restored);
|
|
1593
|
+
}
|
|
1594
|
+
catch (restoreError) {
|
|
1595
|
+
console.error('restart pause recovery failed', restoreError);
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
else if (engineEntered && provenance && !outcomeReadStarted) {
|
|
1281
1599
|
await this.#failUnstorableLeg(workflowId, runId, active, error);
|
|
1282
1600
|
const recovered = await this.#summaryForAttempt(workflowId, runId, provenance);
|
|
1283
1601
|
if (recovered)
|
|
1284
1602
|
return recovered;
|
|
1285
1603
|
}
|
|
1604
|
+
if (mode?.kind === 'child-await' &&
|
|
1605
|
+
error instanceof Error &&
|
|
1606
|
+
isSchemaViolation(error))
|
|
1607
|
+
throw new ChildAwaitResumeSchemaError(error.message);
|
|
1286
1608
|
throw asClientError(error) ?? error;
|
|
1287
1609
|
}
|
|
1288
1610
|
finally {
|
|
1611
|
+
restorePersistenceOverride?.();
|
|
1289
1612
|
await leaveLeg();
|
|
1290
1613
|
}
|
|
1291
1614
|
});
|
|
1292
1615
|
}
|
|
1616
|
+
#claimPausedRun(source, workflowId, runId, expectedGeneration, startToken, attemptToken, onRestartState) {
|
|
1617
|
+
return this.#retryOnRowChange(workflowId, runId, async () => {
|
|
1618
|
+
const { state, row } = await this.#readForTransition(source, workflowId, runId);
|
|
1619
|
+
const provenance = runProvenance(state);
|
|
1620
|
+
if (!row || provenance?.startToken !== startToken)
|
|
1621
|
+
throw new RunStateUnreadableError(workflowId, runId);
|
|
1622
|
+
const { lifecycle, pause } = pauseForResume(state, expectedGeneration);
|
|
1623
|
+
if (state.status !== 'paused')
|
|
1624
|
+
throw new RunNotPausedError();
|
|
1625
|
+
const now = Date.now();
|
|
1626
|
+
const ending = lifecycle.terminal?.status ??
|
|
1627
|
+
lifecycle.transitionIntent?.status ??
|
|
1628
|
+
(lifecycle.deadlineAt !== undefined && lifecycle.deadlineAt <= now
|
|
1629
|
+
? 'timed_out'
|
|
1630
|
+
: undefined);
|
|
1631
|
+
if (ending)
|
|
1632
|
+
throw new RunTerminalConflictError(workflowId, runId, ending, lifecycle.terminal ? 'terminal' : 'ending');
|
|
1633
|
+
const next = advanceLifecycle(lifecycle, {});
|
|
1634
|
+
delete next.pause;
|
|
1635
|
+
const running = await this.#persistLifecycle(workflowId, runId, { ...state, status: 'running' }, { ...next, pause: { ...pause, restartAttemptToken: attemptToken } }, now, source, row);
|
|
1636
|
+
onRestartState?.(summaryFromSelectedSnapshot(workflowId, runId, running, { ...row, updatedAt: new Date(now).toISOString() }, provenance));
|
|
1637
|
+
return next;
|
|
1638
|
+
});
|
|
1639
|
+
}
|
|
1640
|
+
async #restorePausedRestart(source, state, row, now, attemptToken) {
|
|
1641
|
+
const lifecycle = lifecycleFromRequestContext(state.requestContext);
|
|
1642
|
+
if (!lifecycle?.pause ||
|
|
1643
|
+
lifecycle.pause.restartAttemptToken !== attemptToken ||
|
|
1644
|
+
lifecycle.transitionIntent ||
|
|
1645
|
+
RUN_SETTLING_MARKERS.some((marker) => lifecycle[marker] !== undefined) ||
|
|
1646
|
+
!isEntryBoundarySnapshot(state))
|
|
1647
|
+
return;
|
|
1648
|
+
const pause = { ...lifecycle.pause };
|
|
1649
|
+
delete pause.restartAttemptToken;
|
|
1650
|
+
const paused = await this.#persistLifecycle(row.workflowId, row.runId, { ...state, status: 'paused' }, advanceLifecycle(lifecycle, { pause }), now, source, row);
|
|
1651
|
+
return summaryFromSelectedSnapshot(row.workflowId, row.runId, paused, { ...row, updatedAt: new Date(now).toISOString() }, runProvenance(state));
|
|
1652
|
+
}
|
|
1653
|
+
/** Request a cooperative pause without waiting for the executing leg. */
|
|
1654
|
+
async requestPause(workflowId, runId, principal, options) {
|
|
1655
|
+
const { reason, holdsSchedule } = parsePauseRunOptions(options);
|
|
1656
|
+
if (!isExecutionPrincipalKind(principal?.kind) ||
|
|
1657
|
+
!isExecutionPrincipalId(principal?.id))
|
|
1658
|
+
throw new InvalidRunRequestError('pause principal is malformed');
|
|
1659
|
+
const requestedBy = { kind: principal.kind, id: principal.id };
|
|
1660
|
+
this.#getWorkflow(workflowId);
|
|
1661
|
+
return this.#withLifecycleLock(workflowId, runId, () => this.#retryOnRowChange(workflowId, runId, async () => {
|
|
1662
|
+
const active = this.#activeRuns.get(this.#runKey(workflowId, runId));
|
|
1663
|
+
const source = active?.source ?? (await this.#captureWorkflowStorage(workflowId));
|
|
1664
|
+
if (source.storage !== 'd1' ||
|
|
1665
|
+
!source.capability.supportsPause ||
|
|
1666
|
+
!source.enterStoredRun ||
|
|
1667
|
+
!source.replace ||
|
|
1668
|
+
!source.touch)
|
|
1669
|
+
throw new PauseUnsupportedError('storage cannot honor a pause');
|
|
1670
|
+
const { state, row } = await this.#readForTransition(source, workflowId, runId);
|
|
1671
|
+
if (!row)
|
|
1672
|
+
throw new RunStateUnreadableError(workflowId, runId);
|
|
1673
|
+
const lifecycle = lifecycleFromRequestContext(state.requestContext);
|
|
1674
|
+
const provenance = runProvenance(state);
|
|
1675
|
+
if (lifecycle?.terminal || !TERMINABLE_RUN_STATUSES.has(state.status))
|
|
1676
|
+
throw new RunTerminalConflictError(workflowId, runId, state.status);
|
|
1677
|
+
if (lifecycle?.transitionIntent)
|
|
1678
|
+
throw new RunTerminalConflictError(workflowId, runId, state.status, 'ending');
|
|
1679
|
+
if (provenance?.version === 2 &&
|
|
1680
|
+
provenance.startIdentity?.target.kind === 'agent')
|
|
1681
|
+
throw new PauseUnsupportedError('agent runs cannot be paused');
|
|
1682
|
+
if (state.status === 'suspended' && suspendedInsideForeach(state))
|
|
1683
|
+
throw new PauseUnsupportedError('suspended inside foreach');
|
|
1684
|
+
if (lifecycle?.scheduleDispatch && holdsSchedule !== true)
|
|
1685
|
+
throw new PauseHoldsScheduleError();
|
|
1686
|
+
if (lifecycle?.pause) {
|
|
1687
|
+
const pause = lifecycle.pause;
|
|
1688
|
+
if (pause.reason !== reason ||
|
|
1689
|
+
pause.requestedBy.kind !== requestedBy.kind ||
|
|
1690
|
+
pause.requestedBy.id !== requestedBy.id)
|
|
1691
|
+
throw new PauseConflictError();
|
|
1692
|
+
return summaryFromSelectedSnapshot(workflowId, runId, state, row, provenance);
|
|
1693
|
+
}
|
|
1694
|
+
if (state.status === 'paused')
|
|
1695
|
+
throw new PauseUnsupportedError('this paused run has no pause record');
|
|
1696
|
+
const now = Date.now();
|
|
1697
|
+
const next = advanceLifecycle(lifecycle, {
|
|
1698
|
+
pause: {
|
|
1699
|
+
requestedAt: now,
|
|
1700
|
+
requestedBy,
|
|
1701
|
+
reason,
|
|
1702
|
+
generation: nextLifecycleRevision(lifecycle?.revision ?? 0),
|
|
1703
|
+
},
|
|
1704
|
+
});
|
|
1705
|
+
await this.#persistIntent(workflowId, runId, state, next, now, source, row);
|
|
1706
|
+
return summaryFromSelectedSnapshot(workflowId, runId, {
|
|
1707
|
+
...state,
|
|
1708
|
+
requestContext: {
|
|
1709
|
+
...state.requestContext,
|
|
1710
|
+
[RUN_LIFECYCLE_CONTEXT_KEY]: next,
|
|
1711
|
+
},
|
|
1712
|
+
}, { ...row, updatedAt: new Date(now).toISOString() }, provenance);
|
|
1713
|
+
}));
|
|
1714
|
+
}
|
|
1293
1715
|
/** Idempotently cancel a live run from its persisted snapshot. */
|
|
1294
1716
|
terminate(workflowId, runId, now = Date.now()) {
|
|
1295
1717
|
return this.#transitionTerminal(workflowId, runId, 'cancelled', now);
|
|
@@ -1317,11 +1739,11 @@ export class RunnerRuntime {
|
|
|
1317
1739
|
cas !== undefined)
|
|
1318
1740
|
throw read;
|
|
1319
1741
|
}
|
|
1320
|
-
const cancelTarget = () => {
|
|
1742
|
+
const cancelTarget = (status = intendedStatus) => {
|
|
1321
1743
|
if (!active?.run)
|
|
1322
1744
|
return undefined;
|
|
1323
|
-
this.#terminalAbortIntents.set(key,
|
|
1324
|
-
return { run: active.run, legAbort: active.legAbort, key };
|
|
1745
|
+
this.#terminalAbortIntents.set(key, status);
|
|
1746
|
+
return { run: active.run, legAbort: active.legAbort, key, status };
|
|
1325
1747
|
};
|
|
1326
1748
|
const lifecycle = effectiveLifecycle(read instanceof UnknownRunError
|
|
1327
1749
|
? undefined
|
|
@@ -1346,6 +1768,14 @@ export class RunnerRuntime {
|
|
|
1346
1768
|
}
|
|
1347
1769
|
const { state, row } = read;
|
|
1348
1770
|
const existingIntent = lifecycle?.transitionIntent;
|
|
1771
|
+
if (existingIntent?.childCascadeStarted) {
|
|
1772
|
+
if (cas &&
|
|
1773
|
+
(existingIntent.status !== intendedStatus ||
|
|
1774
|
+
existingIntent.expectedRevision !== cas.expectedRevision ||
|
|
1775
|
+
existingIntent.expectedDeadlineAt !== cas.expectedDeadlineAt))
|
|
1776
|
+
return undefined;
|
|
1777
|
+
return cancelTarget(existingIntent.status);
|
|
1778
|
+
}
|
|
1349
1779
|
if (existingIntent?.status === intendedStatus &&
|
|
1350
1780
|
(cas === undefined ||
|
|
1351
1781
|
(existingIntent.expectedRevision === cas.expectedRevision &&
|
|
@@ -1408,12 +1838,16 @@ export class RunnerRuntime {
|
|
|
1408
1838
|
}
|
|
1409
1839
|
// After `run.cancel()` has aborted the engine run, so the engine's
|
|
1410
1840
|
// cancellation precedes any abort error from a call in flight.
|
|
1411
|
-
prepared.legAbort?.abort(terminalLegAbortReason(
|
|
1841
|
+
prepared.legAbort?.abort(terminalLegAbortReason(prepared.status));
|
|
1412
1842
|
return true;
|
|
1413
1843
|
}
|
|
1414
1844
|
/** Trusted host variant that persists the exact identities allowed to retry. */
|
|
1415
|
-
terminateAsPrincipal(workflowId, runId, principal, owner, now = Date.now()) {
|
|
1416
|
-
return this.#transitionTerminal(workflowId, runId, 'cancelled', now,
|
|
1845
|
+
terminateAsPrincipal(workflowId, runId, principal, owner, now = Date.now(), beforeCommit) {
|
|
1846
|
+
return this.#transitionTerminal(workflowId, runId, 'cancelled', now, {
|
|
1847
|
+
replayPrincipals: [principal, owner],
|
|
1848
|
+
replayingPrincipal: principal,
|
|
1849
|
+
beforeCommit,
|
|
1850
|
+
});
|
|
1417
1851
|
}
|
|
1418
1852
|
/** CAS-guarded deadline transition driven through the owner Durable Object. */
|
|
1419
1853
|
timeOut(workflowId, runId, cas, now = Date.now()) {
|
|
@@ -1426,17 +1860,32 @@ export class RunnerRuntime {
|
|
|
1426
1860
|
now < 0) {
|
|
1427
1861
|
throw new InvalidRunRequestError('deadline transition CAS is malformed');
|
|
1428
1862
|
}
|
|
1429
|
-
return this.#transitionTerminal(workflowId, runId, 'timed_out', now,
|
|
1863
|
+
return this.#transitionTerminal(workflowId, runId, 'timed_out', now, {
|
|
1864
|
+
cas,
|
|
1865
|
+
});
|
|
1430
1866
|
}
|
|
1431
1867
|
/** Trusted host deadline transition with retry principals persisted atomically. */
|
|
1432
|
-
timeOutAsPrincipal(workflowId, runId, cas, principal, owner, now = Date.now()) {
|
|
1433
|
-
return this.#transitionTerminal(workflowId, runId, 'timed_out', now,
|
|
1868
|
+
timeOutAsPrincipal(workflowId, runId, cas, principal, owner, now = Date.now(), beforeCommit) {
|
|
1869
|
+
return this.#transitionTerminal(workflowId, runId, 'timed_out', now, {
|
|
1870
|
+
cas,
|
|
1871
|
+
replayPrincipals: [principal, owner],
|
|
1872
|
+
replayingPrincipal: principal,
|
|
1873
|
+
beforeCommit,
|
|
1874
|
+
});
|
|
1875
|
+
}
|
|
1876
|
+
/** @internal A verified parent cascade can end a child before its own deadline. */
|
|
1877
|
+
cascadeTerminateAsPrincipal(workflowId, runId, status, owner, beforeCommit, { recordedIntentOnly = false } = {}) {
|
|
1878
|
+
return this.#transitionTerminal(workflowId, runId, status, Date.now(), {
|
|
1879
|
+
beforeCommit,
|
|
1880
|
+
fallbackReplayPrincipal: owner,
|
|
1881
|
+
recordedIntentOnly,
|
|
1882
|
+
});
|
|
1434
1883
|
}
|
|
1435
|
-
async #transitionTerminal(workflowId, runId, status, now,
|
|
1884
|
+
async #transitionTerminal(workflowId, runId, status, now, options = {}) {
|
|
1436
1885
|
this.#getWorkflow(workflowId);
|
|
1437
1886
|
return this.#withRunLock(workflowId, runId, async () => {
|
|
1438
1887
|
const source = await this.#captureWorkflowStorage(workflowId);
|
|
1439
|
-
return this.#retryOnRowChange(workflowId, runId, async () => this.#transitionTerminalLocked(workflowId, runId, status, now,
|
|
1888
|
+
return this.#withLifecycleLock(workflowId, runId, () => this.#retryOnRowChange(workflowId, runId, async () => this.#transitionTerminalLocked(workflowId, runId, status, now, options, source, await this.#readForTransition(source, workflowId, runId))));
|
|
1440
1889
|
});
|
|
1441
1890
|
}
|
|
1442
1891
|
/**
|
|
@@ -1444,8 +1893,9 @@ export class RunnerRuntime {
|
|
|
1444
1893
|
* for a caller holding the run lock. Where the read carries the row, the
|
|
1445
1894
|
* write is a compare-and-set against it and a miss throws RowChangedError.
|
|
1446
1895
|
*/
|
|
1447
|
-
async #transitionTerminalLocked(workflowId, runId, status, now, { cas, replayPrincipals, replayingPrincipal
|
|
1448
|
-
|
|
1896
|
+
async #transitionTerminalLocked(workflowId, runId, status, now, { cas, replayPrincipals, replayingPrincipal, fallbackReplayPrincipal, recordedIntentOnly, beforeCommit, }, source, read) {
|
|
1897
|
+
let { state, row } = read;
|
|
1898
|
+
let lifecycle = lifecycleFromRequestContext(state.requestContext);
|
|
1449
1899
|
if (lifecycle?.terminal) {
|
|
1450
1900
|
if (replayingPrincipal &&
|
|
1451
1901
|
!lifecycle.terminal.replayPrincipals.some((principal) => principal.kind === replayingPrincipal.kind &&
|
|
@@ -1462,6 +1912,13 @@ export class RunnerRuntime {
|
|
|
1462
1912
|
};
|
|
1463
1913
|
}
|
|
1464
1914
|
const transitionIntent = lifecycle?.transitionIntent;
|
|
1915
|
+
if (recordedIntentOnly &&
|
|
1916
|
+
(!transitionIntent?.childCascadeStarted ||
|
|
1917
|
+
transitionIntent.status !== status)) {
|
|
1918
|
+
throw new RunTerminalConflictError(workflowId, runId, state.status);
|
|
1919
|
+
}
|
|
1920
|
+
if (transitionIntent?.childCascadeStarted && cas === undefined)
|
|
1921
|
+
status = transitionIntent.status;
|
|
1465
1922
|
const intentMatchesTransition = transitionIntent?.status === status &&
|
|
1466
1923
|
(cas === undefined ||
|
|
1467
1924
|
(transitionIntent.expectedRevision === cas.expectedRevision &&
|
|
@@ -1493,6 +1950,8 @@ export class RunnerRuntime {
|
|
|
1493
1950
|
message: 'run termination is blocked while an economic operation is disputed',
|
|
1494
1951
|
});
|
|
1495
1952
|
}
|
|
1953
|
+
if (transitionIntent?.childCascadeStarted && !beforeCommit)
|
|
1954
|
+
throw new RunStateUnreadableError(workflowId, runId);
|
|
1496
1955
|
const currentStatus = state.status;
|
|
1497
1956
|
const abortIntent = this.#terminalAbortIntents.get(this.#runKey(workflowId, runId));
|
|
1498
1957
|
if (!TERMINABLE_RUN_STATUSES.has(currentStatus) &&
|
|
@@ -1505,14 +1964,52 @@ export class RunnerRuntime {
|
|
|
1505
1964
|
throw new RunTerminalConflictError(workflowId, runId, currentStatus);
|
|
1506
1965
|
}
|
|
1507
1966
|
const provenance = runProvenance(state);
|
|
1508
|
-
const fallbackPrincipal =
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1967
|
+
const fallbackPrincipal = fallbackReplayPrincipal ??
|
|
1968
|
+
(provenance?.requestedBy && provenance.requestedByKind
|
|
1969
|
+
? {
|
|
1970
|
+
kind: provenance.requestedByKind,
|
|
1971
|
+
id: provenance.requestedBy,
|
|
1972
|
+
}
|
|
1973
|
+
: { kind: 'system', id: 'flowsafe-system' });
|
|
1974
|
+
const principals = canonicalReplayPrincipals((transitionIntent?.childCascadeStarted
|
|
1975
|
+
? transitionIntent.replayPrincipals
|
|
1976
|
+
: (replayPrincipals ?? transitionIntent?.replayPrincipals)) ?? [
|
|
1977
|
+
fallbackPrincipal,
|
|
1978
|
+
]);
|
|
1979
|
+
if (beforeCommit) {
|
|
1980
|
+
await beforeCommit(status, async () => {
|
|
1981
|
+
if (!row)
|
|
1982
|
+
throw new RunStateUnreadableError(workflowId, runId);
|
|
1983
|
+
if (lifecycle?.transitionIntent?.childCascadeStarted)
|
|
1984
|
+
return;
|
|
1985
|
+
// The exact-row write decides whether the intent may fence the leg.
|
|
1986
|
+
// No child receives cancellation until that write succeeds.
|
|
1987
|
+
const existing = intentMatchesTransition ? transitionIntent : undefined;
|
|
1988
|
+
const intent = advanceLifecycle(lifecycle, {
|
|
1989
|
+
transitionIntent: {
|
|
1990
|
+
...existing,
|
|
1991
|
+
status,
|
|
1992
|
+
requestedAt: existing?.requestedAt ?? now,
|
|
1993
|
+
replayPrincipals: principals,
|
|
1994
|
+
...(cas
|
|
1995
|
+
? {
|
|
1996
|
+
expectedRevision: cas.expectedRevision,
|
|
1997
|
+
expectedDeadlineAt: cas.expectedDeadlineAt,
|
|
1998
|
+
}
|
|
1999
|
+
: {}),
|
|
2000
|
+
childCascadeStarted: true,
|
|
2001
|
+
},
|
|
2002
|
+
});
|
|
2003
|
+
state = await this.#persistLifecycle(workflowId, runId, state, intent, now, source, row);
|
|
2004
|
+
row = {
|
|
2005
|
+
...row,
|
|
2006
|
+
snapshot: JSON.stringify(state),
|
|
2007
|
+
updatedAt: new Date(now).toISOString(),
|
|
2008
|
+
};
|
|
2009
|
+
lifecycle = intent;
|
|
2010
|
+
});
|
|
2011
|
+
now = Date.now();
|
|
2012
|
+
}
|
|
1516
2013
|
const next = projectTerminalLifecycle(lifecycle, status, now, principals);
|
|
1517
2014
|
await this.#persistLifecycle(workflowId, runId, {
|
|
1518
2015
|
...state,
|
|
@@ -1572,7 +2069,7 @@ export class RunnerRuntime {
|
|
|
1572
2069
|
const state = await this.#workflowState(workflowId, runId);
|
|
1573
2070
|
if (!state)
|
|
1574
2071
|
return null;
|
|
1575
|
-
return this.#summaryFromState(runId, state);
|
|
2072
|
+
return this.#summaryFromState(workflowId, runId, state);
|
|
1576
2073
|
}
|
|
1577
2074
|
/**
|
|
1578
2075
|
* status() for a caller about to CONCLUDE something irreversible from what it
|
|
@@ -1594,7 +2091,7 @@ export class RunnerRuntime {
|
|
|
1594
2091
|
if (state.isFromInMemory === true) {
|
|
1595
2092
|
throw new RunStateUnreadableError(workflowId, runId);
|
|
1596
2093
|
}
|
|
1597
|
-
return this.#summaryFromState(runId, state);
|
|
2094
|
+
return this.#summaryFromState(workflowId, runId, state);
|
|
1598
2095
|
}
|
|
1599
2096
|
async authoritativeStartState(workflowId, runId, options) {
|
|
1600
2097
|
const includeLegacy = options?.includeLegacy === true;
|
|
@@ -1774,7 +2271,7 @@ export class RunnerRuntime {
|
|
|
1774
2271
|
runId,
|
|
1775
2272
|
}),
|
|
1776
2273
|
snapshot,
|
|
1777
|
-
summary: summaryFromSelectedSnapshot(runId, snapshot, { createdAt: toIso(createdAt), updatedAt: toIso(updatedAt) }, provenance),
|
|
2274
|
+
summary: summaryFromSelectedSnapshot(workflowId, runId, snapshot, { createdAt: toIso(createdAt), updatedAt: toIso(updatedAt) }, provenance),
|
|
1778
2275
|
};
|
|
1779
2276
|
const execution = runExecutionIdentityFor({ tablePrefix: physical.tablePrefix, workflowId, runId }, provenance);
|
|
1780
2277
|
const state = snapshot.status === 'pending'
|
|
@@ -1783,7 +2280,7 @@ export class RunnerRuntime {
|
|
|
1783
2280
|
kind: 'result',
|
|
1784
2281
|
snapshot,
|
|
1785
2282
|
provenance,
|
|
1786
|
-
summary: summaryFromSelectedSnapshot(runId, snapshot, { createdAt: toIso(createdAt), updatedAt: toIso(updatedAt) }, provenance),
|
|
2283
|
+
summary: summaryFromSelectedSnapshot(workflowId, runId, snapshot, { createdAt: toIso(createdAt), updatedAt: toIso(updatedAt) }, provenance),
|
|
1787
2284
|
};
|
|
1788
2285
|
return physical.storage === 'd1'
|
|
1789
2286
|
? {
|
|
@@ -1892,10 +2389,12 @@ export class RunnerRuntime {
|
|
|
1892
2389
|
}
|
|
1893
2390
|
let selected = state;
|
|
1894
2391
|
let transitioned = false;
|
|
1895
|
-
|
|
2392
|
+
const lifecycle = lifecycleFromRequestContext(state.snapshot.requestContext);
|
|
2393
|
+
let cleanup = terminalCleanupFor(lifecycle);
|
|
1896
2394
|
if (state.kind === 'initial') {
|
|
1897
2395
|
if (!this.#executionFence ||
|
|
1898
2396
|
state.storage !== 'd1' ||
|
|
2397
|
+
lifecycle?.transitionIntent?.childCascadeStarted ||
|
|
1899
2398
|
state.provenance.initialAdmission !== true ||
|
|
1900
2399
|
state.provenance.attemptToken !== attemptToken ||
|
|
1901
2400
|
state.provenance.resumeCounts.length !== 0)
|
|
@@ -2021,6 +2520,56 @@ export class RunnerRuntime {
|
|
|
2021
2520
|
? source.enterStoredRun?.bind(source.capability)
|
|
2022
2521
|
: undefined;
|
|
2023
2522
|
}
|
|
2523
|
+
#enablePauseBoundary(active) {
|
|
2524
|
+
const { storedRunScope, requestContext } = active;
|
|
2525
|
+
if (!storedRunScope || !requestContext)
|
|
2526
|
+
return;
|
|
2527
|
+
storedRunScope.onPauseCommitted = () => {
|
|
2528
|
+
requestContext.set(LEG_OUTCOME_CONTEXT_KEY, 'paused');
|
|
2529
|
+
};
|
|
2530
|
+
storedRunScope.onPauseBoundary = (lifecycle) => {
|
|
2531
|
+
const controller = active.run?.abortController;
|
|
2532
|
+
if (!controller || controller.signal.aborted)
|
|
2533
|
+
return;
|
|
2534
|
+
if (!active.lifecycle || active.lifecycle.revision < lifecycle.revision)
|
|
2535
|
+
active.lifecycle = lifecycle;
|
|
2536
|
+
storedRunScope.pauseAbortRevision = lifecycle.revision;
|
|
2537
|
+
controller.abort(pauseLegAbortReason());
|
|
2538
|
+
};
|
|
2539
|
+
}
|
|
2540
|
+
async #commitPause(workflowId, runId, active) {
|
|
2541
|
+
const { source, storedRunScope } = active;
|
|
2542
|
+
const revision = storedRunScope?.pauseAbortRevision;
|
|
2543
|
+
if (!source || revision === undefined)
|
|
2544
|
+
return false;
|
|
2545
|
+
return this.#withLifecycleLock(workflowId, runId, () => this.#retryOnRowChange(workflowId, runId, async () => {
|
|
2546
|
+
const { state, row } = await this.#readForTransition(source, workflowId, runId);
|
|
2547
|
+
if (state.status === 'paused')
|
|
2548
|
+
return true;
|
|
2549
|
+
return row
|
|
2550
|
+
? this.#persistPausedBoundary(source, state, row, Date.now(), revision)
|
|
2551
|
+
: false;
|
|
2552
|
+
}));
|
|
2553
|
+
}
|
|
2554
|
+
async #persistPausedBoundary(source, state, row, now, expectedRevision) {
|
|
2555
|
+
const lifecycle = lifecycleFromRequestContext(state.requestContext);
|
|
2556
|
+
if (lifecycle?.pause?.honoringAt === undefined ||
|
|
2557
|
+
lifecycle.pause.pausedAt !== undefined ||
|
|
2558
|
+
(expectedRevision !== undefined &&
|
|
2559
|
+
lifecycle.revision !== expectedRevision) ||
|
|
2560
|
+
lifecycle.transitionIntent ||
|
|
2561
|
+
RUN_SETTLING_MARKERS.some((marker) => lifecycle[marker] !== undefined) ||
|
|
2562
|
+
!isEntryBoundarySnapshot(state))
|
|
2563
|
+
return false;
|
|
2564
|
+
const pause = {
|
|
2565
|
+
...lifecycle.pause,
|
|
2566
|
+
pausedAt: now,
|
|
2567
|
+
generation: nextLifecycleRevision(lifecycle.revision),
|
|
2568
|
+
};
|
|
2569
|
+
delete pause.honoringAt;
|
|
2570
|
+
await this.#persistLifecycle(row.workflowId, row.runId, { ...state, status: 'paused' }, advanceLifecycle(lifecycle, { pause }), now, source, row);
|
|
2571
|
+
return true;
|
|
2572
|
+
}
|
|
2024
2573
|
/** Run a leg's writes of its own run inside the storage's stored-run scope. */
|
|
2025
2574
|
#inStoredRunScope(active, operation) {
|
|
2026
2575
|
const withStoredRun = this.#withStoredRunOf(active.source);
|
|
@@ -2029,6 +2578,18 @@ export class RunnerRuntime {
|
|
|
2029
2578
|
? withStoredRun(storedRunScope, operation)
|
|
2030
2579
|
: operation();
|
|
2031
2580
|
}
|
|
2581
|
+
#inWorkflowLeg(workflowId, runId, active, operation) {
|
|
2582
|
+
const key = this.#runKey(workflowId, runId);
|
|
2583
|
+
return activeWorkflowLeg.run({
|
|
2584
|
+
workflowId,
|
|
2585
|
+
runId,
|
|
2586
|
+
signal: active.run?.abortController.signal,
|
|
2587
|
+
isActive: () => this.#activeRuns.get(key) === active &&
|
|
2588
|
+
!this.#terminalAbortIntents.has(key) &&
|
|
2589
|
+
!active.pendingTerminal &&
|
|
2590
|
+
active.run?.abortController.signal.aborted === false,
|
|
2591
|
+
}, operation);
|
|
2592
|
+
}
|
|
2032
2593
|
/**
|
|
2033
2594
|
* @internal Settle a run whose execution leg ended without a durable outcome.
|
|
2034
2595
|
*
|
|
@@ -2038,17 +2599,16 @@ export class RunnerRuntime {
|
|
|
2038
2599
|
* on the outgoing instance, so a run is written only after its row has gone
|
|
2039
2600
|
* untouched for RUN_LEG_SILENT_MS (`live` otherwise).
|
|
2040
2601
|
*
|
|
2041
|
-
* `durable`
|
|
2042
|
-
*
|
|
2043
|
-
*
|
|
2044
|
-
*
|
|
2045
|
-
*
|
|
2046
|
-
* which repairs it as an unknown outcome.
|
|
2602
|
+
* `durable` and `absent` leave the snapshot untouched. A recorded
|
|
2603
|
+
* cancellation or timeout owns the outcome: `transition` completes it or
|
|
2604
|
+
* replays it if cleanup is unfinished. The caller handles cleanup as it does
|
|
2605
|
+
* on the terminate and deadline routes. Start recovery handles the pending
|
|
2606
|
+
* initial row as an unknown outcome.
|
|
2047
2607
|
*
|
|
2048
2608
|
* Any other run becomes `failed` (`interrupted`), never re-executed: the step
|
|
2049
2609
|
* that was in flight may already have had effects.
|
|
2050
2610
|
*/
|
|
2051
|
-
async settleInterruptedRun(workflowId, runId, now = Date.now()) {
|
|
2611
|
+
async settleInterruptedRun(workflowId, runId, now = Date.now(), beforeCommit) {
|
|
2052
2612
|
this.#getWorkflow(workflowId);
|
|
2053
2613
|
// Checked before queueing: a live leg holds the run lock for its whole
|
|
2054
2614
|
// length, and a caller waiting behind it would learn nothing.
|
|
@@ -2087,20 +2647,32 @@ export class RunnerRuntime {
|
|
|
2087
2647
|
// The write replaces the silent row, so it is built from that row; one
|
|
2088
2648
|
// that moved since the decision above waits for the next wake.
|
|
2089
2649
|
const current = snapshotOfRow(silent);
|
|
2650
|
+
const currentLifecycle = lifecycleFromRequestContext(current.requestContext);
|
|
2090
2651
|
try {
|
|
2091
|
-
if (
|
|
2652
|
+
if (current.status !== state.status ||
|
|
2653
|
+
currentLifecycle?.revision !== lifecycle?.revision)
|
|
2654
|
+
return { kind: 'live' };
|
|
2655
|
+
const currentRecorded = currentLifecycle?.terminal ?? currentLifecycle?.transitionIntent;
|
|
2656
|
+
if (recorded && !currentRecorded)
|
|
2657
|
+
return { kind: 'live' };
|
|
2658
|
+
if (currentRecorded)
|
|
2092
2659
|
return {
|
|
2093
2660
|
kind: 'transition',
|
|
2094
|
-
replayPrincipal:
|
|
2661
|
+
replayPrincipal: currentRecorded
|
|
2095
2662
|
.replayPrincipals[0],
|
|
2096
|
-
transition: await this.#transitionTerminalLocked(workflowId, runId,
|
|
2663
|
+
transition: await this.#transitionTerminalLocked(workflowId, runId, currentRecorded.status, now, { beforeCommit }, source, { state: current, row: silent }),
|
|
2664
|
+
};
|
|
2665
|
+
const restartAttempt = currentLifecycle?.pause?.restartAttemptToken;
|
|
2666
|
+
if (restartAttempt !== undefined) {
|
|
2667
|
+
const summary = await this.#restorePausedRestart(source, current, silent, now, restartAttempt);
|
|
2668
|
+
if (summary)
|
|
2669
|
+
return { kind: 'paused', summary };
|
|
2670
|
+
}
|
|
2671
|
+
if (await this.#persistPausedBoundary(source, current, silent, now))
|
|
2672
|
+
return {
|
|
2673
|
+
kind: 'paused',
|
|
2674
|
+
summary: await this.#summaryAfterPersist(workflowId, runId, source, runProvenance(current)),
|
|
2097
2675
|
};
|
|
2098
|
-
const currentLifecycle = lifecycleFromRequestContext(current.requestContext);
|
|
2099
|
-
if (current.status !== state.status ||
|
|
2100
|
-
currentLifecycle?.revision !== lifecycle?.revision ||
|
|
2101
|
-
currentLifecycle?.terminal ||
|
|
2102
|
-
currentLifecycle?.transitionIntent)
|
|
2103
|
-
return { kind: 'live' };
|
|
2104
2676
|
await this.#persistLifecycle(workflowId, runId, { ...current, ...failedByMarker('interruptedAt', now) }, advanceLifecycle(currentLifecycle, { interruptedAt: now }), now, source, silent);
|
|
2105
2677
|
}
|
|
2106
2678
|
catch (error) {
|
|
@@ -2114,6 +2686,45 @@ export class RunnerRuntime {
|
|
|
2114
2686
|
};
|
|
2115
2687
|
}));
|
|
2116
2688
|
}
|
|
2689
|
+
/** @internal Fail a question resume after exhausting its retry budget. */
|
|
2690
|
+
failQuestionResume(workflowId, runId, { stepKey, suspendedAt, resumeCount, }) {
|
|
2691
|
+
return this.#failSuspendedRun(workflowId, runId, 'questionResumeFailedAt', matchesSuspension(stepKey, suspendedAt, resumeCount));
|
|
2692
|
+
}
|
|
2693
|
+
/** @internal Fail a child resume that could not advance its suspension. */
|
|
2694
|
+
failChildAwaitResume(workflowId, runId, { step, suspendedAt, resumeCount, }) {
|
|
2695
|
+
return this.#failSuspendedRun(workflowId, runId, 'childAwaitResumeFailedAt', matchesSuspension(step, suspendedAt, resumeCount));
|
|
2696
|
+
}
|
|
2697
|
+
/** @internal Fail an undeliverable child suspension at the leg boundary. */
|
|
2698
|
+
failInvalidChildAwait(workflowId, runId, invalid) {
|
|
2699
|
+
return this.#failSuspendedRun(workflowId, runId, 'invalidChildAwaitAt', ({ state, row }, provenance) => {
|
|
2700
|
+
const timestamp = new Date(state.timestamp).toISOString();
|
|
2701
|
+
return invalid(summaryFromSelectedSnapshot(workflowId, runId, state, row ?? { createdAt: timestamp, updatedAt: timestamp }, provenance));
|
|
2702
|
+
});
|
|
2703
|
+
}
|
|
2704
|
+
async #failSuspendedRun(workflowId, runId, marker, matches) {
|
|
2705
|
+
const proof = await this.#assertResumeFence(workflowId, runId);
|
|
2706
|
+
return this.#withRunLock(workflowId, runId, () => this.#withLifecycleLock(workflowId, runId, () => this.#retryOnRowChange(workflowId, runId, async () => {
|
|
2707
|
+
const source = await this.#captureWorkflowStorage(workflowId);
|
|
2708
|
+
const read = await this.#readForTransition(source, workflowId, runId);
|
|
2709
|
+
const { state, row } = read;
|
|
2710
|
+
const provenance = runProvenance(state);
|
|
2711
|
+
if (proof &&
|
|
2712
|
+
(provenance?.version !== 2 ||
|
|
2713
|
+
provenance.startToken !== proof.startToken ||
|
|
2714
|
+
source.tablePrefix !== proof.tablePrefix))
|
|
2715
|
+
throw new RunStateUnreadableError(workflowId, runId);
|
|
2716
|
+
const lifecycle = lifecycleFromRequestContext(state.requestContext);
|
|
2717
|
+
if (state.status !== 'suspended' ||
|
|
2718
|
+
lifecycle?.terminal ||
|
|
2719
|
+
lifecycle?.transitionIntent ||
|
|
2720
|
+
!matches(read, provenance))
|
|
2721
|
+
return undefined;
|
|
2722
|
+
const now = Date.now();
|
|
2723
|
+
const patch = { [marker]: now };
|
|
2724
|
+
await this.#persistLifecycle(workflowId, runId, { ...state, ...failedByMarker(marker, now) }, advanceLifecycle(lifecycle, patch), now, source, row);
|
|
2725
|
+
return this.#summaryAfterPersist(workflowId, runId, source, provenance);
|
|
2726
|
+
})));
|
|
2727
|
+
}
|
|
2117
2728
|
/**
|
|
2118
2729
|
* The run's row, when no leg has marked it live within RUN_LEG_SILENT_MS and
|
|
2119
2730
|
* the storage can compare-and-set it; `undefined` otherwise.
|
|
@@ -2203,7 +2814,7 @@ export class RunnerRuntime {
|
|
|
2203
2814
|
// workflow is executing", so the scope is never client-suppliable. Provider values are partitioned into
|
|
2204
2815
|
// stored application context, capabilities, and trusted identity so every
|
|
2205
2816
|
// layer has an explicit order and a provider cannot replace runtime scope.
|
|
2206
|
-
async #requestContextFor(workflowId, runId, leg, provenance, storedRequestContext, lifecycle) {
|
|
2817
|
+
async #requestContextFor(workflowId, runId, leg, provenance, storedRequestContext, lifecycle, lineage) {
|
|
2207
2818
|
const base = {
|
|
2208
2819
|
[BREAKWATER_WORKFLOW_SCOPE_KEY]: workflowId,
|
|
2209
2820
|
runId,
|
|
@@ -2214,17 +2825,26 @@ export class RunnerRuntime {
|
|
|
2214
2825
|
if (lifecycle !== undefined) {
|
|
2215
2826
|
base[RUN_LIFECYCLE_CONTEXT_KEY] = lifecycle;
|
|
2216
2827
|
}
|
|
2828
|
+
if (lineage !== undefined) {
|
|
2829
|
+
base[RUN_LINEAGE_CONTEXT_KEY] = lineage;
|
|
2830
|
+
}
|
|
2831
|
+
if (leg.kind === 'restart') {
|
|
2832
|
+
// Mastra fills missing keys from the prior snapshot.
|
|
2833
|
+
base[BREAKWATER_CONNECTOR_GRANTS_KEY] = [];
|
|
2834
|
+
}
|
|
2217
2835
|
// No isolation scope is minted here: a deployment serves exactly one
|
|
2218
2836
|
// organization. The isolation-scope context key is RESERVED, so a provider
|
|
2219
2837
|
// can never mint a scope that desyncs from the execution identity below.
|
|
2220
|
-
if (leg.kind === 'start') {
|
|
2838
|
+
if (leg.kind === 'start' || leg.kind === 'restart') {
|
|
2221
2839
|
base[BREAKWATER_CONNECTOR_EXECUTION_KEY] = {
|
|
2222
2840
|
kind: 'start',
|
|
2223
2841
|
workflowId,
|
|
2224
2842
|
runId,
|
|
2225
2843
|
};
|
|
2226
2844
|
}
|
|
2227
|
-
else if (leg.
|
|
2845
|
+
else if (leg.kind === 'resume' &&
|
|
2846
|
+
leg.step !== undefined &&
|
|
2847
|
+
leg.suspendedAt !== undefined) {
|
|
2228
2848
|
base[BREAKWATER_CONNECTOR_EXECUTION_KEY] = {
|
|
2229
2849
|
kind: 'resume',
|
|
2230
2850
|
workflowId,
|
|
@@ -2246,7 +2866,7 @@ export class RunnerRuntime {
|
|
|
2246
2866
|
: undefined;
|
|
2247
2867
|
return orderedRequestContext(base, values, storedRequestContext);
|
|
2248
2868
|
}
|
|
2249
|
-
async #trustedResumePreparation(workflowId, runId, state, options) {
|
|
2869
|
+
async #trustedResumePreparation(workflowId, runId, state, options, restart) {
|
|
2250
2870
|
const { step: selectedStep, requestedBy, requestedByKind, deadlineMs, economicOperations, expectedSuspension, } = options;
|
|
2251
2871
|
if (requestedBy !== undefined && !isExecutionPrincipalId(requestedBy)) {
|
|
2252
2872
|
throw new InvalidRunRequestError('requestedBy is malformed');
|
|
@@ -2258,7 +2878,7 @@ export class RunnerRuntime {
|
|
|
2258
2878
|
if ((requestedBy === undefined) !== (requestedByKind === undefined)) {
|
|
2259
2879
|
throw new InvalidRunRequestError('requestedBy and requestedByKind must be provided together');
|
|
2260
2880
|
}
|
|
2261
|
-
const step = resolveResumeStep(selectedStep, state);
|
|
2881
|
+
const step = restart ? undefined : resolveResumeStep(selectedStep, state);
|
|
2262
2882
|
const stepKey = step?.join('.');
|
|
2263
2883
|
// resumeCount is read BEFORE this resume increments it: it is the count
|
|
2264
2884
|
// of prior resumes = the ordinal of the CURRENT suspension being resumed
|
|
@@ -2274,19 +2894,16 @@ export class RunnerRuntime {
|
|
|
2274
2894
|
? storedProvenance?.requestedByKind
|
|
2275
2895
|
: requestedByKind;
|
|
2276
2896
|
const priorCounts = new Map(storedProvenance?.resumeCounts ?? []);
|
|
2277
|
-
const
|
|
2278
|
-
|
|
2279
|
-
|
|
2280
|
-
|
|
2281
|
-
|
|
2282
|
-
};
|
|
2283
|
-
// The pair the leg's grant minting reads, compared as
|
|
2284
|
-
// boundToCurrentSuspension compares it.
|
|
2897
|
+
const suspendedAt = stepKey === undefined ? undefined : suspendedAtOf(state.steps, stepKey);
|
|
2898
|
+
const resumeCount = stepKey === undefined ? undefined : priorCounts.get(stepKey);
|
|
2899
|
+
const leg = restart
|
|
2900
|
+
? { kind: 'restart' }
|
|
2901
|
+
: { kind: 'resume', step, suspendedAt, resumeCount };
|
|
2285
2902
|
if (expectedSuspension !== undefined) {
|
|
2286
2903
|
if (stepKey === undefined)
|
|
2287
2904
|
throw new InvalidRunRequestError('expectedSuspension requires a resolvable resumed step');
|
|
2288
|
-
if (
|
|
2289
|
-
|
|
2905
|
+
if (suspendedAt !== expectedSuspension.suspendedAt ||
|
|
2906
|
+
(resumeCount ?? 0) !== (expectedSuspension.resumeCount ?? 0))
|
|
2290
2907
|
throw new SuspensionChangedError(workflowId, runId, stepKey);
|
|
2291
2908
|
}
|
|
2292
2909
|
const nextCounts = new Map(priorCounts);
|
|
@@ -2305,7 +2922,16 @@ export class RunnerRuntime {
|
|
|
2305
2922
|
resumeCounts: [...nextCounts],
|
|
2306
2923
|
};
|
|
2307
2924
|
const storedLifecycle = lifecycleFromRequestContext(state.requestContext);
|
|
2308
|
-
const
|
|
2925
|
+
const lineage = parseRunLineage(state.requestContext?.[RUN_LINEAGE_CONTEXT_KEY]);
|
|
2926
|
+
let replacementDeadline = relativeDeadline(deadlineMs);
|
|
2927
|
+
if (replacementDeadline !== undefined && lineage) {
|
|
2928
|
+
const parent = await this.authoritativeStartState(lineage.parentWorkflowId, lineage.parentRunId, { includeLegacy: true });
|
|
2929
|
+
if (!parent)
|
|
2930
|
+
throw new UnknownRunError(lineage.parentWorkflowId, lineage.parentRunId);
|
|
2931
|
+
const parentDeadline = lifecycleFromRequestContext(parent.snapshot.requestContext)?.deadlineAt;
|
|
2932
|
+
if (parentDeadline !== undefined)
|
|
2933
|
+
replacementDeadline = Math.min(replacementDeadline, parentDeadline);
|
|
2934
|
+
}
|
|
2309
2935
|
const replacementOperations = canonicalEconomicOperations(economicOperations);
|
|
2310
2936
|
const lifecycle = replacementDeadline === undefined && replacementOperations === undefined
|
|
2311
2937
|
? storedLifecycle
|
|
@@ -2317,7 +2943,7 @@ export class RunnerRuntime {
|
|
|
2317
2943
|
? {}
|
|
2318
2944
|
: { economicOperations: replacementOperations }),
|
|
2319
2945
|
});
|
|
2320
|
-
const requestContext = await this.#requestContextFor(workflowId, runId, leg, provenance, undefined, lifecycle);
|
|
2946
|
+
const requestContext = await this.#requestContextFor(workflowId, runId, leg, provenance, undefined, lifecycle, lineage);
|
|
2321
2947
|
return {
|
|
2322
2948
|
nextCounts,
|
|
2323
2949
|
provenance,
|
|
@@ -2402,13 +3028,13 @@ export class RunnerRuntime {
|
|
|
2402
3028
|
const state = await this.#workflowState(workflowId, runId);
|
|
2403
3029
|
if (!state)
|
|
2404
3030
|
throw new UnknownRunError(workflowId, runId);
|
|
2405
|
-
return this.#summaryFromState(runId, state);
|
|
3031
|
+
return this.#summaryFromState(workflowId, runId, state);
|
|
2406
3032
|
}
|
|
2407
|
-
#summaryFromState(runId, state) {
|
|
3033
|
+
#summaryFromState(workflowId, runId, state) {
|
|
2408
3034
|
const provenance = runProvenance(state);
|
|
2409
3035
|
if (state.status === 'pending' && provenance?.version === 2)
|
|
2410
3036
|
throw new RunStartPendingError();
|
|
2411
|
-
return summarizeState(runId, state, provenance);
|
|
3037
|
+
return summarizeState(workflowId, runId, state, provenance);
|
|
2412
3038
|
}
|
|
2413
3039
|
async #summaryForAttempt(workflowId, runId, expected) {
|
|
2414
3040
|
try {
|
|
@@ -2434,7 +3060,7 @@ export class RunnerRuntime {
|
|
|
2434
3060
|
if (provenance?.version !== expected.version ||
|
|
2435
3061
|
provenance.attemptToken !== expected.attemptToken)
|
|
2436
3062
|
return undefined;
|
|
2437
|
-
return summarizeState(runId, persisted, provenance);
|
|
3063
|
+
return summarizeState(workflowId, runId, persisted, provenance);
|
|
2438
3064
|
}
|
|
2439
3065
|
catch {
|
|
2440
3066
|
return undefined;
|
|
@@ -2449,7 +3075,8 @@ export class RunnerRuntime {
|
|
|
2449
3075
|
* writes. Never throws: the caller's summary read follows.
|
|
2450
3076
|
*/
|
|
2451
3077
|
async #failUnstorableLeg(workflowId, runId, active, error) {
|
|
2452
|
-
if (!isRunStateNotStorable(error)
|
|
3078
|
+
if (!isRunStateNotStorable(error) ||
|
|
3079
|
+
isPauseLegAbort(active.run?.abortController.signal.reason))
|
|
2453
3080
|
return;
|
|
2454
3081
|
const { source, requestContext } = active;
|
|
2455
3082
|
if (source?.storage === 'd1' && source.replace && requestContext) {
|