@proofoftech/flowsafe 0.22.0 → 0.24.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 +160 -0
- package/README.md +77 -12
- package/dist/agent-host/catalog.d.ts.map +1 -1
- package/dist/agent-host/catalog.js +5 -2
- package/dist/agent-host/catalog.js.map +1 -1
- package/dist/agent-host/thread-host.d.ts +16 -0
- package/dist/agent-host/thread-host.d.ts.map +1 -1
- package/dist/agent-host/thread-host.js +81 -27
- package/dist/agent-host/thread-host.js.map +1 -1
- package/dist/agent-runner/durable-agent-runner.d.ts +121 -80
- package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
- package/dist/agent-runner/durable-agent-runner.js +747 -468
- package/dist/agent-runner/durable-agent-runner.js.map +1 -1
- package/dist/approval-ui/use-approval-dashboard.js +6 -6
- package/dist/approval-ui/use-approval-dashboard.js.map +1 -1
- package/dist/background-tasks/d1-storage.d.ts.map +1 -1
- package/dist/background-tasks/d1-storage.js +2 -3
- package/dist/background-tasks/d1-storage.js.map +1 -1
- package/dist/background-tasks/host.d.ts.map +1 -1
- package/dist/background-tasks/host.js +27 -38
- package/dist/background-tasks/host.js.map +1 -1
- package/dist/do-runner/cause-chain.d.ts +5 -0
- package/dist/do-runner/cause-chain.d.ts.map +1 -1
- package/dist/do-runner/cause-chain.js +12 -0
- package/dist/do-runner/cause-chain.js.map +1 -1
- package/dist/do-runner/cf-types.d.ts +3 -0
- package/dist/do-runner/cf-types.d.ts.map +1 -1
- package/dist/do-runner/cf-types.js.map +1 -1
- package/dist/do-runner/constants.d.ts +1 -1
- package/dist/do-runner/constants.d.ts.map +1 -1
- package/dist/do-runner/constants.js +1 -1
- package/dist/do-runner/constants.js.map +1 -1
- package/dist/do-runner/core-events-nonce.d.ts +2 -0
- package/dist/do-runner/core-events-nonce.d.ts.map +1 -0
- package/dist/do-runner/core-events-nonce.js +16 -0
- package/dist/do-runner/core-events-nonce.js.map +1 -0
- package/dist/do-runner/d1-storage.js +1 -9
- package/dist/do-runner/d1-storage.js.map +1 -1
- package/dist/do-runner/do-error-response.d.ts.map +1 -1
- package/dist/do-runner/do-error-response.js +2 -1
- package/dist/do-runner/do-error-response.js.map +1 -1
- package/dist/do-runner/durable-object.d.ts +17 -2
- package/dist/do-runner/durable-object.d.ts.map +1 -1
- package/dist/do-runner/durable-object.js +442 -55
- package/dist/do-runner/durable-object.js.map +1 -1
- package/dist/do-runner/fenced-workflow-capability.d.ts +24 -0
- package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -1
- package/dist/do-runner/fenced-workflows-d1.d.ts +5 -1
- package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -1
- package/dist/do-runner/fenced-workflows-d1.js +149 -48
- package/dist/do-runner/fenced-workflows-d1.js.map +1 -1
- package/dist/do-runner/index.d.ts +2 -2
- package/dist/do-runner/index.d.ts.map +1 -1
- package/dist/do-runner/index.js +2 -2
- package/dist/do-runner/index.js.map +1 -1
- package/dist/do-runner/init.d.ts +2 -3
- package/dist/do-runner/init.d.ts.map +1 -1
- package/dist/do-runner/init.js.map +1 -1
- package/dist/do-runner/memory-id.js +1 -1
- package/dist/do-runner/memory-id.js.map +1 -1
- package/dist/do-runner/pubsub.d.ts +6 -2
- package/dist/do-runner/pubsub.d.ts.map +1 -1
- package/dist/do-runner/pubsub.js +12 -22
- package/dist/do-runner/pubsub.js.map +1 -1
- package/dist/do-runner/run-lifecycle.d.ts +42 -2
- package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
- package/dist/do-runner/run-lifecycle.js +57 -1
- package/dist/do-runner/run-lifecycle.js.map +1 -1
- package/dist/do-runner/run-terminal-state.d.ts +2 -0
- package/dist/do-runner/run-terminal-state.d.ts.map +1 -1
- package/dist/do-runner/run-terminal-state.js +4 -0
- package/dist/do-runner/run-terminal-state.js.map +1 -1
- package/dist/do-runner/runtime.d.ts +91 -58
- package/dist/do-runner/runtime.d.ts.map +1 -1
- package/dist/do-runner/runtime.js +351 -191
- package/dist/do-runner/runtime.js.map +1 -1
- package/dist/do-runner/suspension-deadline.d.ts +25 -17
- package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
- package/dist/do-runner/suspension-deadline.js +44 -21
- package/dist/do-runner/suspension-deadline.js.map +1 -1
- package/dist/do-runner/workflow-snapshot-row.d.ts +7 -0
- package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -1
- package/dist/do-runner/workflow-snapshot-row.js +21 -0
- package/dist/do-runner/workflow-snapshot-row.js.map +1 -1
- package/dist/host-kit/approval-bridge.d.ts +11 -8
- package/dist/host-kit/approval-bridge.d.ts.map +1 -1
- package/dist/host-kit/approval-bridge.js +15 -9
- package/dist/host-kit/approval-bridge.js.map +1 -1
- package/dist/host-kit/do-response.d.ts.map +1 -1
- package/dist/host-kit/do-response.js +7 -1
- package/dist/host-kit/do-response.js.map +1 -1
- package/dist/host-kit/flowsafe-worker.d.ts +2 -1
- package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
- package/dist/host-kit/flowsafe-worker.js +4 -2
- package/dist/host-kit/flowsafe-worker.js.map +1 -1
- package/dist/host-kit/run-router.d.ts.map +1 -1
- package/dist/host-kit/run-router.js +3 -2
- package/dist/host-kit/run-router.js.map +1 -1
- package/dist/schedules/schedules-d1.d.ts +1 -0
- package/dist/schedules/schedules-d1.d.ts.map +1 -1
- package/dist/schedules/schedules-d1.js +35 -22
- package/dist/schedules/schedules-d1.js.map +1 -1
- package/dist/schedules/tick.d.ts +17 -2
- package/dist/schedules/tick.d.ts.map +1 -1
- package/dist/schedules/tick.js +63 -44
- package/dist/schedules/tick.js.map +1 -1
- package/dist/signals/client.d.ts +7 -4
- package/dist/signals/client.d.ts.map +1 -1
- package/dist/signals/client.js +9 -7
- package/dist/signals/client.js.map +1 -1
- package/dist/signals/d1-shared.js +1 -1
- 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.map +1 -1
- package/dist/signals/thread-do-routes.d.ts +56 -10
- package/dist/signals/thread-do-routes.d.ts.map +1 -1
- package/dist/signals/thread-do-routes.js +434 -247
- package/dist/signals/thread-do-routes.js.map +1 -1
- package/package.json +18 -9
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// SPDX-License-Identifier: Apache-2.0
|
|
2
2
|
// RunnerRuntime hosts Mastra workflow execution against injected storage.
|
|
3
|
-
// It is
|
|
3
|
+
// It is environment-free: the Durable Object shell feeds it
|
|
4
4
|
// D1-backed storage; tests feed it InMemoryStore. Durability comes from
|
|
5
5
|
// Mastra's own snapshot persistence — createRun() writes the initial
|
|
6
6
|
// snapshot, the engine persists after each step boundary, and resume()
|
|
@@ -30,12 +30,12 @@ import { FENCED_WORKFLOW_STORAGE, } from './fenced-workflow-capability.js';
|
|
|
30
30
|
import { isDefinitiveInitialAdmissionRefusal } from './initial-admission-refusal.js';
|
|
31
31
|
import { mastraRegistryEntries } from './mastra-registry.js';
|
|
32
32
|
import { isPathSafeId } from './path-safe-id.js';
|
|
33
|
-
import { canonicalEconomicOperations, canonicalReplayPrincipals, canonicalScheduleDispatch, hasDisputedSettlement, lifecycleFromRequestContext,
|
|
33
|
+
import { advanceLifecycle, canonicalEconomicOperations, canonicalReplayPrincipals, canonicalScheduleDispatch, hasDisputedSettlement, lifecycleFromRequestContext, projectTerminalLifecycle, RUN_INTERRUPTED_MESSAGE, RUN_LIFECYCLE_CONTEXT_KEY, RunLifecycleBlockedError, terminalCleanupFor, } from './run-lifecycle.js';
|
|
34
34
|
import { decodeProgressRunProvenance, decodeResumeCounts, nextResumeCount, runExecutionIdentityFor, } from './run-provenance.js';
|
|
35
|
-
import { errorText, isRunStatus, isTerminalRunStatus, terminalStateFields, terminalStateUpdate, } from './run-terminal-state.js';
|
|
35
|
+
import { errorText, isDurableRunStatus, isRunStatus, isTerminalRunStatus, terminalStateFields, terminalStateUpdate, } from './run-terminal-state.js';
|
|
36
36
|
import { captureReservation, } from './start-reservation-contract.js';
|
|
37
37
|
import { validateTablePrefix } from './table-prefix.js';
|
|
38
|
-
export { RunLifecycleBlockedError, } from './run-lifecycle.js';
|
|
38
|
+
export { RunLifecycleBlockedError, RunSettledConflictError, } from './run-lifecycle.js';
|
|
39
39
|
export class UnknownWorkflowError extends Error {
|
|
40
40
|
constructor(workflowId) {
|
|
41
41
|
super(`unknown workflow '${workflowId}'`);
|
|
@@ -58,9 +58,8 @@ export class RunNotSuspendedError extends Error {
|
|
|
58
58
|
* An authoritative run-state read did not succeed, so nothing that read
|
|
59
59
|
* returned is evidence about the run. One cause is Mastra answering from its
|
|
60
60
|
* in-memory fallback instead of from storage — what comes back then describes
|
|
61
|
-
* the Run object this isolate happens to hold rather than what is persisted
|
|
62
|
-
*
|
|
63
|
-
* the underlying fault as `cause`. Distinct from UnknownRunError: the run may
|
|
61
|
+
* the Run object this isolate happens to hold rather than what is persisted.
|
|
62
|
+
* Distinct from UnknownRunError: the run may
|
|
64
63
|
* well exist and be suspended — nothing about it could be READ. The message
|
|
65
64
|
* therefore names no cause: it is minted where the read failed, not where the
|
|
66
65
|
* reason is known.
|
|
@@ -90,14 +89,10 @@ export class InvalidRunRequestError extends Error {
|
|
|
90
89
|
this.name = 'InvalidRunRequestError';
|
|
91
90
|
}
|
|
92
91
|
}
|
|
93
|
-
// PATH_SAFE_ID_PATTERN validates runId and workflowId (full rationale lives on
|
|
94
|
-
// the leaf module). runId is validated at start() (client input →
|
|
95
|
-
// InvalidRunRequestError); workflowId is developer-controlled and validated at
|
|
96
|
-
// register() (programming error → plain Error).
|
|
97
92
|
// Core surfaces input/resume-schema violations and wrong-step selections as
|
|
98
93
|
// untyped Errors. Message matching is brittle, so it is scoped to choosing
|
|
99
94
|
// the HTTP-facing error class only; anything unmatched propagates unchanged
|
|
100
|
-
// (a 500 at the DO boundary
|
|
95
|
+
// (a 500 at the DO boundary).
|
|
101
96
|
const CLIENT_ERROR_MARKERS = [
|
|
102
97
|
'Invalid input',
|
|
103
98
|
'Invalid resume data',
|
|
@@ -229,7 +224,7 @@ function resolveResumeStep(step, state) {
|
|
|
229
224
|
}
|
|
230
225
|
// The live attempt for a step. Repeated steps (foreach) store an array of
|
|
231
226
|
// attempts, so the current suspension/resume is the latest; a single-run step
|
|
232
|
-
// stores one entry.
|
|
227
|
+
// stores one entry.
|
|
233
228
|
function latestAttempt(steps, stepKey) {
|
|
234
229
|
const entry = steps?.[stepKey];
|
|
235
230
|
return Array.isArray(entry) ? entry[entry.length - 1] : entry;
|
|
@@ -248,15 +243,13 @@ function resumedAtOf(steps, stepKey) {
|
|
|
248
243
|
return latestAttempt(steps, stepKey)?.resumedAt;
|
|
249
244
|
}
|
|
250
245
|
/**
|
|
251
|
-
* One home for the per-step projection convention
|
|
252
|
-
* (suspendedAt / resumedAt / resumeCount / suspendPayload): collect
|
|
246
|
+
* One home for the per-step projection convention: collect
|
|
253
247
|
* `stepKey -> value` over the suspended step keys, projecting an empty result
|
|
254
248
|
* as undefined so JSON summaries omit the field. The accumulator is
|
|
255
249
|
* null-prototype because step keys are author-chosen strings: on a plain
|
|
256
250
|
* object literal a step named '__proto__' would route into the
|
|
257
251
|
* Object.prototype setter and silently vanish (or, for an object-valued
|
|
258
|
-
* payload, rewire the accumulator's prototype)
|
|
259
|
-
* snapshot provenance stores [stepKey, count] pairs to avoid.
|
|
252
|
+
* payload, rewire the accumulator's prototype).
|
|
260
253
|
*/
|
|
261
254
|
function byStep(suspendedKeys, lookup) {
|
|
262
255
|
const map = Object.create(null);
|
|
@@ -289,8 +282,14 @@ function summarizeState(runId, state, counts, requestedBy, requestedByKind) {
|
|
|
289
282
|
if (state.status === 'success') {
|
|
290
283
|
summary.result = state.result;
|
|
291
284
|
}
|
|
292
|
-
else if (state.status === 'failed'
|
|
293
|
-
|
|
285
|
+
else if (state.status === 'failed') {
|
|
286
|
+
if (state.error)
|
|
287
|
+
summary.error = errorText(state.error);
|
|
288
|
+
if (lifecycle?.interruptedAt !== undefined)
|
|
289
|
+
summary.errorEnvelope = {
|
|
290
|
+
code: 'INTERRUPTED',
|
|
291
|
+
message: RUN_INTERRUPTED_MESSAGE,
|
|
292
|
+
};
|
|
294
293
|
}
|
|
295
294
|
else if (state.status === 'suspended') {
|
|
296
295
|
const suspendedKeys = Object.keys(state.suspendedPaths ?? {});
|
|
@@ -370,6 +369,22 @@ function orderedRequestContext(runtimeContext, provided, scheduled) {
|
|
|
370
369
|
...identity,
|
|
371
370
|
]);
|
|
372
371
|
}
|
|
372
|
+
/** @internal How often an executing leg marks its run row live. */
|
|
373
|
+
export const RUN_LEG_TOUCH_MS = 30_000;
|
|
374
|
+
// Longer than the largest Workers CPU limit (five minutes), which is the most
|
|
375
|
+
// a busy step can delay a touch timer: a row untouched this long has no leg
|
|
376
|
+
// left marking it, on this instance or one being replaced.
|
|
377
|
+
const RUN_LEG_SILENT_MS = 360_000;
|
|
378
|
+
/** Has no leg marked this row live within RUN_LEG_SILENT_MS? */
|
|
379
|
+
function rowSilent(raw, now) {
|
|
380
|
+
const touchedAt = Date.parse(raw.updatedAt);
|
|
381
|
+
if (!Number.isFinite(touchedAt))
|
|
382
|
+
throw new RunStateUnreadableError(raw.workflowId, raw.runId);
|
|
383
|
+
return now - touchedAt >= RUN_LEG_SILENT_MS;
|
|
384
|
+
}
|
|
385
|
+
/** A settlement compare-and-set found its row changed since the silence read. */
|
|
386
|
+
class SettlementMissError extends Error {
|
|
387
|
+
}
|
|
373
388
|
const TERMINABLE_RUN_STATUSES = new Set([
|
|
374
389
|
'running',
|
|
375
390
|
'waiting',
|
|
@@ -585,10 +600,9 @@ export class RunnerRuntime {
|
|
|
585
600
|
#activeRuns = new Map();
|
|
586
601
|
#terminalAbortIntents = new Map();
|
|
587
602
|
#lifecycleLocks = new Map();
|
|
588
|
-
// The host DO's pubsub identity (RunnerRuntimeOptions.pubsub)
|
|
589
|
-
//
|
|
590
|
-
//
|
|
591
|
-
// run ⇒ byte-identical to before this seam existed.
|
|
603
|
+
// The host DO's pubsub identity (RunnerRuntimeOptions.pubsub) is passed to
|
|
604
|
+
// Mastra and each createRun so a configured host shares one feed.
|
|
605
|
+
// Undefined ⇒ core defaults a fresh emitter per run.
|
|
592
606
|
#pubsub;
|
|
593
607
|
#executionFence;
|
|
594
608
|
#startIdempotency;
|
|
@@ -604,10 +618,7 @@ export class RunnerRuntime {
|
|
|
604
618
|
/**
|
|
605
619
|
* The deployment execution fence this runtime enforces, or undefined when
|
|
606
620
|
* the host built an unfenced runtime. Exposed so the surfaces ABOVE the
|
|
607
|
-
* runtime
|
|
608
|
-
* the same store rather than constructing a second one, and so
|
|
609
|
-
* DurableObjectRunner can assert that a runtime built against a bound
|
|
610
|
-
* database is never fence-less.
|
|
621
|
+
* runtime gate on the same store rather than constructing a second one.
|
|
611
622
|
*/
|
|
612
623
|
get executionFence() {
|
|
613
624
|
return this.#executionFence;
|
|
@@ -671,7 +682,7 @@ export class RunnerRuntime {
|
|
|
671
682
|
throw new Error('RunnerRuntime: register all workflows before the first run — the Mastra instance is frozen once runs start');
|
|
672
683
|
}
|
|
673
684
|
if (!isPathSafeId(workflow.id)) {
|
|
674
|
-
throw new Error(`RunnerRuntime: workflow id '${workflow.id}' must be URL-path-safe
|
|
685
|
+
throw new Error(`RunnerRuntime: workflow id '${workflow.id}' must be URL-path-safe — it feeds the DO name join and the /runs/:workflowId/:runId path`);
|
|
675
686
|
}
|
|
676
687
|
if (this.#workflows.has(workflow.id)) {
|
|
677
688
|
throw new Error(`RunnerRuntime: duplicate workflow id '${workflow.id}'`);
|
|
@@ -819,10 +830,10 @@ export class RunnerRuntime {
|
|
|
819
830
|
const originalCached = workflow.runs.get(runId);
|
|
820
831
|
let provenance;
|
|
821
832
|
try {
|
|
822
|
-
const existing = await
|
|
833
|
+
const existing = await this.#getWorkflow(workflowId).getWorkflowRunById(runId);
|
|
823
834
|
if (existing || originalCached)
|
|
824
835
|
throw new RunAlreadyExistsError(workflowId, runId, existing?.status ?? 'pending');
|
|
825
|
-
const source = await this.#captureWorkflowStorage(
|
|
836
|
+
const source = await this.#captureWorkflowStorage(workflowId);
|
|
826
837
|
active.source = source;
|
|
827
838
|
provenance = {
|
|
828
839
|
version: 2,
|
|
@@ -876,7 +887,7 @@ export class RunnerRuntime {
|
|
|
876
887
|
onInitialWriteAttempt: () => {
|
|
877
888
|
candidate = workflow.runs.get(runId);
|
|
878
889
|
},
|
|
879
|
-
}, () =>
|
|
890
|
+
}, () => this.#createRun(workflowId, runId));
|
|
880
891
|
if (!admitted?.witness ||
|
|
881
892
|
!sameExecution(admitted.witness.execution, d1Execution))
|
|
882
893
|
throw new RunStateUnreadableError(workflowId, runId);
|
|
@@ -895,7 +906,7 @@ export class RunnerRuntime {
|
|
|
895
906
|
...capturedExecution,
|
|
896
907
|
...startIdentity,
|
|
897
908
|
});
|
|
898
|
-
run = await
|
|
909
|
+
run = await this.#createRun(workflowId, runId);
|
|
899
910
|
}
|
|
900
911
|
active.run = run;
|
|
901
912
|
engineEntered = true;
|
|
@@ -928,7 +939,7 @@ export class RunnerRuntime {
|
|
|
928
939
|
await this.#startIdempotency.releaseReservation(claim);
|
|
929
940
|
}
|
|
930
941
|
if (engineEntered && provenance && !outcomeReadStarted) {
|
|
931
|
-
const recovered = await this.#summaryForAttempt(
|
|
942
|
+
const recovered = await this.#summaryForAttempt(workflowId, runId, provenance);
|
|
932
943
|
if (recovered)
|
|
933
944
|
return recovered;
|
|
934
945
|
}
|
|
@@ -951,7 +962,7 @@ export class RunnerRuntime {
|
|
|
951
962
|
* loads it and re-enters the engine at the suspended step.
|
|
952
963
|
*/
|
|
953
964
|
async resume(workflowId, runId, options = {}) {
|
|
954
|
-
|
|
965
|
+
this.#getWorkflow(workflowId);
|
|
955
966
|
const proof = await this.#assertResumeFence(workflowId, runId);
|
|
956
967
|
return this.#withRunLock(workflowId, runId, async () => {
|
|
957
968
|
const activeKey = this.#runKey(workflowId, runId);
|
|
@@ -963,9 +974,9 @@ export class RunnerRuntime {
|
|
|
963
974
|
let engineEntered = false;
|
|
964
975
|
let outcomeReadStarted = false;
|
|
965
976
|
try {
|
|
966
|
-
const source = await this.#captureWorkflowStorage(
|
|
977
|
+
const source = await this.#captureWorkflowStorage(workflowId);
|
|
967
978
|
active.source = source;
|
|
968
|
-
const state = await this.#workflowState(
|
|
979
|
+
const state = await this.#workflowState(workflowId, runId, true);
|
|
969
980
|
if (!state)
|
|
970
981
|
throw new UnknownRunError(workflowId, runId);
|
|
971
982
|
if (state.isFromInMemory)
|
|
@@ -998,7 +1009,7 @@ export class RunnerRuntime {
|
|
|
998
1009
|
await options.prepareExecution(new RequestContext(Object.entries(values)));
|
|
999
1010
|
await this.#withLifecycleLock(workflowId, runId, check);
|
|
1000
1011
|
}
|
|
1001
|
-
const run = await
|
|
1012
|
+
const run = await this.#createRun(workflowId, runId);
|
|
1002
1013
|
const { executionPromise } = await this.#withLifecycleLock(workflowId, runId, async () => {
|
|
1003
1014
|
await check();
|
|
1004
1015
|
active.run = run;
|
|
@@ -1024,7 +1035,7 @@ export class RunnerRuntime {
|
|
|
1024
1035
|
}
|
|
1025
1036
|
catch (error) {
|
|
1026
1037
|
if (engineEntered && provenance && !outcomeReadStarted) {
|
|
1027
|
-
const recovered = await this.#summaryForAttempt(
|
|
1038
|
+
const recovered = await this.#summaryForAttempt(workflowId, runId, provenance);
|
|
1028
1039
|
if (recovered)
|
|
1029
1040
|
return recovered;
|
|
1030
1041
|
}
|
|
@@ -1049,7 +1060,7 @@ export class RunnerRuntime {
|
|
|
1049
1060
|
this.#getWorkflow(workflowId);
|
|
1050
1061
|
const prepared = await this.#withLifecycleLock(workflowId, runId, async () => {
|
|
1051
1062
|
const source = this.#activeRuns.get(this.#runKey(workflowId, runId))?.source ??
|
|
1052
|
-
(await this.#captureWorkflowStorage(
|
|
1063
|
+
(await this.#captureWorkflowStorage(workflowId));
|
|
1053
1064
|
const state = await source.load.call(source.workflows, {
|
|
1054
1065
|
workflowName: workflowId,
|
|
1055
1066
|
runId,
|
|
@@ -1096,9 +1107,7 @@ export class RunnerRuntime {
|
|
|
1096
1107
|
return undefined;
|
|
1097
1108
|
}
|
|
1098
1109
|
const principals = canonicalReplayPrincipals(replayPrincipals);
|
|
1099
|
-
const intent = {
|
|
1100
|
-
...(lifecycle ?? { version: 1, revision: 0 }),
|
|
1101
|
-
revision: nextLifecycleRevision(lifecycle?.revision ?? 0),
|
|
1110
|
+
const intent = advanceLifecycle(lifecycle, {
|
|
1102
1111
|
transitionIntent: {
|
|
1103
1112
|
status: intendedStatus,
|
|
1104
1113
|
requestedAt: now,
|
|
@@ -1110,7 +1119,7 @@ export class RunnerRuntime {
|
|
|
1110
1119
|
}
|
|
1111
1120
|
: {}),
|
|
1112
1121
|
},
|
|
1113
|
-
};
|
|
1122
|
+
});
|
|
1114
1123
|
await this.#persistLifecycle(workflowId, runId, state, intent, now, source);
|
|
1115
1124
|
if (active) {
|
|
1116
1125
|
active.lifecycle = intent;
|
|
@@ -1155,104 +1164,114 @@ export class RunnerRuntime {
|
|
|
1155
1164
|
}
|
|
1156
1165
|
async #transitionTerminal(workflowId, runId, status, now, cas, replayPrincipals, replayingPrincipal) {
|
|
1157
1166
|
this.#getWorkflow(workflowId);
|
|
1158
|
-
return this.#withRunLock(workflowId, runId,
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1167
|
+
return this.#withRunLock(workflowId, runId, () => this.#transitionTerminalLocked(workflowId, runId, status, now, {
|
|
1168
|
+
cas,
|
|
1169
|
+
replayPrincipals,
|
|
1170
|
+
replayingPrincipal,
|
|
1171
|
+
}));
|
|
1172
|
+
}
|
|
1173
|
+
/**
|
|
1174
|
+
* #transitionTerminal's body, for a caller already holding the run lock.
|
|
1175
|
+
* With `expected`, the write is a compare-and-set against that exact row and
|
|
1176
|
+
* a miss throws SettlementMissError.
|
|
1177
|
+
*/
|
|
1178
|
+
async #transitionTerminalLocked(workflowId, runId, status, now, { cas, replayPrincipals, replayingPrincipal, expected, } = {}) {
|
|
1179
|
+
const source = await this.#captureWorkflowStorage(workflowId);
|
|
1180
|
+
const state = await source.load.call(source.workflows, {
|
|
1181
|
+
workflowName: workflowId,
|
|
1182
|
+
runId,
|
|
1183
|
+
});
|
|
1184
|
+
if (!state)
|
|
1185
|
+
throw new UnknownRunError(workflowId, runId);
|
|
1186
|
+
if (state.runId !== runId)
|
|
1187
|
+
throw new RunStateUnreadableError(workflowId, runId);
|
|
1188
|
+
const lifecycle = lifecycleFromRequestContext(state.requestContext);
|
|
1189
|
+
if (lifecycle?.terminal) {
|
|
1190
|
+
if (replayingPrincipal &&
|
|
1191
|
+
!lifecycle.terminal.replayPrincipals.some((principal) => principal.kind === replayingPrincipal.kind &&
|
|
1192
|
+
principal.id === replayingPrincipal.id)) {
|
|
1165
1193
|
throw new UnknownRunError(workflowId, runId);
|
|
1166
|
-
if (state.runId !== runId)
|
|
1167
|
-
throw new RunStateUnreadableError(workflowId, runId);
|
|
1168
|
-
const lifecycle = lifecycleFromRequestContext(state.requestContext);
|
|
1169
|
-
if (lifecycle?.terminal) {
|
|
1170
|
-
if (replayingPrincipal &&
|
|
1171
|
-
!lifecycle.terminal.replayPrincipals.some((principal) => principal.kind === replayingPrincipal.kind &&
|
|
1172
|
-
principal.id === replayingPrincipal.id)) {
|
|
1173
|
-
throw new UnknownRunError(workflowId, runId);
|
|
1174
|
-
}
|
|
1175
|
-
return {
|
|
1176
|
-
summary: await this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state)),
|
|
1177
|
-
transitioned: false,
|
|
1178
|
-
casMatched: cas === undefined ||
|
|
1179
|
-
(lifecycle.terminal.status === 'timed_out' &&
|
|
1180
|
-
lifecycle.deadlineAt === cas.expectedDeadlineAt),
|
|
1181
|
-
cleanup: terminalCleanupFor(lifecycle),
|
|
1182
|
-
};
|
|
1183
1194
|
}
|
|
1184
|
-
const transitionIntent = lifecycle?.transitionIntent;
|
|
1185
|
-
const intentMatchesTransition = transitionIntent?.status === status &&
|
|
1186
|
-
(cas === undefined ||
|
|
1187
|
-
(transitionIntent.expectedRevision === cas.expectedRevision &&
|
|
1188
|
-
transitionIntent.expectedDeadlineAt === cas.expectedDeadlineAt));
|
|
1189
|
-
const intentMatchesCas = cas !== undefined && intentMatchesTransition;
|
|
1190
|
-
if (cas !== undefined &&
|
|
1191
|
-
!intentMatchesCas &&
|
|
1192
|
-
(lifecycle?.revision !== cas.expectedRevision ||
|
|
1193
|
-
lifecycle.deadlineAt !== cas.expectedDeadlineAt ||
|
|
1194
|
-
lifecycle.deadlineAt === undefined ||
|
|
1195
|
-
lifecycle.deadlineAt > now)) {
|
|
1196
|
-
return {
|
|
1197
|
-
summary: await this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state)),
|
|
1198
|
-
transitioned: false,
|
|
1199
|
-
casMatched: false,
|
|
1200
|
-
cleanup: {
|
|
1201
|
-
revision: lifecycle?.revision ?? 0,
|
|
1202
|
-
status,
|
|
1203
|
-
cleanupCompleted: false,
|
|
1204
|
-
...(lifecycle?.scheduleDispatch
|
|
1205
|
-
? { scheduleDispatch: lifecycle.scheduleDispatch }
|
|
1206
|
-
: {}),
|
|
1207
|
-
},
|
|
1208
|
-
};
|
|
1209
|
-
}
|
|
1210
|
-
if (hasDisputedSettlement(lifecycle)) {
|
|
1211
|
-
throw new RunLifecycleBlockedError({
|
|
1212
|
-
code: 'DISPUTED_SETTLEMENT',
|
|
1213
|
-
message: 'run termination is blocked while an economic operation is disputed',
|
|
1214
|
-
});
|
|
1215
|
-
}
|
|
1216
|
-
const currentStatus = state.status;
|
|
1217
|
-
const abortIntent = this.#terminalAbortIntents.get(this.#runKey(workflowId, runId));
|
|
1218
|
-
if (!TERMINABLE_RUN_STATUSES.has(currentStatus) &&
|
|
1219
|
-
!intentMatchesTransition &&
|
|
1220
|
-
!(currentStatus === 'canceled' && abortIntent === status)) {
|
|
1221
|
-
throw new RunTerminalConflictError(workflowId, runId, currentStatus);
|
|
1222
|
-
}
|
|
1223
|
-
const provenance = runProvenance(state);
|
|
1224
|
-
const fallbackPrincipal = provenance?.requestedBy && provenance.requestedByKind
|
|
1225
|
-
? {
|
|
1226
|
-
kind: provenance.requestedByKind,
|
|
1227
|
-
id: provenance.requestedBy,
|
|
1228
|
-
}
|
|
1229
|
-
: { kind: 'system', id: 'flowsafe-system' };
|
|
1230
|
-
const principals = canonicalReplayPrincipals(replayPrincipals ??
|
|
1231
|
-
transitionIntent?.replayPrincipals ?? [fallbackPrincipal]);
|
|
1232
|
-
const next = projectTerminalLifecycle(lifecycle, status, now, principals);
|
|
1233
|
-
await this.#persistLifecycle(workflowId, runId, {
|
|
1234
|
-
...state,
|
|
1235
|
-
...terminalStateFields(status),
|
|
1236
|
-
error: {
|
|
1237
|
-
name: status === 'cancelled' ? 'RunCancelledError' : 'RunTimedOutError',
|
|
1238
|
-
message: next.terminal.error.message,
|
|
1239
|
-
},
|
|
1240
|
-
timestamp: now,
|
|
1241
|
-
}, next, now, source);
|
|
1242
|
-
this.#terminalAbortIntents.delete(this.#runKey(workflowId, runId));
|
|
1243
1195
|
return {
|
|
1244
1196
|
summary: await this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state)),
|
|
1245
|
-
transitioned:
|
|
1246
|
-
casMatched:
|
|
1247
|
-
|
|
1197
|
+
transitioned: false,
|
|
1198
|
+
casMatched: cas === undefined ||
|
|
1199
|
+
(lifecycle.terminal.status === 'timed_out' &&
|
|
1200
|
+
lifecycle.deadlineAt === cas.expectedDeadlineAt),
|
|
1201
|
+
cleanup: terminalCleanupFor(lifecycle),
|
|
1248
1202
|
};
|
|
1249
|
-
}
|
|
1203
|
+
}
|
|
1204
|
+
const transitionIntent = lifecycle?.transitionIntent;
|
|
1205
|
+
const intentMatchesTransition = transitionIntent?.status === status &&
|
|
1206
|
+
(cas === undefined ||
|
|
1207
|
+
(transitionIntent.expectedRevision === cas.expectedRevision &&
|
|
1208
|
+
transitionIntent.expectedDeadlineAt === cas.expectedDeadlineAt));
|
|
1209
|
+
const intentMatchesCas = cas !== undefined && intentMatchesTransition;
|
|
1210
|
+
if (cas !== undefined &&
|
|
1211
|
+
!intentMatchesCas &&
|
|
1212
|
+
(lifecycle?.revision !== cas.expectedRevision ||
|
|
1213
|
+
lifecycle.deadlineAt !== cas.expectedDeadlineAt ||
|
|
1214
|
+
lifecycle.deadlineAt === undefined ||
|
|
1215
|
+
lifecycle.deadlineAt > now)) {
|
|
1216
|
+
return {
|
|
1217
|
+
summary: await this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state)),
|
|
1218
|
+
transitioned: false,
|
|
1219
|
+
casMatched: false,
|
|
1220
|
+
cleanup: {
|
|
1221
|
+
revision: lifecycle?.revision ?? 0,
|
|
1222
|
+
status,
|
|
1223
|
+
cleanupCompleted: false,
|
|
1224
|
+
...(lifecycle?.scheduleDispatch
|
|
1225
|
+
? { scheduleDispatch: lifecycle.scheduleDispatch }
|
|
1226
|
+
: {}),
|
|
1227
|
+
},
|
|
1228
|
+
};
|
|
1229
|
+
}
|
|
1230
|
+
if (hasDisputedSettlement(lifecycle)) {
|
|
1231
|
+
throw new RunLifecycleBlockedError({
|
|
1232
|
+
code: 'DISPUTED_SETTLEMENT',
|
|
1233
|
+
message: 'run termination is blocked while an economic operation is disputed',
|
|
1234
|
+
});
|
|
1235
|
+
}
|
|
1236
|
+
const currentStatus = state.status;
|
|
1237
|
+
const abortIntent = this.#terminalAbortIntents.get(this.#runKey(workflowId, runId));
|
|
1238
|
+
if (!TERMINABLE_RUN_STATUSES.has(currentStatus) &&
|
|
1239
|
+
!intentMatchesTransition &&
|
|
1240
|
+
!(currentStatus === 'canceled' && abortIntent === status)) {
|
|
1241
|
+
throw new RunTerminalConflictError(workflowId, runId, currentStatus);
|
|
1242
|
+
}
|
|
1243
|
+
const provenance = runProvenance(state);
|
|
1244
|
+
const fallbackPrincipal = provenance?.requestedBy && provenance.requestedByKind
|
|
1245
|
+
? {
|
|
1246
|
+
kind: provenance.requestedByKind,
|
|
1247
|
+
id: provenance.requestedBy,
|
|
1248
|
+
}
|
|
1249
|
+
: { kind: 'system', id: 'flowsafe-system' };
|
|
1250
|
+
const principals = canonicalReplayPrincipals(replayPrincipals ??
|
|
1251
|
+
transitionIntent?.replayPrincipals ?? [fallbackPrincipal]);
|
|
1252
|
+
const next = projectTerminalLifecycle(lifecycle, status, now, principals);
|
|
1253
|
+
await this.#persistLifecycle(workflowId, runId, {
|
|
1254
|
+
...state,
|
|
1255
|
+
...terminalStateFields(status),
|
|
1256
|
+
error: {
|
|
1257
|
+
name: status === 'cancelled' ? 'RunCancelledError' : 'RunTimedOutError',
|
|
1258
|
+
message: next.terminal.error.message,
|
|
1259
|
+
},
|
|
1260
|
+
timestamp: now,
|
|
1261
|
+
}, next, now, source, expected);
|
|
1262
|
+
this.#terminalAbortIntents.delete(this.#runKey(workflowId, runId));
|
|
1263
|
+
return {
|
|
1264
|
+
summary: await this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state)),
|
|
1265
|
+
transitioned: true,
|
|
1266
|
+
casMatched: true,
|
|
1267
|
+
cleanup: terminalCleanupFor(next),
|
|
1268
|
+
};
|
|
1250
1269
|
}
|
|
1251
1270
|
/** Marks idempotent terminal side-effect cleanup after every hook succeeds. */
|
|
1252
1271
|
async completeTerminalCleanup(workflowId, runId, expectedRevision, now = Date.now()) {
|
|
1253
1272
|
this.#getWorkflow(workflowId);
|
|
1254
1273
|
return this.#withRunLock(workflowId, runId, async () => {
|
|
1255
|
-
const source = await this.#captureWorkflowStorage(
|
|
1274
|
+
const source = await this.#captureWorkflowStorage(workflowId);
|
|
1256
1275
|
const state = await source.load.call(source.workflows, {
|
|
1257
1276
|
workflowName: workflowId,
|
|
1258
1277
|
runId,
|
|
@@ -1271,14 +1290,9 @@ export class RunnerRuntime {
|
|
|
1271
1290
|
if (lifecycle.revision !== expectedRevision) {
|
|
1272
1291
|
throw new Error('run terminal cleanup CAS no longer matches');
|
|
1273
1292
|
}
|
|
1274
|
-
const next = {
|
|
1275
|
-
...lifecycle,
|
|
1276
|
-
|
|
1277
|
-
terminal: {
|
|
1278
|
-
...lifecycle.terminal,
|
|
1279
|
-
cleanupCompletedAt: now,
|
|
1280
|
-
},
|
|
1281
|
-
};
|
|
1293
|
+
const next = advanceLifecycle(lifecycle, {
|
|
1294
|
+
terminal: { ...lifecycle.terminal, cleanupCompletedAt: now },
|
|
1295
|
+
});
|
|
1282
1296
|
await this.#persistLifecycle(workflowId, runId, state, next, now, source);
|
|
1283
1297
|
return this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state));
|
|
1284
1298
|
});
|
|
@@ -1294,8 +1308,7 @@ export class RunnerRuntime {
|
|
|
1294
1308
|
* that did not reach storage.
|
|
1295
1309
|
*/
|
|
1296
1310
|
async status(workflowId, runId) {
|
|
1297
|
-
const
|
|
1298
|
-
const state = await this.#workflowState(workflow, runId);
|
|
1311
|
+
const state = await this.#workflowState(workflowId, runId);
|
|
1299
1312
|
if (!state)
|
|
1300
1313
|
return null;
|
|
1301
1314
|
return this.#summaryFromState(runId, state);
|
|
@@ -1304,23 +1317,17 @@ export class RunnerRuntime {
|
|
|
1304
1317
|
* status() for a caller about to CONCLUDE something irreversible from what it
|
|
1305
1318
|
* reads — delete a wake record, spend an abandonment budget, resume a run.
|
|
1306
1319
|
*
|
|
1307
|
-
*
|
|
1308
|
-
*
|
|
1309
|
-
*
|
|
1310
|
-
*
|
|
1311
|
-
*
|
|
1312
|
-
* about the run. Mastra stamps `isFromInMemory` on it at its single
|
|
1313
|
-
* construction site and the persisted branch builds its result field by
|
|
1314
|
-
* field without ever copying the marker, so this throws on exactly the reads
|
|
1315
|
-
* that did not reach storage. `null` still means the read SUCCEEDED and
|
|
1316
|
-
* found nothing.
|
|
1320
|
+
* Workflow.getInMemoryRunAsWorkflowState reports the retained Run's lifecycle
|
|
1321
|
+
* status with isFromInMemory: true, without suspended paths or requestContext.
|
|
1322
|
+
* Refusing that marker prevents an approximation from authorizing an
|
|
1323
|
+
* irreversible action; after non-suspended completion the Run leaves the
|
|
1324
|
+
* in-memory map, so the fallback is null.
|
|
1317
1325
|
*
|
|
1318
|
-
*
|
|
1319
|
-
*
|
|
1326
|
+
* A valid v2 pending row is refused before lifecycle projection; it has no
|
|
1327
|
+
* durable execution outcome yet.
|
|
1320
1328
|
*/
|
|
1321
1329
|
async authoritativeStatus(workflowId, runId) {
|
|
1322
|
-
const
|
|
1323
|
-
const state = await this.#workflowState(workflow, runId);
|
|
1330
|
+
const state = await this.#workflowState(workflowId, runId);
|
|
1324
1331
|
if (!state)
|
|
1325
1332
|
return null;
|
|
1326
1333
|
if (state.isFromInMemory === true) {
|
|
@@ -1335,10 +1342,9 @@ export class RunnerRuntime {
|
|
|
1335
1342
|
throw new RunStateUnreadableError(workflowId, runId);
|
|
1336
1343
|
return state;
|
|
1337
1344
|
}
|
|
1338
|
-
async #captureWorkflowStorage(
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
?.getStore('workflows');
|
|
1345
|
+
async #captureWorkflowStorage(workflowId) {
|
|
1346
|
+
this.#getWorkflow(workflowId);
|
|
1347
|
+
const workflows = await this.#mastra?.getStorage()?.getStore('workflows');
|
|
1342
1348
|
if (!workflows)
|
|
1343
1349
|
throw new Error('workflow storage is unavailable');
|
|
1344
1350
|
const methods = {
|
|
@@ -1355,11 +1361,13 @@ export class RunnerRuntime {
|
|
|
1355
1361
|
}
|
|
1356
1362
|
if (capability === null || typeof capability !== 'object')
|
|
1357
1363
|
throw new Error('workflow capability is malformed');
|
|
1358
|
-
const { database, tablePrefix: prefix, readSnapshot, withInitialAdmission: admit, terminalizeInitialAdmission: terminalize, } = capability;
|
|
1364
|
+
const { database, tablePrefix: prefix, readSnapshot, withInitialAdmission: admit, terminalizeInitialAdmission: terminalize, touchRun: touch, replaceSnapshot: replace, } = capability;
|
|
1359
1365
|
if (typeof prefix !== 'string' ||
|
|
1360
1366
|
typeof readSnapshot !== 'function' ||
|
|
1361
1367
|
typeof admit !== 'function' ||
|
|
1362
1368
|
typeof terminalize !== 'function' ||
|
|
1369
|
+
(touch !== undefined && typeof touch !== 'function') ||
|
|
1370
|
+
(replace !== undefined && typeof replace !== 'function') ||
|
|
1363
1371
|
!database ||
|
|
1364
1372
|
typeof database.prepare !== 'function' ||
|
|
1365
1373
|
typeof database.batch !== 'function')
|
|
@@ -1377,6 +1385,8 @@ export class RunnerRuntime {
|
|
|
1377
1385
|
readSnapshot,
|
|
1378
1386
|
admit,
|
|
1379
1387
|
terminalize,
|
|
1388
|
+
...(touch === undefined ? {} : { touch }),
|
|
1389
|
+
...(replace === undefined ? {} : { replace }),
|
|
1380
1390
|
};
|
|
1381
1391
|
}
|
|
1382
1392
|
async #observeStartState(workflowId, runId) {
|
|
@@ -1384,9 +1394,9 @@ export class RunnerRuntime {
|
|
|
1384
1394
|
throw new InvalidRunRequestError('workflowId is malformed');
|
|
1385
1395
|
if (!isPathSafeId(runId))
|
|
1386
1396
|
throw new InvalidRunRequestError('runId is malformed');
|
|
1387
|
-
|
|
1397
|
+
this.#getWorkflow(workflowId);
|
|
1388
1398
|
try {
|
|
1389
|
-
const source = await this.#captureWorkflowStorage(
|
|
1399
|
+
const source = await this.#captureWorkflowStorage(workflowId);
|
|
1390
1400
|
return {
|
|
1391
1401
|
source,
|
|
1392
1402
|
state: await this.#readStartState(source, workflowId, runId),
|
|
@@ -1529,7 +1539,7 @@ export class RunnerRuntime {
|
|
|
1529
1539
|
/** @internal Recover only after the exact owning execution has unwound. */
|
|
1530
1540
|
async recoverStartAttempt(value, recovery) {
|
|
1531
1541
|
const execution = normalizeD1RunExecutionIdentity(value);
|
|
1532
|
-
const { attemptToken, isOwnerQuiescent, startReservation: suppliedClaim, expectedTarget: suppliedTarget, } = recovery;
|
|
1542
|
+
const { attemptToken, isOwnerQuiescent, startReservation: suppliedClaim, expectedTarget: suppliedTarget, startLeg, } = recovery;
|
|
1533
1543
|
let expectedTarget;
|
|
1534
1544
|
if (suppliedTarget !== undefined) {
|
|
1535
1545
|
if (suppliedTarget === null ||
|
|
@@ -1579,17 +1589,21 @@ export class RunnerRuntime {
|
|
|
1579
1589
|
const claim = suppliedClaim === undefined
|
|
1580
1590
|
? undefined
|
|
1581
1591
|
: captureReservation(suppliedClaim, 'started');
|
|
1582
|
-
if (!isPathSafeId(attemptToken) ||
|
|
1592
|
+
if (!isPathSafeId(attemptToken) ||
|
|
1593
|
+
typeof isOwnerQuiescent !== 'function' ||
|
|
1594
|
+
(startLeg !== undefined &&
|
|
1595
|
+
startLeg !== 'unwound' &&
|
|
1596
|
+
startLeg !== 'touched'))
|
|
1583
1597
|
throw new InvalidRunRequestError('start recovery authority is malformed');
|
|
1584
1598
|
if (claim && !this.#startIdempotency)
|
|
1585
1599
|
throw new ExecutionFenceUnreadableError('run start recovery is unresolved');
|
|
1586
1600
|
const { workflowId, runId } = execution;
|
|
1587
|
-
|
|
1601
|
+
this.#getWorkflow(workflowId);
|
|
1588
1602
|
return this.#withRunLock(workflowId, runId, () => this.#withLifecycleLock(workflowId, runId, async () => {
|
|
1589
1603
|
try {
|
|
1590
1604
|
if (this.isRunActive(workflowId, runId))
|
|
1591
1605
|
throw new Error('run owner is not quiescent');
|
|
1592
|
-
const source = await this.#captureWorkflowStorage(
|
|
1606
|
+
const source = await this.#captureWorkflowStorage(workflowId);
|
|
1593
1607
|
if (this.isRunActive(workflowId, runId) ||
|
|
1594
1608
|
(await Reflect.apply(isOwnerQuiescent, undefined, [])) !== true ||
|
|
1595
1609
|
this.isRunActive(workflowId, runId))
|
|
@@ -1623,11 +1637,19 @@ export class RunnerRuntime {
|
|
|
1623
1637
|
state.provenance.attemptToken !== attemptToken ||
|
|
1624
1638
|
state.provenance.resumeCounts.length !== 0)
|
|
1625
1639
|
throw new RunStartPendingError();
|
|
1640
|
+
const nowMs = Date.now();
|
|
1641
|
+
// A source without the touch keeps no silence evidence: its start
|
|
1642
|
+
// leg may still run, so it is repaired at once and unstamped.
|
|
1643
|
+
const waitsForSilence = startLeg === 'touched' && source.touch !== undefined;
|
|
1644
|
+
if (waitsForSilence && !rowSilent(state.raw, nowMs))
|
|
1645
|
+
throw new RunStartPendingError();
|
|
1646
|
+
const legStopped = startLeg === 'unwound' || waitsForSilence;
|
|
1626
1647
|
const result = await source.terminalize.call(source.capability, {
|
|
1627
1648
|
expected: state.raw,
|
|
1628
1649
|
execution,
|
|
1629
1650
|
attemptToken,
|
|
1630
|
-
nowMs
|
|
1651
|
+
nowMs,
|
|
1652
|
+
...(legStopped ? { markOutcomeUnknown: true } : {}),
|
|
1631
1653
|
});
|
|
1632
1654
|
if (result.kind === 'conflict')
|
|
1633
1655
|
throw new Error('initial terminalization conflicts');
|
|
@@ -1664,6 +1686,124 @@ export class RunnerRuntime {
|
|
|
1664
1686
|
}
|
|
1665
1687
|
}));
|
|
1666
1688
|
}
|
|
1689
|
+
/**
|
|
1690
|
+
* @internal Mark this run's row live for an executing leg, from whichever
|
|
1691
|
+
* instance runs it; the evidence #silentRow reads. A storage source without
|
|
1692
|
+
* the touch leaves nothing to read, so its runs are never settled here.
|
|
1693
|
+
*/
|
|
1694
|
+
async touchRun(workflowId, runId, now = Date.now()) {
|
|
1695
|
+
const source = await this.#captureWorkflowStorage(workflowId);
|
|
1696
|
+
if (source.storage === 'd1' && source.touch)
|
|
1697
|
+
await source.touch.call(source.capability, { workflowId, runId }, now);
|
|
1698
|
+
}
|
|
1699
|
+
/**
|
|
1700
|
+
* @internal Settle a run whose execution leg ended without a durable outcome.
|
|
1701
|
+
*
|
|
1702
|
+
* The caller is the run's own Durable Object after it has established that no
|
|
1703
|
+
* leg of its own drives the run; this runtime's `#activeRuns` covers the
|
|
1704
|
+
* in-process drivers. An object can be replaced while its leg keeps running
|
|
1705
|
+
* on the outgoing instance, so a run is written only after its row has gone
|
|
1706
|
+
* untouched for RUN_LEG_SILENT_MS (`live` otherwise).
|
|
1707
|
+
*
|
|
1708
|
+
* `durable` (suspended, or terminal with its cleanup done) and `absent` leave
|
|
1709
|
+
* the snapshot untouched. A recorded cancellation or timeout owns the
|
|
1710
|
+
* outcome: `transition` completes it, or replays a terminal one whose cleanup
|
|
1711
|
+
* is unfinished, and leaves the cleanup to the caller as the terminate and
|
|
1712
|
+
* deadline routes do. The pending initial row stays with start recovery,
|
|
1713
|
+
* which repairs it as an unknown outcome.
|
|
1714
|
+
*
|
|
1715
|
+
* Any other run becomes `failed` (`interrupted`), never re-executed: the step
|
|
1716
|
+
* that was in flight may already have had effects.
|
|
1717
|
+
*/
|
|
1718
|
+
async settleInterruptedRun(workflowId, runId, now = Date.now()) {
|
|
1719
|
+
this.#getWorkflow(workflowId);
|
|
1720
|
+
// Checked before queueing: a live leg holds the run lock for its whole
|
|
1721
|
+
// length, and a caller waiting behind it would learn nothing.
|
|
1722
|
+
if (this.isRunActive(workflowId, runId))
|
|
1723
|
+
return { kind: 'live' };
|
|
1724
|
+
return this.#withRunLock(workflowId, runId, () => this.#withLifecycleLock(workflowId, runId, async () => {
|
|
1725
|
+
const source = await this.#captureWorkflowStorage(workflowId);
|
|
1726
|
+
const state = await source.load.call(source.workflows, {
|
|
1727
|
+
workflowName: workflowId,
|
|
1728
|
+
runId,
|
|
1729
|
+
});
|
|
1730
|
+
if (!state)
|
|
1731
|
+
return { kind: 'absent' };
|
|
1732
|
+
if (state.runId !== runId)
|
|
1733
|
+
throw new RunStateUnreadableError(workflowId, runId);
|
|
1734
|
+
const lifecycle = lifecycleFromRequestContext(state.requestContext);
|
|
1735
|
+
// Ahead of the status checks: a cancel that took effect leaves Mastra's
|
|
1736
|
+
// terminal `canceled` precursor, which only the recorded transition
|
|
1737
|
+
// turns into `cancelled` with its cleanup.
|
|
1738
|
+
const recorded = lifecycle?.terminal ?? lifecycle?.transitionIntent;
|
|
1739
|
+
if (lifecycle?.terminal?.cleanupCompletedAt !== undefined)
|
|
1740
|
+
return { kind: 'durable' };
|
|
1741
|
+
if (!recorded) {
|
|
1742
|
+
if (isDurableRunStatus(state.status))
|
|
1743
|
+
return { kind: 'durable' };
|
|
1744
|
+
if (state.status === 'pending')
|
|
1745
|
+
throw new RunStartPendingError();
|
|
1746
|
+
if (!TERMINABLE_RUN_STATUSES.has(state.status))
|
|
1747
|
+
throw new RunStateUnreadableError(workflowId, runId);
|
|
1748
|
+
}
|
|
1749
|
+
// Every settlement write below is a compare-and-set against this
|
|
1750
|
+
// silent row: a write that lands after the read makes it miss (`live`).
|
|
1751
|
+
const silent = await this.#silentRow(source, workflowId, runId, now);
|
|
1752
|
+
if (!silent)
|
|
1753
|
+
return { kind: 'live' };
|
|
1754
|
+
try {
|
|
1755
|
+
if (recorded)
|
|
1756
|
+
return {
|
|
1757
|
+
kind: 'transition',
|
|
1758
|
+
replayPrincipal: recorded
|
|
1759
|
+
.replayPrincipals[0],
|
|
1760
|
+
transition: await this.#transitionTerminalLocked(workflowId, runId, recorded.status, now, { expected: silent }),
|
|
1761
|
+
};
|
|
1762
|
+
// The write replaces the silent row, so it is built from that row;
|
|
1763
|
+
// one that moved since the decision above waits for the next wake.
|
|
1764
|
+
const current = JSON.parse(silent.snapshot);
|
|
1765
|
+
if (current.runId !== runId)
|
|
1766
|
+
throw new RunStateUnreadableError(workflowId, runId);
|
|
1767
|
+
const currentLifecycle = lifecycleFromRequestContext(current.requestContext);
|
|
1768
|
+
if (current.status !== state.status ||
|
|
1769
|
+
currentLifecycle?.revision !== lifecycle?.revision ||
|
|
1770
|
+
currentLifecycle?.terminal ||
|
|
1771
|
+
currentLifecycle?.transitionIntent)
|
|
1772
|
+
return { kind: 'live' };
|
|
1773
|
+
await this.#persistLifecycle(workflowId, runId, {
|
|
1774
|
+
...current,
|
|
1775
|
+
...terminalStateFields('failed'),
|
|
1776
|
+
error: {
|
|
1777
|
+
name: 'RunInterruptedError',
|
|
1778
|
+
message: RUN_INTERRUPTED_MESSAGE,
|
|
1779
|
+
},
|
|
1780
|
+
timestamp: now,
|
|
1781
|
+
}, advanceLifecycle(currentLifecycle, { interruptedAt: now }), now, source, silent);
|
|
1782
|
+
}
|
|
1783
|
+
catch (error) {
|
|
1784
|
+
if (error instanceof SettlementMissError)
|
|
1785
|
+
return { kind: 'live' };
|
|
1786
|
+
throw error;
|
|
1787
|
+
}
|
|
1788
|
+
return {
|
|
1789
|
+
kind: 'interrupted',
|
|
1790
|
+
summary: await this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state)),
|
|
1791
|
+
};
|
|
1792
|
+
}));
|
|
1793
|
+
}
|
|
1794
|
+
/**
|
|
1795
|
+
* The run's row, when no leg has marked it live within RUN_LEG_SILENT_MS and
|
|
1796
|
+
* the storage can compare-and-set it; `undefined` otherwise.
|
|
1797
|
+
*/
|
|
1798
|
+
async #silentRow(source, workflowId, runId, now) {
|
|
1799
|
+
if (source.storage !== 'd1' || !source.touch || !source.replace)
|
|
1800
|
+
return undefined;
|
|
1801
|
+
const raw = await source.readSnapshot.call(source.capability, {
|
|
1802
|
+
workflowId,
|
|
1803
|
+
runId,
|
|
1804
|
+
});
|
|
1805
|
+
return raw && rowSilent(raw, now) ? raw : undefined;
|
|
1806
|
+
}
|
|
1667
1807
|
/** @internal Settle the exact selected terminal generation before managed cleanup. */
|
|
1668
1808
|
async settleStartExecution(state, originalClaim) {
|
|
1669
1809
|
const claim = originalClaim === undefined
|
|
@@ -1689,9 +1829,8 @@ export class RunnerRuntime {
|
|
|
1689
1829
|
// only ever deny downstream (fail closed), so loud propagation is safe.
|
|
1690
1830
|
//
|
|
1691
1831
|
// Every leg — provider or not — carries a base context minting the
|
|
1692
|
-
// workflow-scope key
|
|
1693
|
-
//
|
|
1694
|
-
// the scope is never client-suppliable. Provider values are partitioned into
|
|
1832
|
+
// workflow-scope key: the runtime is the trusted authority for "which
|
|
1833
|
+
// workflow is executing", so the scope is never client-suppliable. Provider values are partitioned into
|
|
1695
1834
|
// stored application context, capabilities, and trusted identity so every
|
|
1696
1835
|
// layer has an explicit order and a provider cannot replace runtime scope.
|
|
1697
1836
|
async #requestContextFor(workflowId, runId, leg, provenance, storedRequestContext, lifecycle) {
|
|
@@ -1706,13 +1845,8 @@ export class RunnerRuntime {
|
|
|
1706
1845
|
base[RUN_LIFECYCLE_CONTEXT_KEY] = lifecycle;
|
|
1707
1846
|
}
|
|
1708
1847
|
// No isolation scope is minted here: a deployment serves exactly one
|
|
1709
|
-
// organization
|
|
1710
|
-
//
|
|
1711
|
-
// deployment stays available
|
|
1712
|
-
// through breakwater's crossWorkflowIsolation, which reads the workflow
|
|
1713
|
-
// scope minted above. The isolation-scope context key remains RESERVED —
|
|
1714
|
-
// orderedRequestContext drops it from provider values — so a provider can
|
|
1715
|
-
// never mint a scope that desyncs from the execution identity below.
|
|
1848
|
+
// organization. The isolation-scope context key is RESERVED, so a provider
|
|
1849
|
+
// can never mint a scope that desyncs from the execution identity below.
|
|
1716
1850
|
if (leg.kind === 'start') {
|
|
1717
1851
|
base[BREAKWATER_CONNECTOR_EXECUTION_KEY] = {
|
|
1718
1852
|
kind: 'start',
|
|
@@ -1789,16 +1923,14 @@ export class RunnerRuntime {
|
|
|
1789
1923
|
const replacementOperations = canonicalEconomicOperations(economicOperations);
|
|
1790
1924
|
const lifecycle = replacementDeadline === undefined && replacementOperations === undefined
|
|
1791
1925
|
? storedLifecycle
|
|
1792
|
-
: {
|
|
1793
|
-
...(storedLifecycle ?? { version: 1, revision: 0 }),
|
|
1794
|
-
revision: nextLifecycleRevision(storedLifecycle?.revision ?? 0),
|
|
1926
|
+
: advanceLifecycle(storedLifecycle, {
|
|
1795
1927
|
...(replacementDeadline === undefined
|
|
1796
1928
|
? {}
|
|
1797
1929
|
: { deadlineAt: replacementDeadline }),
|
|
1798
1930
|
...(replacementOperations === undefined
|
|
1799
1931
|
? {}
|
|
1800
1932
|
: { economicOperations: replacementOperations }),
|
|
1801
|
-
};
|
|
1933
|
+
});
|
|
1802
1934
|
const requestContext = await this.#requestContextFor(workflowId, runId, {
|
|
1803
1935
|
kind: 'resume',
|
|
1804
1936
|
step,
|
|
@@ -1814,13 +1946,17 @@ export class RunnerRuntime {
|
|
|
1814
1946
|
lifecycle,
|
|
1815
1947
|
};
|
|
1816
1948
|
}
|
|
1817
|
-
#workflowState(
|
|
1818
|
-
return
|
|
1949
|
+
#workflowState(workflowId, runId, withNestedWorkflows = false) {
|
|
1950
|
+
return this.#getWorkflow(workflowId).getWorkflowRunById(runId, {
|
|
1819
1951
|
fields: RUN_STATE_FIELDS,
|
|
1820
1952
|
withNestedWorkflows,
|
|
1821
1953
|
});
|
|
1822
1954
|
}
|
|
1823
|
-
|
|
1955
|
+
/**
|
|
1956
|
+
* With `expected`, a compare-and-set against that exact row, serialized as
|
|
1957
|
+
* Mastra's own persist does; a miss throws SettlementMissError.
|
|
1958
|
+
*/
|
|
1959
|
+
async #persistLifecycle(workflowId, runId, state, lifecycle, now, source, expected) {
|
|
1824
1960
|
const workflows = source.workflows;
|
|
1825
1961
|
const persisted = {
|
|
1826
1962
|
...state,
|
|
@@ -1830,6 +1966,17 @@ export class RunnerRuntime {
|
|
|
1830
1966
|
},
|
|
1831
1967
|
timestamp: now,
|
|
1832
1968
|
};
|
|
1969
|
+
if (expected) {
|
|
1970
|
+
if (source.storage !== 'd1' || !source.replace)
|
|
1971
|
+
throw new Error('settlement storage cannot compare-and-set');
|
|
1972
|
+
const replaced = await source.replace.call(source.capability, expected, {
|
|
1973
|
+
snapshot: JSON.stringify(persisted),
|
|
1974
|
+
updatedAt: new Date(now).toISOString(),
|
|
1975
|
+
});
|
|
1976
|
+
if (!replaced)
|
|
1977
|
+
throw new SettlementMissError();
|
|
1978
|
+
return persisted;
|
|
1979
|
+
}
|
|
1833
1980
|
await source.persist.call(workflows, {
|
|
1834
1981
|
workflowName: workflowId,
|
|
1835
1982
|
runId,
|
|
@@ -1845,7 +1992,7 @@ export class RunnerRuntime {
|
|
|
1845
1992
|
await this.settleStartExecution(selected);
|
|
1846
1993
|
return selected.summary;
|
|
1847
1994
|
}
|
|
1848
|
-
const state = await this.#workflowState(
|
|
1995
|
+
const state = await this.#workflowState(workflowId, runId);
|
|
1849
1996
|
if (!state)
|
|
1850
1997
|
throw new UnknownRunError(workflowId, runId);
|
|
1851
1998
|
return this.#summaryFromState(runId, state);
|
|
@@ -1856,22 +2003,22 @@ export class RunnerRuntime {
|
|
|
1856
2003
|
throw new RunStartPendingError();
|
|
1857
2004
|
return summarizeState(runId, state, provenance ? new Map(provenance.resumeCounts) : undefined, provenance?.requestedBy, provenance?.requestedByKind);
|
|
1858
2005
|
}
|
|
1859
|
-
async #summaryForAttempt(
|
|
2006
|
+
async #summaryForAttempt(workflowId, runId, expected) {
|
|
1860
2007
|
try {
|
|
1861
2008
|
if (expected.version === 2) {
|
|
1862
|
-
const source = this.#activeRuns.get(this.#runKey(
|
|
2009
|
+
const source = this.#activeRuns.get(this.#runKey(workflowId, runId))?.source;
|
|
1863
2010
|
if (!source)
|
|
1864
2011
|
return undefined;
|
|
1865
2012
|
const state = await this.#completedStartState(source, {
|
|
1866
2013
|
tablePrefix: source.tablePrefix,
|
|
1867
|
-
workflowId
|
|
2014
|
+
workflowId,
|
|
1868
2015
|
runId,
|
|
1869
2016
|
startToken: expected.startToken,
|
|
1870
2017
|
}, expected);
|
|
1871
2018
|
await this.#settleStartReservation(state);
|
|
1872
2019
|
return state.summary;
|
|
1873
2020
|
}
|
|
1874
|
-
const persisted = await this.#workflowState(
|
|
2021
|
+
const persisted = await this.#workflowState(workflowId, runId);
|
|
1875
2022
|
if (!persisted ||
|
|
1876
2023
|
persisted.isFromInMemory ||
|
|
1877
2024
|
persisted.status === 'pending')
|
|
@@ -1962,8 +2109,21 @@ export class RunnerRuntime {
|
|
|
1962
2109
|
const workflow = this.#workflows.get(workflowId);
|
|
1963
2110
|
if (!workflow)
|
|
1964
2111
|
throw new UnknownWorkflowError(workflowId);
|
|
2112
|
+
// Run-state reads and run creation go through the workflow's own Mastra,
|
|
2113
|
+
// so a workflow another Mastra registered would reach that Mastra's storage.
|
|
2114
|
+
// Another Mastra can register the object during any await, so callers look
|
|
2115
|
+
// the workflow up again where they reach storage, not only at entry.
|
|
2116
|
+
if (workflow.mastra !== this.#mastra) {
|
|
2117
|
+
throw new Error(`RunnerRuntime: workflow '${workflowId}' is not registered on this runtime's Mastra — another runtime or Mastra has registered the same workflow object`);
|
|
2118
|
+
}
|
|
1965
2119
|
return workflow;
|
|
1966
2120
|
}
|
|
2121
|
+
#createRun(workflowId, runId) {
|
|
2122
|
+
return this.#getWorkflow(workflowId).createRun({
|
|
2123
|
+
runId,
|
|
2124
|
+
pubsub: this.#pubsub,
|
|
2125
|
+
});
|
|
2126
|
+
}
|
|
1967
2127
|
#ensureMastra() {
|
|
1968
2128
|
if (this.#mastra)
|
|
1969
2129
|
return;
|
|
@@ -1983,8 +2143,8 @@ export class RunnerRuntime {
|
|
|
1983
2143
|
// alone. The same caller-supplied runId under two workflows are DISTINCT
|
|
1984
2144
|
// persisted runs (Mastra snapshots key on workflowName+runId) and must never
|
|
1985
2145
|
// share a per-run FIFO entry. Composing the key in ONE place keeps every
|
|
1986
|
-
// per-run map keyed identically, so
|
|
1987
|
-
//
|
|
2146
|
+
// per-run map keyed identically, so no map can key by runId alone and cross
|
|
2147
|
+
// workflow boundaries.
|
|
1988
2148
|
// This is the exact string the DO name join produces
|
|
1989
2149
|
// (idFromName(`${workflowId}:${runId}`)); PATH_SAFE_ID_PATTERN excludes ':'
|
|
1990
2150
|
// from both ids, so the join is unambiguous.
|