@memberjunction/task-graph 6.2.2 → 6.3.0-edge.1
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/dist/TaskGraphDispatcher.d.ts +289 -2
- package/dist/TaskGraphDispatcher.d.ts.map +1 -1
- package/dist/TaskGraphDispatcher.js +1275 -330
- package/dist/TaskGraphDispatcher.js.map +1 -1
- package/dist/TaskGraphService.d.ts +68 -1
- package/dist/TaskGraphService.d.ts.map +1 -1
- package/dist/TaskGraphService.js +226 -24
- package/dist/TaskGraphService.js.map +1 -1
- package/dist/TaskGraphSubmitterImpl.d.ts +1 -0
- package/dist/TaskGraphSubmitterImpl.d.ts.map +1 -1
- package/dist/TaskGraphSubmitterImpl.js +5 -0
- package/dist/TaskGraphSubmitterImpl.js.map +1 -1
- package/dist/decision-node.d.ts +21 -0
- package/dist/decision-node.d.ts.map +1 -1
- package/dist/decision-node.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/operations/TaskGraphDebugOperations.d.ts +23 -0
- package/dist/operations/TaskGraphDebugOperations.d.ts.map +1 -1
- package/dist/operations/TaskGraphDebugOperations.js +13 -13
- package/dist/operations/TaskGraphDebugOperations.js.map +1 -1
- package/dist/operations/TaskGraphOperations.d.ts.map +1 -1
- package/dist/operations/TaskGraphOperations.js +12 -7
- package/dist/operations/TaskGraphOperations.js.map +1 -1
- package/dist/saga-compensation.d.ts +167 -0
- package/dist/saga-compensation.d.ts.map +1 -0
- package/dist/saga-compensation.js +392 -0
- package/dist/saga-compensation.js.map +1 -0
- package/dist/task-security.d.ts +96 -0
- package/dist/task-security.d.ts.map +1 -0
- package/dist/task-security.js +187 -0
- package/dist/task-security.js.map +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/dist/types.d.ts +57 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +1 -0
- package/dist/types.js.map +1 -1
- package/package.json +12 -12
|
@@ -18,9 +18,9 @@
|
|
|
18
18
|
*
|
|
19
19
|
* @module @memberjunction/task-graph
|
|
20
20
|
*/
|
|
21
|
-
import { ComputeEligibleTasks, ComputeParentRollup, ComputeTasksToBlock, IsGraphStalled, ResolveExclusiveGroups, ComputeSkipCascade, ConfirmSkipSeeds, LayoutGraphNodes, ApplyOutputMapping, BuildMappedInput, ResolveLoopBodyParams, LoadAgentRunTree, SumAgentRunTreeCost, WalkAgentRunTree, FinalizeAgentRunStep, InitAgentRunStep, DecisionReferencesIn, ResolveDecisionState, } from '@memberjunction/ai-core-plus';
|
|
22
|
-
import { LogError, LogStatus, RunView } from '@memberjunction/core';
|
|
23
|
-
import { ShutdownRegistry, UUIDsEqual } from '@memberjunction/global';
|
|
21
|
+
import { ComputeEligibleTasks, ComputeParentRollup, ComputeTasksToBlock, IsGraphStalled, ResolveExclusiveGroups, ComputeSkipCascade, ConfirmSkipSeeds, LayoutGraphNodes, ApplyOutputMapping, BuildMappedInput, ResolveLoopBodyParams, LoadAgentRunTree, SumAgentRunTreeCost, WalkAgentRunTree, FinalizeAgentRunStep, InitAgentRunStep, DecisionReferencesIn, ResolveDecisionState, ApplyTaskSecurityEnvelopeToParams, SerializeTaskSecurityEnvelope, TAINTED_EGRESS_BLOCKED, TASK_GRAPH_RUNTIME_SECURITY_OPERATION, } from '@memberjunction/ai-core-plus';
|
|
22
|
+
import { LogError, LogStatus, LogWarning, RunView, ServerOperationScopeManager } from '@memberjunction/core';
|
|
23
|
+
import { EscapeSQLString, GroupByUUID, IndexByUUID, IsValidUUID, ShutdownRegistry, UUIDMap, UUIDSet, UUIDsEqual } from '@memberjunction/global';
|
|
24
24
|
import { TaskClaimStore, TERMINAL_PARENT_STATUSES, TERMINAL_PARENT_STATUS_SQL } from './TaskClaimStore.js';
|
|
25
25
|
import { BuildConditionContext, DecideGate, EvaluateCondition, IsBrokenGuard, ParseConditionOutput, } from './condition-gate.js';
|
|
26
26
|
import { BuildDecisionStepOutput, DecisionStepOutputAnswers, DecisionsPayloadConflict, FailedDecisionIDs, KeptDecisionAnswers, PassOverFailedDecisionPaths, QuestionsToAsk, ReadsFailedDecision, ReadDecisionStepConfiguration, ResolveGraphDecisions, StillHoldingDecisionOutput, } from './decision-node.js';
|
|
@@ -32,6 +32,8 @@ import { DispatcherConditionEvaluator } from './DispatcherConditionEvaluator.js'
|
|
|
32
32
|
import { DecideClaimGate, OverrideVerdictFor, ParseTaskGraphDebugState, } from './debug-state.js';
|
|
33
33
|
import { RunForEachLoop, RunWhileLoop } from './TaskLoopExecutor.js';
|
|
34
34
|
import { RegisterTaskGraphKick } from './task-graph-kick.js';
|
|
35
|
+
import { BuildCompensationEscalationSummary, BuildCompensationInputPayload, IndexCompensationRows, IsCompensationTask, NextSagaStep, ReadActionCompensationMetadata, ReadTaskCompensationMetadata, RetryBackoffMs, SelectTasksToCompensate, } from './saga-compensation.js';
|
|
36
|
+
import { CloneUserWithTenantContext, ComputeNodeInputTaint, EnvelopeConstrains, ResolveStoredNodeSecurity, UpstreamCarriesTaint, WithInputTaint, } from './task-security.js';
|
|
35
37
|
import { NotificationEngine } from '@memberjunction/notifications';
|
|
36
38
|
/** Metadata-seeded notification type for human tasks (metadata/notifications/.task-assignment-type.json). */
|
|
37
39
|
const HUMAN_TASK_NOTIFICATION_TYPE = 'Task Assignment';
|
|
@@ -59,6 +61,20 @@ const STOP_DRAIN_TIMEOUT_MS = 30_000;
|
|
|
59
61
|
* sweep, which is the wider net.
|
|
60
62
|
*/
|
|
61
63
|
const MAX_SETTLEMENT_RETRY_PASSES = 20;
|
|
64
|
+
/**
|
|
65
|
+
* How long this instance leaves a graph alone after processing it threw (S6) — an inactive submitter,
|
|
66
|
+
* a row that will not read. Long enough that a graph that cannot be processed is not re-attempted and
|
|
67
|
+
* re-reported every poll; short enough that one that recovers (the user reactivated) moves on its own.
|
|
68
|
+
*/
|
|
69
|
+
const FAILED_GRAPH_BACKOFF_MS = 5 * 60 * 1000;
|
|
70
|
+
/**
|
|
71
|
+
* How many passes in a row may fail to write one saga row (a compensation, or the Human step escalating a
|
|
72
|
+
* failed one) for a reason that may not repeat before that row is recorded as failed (T5). A deadlock, a
|
|
73
|
+
* timeout or a dropped connection fails one insert or lookup and the next pass usually succeeds, so one
|
|
74
|
+
* failure must not end a compensation for good. A cause that cannot change (the action does not exist, the
|
|
75
|
+
* envelope cannot be read) is recorded at once.
|
|
76
|
+
*/
|
|
77
|
+
const SAGA_ROW_WRITE_ATTEMPTS = 3;
|
|
62
78
|
/**
|
|
63
79
|
* Written to a human task's `ClaimedBy` once its assignee has been told it is ready.
|
|
64
80
|
*
|
|
@@ -269,6 +285,19 @@ export class TaskGraphDispatcher {
|
|
|
269
285
|
* by the wide startup sweep, which is the durable backstop this leans on.
|
|
270
286
|
*/
|
|
271
287
|
this.retryingSettlement = new Map();
|
|
288
|
+
/**
|
|
289
|
+
* Graphs whose processing threw on this instance, and when it may try each again (S6). Reported
|
|
290
|
+
* once per failure streak, not once per poll; cleared the first time the graph processes cleanly,
|
|
291
|
+
* or once the graph is no longer active (settled elsewhere).
|
|
292
|
+
*/
|
|
293
|
+
this.failedGraphs = new UUIDMap();
|
|
294
|
+
/**
|
|
295
|
+
* Saga rows this instance failed to write on its last passes, by the task each would compensate
|
|
296
|
+
* (`CompensatesTaskID`), with the graph it belongs to and how many passes in a row failed
|
|
297
|
+
* ({@link SAGA_ROW_WRITE_ATTEMPTS}). Cleared when the row lands, when another dispatcher's row is
|
|
298
|
+
* found, or once the graph is no longer active.
|
|
299
|
+
*/
|
|
300
|
+
this.sagaRowWriteFailures = new UUIDMap();
|
|
272
301
|
/**
|
|
273
302
|
* Graphs whose settled-branch ANNOUNCEMENTS have already been made by this process.
|
|
274
303
|
*
|
|
@@ -573,7 +602,8 @@ export class TaskGraphDispatcher {
|
|
|
573
602
|
// against a host that believed the dispatcher had stopped.
|
|
574
603
|
this.activePasses++;
|
|
575
604
|
try {
|
|
576
|
-
|
|
605
|
+
// Server work, like every pass: see `pollOnce`.
|
|
606
|
+
await ServerOperationScopeManager.Instance.RunAsServerWork(() => this.sweepUnsettledGraphs(UNSETTLED_STARTUP_WINDOW_HOURS));
|
|
577
607
|
}
|
|
578
608
|
finally {
|
|
579
609
|
this.activePasses--;
|
|
@@ -692,7 +722,8 @@ export class TaskGraphDispatcher {
|
|
|
692
722
|
async Reconcile() {
|
|
693
723
|
this.activePasses++;
|
|
694
724
|
try {
|
|
695
|
-
|
|
725
|
+
// Server work, like every pass: see `pollOnce`.
|
|
726
|
+
await ServerOperationScopeManager.Instance.RunAsServerWork(() => this.reconcileOnce());
|
|
696
727
|
}
|
|
697
728
|
finally {
|
|
698
729
|
this.activePasses--;
|
|
@@ -764,8 +795,16 @@ export class TaskGraphDispatcher {
|
|
|
764
795
|
*
|
|
765
796
|
* Overlap-guarded — a pass that runs long simply skips the next tick rather than stacking, which
|
|
766
797
|
* would otherwise let a slow database multiply in-flight work past the cap.
|
|
798
|
+
*
|
|
799
|
+
* Always server work (`ServerOperationScopeManager.RunAsServerWork`). {@link Kick} runs a pass in its
|
|
800
|
+
* caller's async scope, and a caller inside a client's own CRUD request (a graph submitted from one)
|
|
801
|
+
* would otherwise hand that request's boundary to every node the pass runs, so a node's save of a
|
|
802
|
+
* Human step or an agent request would read as that person's own act.
|
|
767
803
|
*/
|
|
768
|
-
|
|
804
|
+
pollOnce() {
|
|
805
|
+
return ServerOperationScopeManager.Instance.RunAsServerWork(() => this.runPass());
|
|
806
|
+
}
|
|
807
|
+
async runPass() {
|
|
769
808
|
if (!this.running || this.polling)
|
|
770
809
|
return;
|
|
771
810
|
this.polling = true;
|
|
@@ -926,11 +965,16 @@ export class TaskGraphDispatcher {
|
|
|
926
965
|
ClaimEvent: 'claimed', ClaimedBy: this.config.InstanceID,
|
|
927
966
|
ClaimExpiresAt: new Date(Date.now() + this.config.ClaimTTLSeconds * 1000).toISOString(),
|
|
928
967
|
});
|
|
929
|
-
const
|
|
930
|
-
?
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
968
|
+
const dependencies = hydrated?.dependencyOutputs
|
|
969
|
+
? {
|
|
970
|
+
Outputs: hydrated.dependencyOutputs instanceof Map
|
|
971
|
+
? hydrated.dependencyOutputs
|
|
972
|
+
: new Map(Object.entries(hydrated.dependencyOutputs)),
|
|
973
|
+
Upstream: hydrated.upstreamTasks ?? [],
|
|
974
|
+
}
|
|
975
|
+
: await this.loadDependencies(provider, taskID);
|
|
976
|
+
const dependencyOutputs = dependencies.Outputs;
|
|
977
|
+
const nodeHydration = { ...hydrated, upstreamTasks: dependencies.Upstream };
|
|
934
978
|
const parsed = ParseTaskInputPayload(taskID, task.InputPayload);
|
|
935
979
|
let result;
|
|
936
980
|
if ('ErrorMessage' in parsed) {
|
|
@@ -941,7 +985,7 @@ export class TaskGraphDispatcher {
|
|
|
941
985
|
}
|
|
942
986
|
else {
|
|
943
987
|
const onProgress = this.nodeProgressEmitter(graphID, ownerUserID, taskID, task.Name);
|
|
944
|
-
result = await this.runTaskBody(task, provider, parsed.Payload, dependencyOutputs, onProgress,
|
|
988
|
+
result = await this.runTaskBody(task, provider, parsed.Payload, dependencyOutputs, onProgress, nodeHydration);
|
|
945
989
|
}
|
|
946
990
|
// ONLY THE CONFIRMED OWNER MUTATES THE GRAPH (R2-10).
|
|
947
991
|
//
|
|
@@ -958,7 +1002,7 @@ export class TaskGraphDispatcher {
|
|
|
958
1002
|
OutputPayload: result.Output != null ? JSON.stringify(result.Output) : null,
|
|
959
1003
|
ErrorMessage: result.ErrorMessage ?? null,
|
|
960
1004
|
AgentRunID: result.AgentRunID ?? null,
|
|
961
|
-
Configuration: this.configurationWithRuntime(task, result.PromptRunID, result.ActionLogID, result.Iterations, result.PayloadAtStart),
|
|
1005
|
+
Configuration: this.configurationWithRuntime(task, result.PromptRunID, result.ActionLogID, result.Iterations, result.PayloadAtStart, result.IsOutputTainted, result.ActionInput),
|
|
962
1006
|
}, this.contextUser);
|
|
963
1007
|
if (!recorded) {
|
|
964
1008
|
// The guarded write refused: the row changed underneath us (cancelled, reassigned,
|
|
@@ -1010,266 +1054,320 @@ export class TaskGraphDispatcher {
|
|
|
1010
1054
|
*/
|
|
1011
1055
|
async propagateAndRollup(provider, graphIDs) {
|
|
1012
1056
|
const graphs = graphIDs ?? await this.findActiveGraphIDs(provider);
|
|
1057
|
+
if (!graphIDs) {
|
|
1058
|
+
// A set-aside graph that left the active set (another instance settled it) is never processed
|
|
1059
|
+
// here again, so its back-off entry would never clear.
|
|
1060
|
+
const active = new UUIDSet(graphs);
|
|
1061
|
+
for (const id of [...this.failedGraphs.Keys()]) {
|
|
1062
|
+
if (!active.Has(id))
|
|
1063
|
+
this.failedGraphs.Delete(id);
|
|
1064
|
+
}
|
|
1065
|
+
for (const [id, failure] of [...this.sagaRowWriteFailures]) {
|
|
1066
|
+
if (!active.Has(failure.GraphID))
|
|
1067
|
+
this.sagaRowWriteFailures.Delete(id);
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1013
1070
|
const survivingGraphs = [];
|
|
1014
1071
|
for (const parentID of graphs) {
|
|
1015
|
-
//
|
|
1016
|
-
//
|
|
1017
|
-
//
|
|
1018
|
-
|
|
1019
|
-
let graph = await this.loadGraphState(provider, parentID);
|
|
1020
|
-
if (graph.nodes.length === 0)
|
|
1072
|
+
// ONE GRAPH'S FAILURE IS ITS OWN (S6). Anything this throws (an inactive submitter in the
|
|
1073
|
+
// saga's user resolution, an unreadable row) used to escape the loop and abort the whole
|
|
1074
|
+
// pass, on every instance, every poll: no graph anywhere settled, skipped or claimed.
|
|
1075
|
+
if (this.isBackingOffFailedGraph(parentID))
|
|
1021
1076
|
continue;
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
if (pendingHumanTasks.length > 0) {
|
|
1028
|
-
await this.expireOverdueRequests(provider, parentID, pendingHumanTasks);
|
|
1029
|
-
const settledHumanCount = await this.settleAnsweredHumanTasks(provider, parentID, pendingHumanTasks);
|
|
1030
|
-
await this.reconcileWaitingHumanTasks(provider, parentID, pendingHumanTasks);
|
|
1031
|
-
if (settledHumanCount > 0) {
|
|
1032
|
-
// Re-evaluate conditional edges and skip/block cascades now that a human step's
|
|
1033
|
-
// answer and status have landed, reusing the already-loaded parent task.
|
|
1034
|
-
graph = await this.loadGraphState(provider, parentID, debug, graph.parent);
|
|
1035
|
-
if (graph.nodes.length === 0)
|
|
1036
|
-
continue;
|
|
1037
|
-
}
|
|
1077
|
+
try {
|
|
1078
|
+
const live = await this.propagateAndRollupGraph(provider, parentID);
|
|
1079
|
+
this.failedGraphs.Delete(parentID);
|
|
1080
|
+
if (live)
|
|
1081
|
+
survivingGraphs.push(live);
|
|
1038
1082
|
}
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
// "to be skipped"; deciding eligibility first would dispatch the branch nobody took.
|
|
1042
|
-
//
|
|
1043
|
-
// `unreachableTaskIDs` seeds this too, and that is a correction (R6). A target whose only
|
|
1044
|
-
// route in was an ordinary conditional edge that evaluated DEFINITELY FALSE is a branch
|
|
1045
|
-
// that was not taken — semantically identical to an XOR loser — yet it used to settle
|
|
1046
|
-
// `Blocked`. That made `Blocked` mean two unrelated things: "the workflow chose another
|
|
1047
|
-
// route" and "something upstream broke". A reader cannot tell those apart, so every
|
|
1048
|
-
// conditional workflow looked half-failed and people went hunting for bugs that did not
|
|
1049
|
-
// exist. `Blocked` is now reserved for FAILURE-driven unsatisfiability.
|
|
1050
|
-
// Computed once in `loadGraphState` so the claim filter sees the same set this pass is
|
|
1051
|
-
// about to write — see R2-14 there.
|
|
1052
|
-
const toSkip = graph.cascadeSkipTaskIDs;
|
|
1053
|
-
const skippedByRoute = [];
|
|
1054
|
-
for (const taskID of toSkip) {
|
|
1055
|
-
const entity = graph.entityById.get(taskID);
|
|
1056
|
-
if (!entity || entity.Status !== 'Pending')
|
|
1057
|
-
continue;
|
|
1058
|
-
// The in-memory check above is a cheap pre-filter; the guard that matters is IN the
|
|
1059
|
-
// statement (R3-1's audit item). This snapshot was loaded at the top of the pass and
|
|
1060
|
-
// a task can be claimed and started before its skip write lands — R2-14 closed that
|
|
1061
|
-
// window for the claim filter, and this closes it for the write itself.
|
|
1062
|
-
const skipTypeID = await this.workflowTaskTypeID(provider);
|
|
1063
|
-
if (skipTypeID && await this.claims.TrySkipPending(provider, taskID, skipTypeID, this.contextUser)) {
|
|
1064
|
-
entity.Status = 'Skipped';
|
|
1065
|
-
skippedByRoute.push(taskID);
|
|
1066
|
-
LogStatus(`[TaskGraphDispatcher] Skipped '${entity.Name}' (${taskID}) — another branch was taken.`);
|
|
1067
|
-
// Announced separately from TaskBlocked because it means something different to
|
|
1068
|
-
// a viewer: nothing went wrong, this route simply was not the one chosen.
|
|
1069
|
-
this.emit({
|
|
1070
|
-
Kind: 'TaskSkipped',
|
|
1071
|
-
ParentTaskID: parentID,
|
|
1072
|
-
OwnerUserID: await this.resolveOwner(provider, parentID),
|
|
1073
|
-
TaskID: taskID,
|
|
1074
|
-
TaskName: entity.Name,
|
|
1075
|
-
Status: 'Skipped',
|
|
1076
|
-
});
|
|
1077
|
-
// Keep the in-memory graph consistent so the blocking pass below and the rollup
|
|
1078
|
-
// both see the skip rather than a stale Pending.
|
|
1079
|
-
const node = graph.nodes.find((n) => n.id === taskID);
|
|
1080
|
-
if (node)
|
|
1081
|
-
node.status = 'Skipped';
|
|
1082
|
-
}
|
|
1083
|
+
catch (e) {
|
|
1084
|
+
this.backOffFailedGraph(parentID, e);
|
|
1083
1085
|
}
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1086
|
+
}
|
|
1087
|
+
return survivingGraphs;
|
|
1088
|
+
}
|
|
1089
|
+
/** Whether a graph that threw is still inside its back-off on this instance. */
|
|
1090
|
+
isBackingOffFailedGraph(parentID) {
|
|
1091
|
+
const failed = this.failedGraphs.Get(parentID);
|
|
1092
|
+
return failed !== undefined && Date.now() < failed.RetryAt;
|
|
1093
|
+
}
|
|
1094
|
+
/**
|
|
1095
|
+
* Sets a graph whose processing threw aside for {@link FAILED_GRAPH_BACKOFF_MS}, so the other graphs
|
|
1096
|
+
* go on settling and claiming. Logged on the first failure of a streak only.
|
|
1097
|
+
*/
|
|
1098
|
+
backOffFailedGraph(parentID, error) {
|
|
1099
|
+
const alreadyFailing = this.failedGraphs.Has(parentID);
|
|
1100
|
+
this.failedGraphs.Set(parentID, { RetryAt: Date.now() + FAILED_GRAPH_BACKOFF_MS });
|
|
1101
|
+
if (alreadyFailing)
|
|
1102
|
+
return;
|
|
1103
|
+
LogError(`[TaskGraphDispatcher] Graph ${parentID} could not be processed and is set aside for ` +
|
|
1104
|
+
`${FAILED_GRAPH_BACKOFF_MS / 1000}s; the other graphs continue. ${error instanceof Error ? error.message : String(error)}`);
|
|
1105
|
+
}
|
|
1106
|
+
/**
|
|
1107
|
+
* {@link propagateAndRollup} for one graph: returns the graph when it is still live (so claiming can
|
|
1108
|
+
* reuse it), or `undefined` when it settled, emptied or is waiting on a retry.
|
|
1109
|
+
*/
|
|
1110
|
+
async propagateAndRollupGraph(provider, parentID) {
|
|
1111
|
+
// Edge overrides apply to propagation exactly as they apply to claiming — a branch the
|
|
1112
|
+
// operator answered 'false' must cascade its skips here, not merely stop being claimed.
|
|
1113
|
+
// `loadGraphState` loads the parent row once and populates `debugStateByGraph` and
|
|
1114
|
+
// `ownerByParentID` from it, avoiding a separate `primeDebugStates` RunView round-trip.
|
|
1115
|
+
let graph = await this.loadGraphState(provider, parentID);
|
|
1116
|
+
if (graph.nodes.length === 0)
|
|
1117
|
+
return undefined;
|
|
1118
|
+
const debug = await this.readDebugState(provider, parentID);
|
|
1119
|
+
// Human steps are only swept when the loaded graph actually contains at least one
|
|
1120
|
+
// non-terminal Human task. When a graph has 0 pending human tasks (99% of graphs), this
|
|
1121
|
+
// check short-circuits in memory with 0 DB queries instead of running 3 RunViews per graph.
|
|
1122
|
+
const pendingHumanTasks = [...graph.entityById.values()].filter((t) => t.Status === 'Pending' && IsHumanTask(t));
|
|
1123
|
+
if (pendingHumanTasks.length > 0) {
|
|
1124
|
+
await this.expireOverdueRequests(provider, parentID, pendingHumanTasks);
|
|
1125
|
+
const settledHumanCount = await this.settleAnsweredHumanTasks(provider, parentID, pendingHumanTasks);
|
|
1126
|
+
await this.reconcileWaitingHumanTasks(provider, parentID, pendingHumanTasks);
|
|
1127
|
+
if (settledHumanCount > 0) {
|
|
1128
|
+
// Re-evaluate conditional edges and skip/block cascades now that a human step's
|
|
1129
|
+
// answer and status have landed, reusing the already-loaded parent task.
|
|
1130
|
+
graph = await this.loadGraphState(provider, parentID, debug, graph.parent);
|
|
1131
|
+
if (graph.nodes.length === 0)
|
|
1132
|
+
return undefined;
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
// SKIPS FIRST — before blocking, before eligibility. A task whose gating predecessors
|
|
1136
|
+
// are all Skipped is simultaneously "eligible" (Skipped satisfies a prerequisite) and
|
|
1137
|
+
// "to be skipped"; deciding eligibility first would dispatch the branch nobody took.
|
|
1138
|
+
//
|
|
1139
|
+
// `unreachableTaskIDs` seeds this too, and that is a correction (R6). A target whose only
|
|
1140
|
+
// route in was an ordinary conditional edge that evaluated DEFINITELY FALSE is a branch
|
|
1141
|
+
// that was not taken — semantically identical to an XOR loser — yet it used to settle
|
|
1142
|
+
// `Blocked`. That made `Blocked` mean two unrelated things: "the workflow chose another
|
|
1143
|
+
// route" and "something upstream broke". A reader cannot tell those apart, so every
|
|
1144
|
+
// conditional workflow looked half-failed and people went hunting for bugs that did not
|
|
1145
|
+
// exist. `Blocked` is now reserved for FAILURE-driven unsatisfiability.
|
|
1146
|
+
// Computed once in `loadGraphState` so the claim filter sees the same set this pass is
|
|
1147
|
+
// about to write — see R2-14 there.
|
|
1148
|
+
const toSkip = graph.cascadeSkipTaskIDs;
|
|
1149
|
+
const skippedByRoute = [];
|
|
1150
|
+
for (const taskID of toSkip) {
|
|
1151
|
+
const entity = graph.entityById.get(taskID);
|
|
1152
|
+
if (!entity || entity.Status !== 'Pending')
|
|
1153
|
+
continue;
|
|
1154
|
+
// The in-memory check above is a cheap pre-filter; the guard that matters is IN the
|
|
1155
|
+
// statement (R3-1's audit item). This snapshot was loaded at the top of the pass and
|
|
1156
|
+
// a task can be claimed and started before its skip write lands — R2-14 closed that
|
|
1157
|
+
// window for the claim filter, and this closes it for the write itself.
|
|
1158
|
+
const skipTypeID = await this.workflowTaskTypeID(provider);
|
|
1159
|
+
if (skipTypeID && await this.claims.TrySkipPending(provider, taskID, skipTypeID, this.contextUser)) {
|
|
1160
|
+
entity.Status = 'Skipped';
|
|
1161
|
+
skippedByRoute.push(taskID);
|
|
1162
|
+
LogStatus(`[TaskGraphDispatcher] Skipped '${entity.Name}' (${taskID}) — another branch was taken.`);
|
|
1163
|
+
// Announced separately from TaskBlocked because it means something different to
|
|
1164
|
+
// a viewer: nothing went wrong, this route simply was not the one chosen.
|
|
1165
|
+
this.emit({
|
|
1166
|
+
Kind: 'TaskSkipped',
|
|
1167
|
+
ParentTaskID: parentID,
|
|
1168
|
+
OwnerUserID: await this.resolveOwner(provider, parentID),
|
|
1169
|
+
TaskID: taskID,
|
|
1170
|
+
TaskName: entity.Name,
|
|
1171
|
+
Status: 'Skipped',
|
|
1172
|
+
});
|
|
1173
|
+
// Keep the in-memory graph consistent so the blocking pass below and the rollup
|
|
1174
|
+
// both see the skip rather than a stale Pending.
|
|
1175
|
+
const node = graph.nodes.find((n) => n.id === taskID);
|
|
1176
|
+
if (node)
|
|
1177
|
+
node.status = 'Skipped';
|
|
1115
1178
|
}
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1179
|
+
}
|
|
1180
|
+
// A human step reached by a route the workflow did not take has the same zombie request
|
|
1181
|
+
// as one skipped by an early finish (R2-10): notified, `Requested` forever, and invisible
|
|
1182
|
+
// to the settle and expiry sweeps because they filter on Pending tasks and this one is
|
|
1183
|
+
// not Pending any more. Same treatment, different reason.
|
|
1184
|
+
await this.withdrawOpenRequests(provider, skippedByRoute, 'The workflow took a different route, so this step is no longer needed.');
|
|
1185
|
+
// Only failure-driven unsatisfiability reaches here now; not-taken branches were skipped
|
|
1186
|
+
// above. A task already Skipped is left alone rather than overwritten — the two passes
|
|
1187
|
+
// must not fight over the same row.
|
|
1188
|
+
const toBlock = [...ComputeTasksToBlock(graph.nodes, graph.edges, graph.handledFailureIDs)]
|
|
1189
|
+
.filter((id) => !toSkip.has(id));
|
|
1190
|
+
for (const taskID of toBlock) {
|
|
1191
|
+
const entity = graph.entityById.get(taskID);
|
|
1192
|
+
if (!entity)
|
|
1193
|
+
continue;
|
|
1194
|
+
entity.Status = 'Blocked';
|
|
1195
|
+
// A workflow step's status is the dispatcher's (`MJTaskEntityServer`), so the write runs in its scope.
|
|
1196
|
+
if (await this.saveWithRuntimeAuthority(entity)) {
|
|
1197
|
+
const node = graph.nodes.find((n) => n.id === taskID);
|
|
1198
|
+
if (node)
|
|
1199
|
+
node.status = 'Blocked';
|
|
1200
|
+
LogStatus(`[TaskGraphDispatcher] Blocked '${entity.Name}' (${taskID}) — a dependency can never be satisfied.`);
|
|
1201
|
+
// Worth announcing on its own: a blocked step is the one outcome a viewer would
|
|
1202
|
+
// otherwise see as a task that simply never starts.
|
|
1203
|
+
this.emit({
|
|
1204
|
+
Kind: 'TaskBlocked',
|
|
1205
|
+
ParentTaskID: parentID,
|
|
1206
|
+
OwnerUserID: await this.resolveOwner(provider, parentID),
|
|
1207
|
+
TaskID: taskID,
|
|
1208
|
+
TaskName: entity.Name,
|
|
1209
|
+
Status: 'Blocked',
|
|
1210
|
+
});
|
|
1122
1211
|
}
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1212
|
+
}
|
|
1213
|
+
const saga = await this.coordinateSagaCompensation(provider, parentID, graph, debug);
|
|
1214
|
+
graph = saga.Graph;
|
|
1215
|
+
// Holds are passed in, or the detector reports a held graph as healthy: a held target's
|
|
1216
|
+
// gating edge is still live and its origin Complete, so ComputeEligibleTasks counts it
|
|
1217
|
+
// as eligible and "something is eligible" reads as "not stalled". A graph waiting
|
|
1218
|
+
// forever on a broken condition then produced no diagnostics at all.
|
|
1219
|
+
if (IsGraphStalled(graph.nodes, graph.edges, graph.holdTaskIDs)) {
|
|
1220
|
+
LogError(`[TaskGraphDispatcher] Graph ${parentID} is stalled: pending work with no satisfiable path.`);
|
|
1221
|
+
}
|
|
1222
|
+
// Reuse the in-memory `graph` (whose `nodes` and `entityById` were updated in-place as
|
|
1223
|
+
// skips and blocks landed) and its pre-loaded `graph.parent` instead of reloading the
|
|
1224
|
+
// graph state and parent task a second time.
|
|
1225
|
+
const rollup = this.rollupWhileCompensating(ComputeParentRollup(graph.nodes, graph.handledFailureIDs), saga.Pending);
|
|
1226
|
+
let parent = graph.parent;
|
|
1227
|
+
if (!parent) {
|
|
1228
|
+
const fallbackParent = await provider.GetEntityObject('MJ: Tasks', this.contextUser);
|
|
1229
|
+
if (!(await fallbackParent.Load(parentID)))
|
|
1230
|
+
return undefined;
|
|
1231
|
+
parent = fallbackParent;
|
|
1232
|
+
graph.parent = parent;
|
|
1233
|
+
}
|
|
1234
|
+
// A graph starts when its first step does.
|
|
1235
|
+
//
|
|
1236
|
+
// `StartedAt` is stamped by the CLAIM, and a parent is never claimed — it is a container,
|
|
1237
|
+
// not a unit of work — so the graph row carried no start time even after it completed.
|
|
1238
|
+
// A settled workflow therefore reported a CompletedAt with no beginning: it sorted as
|
|
1239
|
+
// "not started" in the run tree, showed no timestamp, and no duration could be computed
|
|
1240
|
+
// for the thing whose duration people actually ask about.
|
|
1241
|
+
//
|
|
1242
|
+
// Taken from the earliest child rather than from the clock, because that is when work
|
|
1243
|
+
// genuinely began — a graph can sit Pending for a long time between submission (already
|
|
1244
|
+
// recorded as CreatedAt) and a dispatcher picking up its first task.
|
|
1245
|
+
// Column-scoped for the same reason the terminal write is: a full-row save here would
|
|
1246
|
+
// carry this instance's `InputPayload` snapshot and could erase a continuation marker
|
|
1247
|
+
// another instance had just claimed. Guarded on `StartedAt IS NULL`, so calling it on
|
|
1248
|
+
// every pass is free.
|
|
1249
|
+
const earliestChildStart = this.earliestStart(graph.entityById);
|
|
1250
|
+
if (parent.StartedAt == null && earliestChildStart != null) {
|
|
1251
|
+
await this.claims.TryStampParentStart(provider, parentID, earliestChildStart, this.contextUser);
|
|
1252
|
+
parent.StartedAt = earliestChildStart;
|
|
1253
|
+
}
|
|
1254
|
+
// THE TERMINAL WRITE IS GUARDED AND COLUMN-SCOPED, not a full-row save.
|
|
1255
|
+
//
|
|
1256
|
+
// `GenerateSaveSQL` sends every updateable column on every save, so a full-row save
|
|
1257
|
+
// carries the whole in-memory snapshot — including `InputPayload`, where the continuation
|
|
1258
|
+
// marker lives. Two instances both compute the terminal rollup; if one claims the marker
|
|
1259
|
+
// and the other then saves its pre-marker snapshot, the marker is ERASED and the
|
|
1260
|
+
// settlement delivers twice. For `reinvoke` that is a second billed agent turn.
|
|
1261
|
+
//
|
|
1262
|
+
// Guarding on "not already terminal" also makes the write idempotent across the
|
|
1263
|
+
// re-entrant settle path below, and replaces an unchecked `Save()` whose failure left the
|
|
1264
|
+
// graph active — re-emitting frames and recomputing cost every poll, forever.
|
|
1265
|
+
if (rollup.outcome === 'settled') {
|
|
1266
|
+
const settled = await this.claims.TrySettleParent(provider, parentID, rollup.status, rollup.percentComplete, this.contextUser);
|
|
1267
|
+
if (!settled && !TERMINAL_TASK_STATUSES.has(parent.Status)) {
|
|
1268
|
+
// Neither "already terminal" nor a successful write: the statement failed. Leave
|
|
1269
|
+
// the graph active so the next pass retries rather than settling on a status the
|
|
1270
|
+
// database never accepted. Re-queued explicitly, because a failed write is
|
|
1271
|
+
// exactly the case where the row's own timestamp does not advance.
|
|
1272
|
+
LogError(`[TaskGraphDispatcher] Could not write terminal status for graph ${parentID}; leaving it active to retry.`);
|
|
1273
|
+
this.keepRetryingSettlement(parentID);
|
|
1274
|
+
return undefined;
|
|
1134
1275
|
}
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
//
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1276
|
+
parent.Status = rollup.status;
|
|
1277
|
+
}
|
|
1278
|
+
else {
|
|
1279
|
+
if (parent.Status !== rollup.status || parent.PercentComplete !== rollup.percentComplete) {
|
|
1280
|
+
// Guarded and column-scoped for the same reason the terminal write is — and the race
|
|
1281
|
+
// here needs no exotic timing. This instance may have computed a non-terminal rollup
|
|
1282
|
+
// from a snapshot taken before another instance settled the graph; a full-row save
|
|
1283
|
+
// would then REVERT the status and erase the continuation marker with it, and the
|
|
1284
|
+
// next pass would settle and deliver a second time. See TryUpdateParentProgress.
|
|
1285
|
+
await this.claims.TryUpdateParentProgress(provider, parentID, rollup.status, rollup.percentComplete, this.contextUser);
|
|
1286
|
+
}
|
|
1287
|
+
return graph;
|
|
1288
|
+
}
|
|
1289
|
+
if (rollup.outcome === 'settled') {
|
|
1290
|
+
// ANNOUNCE ONCE PER PROCESS, RETRY THE REST (R2-12). Layout and the frame are
|
|
1291
|
+
// idempotent facts about a finished graph; the cost, lifecycle and delivery writes
|
|
1292
|
+
// below are the ones re-entry exists to retry. Without this split, a graph that keeps
|
|
1293
|
+
// failing to settle re-persisted geometry and re-emitted the same frame every poll
|
|
1294
|
+
// for the whole rescue window.
|
|
1295
|
+
if (!this.announcedSettlements.has(parentID)) {
|
|
1296
|
+
// Geometry is settled once, here, so every viewer of this run agrees on it.
|
|
1297
|
+
await this.persistComputedLayout(graph);
|
|
1298
|
+
// Emitted before the continuation is delivered, and outside its once-only guard: a
|
|
1299
|
+
// viewer watching the run should learn it finished whether or not this instance is
|
|
1300
|
+
// the one that wins the delivery CAS.
|
|
1301
|
+
this.emit({
|
|
1302
|
+
Kind: 'GraphSettled',
|
|
1303
|
+
ParentTaskID: parentID,
|
|
1304
|
+
OwnerUserID: await this.resolveOwner(provider, parentID),
|
|
1305
|
+
Status: rollup.status,
|
|
1306
|
+
CompletedCount: graph.nodes.filter((n) => n.status === 'Complete').length,
|
|
1307
|
+
TotalCount: graph.nodes.length,
|
|
1308
|
+
});
|
|
1309
|
+
this.announcedSettlements.add(parentID);
|
|
1154
1310
|
}
|
|
1155
|
-
//
|
|
1311
|
+
// READ-ONLY GATE, before any write to the submitting run's half (R2-2).
|
|
1156
1312
|
//
|
|
1157
|
-
//
|
|
1158
|
-
//
|
|
1159
|
-
//
|
|
1160
|
-
//
|
|
1161
|
-
//
|
|
1313
|
+
// A graph can settle before the run that submitted it has parked at all. `BaseAgent`
|
|
1314
|
+
// sets `Paused` in `finalizeAgentRun`, AFTER the graph is durable and dispatchable —
|
|
1315
|
+
// so a fast graph finishes first, and both writes below then land wrong: the
|
|
1316
|
+
// lifecycle write silently returns (its guard is `Status === 'Paused'`), and the cost
|
|
1317
|
+
// write is overwritten moments later by finalize's own full-row save, which carries
|
|
1318
|
+
// the in-memory nulls it had before the dispatcher wrote anything.
|
|
1162
1319
|
//
|
|
1163
|
-
//
|
|
1164
|
-
//
|
|
1165
|
-
//
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
// database never accepted. Re-queued explicitly, because a failed write is
|
|
1172
|
-
// exactly the case where the row's own timestamp does not advance.
|
|
1173
|
-
LogError(`[TaskGraphDispatcher] Could not write terminal status for graph ${parentID}; leaving it active to retry.`);
|
|
1174
|
-
this.keepRetryingSettlement(parentID);
|
|
1175
|
-
continue;
|
|
1176
|
-
}
|
|
1177
|
-
parent.Status = rollup.status;
|
|
1320
|
+
// Deferring the whole half — rather than doing the parts that happen to work — is
|
|
1321
|
+
// what keeps the marker honest: nothing below claims it, so the graph stays
|
|
1322
|
+
// terminal-and-undelivered and the rescue sweep brings it back next pass, by which
|
|
1323
|
+
// time finalize has parked the run and both writes land.
|
|
1324
|
+
const readiness = await this.submittingRunReadiness(provider, parent);
|
|
1325
|
+
if (readiness.Verdict === 'defer') {
|
|
1326
|
+
this.keepRetryingSettlement(parentID);
|
|
1327
|
+
return undefined;
|
|
1178
1328
|
}
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1329
|
+
// A settled graph will not produce another verdict, claim or progress report, so the
|
|
1330
|
+
// per-graph observability caches for it are dead weight from here. Unbounded, they
|
|
1331
|
+
// are a slow leak in a process that runs for weeks — one that grows with every
|
|
1332
|
+
// workflow the server has ever seen rather than with anything live. (A deferred
|
|
1333
|
+
// settlement below repopulates them naturally on the retry pass.)
|
|
1334
|
+
this.forgetGraphObservability(parentID);
|
|
1335
|
+
// R3-8: the rollup gets a verdict, and a TRANSIENT failure defers exactly as a
|
|
1336
|
+
// failed lifecycle write does. Continuing past one would settle the run and claim
|
|
1337
|
+
// the marker, which permanently excludes the graph from the rescue sweep — making
|
|
1338
|
+
// the rollup's own "retrying on a later settlement" log a promise it could not keep.
|
|
1339
|
+
// Permanent refusals (truncated tree, graph not in the tree) proceed as before:
|
|
1340
|
+
// those do not clear on their own, and deferring on them would stall forever.
|
|
1341
|
+
if (await this.rollUpCostToSubmittingRun(provider, parent) === 'failed-transient') {
|
|
1342
|
+
this.keepRetryingSettlement(parentID);
|
|
1343
|
+
return undefined;
|
|
1189
1344
|
}
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
//
|
|
1214
|
-
// A graph can settle before the run that submitted it has parked at all. `BaseAgent`
|
|
1215
|
-
// sets `Paused` in `finalizeAgentRun`, AFTER the graph is durable and dispatchable —
|
|
1216
|
-
// so a fast graph finishes first, and both writes below then land wrong: the
|
|
1217
|
-
// lifecycle write silently returns (its guard is `Status === 'Paused'`), and the cost
|
|
1218
|
-
// write is overwritten moments later by finalize's own full-row save, which carries
|
|
1219
|
-
// the in-memory nulls it had before the dispatcher wrote anything.
|
|
1220
|
-
//
|
|
1221
|
-
// Deferring the whole half — rather than doing the parts that happen to work — is
|
|
1222
|
-
// what keeps the marker honest: nothing below claims it, so the graph stays
|
|
1223
|
-
// terminal-and-undelivered and the rescue sweep brings it back next pass, by which
|
|
1224
|
-
// time finalize has parked the run and both writes land.
|
|
1225
|
-
const readiness = await this.submittingRunReadiness(provider, parent);
|
|
1226
|
-
if (readiness.Verdict === 'defer') {
|
|
1227
|
-
this.keepRetryingSettlement(parentID);
|
|
1228
|
-
continue;
|
|
1229
|
-
}
|
|
1230
|
-
// A settled graph will not produce another verdict, claim or progress report, so the
|
|
1231
|
-
// per-graph observability caches for it are dead weight from here. Unbounded, they
|
|
1232
|
-
// are a slow leak in a process that runs for weeks — one that grows with every
|
|
1233
|
-
// workflow the server has ever seen rather than with anything live. (A deferred
|
|
1234
|
-
// settlement below repopulates them naturally on the retry pass.)
|
|
1235
|
-
this.forgetGraphObservability(parentID);
|
|
1236
|
-
// R3-8: the rollup gets a verdict, and a TRANSIENT failure defers exactly as a
|
|
1237
|
-
// failed lifecycle write does. Continuing past one would settle the run and claim
|
|
1238
|
-
// the marker, which permanently excludes the graph from the rescue sweep — making
|
|
1239
|
-
// the rollup's own "retrying on a later settlement" log a promise it could not keep.
|
|
1240
|
-
// Permanent refusals (truncated tree, graph not in the tree) proceed as before:
|
|
1241
|
-
// those do not clear on their own, and deferring on them would stall forever.
|
|
1242
|
-
if (await this.rollUpCostToSubmittingRun(provider, parent) === 'failed-transient') {
|
|
1243
|
-
this.keepRetryingSettlement(parentID);
|
|
1244
|
-
continue;
|
|
1245
|
-
}
|
|
1246
|
-
// Deliberately AFTER the rollup and OUTSIDE its refusal paths. The rollup declines
|
|
1247
|
-
// to write a number it cannot stand behind — a truncated tree, an unreachable graph
|
|
1248
|
-
// — and every one of those returns early. If the run's lifecycle were settled in
|
|
1249
|
-
// there, a refused rollup would strand the run parked forever, which is a far worse
|
|
1250
|
-
// failure than a missing cost figure. Cost and lifecycle are separate concerns with
|
|
1251
|
-
// separate failure modes, so they get separate writes.
|
|
1252
|
-
if (await this.settleSubmittingRun(provider, parent, rollup.status) === 'defer') {
|
|
1253
|
-
// The lifecycle write did not land. Delivering now would claim the marker and
|
|
1254
|
-
// make this the LAST pass to look at the graph — leaving the run Paused forever,
|
|
1255
|
-
// which is the exact permanence R2-2 removes. Leave the marker unset and retry.
|
|
1256
|
-
this.keepRetryingSettlement(parentID);
|
|
1257
|
-
continue;
|
|
1258
|
-
}
|
|
1259
|
-
if (await this.deliverContinuation(provider, parent, graph, readiness.SubmitterCancelled)) {
|
|
1260
|
-
// Delivered, expired, or lost the CAS to a peer — every one of those means this
|
|
1261
|
-
// graph is somebody's finished business and needs nothing further from here.
|
|
1262
|
-
this.retryingSettlement.delete(parentID);
|
|
1263
|
-
this.announcedSettlements.delete(parentID);
|
|
1264
|
-
}
|
|
1265
|
-
else {
|
|
1266
|
-
// This instance cannot deliver. Stay quiet about it — the frame is already out —
|
|
1267
|
-
// and leave the graph for a capable peer via the sweep.
|
|
1268
|
-
this.keepRetryingSettlement(parentID);
|
|
1269
|
-
}
|
|
1345
|
+
// Deliberately AFTER the rollup and OUTSIDE its refusal paths. The rollup declines
|
|
1346
|
+
// to write a number it cannot stand behind — a truncated tree, an unreachable graph
|
|
1347
|
+
// — and every one of those returns early. If the run's lifecycle were settled in
|
|
1348
|
+
// there, a refused rollup would strand the run parked forever, which is a far worse
|
|
1349
|
+
// failure than a missing cost figure. Cost and lifecycle are separate concerns with
|
|
1350
|
+
// separate failure modes, so they get separate writes.
|
|
1351
|
+
if (await this.settleSubmittingRun(provider, parent, rollup.status) === 'defer') {
|
|
1352
|
+
// The lifecycle write did not land. Delivering now would claim the marker and
|
|
1353
|
+
// make this the LAST pass to look at the graph — leaving the run Paused forever,
|
|
1354
|
+
// which is the exact permanence R2-2 removes. Leave the marker unset and retry.
|
|
1355
|
+
this.keepRetryingSettlement(parentID);
|
|
1356
|
+
return undefined;
|
|
1357
|
+
}
|
|
1358
|
+
if (await this.deliverContinuation(provider, parent, graph, readiness.SubmitterCancelled)) {
|
|
1359
|
+
// Delivered, expired, or lost the CAS to a peer — every one of those means this
|
|
1360
|
+
// graph is somebody's finished business and needs nothing further from here.
|
|
1361
|
+
this.retryingSettlement.delete(parentID);
|
|
1362
|
+
this.announcedSettlements.delete(parentID);
|
|
1363
|
+
}
|
|
1364
|
+
else {
|
|
1365
|
+
// This instance cannot deliver. Stay quiet about it — the frame is already out —
|
|
1366
|
+
// and leave the graph for a capable peer via the sweep.
|
|
1367
|
+
this.keepRetryingSettlement(parentID);
|
|
1270
1368
|
}
|
|
1271
1369
|
}
|
|
1272
|
-
return
|
|
1370
|
+
return undefined;
|
|
1273
1371
|
}
|
|
1274
1372
|
/**
|
|
1275
1373
|
* Credits a finished graph's spending back to the agent run that submitted it.
|
|
@@ -1536,6 +1634,20 @@ export class TaskGraphDispatcher {
|
|
|
1536
1634
|
LogError(`[TaskGraphDispatcher] Could not end graph early for ${task.ID}: ${e instanceof Error ? e.message : String(e)}`);
|
|
1537
1635
|
}
|
|
1538
1636
|
}
|
|
1637
|
+
/**
|
|
1638
|
+
* Makes visible that an Agent task runs with no parent run (#4623).
|
|
1639
|
+
*
|
|
1640
|
+
* The spawned agent gets no `parentRun`, so a Flow agent in it takes the top-level default and
|
|
1641
|
+
* dispatches its own graph: the task then completes when that graph is scheduled, not when its
|
|
1642
|
+
* work is done. That is expected for a graph a person, a schedule or MCP submitted, and a defect
|
|
1643
|
+
* for one an agent run submitted whose run ID was not recorded. Logged, not refused: routing is
|
|
1644
|
+
* unchanged.
|
|
1645
|
+
*/
|
|
1646
|
+
warnAgentTaskWithoutSubmittingRun(task) {
|
|
1647
|
+
LogWarning(`[TaskGraphDispatcher] Agent task ${task.ID} ('${task.Name}'): graph parent ${task.ParentID} has no ` +
|
|
1648
|
+
`submitting agent run, so the agent runs with no parent run. A Flow agent there takes the ` +
|
|
1649
|
+
`top-level default and dispatches its own steps, completing this task before that work runs.`);
|
|
1650
|
+
}
|
|
1539
1651
|
/**
|
|
1540
1652
|
* How deep the continuation chain already is, read from the graph's parent metadata, plus
|
|
1541
1653
|
* the resolved `ExecutionUser` of the user who submitted the graph.
|
|
@@ -1550,15 +1662,24 @@ export class TaskGraphDispatcher {
|
|
|
1550
1662
|
let invocation = {};
|
|
1551
1663
|
let submittedByUserID = task.UserID;
|
|
1552
1664
|
let parentAgentHierarchy = undefined;
|
|
1665
|
+
let parentRead = false;
|
|
1666
|
+
// The parent's stored envelope. Every child carries its own copy too, so a parent that cannot
|
|
1667
|
+
// be read still leaves the node constrained by its own row.
|
|
1668
|
+
let parentEnvelopeColumn = null;
|
|
1669
|
+
let recordsTaint = true;
|
|
1553
1670
|
if (task.ParentID && prehydrated && (prehydrated.parentMetadata || prehydrated.parentTask)) {
|
|
1671
|
+
parentRead = true;
|
|
1554
1672
|
const parent = prehydrated.parentTask ?? null;
|
|
1555
1673
|
const meta = (prehydrated.parentMetadata && typeof prehydrated.parentMetadata.reinvokeDepth === 'number')
|
|
1556
1674
|
? prehydrated.parentMetadata
|
|
1557
1675
|
: ParseTaskGraphParentMetadata(parent?.InputPayload ?? null);
|
|
1558
1676
|
depth = meta.reinvokeDepth + 1;
|
|
1559
1677
|
submittingAgentRunID = parent?.AgentRunID ?? meta.submittedByAgentRunID ?? null;
|
|
1678
|
+
parentAgentHierarchy = meta.parentAgentHierarchy;
|
|
1560
1679
|
invocation = { data: meta.invocation?.data, context: meta.invocation?.context };
|
|
1561
1680
|
submittedByUserID = meta.submittedByUserID ?? parent?.UserID ?? task.UserID;
|
|
1681
|
+
parentEnvelopeColumn = parent?.SecurityEnvelope ?? null;
|
|
1682
|
+
recordsTaint = meta.recordsTaint === true;
|
|
1562
1683
|
}
|
|
1563
1684
|
else if (task.ParentID && typeof provider?.GetEntityObject === 'function') {
|
|
1564
1685
|
try {
|
|
@@ -1567,12 +1688,15 @@ export class TaskGraphDispatcher {
|
|
|
1567
1688
|
LogError(`[TaskGraphDispatcher] Task ${task.ID}: parent ${task.ParentID} could not be loaded; running at depth 0 with no invocation data/context.`);
|
|
1568
1689
|
}
|
|
1569
1690
|
else {
|
|
1691
|
+
parentRead = true;
|
|
1570
1692
|
const meta = ParseTaskGraphParentMetadata(parent.InputPayload);
|
|
1571
1693
|
depth = meta.reinvokeDepth + 1;
|
|
1572
1694
|
submittingAgentRunID = parent.AgentRunID;
|
|
1573
1695
|
parentAgentHierarchy = meta.parentAgentHierarchy;
|
|
1574
1696
|
invocation = { data: meta.invocation?.data, context: meta.invocation?.context };
|
|
1575
1697
|
submittedByUserID = meta.submittedByUserID ?? parent.UserID ?? task.UserID;
|
|
1698
|
+
parentEnvelopeColumn = parent.SecurityEnvelope;
|
|
1699
|
+
recordsTaint = meta.recordsTaint === true;
|
|
1576
1700
|
}
|
|
1577
1701
|
}
|
|
1578
1702
|
catch (e) {
|
|
@@ -1581,13 +1705,23 @@ export class TaskGraphDispatcher {
|
|
|
1581
1705
|
LogError(`[TaskGraphDispatcher] Task ${task.ID}: reading parent ${task.ParentID} failed; running at depth 0 with no invocation data/context: ${e instanceof Error ? e.message : String(e)}`);
|
|
1582
1706
|
}
|
|
1583
1707
|
}
|
|
1584
|
-
|
|
1708
|
+
if (parentRead && !submittingAgentRunID && task.StepType === 'Agent') {
|
|
1709
|
+
this.warnAgentTaskWithoutSubmittingRun(task);
|
|
1710
|
+
}
|
|
1711
|
+
const security = ResolveStoredNodeSecurity(parentEnvelopeColumn, task.SecurityEnvelope);
|
|
1712
|
+
const submitter = await this.resolveGraphExecutionUser(submittedByUserID, task.ParentID ?? task.ID);
|
|
1713
|
+
// The submitter resolves to the process-wide UserCache instance (or this dispatcher's own
|
|
1714
|
+
// user), which every other task shares: the caller's tenant goes on a per-task clone, never
|
|
1715
|
+
// on that instance (see CloneUserWithTenantContext).
|
|
1716
|
+
const tenant = 'Envelope' in security ? security.Envelope?.CallerTenantContext : undefined;
|
|
1585
1717
|
return {
|
|
1586
1718
|
Depth: depth,
|
|
1587
1719
|
SubmittingAgentRunID: submittingAgentRunID,
|
|
1588
1720
|
ParentAgentHierarchy: parentAgentHierarchy,
|
|
1589
1721
|
Invocation: invocation,
|
|
1590
|
-
ExecutionUser:
|
|
1722
|
+
ExecutionUser: tenant ? CloneUserWithTenantContext(submitter, tenant, provider) : submitter,
|
|
1723
|
+
Security: security,
|
|
1724
|
+
RecordsTaint: recordsTaint,
|
|
1591
1725
|
};
|
|
1592
1726
|
}
|
|
1593
1727
|
/**
|
|
@@ -1630,13 +1764,21 @@ export class TaskGraphDispatcher {
|
|
|
1630
1764
|
* as a recovery path; they are ordinary sequencing, and treating them as recovery would let a
|
|
1631
1765
|
* graph sail past a failure it never anticipated.
|
|
1632
1766
|
*/
|
|
1633
|
-
computeHandledFailures(failureSemantics, nodes, edges) {
|
|
1767
|
+
computeHandledFailures(failureSemantics, nodes, edges, entityById) {
|
|
1634
1768
|
const handled = new Set();
|
|
1635
|
-
if (failureSemantics !== 'edges')
|
|
1636
|
-
return handled;
|
|
1637
1769
|
for (const node of nodes) {
|
|
1638
1770
|
if (node.status !== 'Failed')
|
|
1639
1771
|
continue;
|
|
1772
|
+
const entity = entityById?.get(node.id);
|
|
1773
|
+
if (entity && IsCompensationTask(entity)) {
|
|
1774
|
+
const compMeta = ReadTaskCompensationMetadata(entity.Configuration);
|
|
1775
|
+
if (compMeta?.onCompensationFailure === 'ContinueCompensation') {
|
|
1776
|
+
handled.add(node.id);
|
|
1777
|
+
continue;
|
|
1778
|
+
}
|
|
1779
|
+
}
|
|
1780
|
+
if (failureSemantics !== 'edges')
|
|
1781
|
+
continue;
|
|
1640
1782
|
// "Has somewhere to go" is the test. An edge out of a failed step that survived condition
|
|
1641
1783
|
// evaluation IS the drawn recovery route; a failed step with no outgoing edges has none,
|
|
1642
1784
|
// and stays terminal.
|
|
@@ -1737,6 +1879,7 @@ export class TaskGraphDispatcher {
|
|
|
1737
1879
|
return true;
|
|
1738
1880
|
const summary = this.buildContinuationSummary(parent, graph);
|
|
1739
1881
|
LogStatus(`[TaskGraphDispatcher] Graph ${parent.ID} finished — ${summary}`);
|
|
1882
|
+
const security = this.continuationEnvelope(parent, graph);
|
|
1740
1883
|
const params = {
|
|
1741
1884
|
ParentTaskID: parent.ID,
|
|
1742
1885
|
WorkflowName: parent.Name,
|
|
@@ -1744,6 +1887,7 @@ export class TaskGraphDispatcher {
|
|
|
1744
1887
|
SubmittedByAgentRunID: meta.submittedByAgentRunID,
|
|
1745
1888
|
SubmittedByUserID: meta.submittedByUserID ?? null,
|
|
1746
1889
|
ReinvokeDepth: meta.reinvokeDepth,
|
|
1890
|
+
...('Envelope' in security && security.Envelope ? { SecurityEnvelope: security.Envelope } : {}),
|
|
1747
1891
|
Tasks: [...graph.entityById.values()].map((t) => ({
|
|
1748
1892
|
TaskID: t.ID,
|
|
1749
1893
|
Name: t.Name,
|
|
@@ -1759,11 +1903,15 @@ export class TaskGraphDispatcher {
|
|
|
1759
1903
|
// Reinvoke degrades to a message when the host cannot start agent turns. Degrading is
|
|
1760
1904
|
// right rather than throwing: the work genuinely ran, and the user losing the results
|
|
1761
1905
|
// because nobody could start a follow-up turn would be the worse outcome.
|
|
1762
|
-
|
|
1906
|
+
const reinvokeRefusal = mode === 'reinvoke' ? this.reinvokeRefusal(security) : null;
|
|
1907
|
+
if (mode === 'reinvoke' && this.continuationDeliverer.Reinvoke && !reinvokeRefusal) {
|
|
1763
1908
|
await this.continuationDeliverer.Reinvoke(params);
|
|
1764
1909
|
}
|
|
1765
1910
|
else {
|
|
1766
|
-
if (
|
|
1911
|
+
if (reinvokeRefusal) {
|
|
1912
|
+
LogError(`[TaskGraphDispatcher] Graph ${parent.ID}: not starting a continuation turn (${reinvokeRefusal}); delivering as a message.`);
|
|
1913
|
+
}
|
|
1914
|
+
else if (mode === 'reinvoke') {
|
|
1767
1915
|
LogStatus(`[TaskGraphDispatcher] Graph ${parent.ID}: host cannot reinvoke; delivering as a message.`);
|
|
1768
1916
|
}
|
|
1769
1917
|
await this.continuationDeliverer.PostMessage(params);
|
|
@@ -1781,6 +1929,37 @@ export class TaskGraphDispatcher {
|
|
|
1781
1929
|
// wasted pass per settlement and a retry counter measuring the wrong thing.
|
|
1782
1930
|
return true;
|
|
1783
1931
|
}
|
|
1932
|
+
/**
|
|
1933
|
+
* What a `reinvoke` continuation turn runs under (B1): the graph's stored envelope, tainted when the
|
|
1934
|
+
* submitting run was or when any step's output carries taint — the turn reads every step's outcome,
|
|
1935
|
+
* so a completed Human step clears only what it reviewed. A stored envelope that cannot be read is a
|
|
1936
|
+
* refusal: the turn is then not started at all.
|
|
1937
|
+
*/
|
|
1938
|
+
continuationEnvelope(parent, graph) {
|
|
1939
|
+
const stored = ResolveStoredNodeSecurity(parent.SecurityEnvelope, null);
|
|
1940
|
+
if ('Refusal' in stored) {
|
|
1941
|
+
return stored;
|
|
1942
|
+
}
|
|
1943
|
+
const graphTainted = stored.Envelope?.IsRunTainted === true;
|
|
1944
|
+
const lookup = this.upstreamLookupInGraph(graph);
|
|
1945
|
+
const outputsTainted = [...graph.entityById.values()].some((task) => UpstreamCarriesTaint(task, graphTainted, lookup, graph.parentMetadata?.recordsTaint === true));
|
|
1946
|
+
return { Envelope: WithInputTaint(stored.Envelope, graphTainted || outputsTainted) };
|
|
1947
|
+
}
|
|
1948
|
+
/**
|
|
1949
|
+
* Why a `reinvoke` turn must not start, or null. A fresh agent turn that ran without the graph's
|
|
1950
|
+
* constraints would search without its tenant and readers and post into a shared conversation, so a
|
|
1951
|
+
* graph whose envelope cannot be read, or that constrains anything on a host whose deliverer does not
|
|
1952
|
+
* enforce envelopes, is delivered as a message instead.
|
|
1953
|
+
*/
|
|
1954
|
+
reinvokeRefusal(security) {
|
|
1955
|
+
if ('Refusal' in security) {
|
|
1956
|
+
return security.Refusal;
|
|
1957
|
+
}
|
|
1958
|
+
if (EnvelopeConstrains(security.Envelope) && this.continuationDeliverer?.EnforcesSecurityEnvelope !== true) {
|
|
1959
|
+
return 'the graph carries security constraints and this host\'s deliverer does not start a turn under them';
|
|
1960
|
+
}
|
|
1961
|
+
return null;
|
|
1962
|
+
}
|
|
1784
1963
|
/** Reads the parent's durable continuation metadata through the shared parser. */
|
|
1785
1964
|
readParentMetadata(parent) {
|
|
1786
1965
|
return ParseTaskGraphParentMetadata(parent.InputPayload);
|
|
@@ -2033,9 +2212,30 @@ export class TaskGraphDispatcher {
|
|
|
2033
2212
|
// will eventually stop finding them — which would turn a retry into a silent abandonment.
|
|
2034
2213
|
for (const id of this.retryingSettlement.keys())
|
|
2035
2214
|
ids.add(id);
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2215
|
+
// A parent counts only when it is a workflow (a parentless task of the workflow type): the first arm finds parents
|
|
2216
|
+
// by their steps' type alone, and a workflow-typed row under any other task must not turn that task into a graph
|
|
2217
|
+
// whose metadata the dispatcher would trust. The other two arms prove most of them; the rest (a step retried in a
|
|
2218
|
+
// run that settled before the sweep window) are checked with one read, whatever their status or age.
|
|
2219
|
+
const workflowParents = new Set([
|
|
2220
|
+
...(unsettledParents?.Results ?? []).map((r) => r.ID?.toUpperCase()),
|
|
2221
|
+
...(terminalRecent?.Results ?? []).map((r) => r.ID?.toUpperCase()),
|
|
2222
|
+
]);
|
|
2223
|
+
const pendingParents = (withPendingWork?.Results ?? []).map((r) => r.ParentID).filter(Boolean);
|
|
2224
|
+
const unproven = [...new Set(pendingParents.map((id) => id.toUpperCase()))].filter((id) => !workflowParents.has(id) && IsValidUUID(id));
|
|
2225
|
+
if (unproven.length > 0) {
|
|
2226
|
+
const proven = await rv.RunView({
|
|
2227
|
+
EntityName: 'MJ: Tasks',
|
|
2228
|
+
ExtraFilter: `${ofWorkflowType} AND ParentID IS NULL AND ID IN (${unproven.map((id) => `'${id}'`).join(',')})`,
|
|
2229
|
+
Fields: ['ID'],
|
|
2230
|
+
ResultType: 'simple',
|
|
2231
|
+
BypassCache: true,
|
|
2232
|
+
}, this.contextUser);
|
|
2233
|
+
for (const r of (proven.Success ? proven.Results : []) ?? [])
|
|
2234
|
+
workflowParents.add(r.ID.toUpperCase());
|
|
2235
|
+
}
|
|
2236
|
+
for (const parentID of pendingParents) {
|
|
2237
|
+
if (workflowParents.has(parentID.toUpperCase()))
|
|
2238
|
+
ids.add(parentID);
|
|
2039
2239
|
}
|
|
2040
2240
|
// Childless tasks match the second query too; propagateAndRollup skips anything with no
|
|
2041
2241
|
// nodes, so they cost one empty load and nothing else.
|
|
@@ -2158,12 +2358,17 @@ export class TaskGraphDispatcher {
|
|
|
2158
2358
|
continue;
|
|
2159
2359
|
}
|
|
2160
2360
|
}
|
|
2361
|
+
// A graph rolling back starts no new forward work, on any instance: the same rows decide it
|
|
2362
|
+
// everywhere (sagaHoldsForwardWork), so no dispatcher claims a step another is skipping.
|
|
2363
|
+
const sagaHolds = this.sagaHoldsForwardWork(graph);
|
|
2161
2364
|
for (const node of eligible) {
|
|
2162
2365
|
if (allowedTaskIDs && !allowedTaskIDs.has(node.id))
|
|
2163
2366
|
continue;
|
|
2164
2367
|
const entity = graph.entityById.get(node.id);
|
|
2165
2368
|
if (!entity)
|
|
2166
2369
|
continue;
|
|
2370
|
+
if (sagaHolds && !IsCompensationTask(entity))
|
|
2371
|
+
continue;
|
|
2167
2372
|
// Human tasks are never dispatched — a person completes them. But "eligible" is the
|
|
2168
2373
|
// moment that person can finally act, and nothing else in the system knows it has
|
|
2169
2374
|
// arrived: the task sat Pending behind prerequisites, and no save touched it when
|
|
@@ -2219,6 +2424,8 @@ export class TaskGraphDispatcher {
|
|
|
2219
2424
|
parentTask: graph.parent ?? null,
|
|
2220
2425
|
parentMetadata: graph.parentMetadata,
|
|
2221
2426
|
dependencyOutputs: this.extractDependencyOutputsFromGraph(entity.ID, graph),
|
|
2427
|
+
upstreamTasks: this.upstreamTasksInGraph(entity.ID, graph),
|
|
2428
|
+
upstreamOf: this.upstreamLookupInGraph(graph),
|
|
2222
2429
|
});
|
|
2223
2430
|
if (claimable.length >= limit)
|
|
2224
2431
|
break;
|
|
@@ -2375,7 +2582,7 @@ export class TaskGraphDispatcher {
|
|
|
2375
2582
|
if (expiresInHours && expiresInHours > 0) {
|
|
2376
2583
|
request.ExpiresAt = new Date(Date.now() + expiresInHours * 60 * 60 * 1000);
|
|
2377
2584
|
}
|
|
2378
|
-
if (await
|
|
2585
|
+
if (await this.saveWithRuntimeAuthority(request, 'MJ: AI Agent Requests')) {
|
|
2379
2586
|
// INSERT-THEN-RESELECT (R3-5). The check above is read-then-write in a system whose
|
|
2380
2587
|
// every other cross-instance write is a CAS, and there is no unique index behind it —
|
|
2381
2588
|
// so two overlapping instances both read "none open", both insert, and both ping the
|
|
@@ -2507,7 +2714,12 @@ export class TaskGraphDispatcher {
|
|
|
2507
2714
|
// this whole path exists to avoid, and a give-up edge can now route around it.
|
|
2508
2715
|
task.ErrorMessage = 'Nobody answered this step before its request expired.';
|
|
2509
2716
|
}
|
|
2510
|
-
|
|
2717
|
+
else {
|
|
2718
|
+
// Who answered: the step's review clears taint only when its assignee gave it
|
|
2719
|
+
// (HumanReviewClearsTaint). The request records its responder server-side when answered.
|
|
2720
|
+
task.Configuration = this.configurationWithCompletedBy(task, request.ResponseByUserID);
|
|
2721
|
+
}
|
|
2722
|
+
if (!(await this.saveWithRuntimeAuthority(task))) {
|
|
2511
2723
|
LogError(`[TaskGraphDispatcher] Could not settle human task ${task.ID}: ` +
|
|
2512
2724
|
`${task.LatestResult?.CompleteMessage ?? 'unknown error'}`);
|
|
2513
2725
|
continue;
|
|
@@ -2592,6 +2804,26 @@ export class TaskGraphDispatcher {
|
|
|
2592
2804
|
}
|
|
2593
2805
|
}
|
|
2594
2806
|
}
|
|
2807
|
+
/** The step's Configuration with `runtime.completedByUserID` set to `userID` (removed when there is none). */
|
|
2808
|
+
configurationWithCompletedBy(task, userID) {
|
|
2809
|
+
const existing = this.parseConfiguration(task);
|
|
2810
|
+
const { completedByUserID: _previous, ...runtime } = existing?.runtime ?? {};
|
|
2811
|
+
return JSON.stringify({ ...existing, runtime: { ...runtime, ...(userID ? { completedByUserID: userID } : {}) } });
|
|
2812
|
+
}
|
|
2813
|
+
/**
|
|
2814
|
+
* Saves a row inside {@link TASK_GRAPH_RUNTIME_SECURITY_OPERATION}, bound to this dispatcher's user and to
|
|
2815
|
+
* the row's entity: the one scope in which `MJTaskEntityServer` accepts a write of a task's runtime
|
|
2816
|
+
* security fields, and `MJAIAgentRequestEntityServer` accepts a new request for a workflow step. Only
|
|
2817
|
+
* the save runs inside it.
|
|
2818
|
+
*/
|
|
2819
|
+
saveWithRuntimeAuthority(row, entityName = 'MJ: Tasks') {
|
|
2820
|
+
return ServerOperationScopeManager.Instance.RunWithAuthority({
|
|
2821
|
+
operationKey: TASK_GRAPH_RUNTIME_SECURITY_OPERATION,
|
|
2822
|
+
source: 'ServerEngine',
|
|
2823
|
+
allowedEntities: [entityName],
|
|
2824
|
+
userId: this.contextUser.ID,
|
|
2825
|
+
}, () => row.Save());
|
|
2826
|
+
}
|
|
2595
2827
|
/** The answered (or expired) request for a task, if any. */
|
|
2596
2828
|
async answeredRequestFor(provider, taskID) {
|
|
2597
2829
|
const result = await RunView.FromMetadataProvider(provider).RunView({
|
|
@@ -2662,6 +2894,19 @@ export class TaskGraphDispatcher {
|
|
|
2662
2894
|
}
|
|
2663
2895
|
}
|
|
2664
2896
|
/** Loads a graph's children and edges in the shapes both the algorithms and mutation need. */
|
|
2897
|
+
/** A graph state with no steps: what a parent with no children, or one that is not a workflow, loads as. */
|
|
2898
|
+
emptyGraphState(parentTaskID, parent) {
|
|
2899
|
+
return {
|
|
2900
|
+
parentTaskID,
|
|
2901
|
+
parent,
|
|
2902
|
+
parentMetadata: ParseTaskGraphParentMetadata(parent?.InputPayload ?? null),
|
|
2903
|
+
nodes: [], edges: [], entityById: new Map(),
|
|
2904
|
+
rawDependencies: [],
|
|
2905
|
+
unreachableTaskIDs: new Set(), cascadeSkipTaskIDs: new Set(),
|
|
2906
|
+
skipSeedTaskIDs: new Set(), holdTaskIDs: new Set(),
|
|
2907
|
+
handledFailureIDs: new Set(),
|
|
2908
|
+
};
|
|
2909
|
+
}
|
|
2665
2910
|
async loadGraphState(provider, parentTaskID, debug, preloadedParent) {
|
|
2666
2911
|
const rv = RunView.FromMetadataProvider(provider);
|
|
2667
2912
|
// BypassCache throughout: task status is written by the claim protocol's direct SQL, which
|
|
@@ -2669,16 +2914,7 @@ export class TaskGraphDispatcher {
|
|
|
2669
2914
|
const childrenResult = await rv.RunView({ EntityName: 'MJ: Tasks', ExtraFilter: `ParentID='${parentTaskID}'`, ResultType: 'entity_object', BypassCache: true }, this.contextUser);
|
|
2670
2915
|
const children = (childrenResult.Success ? childrenResult.Results : []) ?? [];
|
|
2671
2916
|
if (children.length === 0) {
|
|
2672
|
-
return
|
|
2673
|
-
parentTaskID,
|
|
2674
|
-
parent: preloadedParent ?? null,
|
|
2675
|
-
parentMetadata: ParseTaskGraphParentMetadata(preloadedParent?.InputPayload ?? null),
|
|
2676
|
-
nodes: [], edges: [], entityById: new Map(),
|
|
2677
|
-
rawDependencies: [],
|
|
2678
|
-
unreachableTaskIDs: new Set(), cascadeSkipTaskIDs: new Set(),
|
|
2679
|
-
skipSeedTaskIDs: new Set(), holdTaskIDs: new Set(),
|
|
2680
|
-
handledFailureIDs: new Set(),
|
|
2681
|
-
};
|
|
2917
|
+
return this.emptyGraphState(parentTaskID, preloadedParent ?? null);
|
|
2682
2918
|
}
|
|
2683
2919
|
const idList = children.map((c) => `'${c.ID}'`).join(',');
|
|
2684
2920
|
const depsResult = await rv.RunView({ EntityName: 'MJ: Task Dependencies', ExtraFilter: `TaskID IN (${idList})`, ResultType: 'entity_object', BypassCache: true }, this.contextUser);
|
|
@@ -2690,6 +2926,13 @@ export class TaskGraphDispatcher {
|
|
|
2690
2926
|
const parent = preloadedParent !== undefined
|
|
2691
2927
|
? preloadedParent
|
|
2692
2928
|
: await this.loadParentTask(provider, parentTaskID);
|
|
2929
|
+
// Only a workflow's steps run: its metadata names the user they run as, and a graph is trusted on that alone. A
|
|
2930
|
+
// missing parent, or one that is not a parentless task of the workflow type, runs nothing.
|
|
2931
|
+
const workflowTypeID = await this.workflowTaskTypeID(provider);
|
|
2932
|
+
if (!parent || parent.ParentID != null || !workflowTypeID || !UUIDsEqual(parent.TypeID, workflowTypeID)) {
|
|
2933
|
+
LogError(`[TaskGraphDispatcher] ${parentTaskID} has workflow steps but is not a workflow; its steps are not run.`);
|
|
2934
|
+
return this.emptyGraphState(parentTaskID, parent ?? null);
|
|
2935
|
+
}
|
|
2693
2936
|
const parentMeta = parent
|
|
2694
2937
|
? ParseTaskGraphParentMetadata(parent.InputPayload)
|
|
2695
2938
|
: ParseTaskGraphParentMetadata(null);
|
|
@@ -2909,7 +3152,7 @@ export class TaskGraphDispatcher {
|
|
|
2909
3152
|
// Exclusive holds and ordinary-condition holds are the same state and share one set:
|
|
2910
3153
|
// "we cannot tell yet, so nothing may claim this."
|
|
2911
3154
|
holdTaskIDs: new Set([...resolution.holdTaskIDs, ...heldByCondition]),
|
|
2912
|
-
handledFailureIDs: this.computeHandledFailures(failureSemantics, nodes, liveEdges),
|
|
3155
|
+
handledFailureIDs: this.computeHandledFailures(failureSemantics, nodes, liveEdges, entityById),
|
|
2913
3156
|
};
|
|
2914
3157
|
}
|
|
2915
3158
|
/**
|
|
@@ -3074,6 +3317,85 @@ export class TaskGraphDispatcher {
|
|
|
3074
3317
|
}
|
|
3075
3318
|
}).catch(() => { });
|
|
3076
3319
|
}
|
|
3320
|
+
/** The task rows `taskID` depends on, from the loaded graph (no query). */
|
|
3321
|
+
upstreamTasksInGraph(taskID, graph) {
|
|
3322
|
+
const upstream = [];
|
|
3323
|
+
for (const dep of this.dependencyRowsOf(taskID, graph)) {
|
|
3324
|
+
const row = graph.entityById.get(dep.DependsOnTaskID);
|
|
3325
|
+
if (row)
|
|
3326
|
+
upstream.push(row);
|
|
3327
|
+
}
|
|
3328
|
+
return upstream;
|
|
3329
|
+
}
|
|
3330
|
+
/**
|
|
3331
|
+
* Every task's prerequisites in the loaded graph, for the taint check to follow past a
|
|
3332
|
+
* prerequisite that recorded no taint. A dependency whose row is not in the graph makes that
|
|
3333
|
+
* task's prerequisites unknown, which the check reads as tainted.
|
|
3334
|
+
*/
|
|
3335
|
+
upstreamLookupInGraph(graph) {
|
|
3336
|
+
return (taskID) => {
|
|
3337
|
+
const rows = [];
|
|
3338
|
+
for (const dep of this.dependencyRowsOf(taskID, graph)) {
|
|
3339
|
+
const row = graph.entityById.get(dep.DependsOnTaskID);
|
|
3340
|
+
if (!row)
|
|
3341
|
+
return undefined;
|
|
3342
|
+
rows.push(row);
|
|
3343
|
+
}
|
|
3344
|
+
return rows;
|
|
3345
|
+
};
|
|
3346
|
+
}
|
|
3347
|
+
/**
|
|
3348
|
+
* The graph's dependency rows of `taskID`. Indexed once per graph load: callers ask for every
|
|
3349
|
+
* claimable task in turn, and scanning all edges per task made a pass O(tasks × edges).
|
|
3350
|
+
*/
|
|
3351
|
+
dependencyRowsOf(taskID, graph) {
|
|
3352
|
+
graph.dependenciesByTask ??= GroupByUUID(graph.rawDependencies ?? [], (dep) => dep.TaskID);
|
|
3353
|
+
return graph.dependenciesByTask.Get(taskID) ?? [];
|
|
3354
|
+
}
|
|
3355
|
+
/**
|
|
3356
|
+
* The envelope a node's runners receive: its stored constraints ({@link GraphContext.Security})
|
|
3357
|
+
* with `IsRunTainted` set to the node's input taint (`ComputeNodeInputTaint`), or why the node
|
|
3358
|
+
* must not run.
|
|
3359
|
+
*/
|
|
3360
|
+
nodeEnvelope(task, context, prehydrated) {
|
|
3361
|
+
if ('Refusal' in context.Security) {
|
|
3362
|
+
return context.Security;
|
|
3363
|
+
}
|
|
3364
|
+
const stored = context.Security.Envelope;
|
|
3365
|
+
const inputTainted = ComputeNodeInputTaint({
|
|
3366
|
+
EnvelopeTainted: stored?.IsRunTainted === true,
|
|
3367
|
+
IsCompensation: IsCompensationTask(task),
|
|
3368
|
+
Upstream: prehydrated?.upstreamTasks ?? [],
|
|
3369
|
+
UpstreamOf: prehydrated?.upstreamOf,
|
|
3370
|
+
RecordsTaint: context.RecordsTaint,
|
|
3371
|
+
});
|
|
3372
|
+
return { Envelope: WithInputTaint(stored, inputTainted) };
|
|
3373
|
+
}
|
|
3374
|
+
/** Whether a node's input is tainted; a node refused on security grounds counts as tainted. */
|
|
3375
|
+
inputTaintOf(envelope) {
|
|
3376
|
+
return 'Refusal' in envelope || envelope.Envelope?.IsRunTainted === true;
|
|
3377
|
+
}
|
|
3378
|
+
/**
|
|
3379
|
+
* The failed outcome for a node refused on security grounds, or null when it may run. A node whose
|
|
3380
|
+
* envelope constrains anything runs only on a runner that enforces envelopes: the dispatcher
|
|
3381
|
+
* cannot apply a run scope, an audience or the taint gate itself, so a runner that does not
|
|
3382
|
+
* declare it would run the node unconstrained.
|
|
3383
|
+
*/
|
|
3384
|
+
securityRefusal(task, envelope, runnerEnforces) {
|
|
3385
|
+
if ('Refusal' in envelope) {
|
|
3386
|
+
return this.refusedNode(task, envelope.Refusal);
|
|
3387
|
+
}
|
|
3388
|
+
if (EnvelopeConstrains(envelope.Envelope) && runnerEnforces !== true) {
|
|
3389
|
+
return this.refusedNode(task, 'This host\'s runner for the step does not enforce task security envelopes, and the workflow was ' +
|
|
3390
|
+
'submitted by a run with an audience, a scope, a tenant, bound parameters or tainted content.');
|
|
3391
|
+
}
|
|
3392
|
+
return null;
|
|
3393
|
+
}
|
|
3394
|
+
/** A node refused on security grounds: failed, never run, and its output counted as tainted. */
|
|
3395
|
+
refusedNode(task, message) {
|
|
3396
|
+
LogError(`[TaskGraphDispatcher] Task '${task.Name}' (${task.ID}) refused: ${message}`);
|
|
3397
|
+
return { Success: false, AgentRunID: null, ErrorMessage: message, IsOutputTainted: true };
|
|
3398
|
+
}
|
|
3077
3399
|
/**
|
|
3078
3400
|
* Extracts parsed `OutputPayload` values for all dependencies of `taskID` directly from the
|
|
3079
3401
|
* already-loaded `GraphState`, avoiding any additional database round-trips when claiming and
|
|
@@ -3081,10 +3403,7 @@ export class TaskGraphDispatcher {
|
|
|
3081
3403
|
*/
|
|
3082
3404
|
extractDependencyOutputsFromGraph(taskID, graph) {
|
|
3083
3405
|
const outputs = new Map();
|
|
3084
|
-
const
|
|
3085
|
-
for (const dep of deps) {
|
|
3086
|
-
if (!UUIDsEqual(dep.TaskID, taskID))
|
|
3087
|
-
continue;
|
|
3406
|
+
for (const dep of this.dependencyRowsOf(taskID, graph)) {
|
|
3088
3407
|
const upstream = graph.entityById.get(dep.DependsOnTaskID);
|
|
3089
3408
|
if (!upstream?.OutputPayload)
|
|
3090
3409
|
continue;
|
|
@@ -3097,9 +3416,14 @@ export class TaskGraphDispatcher {
|
|
|
3097
3416
|
}
|
|
3098
3417
|
return outputs;
|
|
3099
3418
|
}
|
|
3100
|
-
/**
|
|
3101
|
-
|
|
3419
|
+
/**
|
|
3420
|
+
* The task rows `taskID` depends on, and the parsed `OutputPayload` of each, keyed by that task's
|
|
3421
|
+
* ID. The path for a task claimed without a graph load; `findClaimableTasks` reads both from the
|
|
3422
|
+
* graph it already holds.
|
|
3423
|
+
*/
|
|
3424
|
+
async loadDependencies(provider, taskID) {
|
|
3102
3425
|
const outputs = new Map();
|
|
3426
|
+
const upstreamRows = [];
|
|
3103
3427
|
const rv = RunView.FromMetadataProvider(provider);
|
|
3104
3428
|
// BypassCache: an upstream task's OutputPayload is written on the completion path, so a
|
|
3105
3429
|
// cached read here can hand a dependent task the previous run's output — or none at all.
|
|
@@ -3108,6 +3432,7 @@ export class TaskGraphDispatcher {
|
|
|
3108
3432
|
const upstream = await provider.GetEntityObject('MJ: Tasks', this.contextUser);
|
|
3109
3433
|
if (!(await upstream.Load(dep.DependsOnTaskID)))
|
|
3110
3434
|
continue;
|
|
3435
|
+
upstreamRows.push(upstream);
|
|
3111
3436
|
if (!upstream.OutputPayload)
|
|
3112
3437
|
continue;
|
|
3113
3438
|
try {
|
|
@@ -3117,7 +3442,7 @@ export class TaskGraphDispatcher {
|
|
|
3117
3442
|
LogError(`[TaskGraphDispatcher] Task ${dep.DependsOnTaskID} has malformed OutputPayload: ${e}`);
|
|
3118
3443
|
}
|
|
3119
3444
|
}
|
|
3120
|
-
return outputs;
|
|
3445
|
+
return { Outputs: outputs, Upstream: upstreamRows };
|
|
3121
3446
|
}
|
|
3122
3447
|
/**
|
|
3123
3448
|
* Runs one task's body, whatever kind of step it is.
|
|
@@ -3129,6 +3454,10 @@ export class TaskGraphDispatcher {
|
|
|
3129
3454
|
*
|
|
3130
3455
|
* Every branch is normalized to one shape so the recording path above stays single: an action has
|
|
3131
3456
|
* no agent run to point at, because its forensics live in `ActionExecutionLog` instead.
|
|
3457
|
+
*
|
|
3458
|
+
* **Every kind records its output taint here, as its input taint OR its own** (a Decision, a loop,
|
|
3459
|
+
* a failure and a refusal included). A kind that returned none — a Decision did, before — let its
|
|
3460
|
+
* output read as clean, so Fetch → Decision → Send Email ran the egress action ungated.
|
|
3132
3461
|
*/
|
|
3133
3462
|
async runTaskBody(task, provider, inputPayload, dependencyOutputs, onProgress, prehydrated) {
|
|
3134
3463
|
// A node's input is a name → value object (`TaskGraphSpecNode.inputPayload: Record<string, unknown>`).
|
|
@@ -3146,23 +3475,38 @@ export class TaskGraphDispatcher {
|
|
|
3146
3475
|
LogError(`[TaskGraphDispatcher] ${message}`);
|
|
3147
3476
|
return { Success: false, ErrorMessage: message };
|
|
3148
3477
|
}
|
|
3149
|
-
const
|
|
3478
|
+
const rawPayload = this.mergedPayload(inputPayload, dependencyOutputs);
|
|
3479
|
+
// `data.*` / `context.*` resolve against the invocation that submitted the graph, exactly as
|
|
3480
|
+
// the in-run walker resolves them and as branch conditions already see them (R3-3). Without
|
|
3481
|
+
// it a mapping like `RecordID: data.ID` reached the action as the literal "data.ID".
|
|
3482
|
+
const context = await this.graphContext(provider, task, prehydrated);
|
|
3483
|
+
const nodeEnvelope = this.nodeEnvelope(task, context, prehydrated);
|
|
3484
|
+
const outcome = await this.runTaskBodyOfKind(task, provider, rawPayload, dependencyOutputs, context, nodeEnvelope, onProgress);
|
|
3485
|
+
return { ...outcome, IsOutputTainted: this.inputTaintOf(nodeEnvelope) || outcome.IsOutputTainted === true };
|
|
3486
|
+
}
|
|
3487
|
+
/** {@link runTaskBody} for one step kind, with the node's context and envelope already resolved. */
|
|
3488
|
+
async runTaskBodyOfKind(task, provider, rawPayload, dependencyOutputs, context, nodeEnvelope, onProgress) {
|
|
3150
3489
|
const config = task.ConfigurationObject;
|
|
3151
3490
|
// A loop's own step type decides how many times its body runs; the body itself is dispatched
|
|
3152
3491
|
// through the very same runners as a one-shot step.
|
|
3153
3492
|
if (task.StepType === 'ForEach' || task.StepType === 'While') {
|
|
3154
|
-
return {
|
|
3493
|
+
return {
|
|
3494
|
+
...await this.runLoopTask(task, provider, rawPayload, dependencyOutputs, context, nodeEnvelope),
|
|
3495
|
+
PayloadAtStart: rawPayload,
|
|
3496
|
+
};
|
|
3155
3497
|
}
|
|
3156
3498
|
// Routed on StepType before the mappings below: a Decision reads its state from the merged
|
|
3157
3499
|
// payload by path and writes its answers back under `decisions`, so it has no mapping of its
|
|
3158
3500
|
// own. And it carries a PromptID, so the Prompt branch would otherwise take it.
|
|
3159
3501
|
if (task.StepType === 'Decision') {
|
|
3160
|
-
return { ...await this.runDecisionNode(task, provider,
|
|
3502
|
+
return { ...await this.runDecisionNode(task, provider, rawPayload, context, onProgress), PayloadAtStart: rawPayload };
|
|
3161
3503
|
}
|
|
3162
|
-
|
|
3163
|
-
|
|
3164
|
-
|
|
3165
|
-
const
|
|
3504
|
+
if ('Refusal' in nodeEnvelope) {
|
|
3505
|
+
return { ...this.refusedNode(task, nodeEnvelope.Refusal), PayloadAtStart: rawPayload };
|
|
3506
|
+
}
|
|
3507
|
+
const effectiveEnvelope = nodeEnvelope.Envelope;
|
|
3508
|
+
const inputTainted = effectiveEnvelope?.IsRunTainted === true;
|
|
3509
|
+
const payload = rawPayload;
|
|
3166
3510
|
const invocation = config?.inputMapping ? context.Invocation : {};
|
|
3167
3511
|
const { params, errors } = BuildMappedInput(config?.inputMapping, { payload, ...invocation });
|
|
3168
3512
|
for (const e of errors)
|
|
@@ -3180,7 +3524,16 @@ export class TaskGraphDispatcher {
|
|
|
3180
3524
|
// which was TRUE of what it had been handed while twenty research results sat in the
|
|
3181
3525
|
// dependency outputs beside it, and the reviewer then rejected the draft for saying so.
|
|
3182
3526
|
// Every layer looked like it was working.
|
|
3183
|
-
const
|
|
3527
|
+
const rawEffectiveInput = Object.keys(params).length > 0 ? params : payload;
|
|
3528
|
+
const inputEnforcement = task.ActionID
|
|
3529
|
+
? ApplyTaskSecurityEnvelopeToParams(rawEffectiveInput, effectiveEnvelope, task.ActionID)
|
|
3530
|
+
: { Params: rawEffectiveInput, OverriddenKeys: [] };
|
|
3531
|
+
const effectiveInput = inputEnforcement.Params;
|
|
3532
|
+
if (inputEnforcement.OverriddenKeys.length > 0) {
|
|
3533
|
+
const overridden = [...new Set(inputEnforcement.OverriddenKeys)];
|
|
3534
|
+
LogStatus(`[TaskGraphDispatcher] Task '${task.Name}' (${task.ID}): restored ${overridden.length} bound parameter(s) ` +
|
|
3535
|
+
`(${overridden.join(', ')}) from TaskSecurityEnvelope.`);
|
|
3536
|
+
}
|
|
3184
3537
|
if (task.StepType === 'Prompt') {
|
|
3185
3538
|
if (!this.promptRunner) {
|
|
3186
3539
|
// Not a failure: "nobody here can run this" is not "this ran and did not work".
|
|
@@ -3195,6 +3548,7 @@ export class TaskGraphDispatcher {
|
|
|
3195
3548
|
Provider: provider,
|
|
3196
3549
|
ContextUser: context.ExecutionUser,
|
|
3197
3550
|
OnProgress: onProgress,
|
|
3551
|
+
...(effectiveEnvelope ? { SecurityEnvelope: effectiveEnvelope } : {}),
|
|
3198
3552
|
});
|
|
3199
3553
|
// A prompt's response is DEEP-MERGED into the payload rather than replacing it. A prompt
|
|
3200
3554
|
// answers one question; replacing the payload with its answer would discard everything
|
|
@@ -3213,24 +3567,556 @@ export class TaskGraphDispatcher {
|
|
|
3213
3567
|
// cost rollup that silently omits failures under-reports exactly the runs someone
|
|
3214
3568
|
// is most likely to be investigating.
|
|
3215
3569
|
PromptRunID: promptResult.PromptRunID,
|
|
3570
|
+
// Monotonic: a prompt fed tainted input writes tainted output.
|
|
3571
|
+
IsOutputTainted: inputTainted || promptResult.IsOutputTainted === true,
|
|
3216
3572
|
};
|
|
3217
3573
|
}
|
|
3574
|
+
const refusal = this.securityRefusal(task, nodeEnvelope, task.ActionID ? this.actionRunner?.EnforcesSecurityEnvelope : this.agentRunner.EnforcesSecurityEnvelope);
|
|
3575
|
+
if (refusal) {
|
|
3576
|
+
return { ...refusal, PayloadAtStart: payload };
|
|
3577
|
+
}
|
|
3218
3578
|
const raw = task.ActionID
|
|
3219
|
-
? {
|
|
3220
|
-
|
|
3221
|
-
|
|
3222
|
-
|
|
3223
|
-
|
|
3224
|
-
Provider: provider,
|
|
3225
|
-
ContextUser: context.ExecutionUser,
|
|
3226
|
-
OnProgress: onProgress,
|
|
3227
|
-
}), AgentRunID: null }
|
|
3228
|
-
: await this.runAgentNode(task, provider, effectiveInput, dependencyOutputs, onProgress, context);
|
|
3579
|
+
? {
|
|
3580
|
+
...await this.invokeActionWithRetry(task, provider, effectiveInput, dependencyOutputs, context.ExecutionUser, onProgress, effectiveEnvelope),
|
|
3581
|
+
AgentRunID: null,
|
|
3582
|
+
}
|
|
3583
|
+
: await this.runAgentNode(task, provider, effectiveInput, dependencyOutputs, onProgress, context, effectiveEnvelope);
|
|
3229
3584
|
return {
|
|
3230
3585
|
...raw,
|
|
3231
3586
|
Output: this.applyStepOutputMapping(task, payload, raw.Output, config?.outputMapping),
|
|
3232
3587
|
PayloadAtStart: payload,
|
|
3588
|
+
...(task.ActionID ? { ActionInput: effectiveInput } : {}),
|
|
3589
|
+
// Monotonic: tainted input taints the output, and so does an action or agent that read
|
|
3590
|
+
// untrusted content (the runner reports that from the action's trust level or the run's
|
|
3591
|
+
// tainted sources).
|
|
3592
|
+
IsOutputTainted: inputTainted || raw.IsOutputTainted === true,
|
|
3593
|
+
};
|
|
3594
|
+
}
|
|
3595
|
+
/**
|
|
3596
|
+
* Runs an action task, retrying a failure up to the step's `retryCount` — but only when running the
|
|
3597
|
+
* action again is safe: only when the action's `IsIdempotent` column says so. A forward step's node may
|
|
3598
|
+
* turn that off (`compensation.isIdempotent: false`) but never on, because the node is written by a
|
|
3599
|
+
* model and the column by whoever owns the action; a compensation task retries when its compensation
|
|
3600
|
+
* action is idempotent. A non-idempotent action is never re-run: a payment that failed after charging
|
|
3601
|
+
* must not charge again. Retries back off exponentially (`RetryBackoffBaseMs`, doubling, capped at 30×).
|
|
3602
|
+
*/
|
|
3603
|
+
async invokeActionWithRetry(task, provider, effectiveInput, dependencyOutputs, executionUser, onProgress, effectiveEnvelope) {
|
|
3604
|
+
const run = () => this.actionRunner.RunActionForTask({
|
|
3605
|
+
TaskID: task.ID,
|
|
3606
|
+
ActionID: task.ActionID,
|
|
3607
|
+
InputPayload: effectiveInput,
|
|
3608
|
+
DependencyOutputs: dependencyOutputs,
|
|
3609
|
+
Provider: provider,
|
|
3610
|
+
ContextUser: executionUser,
|
|
3611
|
+
OnProgress: onProgress,
|
|
3612
|
+
...(effectiveEnvelope ? { SecurityEnvelope: effectiveEnvelope } : {}),
|
|
3613
|
+
});
|
|
3614
|
+
let result = await run();
|
|
3615
|
+
if (result.Success || result.ResultCode === TAINTED_EGRESS_BLOCKED) {
|
|
3616
|
+
return result;
|
|
3617
|
+
}
|
|
3618
|
+
const retries = await this.allowedRetries(provider, task);
|
|
3619
|
+
for (let attempt = 1; !result.Success && attempt <= retries; attempt++) {
|
|
3620
|
+
const delay = RetryBackoffMs(attempt, this.config.RetryBackoffBaseMs);
|
|
3621
|
+
LogStatus(`[TaskGraphDispatcher] Retrying idempotent action task '${task.Name}' (${task.ID}) in ${delay}ms, attempt ${attempt}/${retries}.`);
|
|
3622
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
3623
|
+
result = await run();
|
|
3624
|
+
}
|
|
3625
|
+
return result;
|
|
3626
|
+
}
|
|
3627
|
+
/**
|
|
3628
|
+
* How many times a failed action step may be retried: its `retryCount`, or 0 when the action is not
|
|
3629
|
+
* idempotent. Effective idempotency is `Action.IsIdempotent && node !== false`.
|
|
3630
|
+
*/
|
|
3631
|
+
async allowedRetries(provider, task) {
|
|
3632
|
+
const config = this.parseConfiguration(task);
|
|
3633
|
+
const compensation = ReadTaskCompensationMetadata(task.Configuration);
|
|
3634
|
+
const requested = Math.max(0, Math.floor(config?.policy?.retryCount ?? compensation?.retryCount ?? 0));
|
|
3635
|
+
if (requested === 0 || !task.ActionID) {
|
|
3636
|
+
return 0;
|
|
3637
|
+
}
|
|
3638
|
+
// The action's own column decides. A forward step's node can only narrow it: a model-written
|
|
3639
|
+
// `isIdempotent: true` must not make a payment retryable that its action says is not.
|
|
3640
|
+
const actionIdempotent = (await this.actionRows(provider, [task.ActionID])).Get(task.ActionID)?.IsIdempotent === true;
|
|
3641
|
+
const nodeOptsOut = !IsCompensationTask(task) && compensation?.isIdempotent === false;
|
|
3642
|
+
const idempotent = actionIdempotent && !nodeOptsOut;
|
|
3643
|
+
if (!idempotent) {
|
|
3644
|
+
LogStatus(`[TaskGraphDispatcher] Not retrying '${task.Name}' (${task.ID}): its action is not marked idempotent.`);
|
|
3645
|
+
return 0;
|
|
3646
|
+
}
|
|
3647
|
+
return requested;
|
|
3648
|
+
}
|
|
3649
|
+
/**
|
|
3650
|
+
* The saga columns of the given actions (`CompensationActionID`, `CompensationInputMapping`,
|
|
3651
|
+
* `IsIdempotent`), read through their typed fields.
|
|
3652
|
+
*/
|
|
3653
|
+
async actionRows(provider, actionIDs) {
|
|
3654
|
+
const byID = new UUIDMap();
|
|
3655
|
+
if (actionIDs.length === 0)
|
|
3656
|
+
return byID;
|
|
3657
|
+
const result = await RunView.FromMetadataProvider(provider).RunView({
|
|
3658
|
+
EntityName: 'MJ: Actions',
|
|
3659
|
+
ExtraFilter: `ID IN (${actionIDs.map((id) => `'${EscapeSQLString(id)}'`).join(',')})`,
|
|
3660
|
+
Fields: ['ID', 'CompensationActionID', 'CompensationInputMapping', 'IsIdempotent'],
|
|
3661
|
+
ResultType: 'simple',
|
|
3662
|
+
}, this.contextUser);
|
|
3663
|
+
if (!result.Success) {
|
|
3664
|
+
LogError(`[TaskGraphDispatcher] Could not read action saga settings: ${result.ErrorMessage}`);
|
|
3665
|
+
return byID;
|
|
3666
|
+
}
|
|
3667
|
+
for (const row of result.Results ?? [])
|
|
3668
|
+
byID.Set(row.ID, row);
|
|
3669
|
+
return byID;
|
|
3670
|
+
}
|
|
3671
|
+
/**
|
|
3672
|
+
* The parent rollup while a saga still has work (S7): every forward step can be terminal while a
|
|
3673
|
+
* compensation is yet to be created or run, and settling then would mark the graph `Failed` (and
|
|
3674
|
+
* announce it) with the rollback unfinished, or never started. Such a graph stays `In Progress`.
|
|
3675
|
+
*/
|
|
3676
|
+
rollupWhileCompensating(rollup, sagaPending) {
|
|
3677
|
+
if (!sagaPending || rollup.outcome !== 'settled') {
|
|
3678
|
+
return rollup;
|
|
3679
|
+
}
|
|
3680
|
+
return { status: 'In Progress', percentComplete: rollup.percentComplete, outcome: 'active' };
|
|
3681
|
+
}
|
|
3682
|
+
/**
|
|
3683
|
+
* Drives a graph's saga one move per pass (WS-4.3), when its `failurePolicy` is
|
|
3684
|
+
* `'CompensateCompleted'` and a forward step failed unhandled.
|
|
3685
|
+
*
|
|
3686
|
+
* Every decision is recomputed from durable rows ({@link NextSagaStep}), so any dispatcher picks up
|
|
3687
|
+
* where another left off, and every write is one that cannot be raced into a wrong state: the
|
|
3688
|
+
* remaining forward steps are skipped through the guarded `TrySkipPending` (and the claim filter
|
|
3689
|
+
* already refuses them, see `sagaHoldsForwardWork`), and each compensation or escalation row is
|
|
3690
|
+
* inserted with `CompensatesTaskID`, whose unique index lets exactly one dispatcher create it.
|
|
3691
|
+
*
|
|
3692
|
+
* @returns the graph (reloaded whenever this pass tried to insert a row, won or lost) and whether the
|
|
3693
|
+
* saga still has work, so the caller does not settle the parent under it
|
|
3694
|
+
*/
|
|
3695
|
+
async coordinateSagaCompensation(provider, parentID, graph, debug) {
|
|
3696
|
+
if (!this.sagaHoldsForwardWork(graph)) {
|
|
3697
|
+
return { Graph: graph, Pending: false };
|
|
3698
|
+
}
|
|
3699
|
+
const forwardTasks = [...graph.entityById.values()].filter((t) => !IsCompensationTask(t));
|
|
3700
|
+
const snapshotHolds = await this.skipRemainingForwardTasks(provider, graph, forwardTasks);
|
|
3701
|
+
// A forward step still running may yet complete — and then needs compensating too. One claimed
|
|
3702
|
+
// elsewhere since this pass loaded the graph still reads Pending here; the next pass sees it.
|
|
3703
|
+
if (!snapshotHolds || forwardTasks.some((t) => t.Status === 'In Progress')) {
|
|
3704
|
+
return { Graph: graph, Pending: true };
|
|
3705
|
+
}
|
|
3706
|
+
const completedActionIDs = forwardTasks.filter((t) => t.Status === 'Complete' && t.ActionID).map((t) => t.ActionID);
|
|
3707
|
+
const actionDefaults = new UUIDMap();
|
|
3708
|
+
for (const [id, row] of await this.actionRows(provider, completedActionIDs)) {
|
|
3709
|
+
const meta = ReadActionCompensationMetadata(row);
|
|
3710
|
+
if (meta)
|
|
3711
|
+
actionDefaults.Set(id, meta);
|
|
3712
|
+
}
|
|
3713
|
+
const plan = SelectTasksToCompensate(forwardTasks, actionDefaults, graph.rawDependencies);
|
|
3714
|
+
const rows = IndexCompensationRows([...graph.entityById.values()]);
|
|
3715
|
+
const step = NextSagaStep({
|
|
3716
|
+
Plan: plan,
|
|
3717
|
+
CompensationFor: (id) => rows.Compensations.Get(id),
|
|
3718
|
+
EscalationFor: (id) => rows.Escalations.Get(id),
|
|
3719
|
+
});
|
|
3720
|
+
switch (step.Kind) {
|
|
3721
|
+
case 'Wait':
|
|
3722
|
+
await this.updateParentSagaState(provider, graph, 'Compensating');
|
|
3723
|
+
return { Graph: graph, Pending: true };
|
|
3724
|
+
case 'Compensate':
|
|
3725
|
+
await this.updateParentSagaState(provider, graph, 'Compensating');
|
|
3726
|
+
await this.materializeCompensation(provider, graph, step.Forward, step.Compensation);
|
|
3727
|
+
// Reloaded whether this insert won or not: a lost insert means another dispatcher's row
|
|
3728
|
+
// exists, and this snapshot does not hold it (S7).
|
|
3729
|
+
return { Graph: await this.loadGraphState(provider, parentID, debug, graph.parent), Pending: true };
|
|
3730
|
+
case 'Escalate':
|
|
3731
|
+
await this.updateParentSagaState(provider, graph, 'CompensationEscalated');
|
|
3732
|
+
await this.escalateCompensationFailure(provider, graph, step.Forward, step.FailedCompensation);
|
|
3733
|
+
return { Graph: await this.loadGraphState(provider, parentID, debug, graph.parent), Pending: true };
|
|
3734
|
+
case 'Finished':
|
|
3735
|
+
await this.updateParentSagaState(provider, graph, step.State);
|
|
3736
|
+
return { Graph: graph, Pending: false };
|
|
3737
|
+
}
|
|
3738
|
+
}
|
|
3739
|
+
/**
|
|
3740
|
+
* Whether a graph is rolling back, so its forward steps must not start: its policy is
|
|
3741
|
+
* `'CompensateCompleted'` and a forward step failed with no drawn route out of the failure. Read from
|
|
3742
|
+
* the rows, so every dispatcher's claim filter agrees.
|
|
3743
|
+
*/
|
|
3744
|
+
sagaHoldsForwardWork(graph) {
|
|
3745
|
+
if (graph.parentMetadata?.failurePolicy !== 'CompensateCompleted') {
|
|
3746
|
+
return false;
|
|
3747
|
+
}
|
|
3748
|
+
return [...graph.entityById.values()].some((t) => !IsCompensationTask(t) && t.Status === 'Failed' && !graph.handledFailureIDs.has(t.ID));
|
|
3749
|
+
}
|
|
3750
|
+
/**
|
|
3751
|
+
* Skips every forward step still `Pending` once the graph is rolling back — independent branches too,
|
|
3752
|
+
* since running new work while undoing old work is what the policy exists to prevent. Guarded on
|
|
3753
|
+
* `Pending` in the statement, so a step another dispatcher claimed meanwhile is left to finish (and
|
|
3754
|
+
* is then compensated), never overwritten.
|
|
3755
|
+
*
|
|
3756
|
+
* @returns false when a skip did not land: that step was claimed elsewhere after this pass loaded
|
|
3757
|
+
* the graph (or the write failed), so this snapshot no longer says what is running, and the
|
|
3758
|
+
* saga must not plan from it — a step about to complete would be compensated out of reverse
|
|
3759
|
+
* order, or after the saga reported itself finished
|
|
3760
|
+
*/
|
|
3761
|
+
async skipRemainingForwardTasks(provider, graph, forwardTasks) {
|
|
3762
|
+
const pending = forwardTasks.filter((t) => t.Status === 'Pending');
|
|
3763
|
+
if (pending.length === 0)
|
|
3764
|
+
return true;
|
|
3765
|
+
const typeID = await this.workflowTaskTypeID(provider);
|
|
3766
|
+
if (!typeID)
|
|
3767
|
+
return true;
|
|
3768
|
+
const nodeByID = IndexByUUID(graph.nodes, (n) => n.id);
|
|
3769
|
+
let allSkipped = true;
|
|
3770
|
+
for (const task of pending) {
|
|
3771
|
+
if (!(await this.claims.TrySkipPending(provider, task.ID, typeID, this.contextUser))) {
|
|
3772
|
+
allSkipped = false;
|
|
3773
|
+
continue;
|
|
3774
|
+
}
|
|
3775
|
+
task.Status = 'Skipped';
|
|
3776
|
+
const node = nodeByID.Get(task.ID);
|
|
3777
|
+
if (node)
|
|
3778
|
+
node.status = 'Skipped';
|
|
3779
|
+
LogStatus(`[TaskGraphDispatcher] Skipped '${task.Name}' (${task.ID}) — the workflow is rolling back.`);
|
|
3780
|
+
}
|
|
3781
|
+
await this.withdrawOpenRequests(provider, pending.filter((t) => t.Status === 'Skipped').map((t) => t.ID), 'The workflow is rolling back, so this step is no longer needed.');
|
|
3782
|
+
return allSkipped;
|
|
3783
|
+
}
|
|
3784
|
+
/**
|
|
3785
|
+
* Creates the compensation task for one forward step, linked by `CompensatesTaskID`. Its unique index
|
|
3786
|
+
* is the claim: when two dispatchers both get here, one insert succeeds and the other finds the
|
|
3787
|
+
* winner's row and treats the step as already materialized. Nothing is written to the forward step.
|
|
3788
|
+
*
|
|
3789
|
+
* A compensation that can never be created (its action does not exist, or the step's envelope cannot
|
|
3790
|
+
* be read) is recorded as a failed one at once ({@link recordUncreatableSagaRow}), so the saga
|
|
3791
|
+
* escalates it rather than waiting. One that failed for a reason that may not repeat (the action
|
|
3792
|
+
* lookup errored, or the insert failed with no other dispatcher's row behind it) is retried on later
|
|
3793
|
+
* passes, and recorded as failed only after {@link SAGA_ROW_WRITE_ATTEMPTS} of them in a row
|
|
3794
|
+
* ({@link retrySagaRowOrRecordFailed}).
|
|
3795
|
+
*
|
|
3796
|
+
* @returns true when this call wrote a row
|
|
3797
|
+
*/
|
|
3798
|
+
async materializeCompensation(provider, graph, forwardTask, compensation) {
|
|
3799
|
+
const action = await this.resolveCompensationActionID(provider, compensation);
|
|
3800
|
+
const compActionID = action.ActionID;
|
|
3801
|
+
const envelope = this.compensationEnvelope(graph, forwardTask);
|
|
3802
|
+
const compTask = await provider.GetEntityObject('MJ: Tasks', this.contextUser);
|
|
3803
|
+
compTask.NewRecord();
|
|
3804
|
+
compTask.ParentID = graph.parentTaskID;
|
|
3805
|
+
compTask.TypeID = forwardTask.TypeID;
|
|
3806
|
+
compTask.Name = `Compensate: ${forwardTask.Name}`;
|
|
3807
|
+
compTask.Description = `Saga compensation for task "${forwardTask.Name}" (${forwardTask.ID}).`;
|
|
3808
|
+
compTask.StepType = 'Action';
|
|
3809
|
+
compTask.Status = 'Pending';
|
|
3810
|
+
compTask.PercentComplete = 0;
|
|
3811
|
+
compTask.ActionID = compActionID;
|
|
3812
|
+
compTask.AgentRunID = forwardTask.AgentRunID ?? graph.parent?.AgentRunID ?? null;
|
|
3813
|
+
compTask.CompensatesTaskID = forwardTask.ID;
|
|
3814
|
+
// An envelope that cannot be read stays as stored, so the row is refused exactly as the step is.
|
|
3815
|
+
compTask.SecurityEnvelope = 'Refusal' in envelope ? forwardTask.SecurityEnvelope : SerializeTaskSecurityEnvelope(envelope.Envelope);
|
|
3816
|
+
const compConfig = {
|
|
3817
|
+
...(compensation.retryCount != null ? { policy: { retryCount: compensation.retryCount } } : {}),
|
|
3818
|
+
compensation: {
|
|
3819
|
+
...(compActionID ? { compensationActionId: compActionID } : {}),
|
|
3820
|
+
...(compensation.onCompensationFailure ? { onCompensationFailure: compensation.onCompensationFailure } : {}),
|
|
3821
|
+
},
|
|
3233
3822
|
};
|
|
3823
|
+
compTask.Configuration = JSON.stringify(compConfig);
|
|
3824
|
+
const cannotRun = !compActionID && action.LookupError === undefined
|
|
3825
|
+
? 'its compensation action could not be resolved'
|
|
3826
|
+
: 'Refusal' in envelope ? `its security envelope cannot be enforced: ${envelope.Refusal}` : null;
|
|
3827
|
+
if (cannotRun) {
|
|
3828
|
+
return this.recordUncreatableSagaRow(provider, compTask, `Cannot compensate '${forwardTask.Name}' (${forwardTask.ID}): ${cannotRun}.`);
|
|
3829
|
+
}
|
|
3830
|
+
if (action.LookupError !== undefined) {
|
|
3831
|
+
return this.retrySagaRowOrRecordFailed(provider, graph, compTask, `Cannot compensate '${forwardTask.Name}' (${forwardTask.ID}): looking up its compensation action failed: ${action.LookupError}.`);
|
|
3832
|
+
}
|
|
3833
|
+
const actingUser = await this.sagaActingUser(provider, graph, forwardTask);
|
|
3834
|
+
const recordChanges = await this.loadCorrelatedRecordChanges(provider, forwardTask, actingUser);
|
|
3835
|
+
compTask.InputPayload = JSON.stringify(this.buildForwardTaskCompensationInput(forwardTask, compensation, recordChanges));
|
|
3836
|
+
if (await this.saveWithRuntimeAuthority(compTask)) {
|
|
3837
|
+
this.sagaRowWriteFailures.Delete(forwardTask.ID);
|
|
3838
|
+
LogStatus(`[TaskGraphDispatcher] Compensating '${forwardTask.Name}' (${forwardTask.ID}) with task ${compTask.ID}.`);
|
|
3839
|
+
return true;
|
|
3840
|
+
}
|
|
3841
|
+
if (await this.rowCompensating(provider, forwardTask.ID)) {
|
|
3842
|
+
this.sagaRowWriteFailures.Delete(forwardTask.ID);
|
|
3843
|
+
LogStatus(`[TaskGraphDispatcher] '${forwardTask.Name}' (${forwardTask.ID}) is already being compensated by another dispatcher.`);
|
|
3844
|
+
return false;
|
|
3845
|
+
}
|
|
3846
|
+
return this.retrySagaRowOrRecordFailed(provider, graph, compTask, `Could not create the compensation task for '${forwardTask.Name}' (${forwardTask.ID}): ${compTask.LatestResult?.CompleteMessage ?? 'unknown error'}.`);
|
|
3847
|
+
}
|
|
3848
|
+
/**
|
|
3849
|
+
* A saga row's write failed for a reason that may not repeat: a lookup that errored, or an insert
|
|
3850
|
+
* that failed with no other dispatcher's row behind it (or with that check failing too). The next
|
|
3851
|
+
* pass retries it; only after {@link SAGA_ROW_WRITE_ATTEMPTS} passes in a row have failed for the
|
|
3852
|
+
* same row is it recorded as failed ({@link recordUncreatableSagaRow}).
|
|
3853
|
+
*
|
|
3854
|
+
* @returns true when this call wrote the failed row
|
|
3855
|
+
*/
|
|
3856
|
+
async retrySagaRowOrRecordFailed(provider, graph, intended, reason) {
|
|
3857
|
+
const key = intended.CompensatesTaskID;
|
|
3858
|
+
const passes = (this.sagaRowWriteFailures.Get(key)?.Passes ?? 0) + 1;
|
|
3859
|
+
this.sagaRowWriteFailures.Set(key, { GraphID: graph.parentTaskID, Passes: passes });
|
|
3860
|
+
if (passes < SAGA_ROW_WRITE_ATTEMPTS) {
|
|
3861
|
+
LogError(`[TaskGraphDispatcher] ${reason} Failed ${passes} of ${SAGA_ROW_WRITE_ATTEMPTS} passes in a row; the next pass retries.`);
|
|
3862
|
+
return false;
|
|
3863
|
+
}
|
|
3864
|
+
return this.recordUncreatableSagaRow(provider, intended, reason);
|
|
3865
|
+
}
|
|
3866
|
+
/**
|
|
3867
|
+
* Records a saga row that cannot be created as intended — a compensation, or the Human step escalating
|
|
3868
|
+
* a failed one — as a `Failed` row carrying the reason. The saga then moves on by its own rules
|
|
3869
|
+
* ({@link NextSagaStep}): a failed compensation escalates to a person (or halts or continues, per its
|
|
3870
|
+
* `onCompensationFailure`), and a failed escalation ends the rollback, so the graph settles. Leaving
|
|
3871
|
+
* the row unwritten kept the graph `In Progress` and its submitting run `Paused` forever, retrying a
|
|
3872
|
+
* write that could not succeed and logging it on every poll.
|
|
3873
|
+
*
|
|
3874
|
+
* The row carries only what the saga reads plus the reason, none of the columns that can make an
|
|
3875
|
+
* insert fail (payload, assignee, action), so it lands where the full row did not. It is claimed by
|
|
3876
|
+
* the same unique `CompensatesTaskID`. When even it cannot be written the database itself is failing,
|
|
3877
|
+
* and the next pass tries again.
|
|
3878
|
+
*
|
|
3879
|
+
* @returns true when this call wrote the row
|
|
3880
|
+
*/
|
|
3881
|
+
async recordUncreatableSagaRow(provider, intended, reason) {
|
|
3882
|
+
const row = await provider.GetEntityObject('MJ: Tasks', this.contextUser);
|
|
3883
|
+
row.NewRecord();
|
|
3884
|
+
const nameLimit = row.EntityInfo?.Fields.find((f) => f.Name === 'Name')?.MaxLength;
|
|
3885
|
+
row.ParentID = intended.ParentID;
|
|
3886
|
+
row.TypeID = intended.TypeID;
|
|
3887
|
+
row.Name = nameLimit ? intended.Name.slice(0, nameLimit) : intended.Name;
|
|
3888
|
+
row.Description = intended.Description;
|
|
3889
|
+
row.StepType = intended.StepType;
|
|
3890
|
+
row.Status = 'Failed';
|
|
3891
|
+
row.PercentComplete = 0;
|
|
3892
|
+
row.CompletedAt = new Date();
|
|
3893
|
+
row.ErrorMessage = reason;
|
|
3894
|
+
row.CompensatesTaskID = intended.CompensatesTaskID;
|
|
3895
|
+
row.SecurityEnvelope = intended.SecurityEnvelope;
|
|
3896
|
+
row.Configuration = intended.Configuration;
|
|
3897
|
+
if (await this.saveWithRuntimeAuthority(row)) {
|
|
3898
|
+
this.sagaRowWriteFailures.Delete(intended.CompensatesTaskID);
|
|
3899
|
+
LogError(`[TaskGraphDispatcher] ${reason} Recorded as failed step ${row.ID} so the rollback can go on.`);
|
|
3900
|
+
return true;
|
|
3901
|
+
}
|
|
3902
|
+
if (!(intended.CompensatesTaskID && await this.rowCompensating(provider, intended.CompensatesTaskID))) {
|
|
3903
|
+
LogError(`[TaskGraphDispatcher] ${reason} Could not record that either (${row.LatestResult?.CompleteMessage ?? 'unknown error'}); the next pass retries.`);
|
|
3904
|
+
}
|
|
3905
|
+
return false;
|
|
3906
|
+
}
|
|
3907
|
+
/**
|
|
3908
|
+
* Asks a person to undo a step by hand after its compensation failed under
|
|
3909
|
+
* `onCompensationFailure: 'EscalateToHumanTask'`: a `Human` step under the graph, assigned to the user
|
|
3910
|
+
* who submitted it, linked to the failed compensation task by `CompensatesTaskID` (unique, so one
|
|
3911
|
+
* escalation per failure however many dispatchers see it). The ordinary human-step machinery then
|
|
3912
|
+
* notifies the person and raises an `MJ: AI Agent Requests` row on behalf of the graph's agent — or,
|
|
3913
|
+
* for a graph with no agent, logs that once and leaves the step in the Tasks UI. Completing the step
|
|
3914
|
+
* resumes the rollback; cancelling it (or letting it expire) stops it (see {@link NextSagaStep}). A step
|
|
3915
|
+
* that cannot be created after {@link SAGA_ROW_WRITE_ATTEMPTS} passes in a row is recorded as a failed
|
|
3916
|
+
* one ({@link retrySagaRowOrRecordFailed}), which stops it too.
|
|
3917
|
+
*
|
|
3918
|
+
* The step carries the forward step's record changes, read as the user the graph's work runs as with
|
|
3919
|
+
* the caller's tenant from the envelope. An envelope that cannot be read carries no tenant
|
|
3920
|
+
* ({@link graphContext}), so that read would run untenanted: the step then gets no record changes.
|
|
3921
|
+
*
|
|
3922
|
+
* @returns true when this call wrote a row
|
|
3923
|
+
*/
|
|
3924
|
+
async escalateCompensationFailure(provider, graph, forwardTask, failedCompensation) {
|
|
3925
|
+
const context = await this.graphContext(provider, forwardTask, { parentTask: graph.parent, parentMetadata: graph.parentMetadata });
|
|
3926
|
+
const actingUser = context.ExecutionUser;
|
|
3927
|
+
const escalation = BuildCompensationEscalationSummary({
|
|
3928
|
+
WorkflowName: graph.parent?.Name ?? graph.parentTaskID,
|
|
3929
|
+
ForwardTask: forwardTask,
|
|
3930
|
+
ForwardInput: this.runtimeActionInput(forwardTask),
|
|
3931
|
+
CompensationTask: failedCompensation,
|
|
3932
|
+
ActionLogID: this.runtimeActionLogID(forwardTask),
|
|
3933
|
+
RecordChanges: 'Refusal' in context.Security ? [] : await this.loadCorrelatedRecordChanges(provider, forwardTask, actingUser),
|
|
3934
|
+
});
|
|
3935
|
+
const human = await provider.GetEntityObject('MJ: Tasks', this.contextUser);
|
|
3936
|
+
human.NewRecord();
|
|
3937
|
+
human.ParentID = graph.parentTaskID;
|
|
3938
|
+
human.TypeID = failedCompensation.TypeID;
|
|
3939
|
+
human.Name = `Undo by hand: ${forwardTask.Name}`;
|
|
3940
|
+
human.Description = escalation.RequestText;
|
|
3941
|
+
human.StepType = 'Human';
|
|
3942
|
+
human.Status = 'Pending';
|
|
3943
|
+
human.PercentComplete = 0;
|
|
3944
|
+
human.UserID = graph.parentMetadata?.submittedByUserID ?? graph.parent?.UserID ?? actingUser.ID;
|
|
3945
|
+
human.CompensatesTaskID = failedCompensation.ID;
|
|
3946
|
+
human.SecurityEnvelope = failedCompensation.SecurityEnvelope;
|
|
3947
|
+
human.InputPayload = JSON.stringify(escalation.ContextData);
|
|
3948
|
+
if (await this.saveWithRuntimeAuthority(human)) {
|
|
3949
|
+
this.sagaRowWriteFailures.Delete(failedCompensation.ID);
|
|
3950
|
+
LogStatus(`[TaskGraphDispatcher] Compensation ${failedCompensation.ID} failed; asked a person to undo '${forwardTask.Name}' (task ${human.ID}).`);
|
|
3951
|
+
return true;
|
|
3952
|
+
}
|
|
3953
|
+
if (await this.rowCompensating(provider, failedCompensation.ID)) {
|
|
3954
|
+
this.sagaRowWriteFailures.Delete(failedCompensation.ID);
|
|
3955
|
+
return false;
|
|
3956
|
+
}
|
|
3957
|
+
return this.retrySagaRowOrRecordFailed(provider, graph, human, `Could not ask a person to undo '${forwardTask.Name}' (${forwardTask.ID}) after compensation ${failedCompensation.ID} failed: ` +
|
|
3958
|
+
`${human.LatestResult?.CompleteMessage ?? 'unknown error'}.`);
|
|
3959
|
+
}
|
|
3960
|
+
/** Whether some task already undoes `taskID` — the row the unique `CompensatesTaskID` index let another dispatcher insert. */
|
|
3961
|
+
async rowCompensating(provider, taskID) {
|
|
3962
|
+
const result = await RunView.FromMetadataProvider(provider).RunView({
|
|
3963
|
+
EntityName: 'MJ: Tasks',
|
|
3964
|
+
ExtraFilter: `CompensatesTaskID='${EscapeSQLString(taskID)}'`,
|
|
3965
|
+
Fields: ['ID'],
|
|
3966
|
+
ResultType: 'simple',
|
|
3967
|
+
BypassCache: true,
|
|
3968
|
+
MaxRows: 1,
|
|
3969
|
+
}, this.contextUser);
|
|
3970
|
+
return result.Success && (result.Results?.length ?? 0) > 0;
|
|
3971
|
+
}
|
|
3972
|
+
/** The user the graph's work runs as (the submitter, stamped with the caller's tenant when the graph carries one). */
|
|
3973
|
+
async sagaActingUser(provider, graph, forwardTask) {
|
|
3974
|
+
const context = await this.graphContext(provider, forwardTask, { parentTask: graph.parent, parentMetadata: graph.parentMetadata });
|
|
3975
|
+
return context.ExecutionUser;
|
|
3976
|
+
}
|
|
3977
|
+
/** The `MJ: Action Execution Logs` row a completed action step recorded (`runtime.actionLogID`). */
|
|
3978
|
+
runtimeActionLogID(task) {
|
|
3979
|
+
return this.parseConfiguration(task)?.runtime?.actionLogID ?? null;
|
|
3980
|
+
}
|
|
3981
|
+
/**
|
|
3982
|
+
* The parameters a completed action step's action was given (`runtime.actionInput`), which the
|
|
3983
|
+
* dispatcher records when the step runs. Not `InputPayload`: that is only the authored input, and
|
|
3984
|
+
* the action's real parameters come from its input mapping over upstream outputs and the envelope.
|
|
3985
|
+
*/
|
|
3986
|
+
runtimeActionInput(task) {
|
|
3987
|
+
return this.parseConfiguration(task)?.runtime?.actionInput ?? {};
|
|
3988
|
+
}
|
|
3989
|
+
/**
|
|
3990
|
+
* The envelope a compensation task is written with: the forward task's constraints, tainted when
|
|
3991
|
+
* the forward task's output carries taint ({@link UpstreamCarriesTaint}, so a forward task that
|
|
3992
|
+
* recorded none is read as tainted when the graph or anything upstream of it could be). A
|
|
3993
|
+
* compensation reads the forward run's input and output, so it runs under exactly what the forward
|
|
3994
|
+
* task ran under, and never less tainted than what it reads.
|
|
3995
|
+
*/
|
|
3996
|
+
compensationEnvelope(graph, forwardTask) {
|
|
3997
|
+
const stored = ResolveStoredNodeSecurity(graph.parent?.SecurityEnvelope, forwardTask.SecurityEnvelope);
|
|
3998
|
+
if ('Refusal' in stored) {
|
|
3999
|
+
return stored;
|
|
4000
|
+
}
|
|
4001
|
+
const graphTainted = stored.Envelope?.IsRunTainted === true;
|
|
4002
|
+
const forwardTainted = UpstreamCarriesTaint(forwardTask, graphTainted, this.upstreamLookupInGraph(graph), graph.parentMetadata?.recordsTaint === true);
|
|
4003
|
+
return { Envelope: forwardTainted ? WithInputTaint(stored.Envelope, true) : stored.Envelope };
|
|
4004
|
+
}
|
|
4005
|
+
/**
|
|
4006
|
+
* Resolves a compensation action UUID from `compensationActionId` or `compensationActionName`.
|
|
4007
|
+
* `ActionID` is null when neither names an action that exists. `LookupError` says the name lookup
|
|
4008
|
+
* itself failed, so whether the action exists is unknown and a later pass may yet find it.
|
|
4009
|
+
*/
|
|
4010
|
+
async resolveCompensationActionID(provider, compMeta) {
|
|
4011
|
+
if (compMeta.compensationActionId?.trim()) {
|
|
4012
|
+
return { ActionID: compMeta.compensationActionId.trim() };
|
|
4013
|
+
}
|
|
4014
|
+
const name = compMeta.compensationActionName?.trim();
|
|
4015
|
+
if (!name)
|
|
4016
|
+
return { ActionID: null };
|
|
4017
|
+
const resolved = await ResolveRecordsByNameOrToolName({
|
|
4018
|
+
EntityName: 'MJ: Actions',
|
|
4019
|
+
Names: [name],
|
|
4020
|
+
Provider: provider,
|
|
4021
|
+
ContextUser: this.contextUser,
|
|
4022
|
+
});
|
|
4023
|
+
if (!resolved.Success) {
|
|
4024
|
+
return { ActionID: null, LookupError: resolved.ErrorMessage || 'unknown error' };
|
|
4025
|
+
}
|
|
4026
|
+
return { ActionID: resolved.Map?.get(name) ?? resolved.Map?.get(name.toLowerCase()) ?? null };
|
|
4027
|
+
}
|
|
4028
|
+
/**
|
|
4029
|
+
* The `MJ: Record Changes` a forward action step made, for its compensation's input and a failed
|
|
4030
|
+
* compensation's escalation. Read as the user the graph's work runs as — never the system user — so
|
|
4031
|
+
* the user's own permissions bound what comes back.
|
|
4032
|
+
*
|
|
4033
|
+
* Bounded to the action's own execution window, `StartedAt`..`EndedAt` of the `MJ: Action Execution
|
|
4034
|
+
* Logs` row the step recorded, and to the user that log ran as. That is the tightest correlation the
|
|
4035
|
+
* data allows: a Record Change carries no action-log or task reference, only who changed what and
|
|
4036
|
+
* when, so a window around the one execution — not the task's whole life, which spans its queueing
|
|
4037
|
+
* and retries — is as close as it gets. Changes the same user made elsewhere inside that window can
|
|
4038
|
+
* still appear; a step with no recorded log gets none.
|
|
4039
|
+
*/
|
|
4040
|
+
async loadCorrelatedRecordChanges(provider, forwardTask, actingUser) {
|
|
4041
|
+
const logID = this.runtimeActionLogID(forwardTask);
|
|
4042
|
+
if (!logID)
|
|
4043
|
+
return [];
|
|
4044
|
+
try {
|
|
4045
|
+
const rv = RunView.FromMetadataProvider(provider);
|
|
4046
|
+
const logs = await rv.RunView({
|
|
4047
|
+
EntityName: 'MJ: Action Execution Logs',
|
|
4048
|
+
ExtraFilter: `ID='${EscapeSQLString(logID)}'`,
|
|
4049
|
+
Fields: ['ID', 'StartedAt', 'EndedAt', 'UserID'],
|
|
4050
|
+
ResultType: 'simple',
|
|
4051
|
+
MaxRows: 1,
|
|
4052
|
+
}, actingUser);
|
|
4053
|
+
const log = logs.Success ? logs.Results?.[0] : undefined;
|
|
4054
|
+
if (!log?.StartedAt || !log.EndedAt)
|
|
4055
|
+
return [];
|
|
4056
|
+
const changes = await rv.RunView({
|
|
4057
|
+
EntityName: 'MJ: Record Changes',
|
|
4058
|
+
ExtraFilter: `UserID='${EscapeSQLString(log.UserID)}' AND ` +
|
|
4059
|
+
`ChangedAt >= '${new Date(log.StartedAt).toISOString()}' AND ChangedAt <= '${new Date(log.EndedAt).toISOString()}'`,
|
|
4060
|
+
Fields: ['ID', 'EntityID', 'Entity', 'RecordID', 'Type', 'ChangesJSON', 'ChangedAt'],
|
|
4061
|
+
OrderBy: 'ChangedAt ASC',
|
|
4062
|
+
MaxRows: 50,
|
|
4063
|
+
ResultType: 'simple',
|
|
4064
|
+
}, actingUser);
|
|
4065
|
+
return changes.Success ? changes.Results ?? [] : [];
|
|
4066
|
+
}
|
|
4067
|
+
catch (e) {
|
|
4068
|
+
LogError(`[TaskGraphDispatcher] Could not read the record changes of task ${forwardTask.ID}: ${e instanceof Error ? e.message : String(e)}`);
|
|
4069
|
+
return [];
|
|
4070
|
+
}
|
|
4071
|
+
}
|
|
4072
|
+
/**
|
|
4073
|
+
* Builds the compensation input payload from a completed forward task's input (the parameters its
|
|
4074
|
+
* action was given, {@link runtimeActionInput}), output, runtime log ID, and correlated
|
|
4075
|
+
* `MJ: Record Changes` rows.
|
|
4076
|
+
*/
|
|
4077
|
+
buildForwardTaskCompensationInput(forwardTask, compMeta, recordChanges) {
|
|
4078
|
+
const forwardInput = this.runtimeActionInput(forwardTask);
|
|
4079
|
+
let forwardOutput = {};
|
|
4080
|
+
if (forwardTask.OutputPayload) {
|
|
4081
|
+
try {
|
|
4082
|
+
const parsedOutput = JSON.parse(forwardTask.OutputPayload);
|
|
4083
|
+
if (parsedOutput && typeof parsedOutput === 'object' && !Array.isArray(parsedOutput)) {
|
|
4084
|
+
forwardOutput = parsedOutput;
|
|
4085
|
+
}
|
|
4086
|
+
}
|
|
4087
|
+
catch {
|
|
4088
|
+
// Non-object output payloads default to `{}`
|
|
4089
|
+
}
|
|
4090
|
+
}
|
|
4091
|
+
return BuildCompensationInputPayload({
|
|
4092
|
+
ForwardInput: forwardInput,
|
|
4093
|
+
ForwardOutput: forwardOutput,
|
|
4094
|
+
ActionLogID: this.runtimeActionLogID(forwardTask),
|
|
4095
|
+
RecordChanges: recordChanges,
|
|
4096
|
+
InputMapping: compMeta.inputMapping,
|
|
4097
|
+
});
|
|
4098
|
+
}
|
|
4099
|
+
/**
|
|
4100
|
+
* Records the saga's state on the parent (`InputPayload.sagaState`) for anyone reading the graph.
|
|
4101
|
+
*
|
|
4102
|
+
* Written through the guarded, type-scoped single-field write and nothing else: a full-row save of the
|
|
4103
|
+
* parent would carry this pass's snapshot of `InputPayload` and could erase a continuation marker or a
|
|
4104
|
+
* debug field another dispatcher wrote meanwhile (R2-14, R3-1). The state is informational — every saga
|
|
4105
|
+
* decision is recomputed from the rows — so a write that does not land is retried on the next pass.
|
|
4106
|
+
*/
|
|
4107
|
+
async updateParentSagaState(provider, graph, nextState) {
|
|
4108
|
+
if (graph.parentMetadata?.sagaState === nextState)
|
|
4109
|
+
return;
|
|
4110
|
+
const typeID = await this.workflowTaskTypeID(provider);
|
|
4111
|
+
if (!typeID)
|
|
4112
|
+
return;
|
|
4113
|
+
const wrote = await this.claims.TryWriteDebugFields(provider, graph.parentTaskID, [TaskClaimStore.DebugField('$.sagaState', { Kind: 'string', Value: nextState })], typeID, this.contextUser);
|
|
4114
|
+
if (wrote && graph.parentMetadata) {
|
|
4115
|
+
graph.parentMetadata.sagaState = nextState;
|
|
4116
|
+
}
|
|
4117
|
+
else if (!wrote) {
|
|
4118
|
+
LogError(`[TaskGraphDispatcher] Could not record sagaState='${nextState}' on graph ${graph.parentTaskID}; the next pass retries.`);
|
|
4119
|
+
}
|
|
3234
4120
|
}
|
|
3235
4121
|
/**
|
|
3236
4122
|
* Runs a loop step: its body once per iteration, with the item and index in scope.
|
|
@@ -3240,7 +4126,7 @@ export class TaskGraphDispatcher {
|
|
|
3240
4126
|
* merged into the payload before the mapping is applied, which is how a body can reference the
|
|
3241
4127
|
* current item at all.
|
|
3242
4128
|
*/
|
|
3243
|
-
async runLoopTask(task, provider, payload, dependencyOutputs,
|
|
4129
|
+
async runLoopTask(task, provider, payload, dependencyOutputs, graphContext, startEnvelope) {
|
|
3244
4130
|
const config = task.ConfigurationObject;
|
|
3245
4131
|
const op = task.StepType === 'ForEach' ? config?.forEach : config?.while;
|
|
3246
4132
|
if (!op) {
|
|
@@ -3262,13 +4148,22 @@ export class TaskGraphDispatcher {
|
|
|
3262
4148
|
// the shared payload instead, each overwriting the last, and the mapping matched nothing and
|
|
3263
4149
|
// wrote nothing. A ForEach over five items reported five successes and kept item five.
|
|
3264
4150
|
const bodyOutputMapping = op.action?.outputMapping ?? op.prompt?.outputMapping;
|
|
3265
|
-
// Where this step sits in its graph, resolved ONCE
|
|
3266
|
-
// dispatched exactly like a one-shot step and needs the same two
|
|
3267
|
-
// submitted the graph (so a spawned run gets a ParentRunID and is visible
|
|
3268
|
-
// cost), and the continuation depth (so the recursion cap still applies).
|
|
3269
|
-
// loop bodies second-class in every dimension — and reopened the
|
|
3270
|
-
// THROUGH loops, since each spawned run restarted the chain at zero.
|
|
3271
|
-
|
|
4151
|
+
// Where this step sits in its graph (`graphContext`), resolved ONCE by the caller rather than
|
|
4152
|
+
// per iteration. A loop body is dispatched exactly like a one-shot step and needs the same two
|
|
4153
|
+
// things: the run that submitted the graph (so a spawned run gets a ParentRunID and is visible
|
|
4154
|
+
// to the tree and to cost), and the continuation depth (so the recursion cap still applies).
|
|
4155
|
+
// Omitting them made loop bodies second-class in every dimension — and reopened the
|
|
4156
|
+
// unbounded-recursion hole THROUGH loops, since each spawned run restarted the chain at zero.
|
|
4157
|
+
if ('Refusal' in startEnvelope) {
|
|
4158
|
+
return this.refusedNode(task, startEnvelope.Refusal);
|
|
4159
|
+
}
|
|
4160
|
+
// Monotonic across passes as well as across nodes: once a pass reports tainted output, every
|
|
4161
|
+
// later pass reads it through the running payload, so it runs tainted too.
|
|
4162
|
+
let loopEnvelope = startEnvelope.Envelope;
|
|
4163
|
+
const markLoopTainted = () => {
|
|
4164
|
+
loopEnvelope = WithInputTaint(loopEnvelope, true);
|
|
4165
|
+
};
|
|
4166
|
+
const executionProvider = provider;
|
|
3272
4167
|
// Pre-resolve ActionIDs once for multi-step action bodies (`op.steps[]`). Submit stamps
|
|
3273
4168
|
// `config.stepActionIds`; fallback RunView covers callers constructing Task rows directly.
|
|
3274
4169
|
const multiSteps = op.steps && op.steps.length > 0 ? op.steps : null;
|
|
@@ -3277,7 +4172,7 @@ export class TaskGraphDispatcher {
|
|
|
3277
4172
|
if (!this.actionRunner) {
|
|
3278
4173
|
return { Success: false, AgentRunID: null, ErrorMessage: 'No action runner is loaded on this host.' };
|
|
3279
4174
|
}
|
|
3280
|
-
const resolvedIds = await this.resolveLoopStepActionIds(multiSteps, config?.stepActionIds, task.ActionID,
|
|
4175
|
+
const resolvedIds = await this.resolveLoopStepActionIds(multiSteps, config?.stepActionIds, task.ActionID, executionProvider, graphContext.ExecutionUser);
|
|
3281
4176
|
if (!resolvedIds.Success || !resolvedIds.Map) {
|
|
3282
4177
|
return { Success: false, AgentRunID: null, ErrorMessage: resolvedIds.ErrorMessage };
|
|
3283
4178
|
}
|
|
@@ -3314,11 +4209,13 @@ export class TaskGraphDispatcher {
|
|
|
3314
4209
|
deferLivePayloadFold: isParallelForEach,
|
|
3315
4210
|
deferredFoldsByIndex,
|
|
3316
4211
|
dependencyOutputs,
|
|
3317
|
-
provider,
|
|
4212
|
+
provider: executionProvider,
|
|
3318
4213
|
executionUser: graphContext.ExecutionUser,
|
|
3319
4214
|
invocation: graphContext.Invocation,
|
|
3320
4215
|
iterationTrace,
|
|
3321
4216
|
budget,
|
|
4217
|
+
securityEnvelope: loopEnvelope,
|
|
4218
|
+
onIterationTainted: markLoopTainted,
|
|
3322
4219
|
});
|
|
3323
4220
|
}
|
|
3324
4221
|
// Bindings go INTO `iterationPayload` AND are passed explicitly to `ResolveLoopBodyParams`,
|
|
@@ -3326,10 +4223,14 @@ export class TaskGraphDispatcher {
|
|
|
3326
4223
|
// `data.*`, `context.*`, `static:*`) AND the unified ForEachOperation/WhileOperation dialect
|
|
3327
4224
|
// (`<itemVar>.*`, `{{<itemVar>.*}}`, inline `{{...}}`) while keeping unresolved paths/tokens literal.
|
|
3328
4225
|
const iterationPayload = { ...livePayload, ...Bindings };
|
|
3329
|
-
const
|
|
4226
|
+
const rawResolved = ResolveLoopBodyParams(bodyMapping, Bindings, {
|
|
3330
4227
|
payload: iterationPayload,
|
|
3331
4228
|
...graphContext.Invocation,
|
|
3332
4229
|
});
|
|
4230
|
+
const envelope = loopEnvelope;
|
|
4231
|
+
const resolved = task.ActionID
|
|
4232
|
+
? ApplyTaskSecurityEnvelopeToParams(rawResolved, envelope, task.ActionID).Params
|
|
4233
|
+
: rawResolved;
|
|
3333
4234
|
/**
|
|
3334
4235
|
* Folds an iteration's output into the running payload the next pass will see, and
|
|
3335
4236
|
* records what the pass produced.
|
|
@@ -3339,6 +4240,9 @@ export class TaskGraphDispatcher {
|
|
|
3339
4240
|
* because the loop as a whole did not finish.
|
|
3340
4241
|
*/
|
|
3341
4242
|
const absorb = (outcome, bodyInput) => {
|
|
4243
|
+
if (outcome.IsOutputTainted) {
|
|
4244
|
+
markLoopTainted();
|
|
4245
|
+
}
|
|
3342
4246
|
livePayload = this.foldIterationOutput(task, livePayload, outcome.Output, bodyOutputMapping);
|
|
3343
4247
|
iterationTrace.push({
|
|
3344
4248
|
index: Index,
|
|
@@ -3396,18 +4300,24 @@ export class TaskGraphDispatcher {
|
|
|
3396
4300
|
// getting it wrong is silent: the variable renders empty and the model answers
|
|
3397
4301
|
// confidently about nothing.
|
|
3398
4302
|
TemplateParameters: { ...stringifyBindings(Bindings), ...op.prompt?.templateParameters },
|
|
3399
|
-
Provider:
|
|
4303
|
+
Provider: executionProvider,
|
|
3400
4304
|
ContextUser: graphContext.ExecutionUser,
|
|
4305
|
+
...(envelope ? { SecurityEnvelope: envelope } : {}),
|
|
3401
4306
|
}), iterationPayload);
|
|
3402
4307
|
}
|
|
4308
|
+
const refusal = this.securityRefusal(task, { Envelope: envelope }, task.ActionID ? this.actionRunner?.EnforcesSecurityEnvelope : this.agentRunner.EnforcesSecurityEnvelope);
|
|
4309
|
+
if (refusal) {
|
|
4310
|
+
return refusal;
|
|
4311
|
+
}
|
|
3403
4312
|
if (task.ActionID) {
|
|
3404
4313
|
return absorb(await this.actionRunner.RunActionForTask({
|
|
3405
4314
|
TaskID: task.ID,
|
|
3406
4315
|
ActionID: task.ActionID,
|
|
3407
4316
|
InputPayload: resolved,
|
|
3408
4317
|
DependencyOutputs: dependencyOutputs,
|
|
3409
|
-
Provider:
|
|
4318
|
+
Provider: executionProvider,
|
|
3410
4319
|
ContextUser: graphContext.ExecutionUser,
|
|
4320
|
+
...(envelope ? { SecurityEnvelope: envelope } : {}),
|
|
3411
4321
|
}), resolved);
|
|
3412
4322
|
}
|
|
3413
4323
|
const agentInput = Object.keys(resolved).length > 0 ? resolved : iterationPayload;
|
|
@@ -3422,13 +4332,14 @@ export class TaskGraphDispatcher {
|
|
|
3422
4332
|
ContinuationDepth: graphContext.Depth,
|
|
3423
4333
|
SubmittingAgentRunID: graphContext.SubmittingAgentRunID,
|
|
3424
4334
|
...(graphContext.ParentAgentHierarchy ? { ParentAgentHierarchy: graphContext.ParentAgentHierarchy } : {}),
|
|
3425
|
-
Provider:
|
|
4335
|
+
Provider: executionProvider,
|
|
3426
4336
|
ContextUser: graphContext.ExecutionUser,
|
|
4337
|
+
...(envelope ? { SecurityEnvelope: envelope } : {}),
|
|
3427
4338
|
}), agentInput);
|
|
3428
4339
|
};
|
|
3429
4340
|
const evaluator = this.conditionEvaluator ?? new DispatcherConditionEvaluator();
|
|
3430
4341
|
const outcome = task.StepType === 'ForEach'
|
|
3431
|
-
? await RunForEachLoop(op, { payload, ...graphContext.Invocation }, invokeBody)
|
|
4342
|
+
? await RunForEachLoop(op, { payload: livePayload, ...graphContext.Invocation }, invokeBody)
|
|
3432
4343
|
: await RunWhileLoop(op, (iteration) => evaluator.Evaluate(op.condition,
|
|
3433
4344
|
// BOTH forms, because a workflow should not have two condition dialects. An
|
|
3434
4345
|
// EDGE condition is written `payload.brandOK !== true`; a loop condition used
|
|
@@ -3461,6 +4372,7 @@ export class TaskGraphDispatcher {
|
|
|
3461
4372
|
// pass inside `foldIterationOutput`; applying it again against the accumulated payload
|
|
3462
4373
|
// is what used to make it match nothing.
|
|
3463
4374
|
Output: this.applyStepOutputMapping(task, livePayload, outcome.Output, config?.outputMapping),
|
|
4375
|
+
IsOutputTainted: loopEnvelope?.IsRunTainted === true,
|
|
3464
4376
|
};
|
|
3465
4377
|
}
|
|
3466
4378
|
/**
|
|
@@ -3504,7 +4416,7 @@ export class TaskGraphDispatcher {
|
|
|
3504
4416
|
* `outputMapping` declarations into the loop's running payload.
|
|
3505
4417
|
*/
|
|
3506
4418
|
async executeMultiStepLoopPass(args) {
|
|
3507
|
-
const { task, op, steps, stepActionIds, index, bindings, getLivePayload, setLivePayload, deferLivePayloadFold, deferredFoldsByIndex, dependencyOutputs, provider, executionUser, invocation, iterationTrace, budget, } = args;
|
|
4419
|
+
const { task, op, steps, stepActionIds, index, bindings, getLivePayload, setLivePayload, deferLivePayloadFold, deferredFoldsByIndex, dependencyOutputs, provider, executionUser, invocation, iterationTrace, budget, securityEnvelope, onIterationTainted, } = args;
|
|
3508
4420
|
const evaluator = this.conditionEvaluator ?? new DispatcherConditionEvaluator();
|
|
3509
4421
|
const stepsOutputs = {};
|
|
3510
4422
|
const stepInputsTrace = {};
|
|
@@ -3514,6 +4426,8 @@ export class TaskGraphDispatcher {
|
|
|
3514
4426
|
let workingPayload = structuredClone(getLivePayload());
|
|
3515
4427
|
let lastActionLogID;
|
|
3516
4428
|
let lastStepOutput;
|
|
4429
|
+
// A later step reads an earlier step's output, so taint is monotonic within the pass too.
|
|
4430
|
+
let stepEnvelope = securityEnvelope;
|
|
3517
4431
|
for (let stepIdx = 0; stepIdx < steps.length; stepIdx++) {
|
|
3518
4432
|
const step = steps[stepIdx];
|
|
3519
4433
|
const stepKey = step.id?.trim() || `step_${stepIdx}`;
|
|
@@ -3555,9 +4469,26 @@ export class TaskGraphDispatcher {
|
|
|
3555
4469
|
}
|
|
3556
4470
|
}
|
|
3557
4471
|
const stepPayload = { ...workingPayload, ...stepBindings };
|
|
3558
|
-
const
|
|
3559
|
-
stepInputsTrace[stepKey] = resolvedParams;
|
|
4472
|
+
const rawResolvedParams = ResolveLoopBodyParams(step.params ?? {}, stepBindings, { payload: stepPayload, ...invocation });
|
|
3560
4473
|
const actionId = stepActionIds.get(step.name);
|
|
4474
|
+
const resolvedParams = ApplyTaskSecurityEnvelopeToParams(rawResolvedParams, stepEnvelope, actionId).Params;
|
|
4475
|
+
stepInputsTrace[stepKey] = resolvedParams;
|
|
4476
|
+
const gateRejection = this.securityRefusal(task, { Envelope: stepEnvelope }, this.actionRunner?.EnforcesSecurityEnvelope);
|
|
4477
|
+
if (gateRejection) {
|
|
4478
|
+
iterationTrace.push({
|
|
4479
|
+
index,
|
|
4480
|
+
payloadAtStart: budget.Take(stepInputsTrace),
|
|
4481
|
+
payloadAtEnd: budget.Take({ steps: stepsOutputs }),
|
|
4482
|
+
actionLogID: lastActionLogID,
|
|
4483
|
+
success: false,
|
|
4484
|
+
errorMessage: gateRejection.ErrorMessage,
|
|
4485
|
+
});
|
|
4486
|
+
return {
|
|
4487
|
+
Success: false,
|
|
4488
|
+
ErrorMessage: gateRejection.ErrorMessage,
|
|
4489
|
+
ActionLogID: lastActionLogID,
|
|
4490
|
+
};
|
|
4491
|
+
}
|
|
3561
4492
|
const actionOutcome = await this.actionRunner.RunActionForTask({
|
|
3562
4493
|
TaskID: task.ID,
|
|
3563
4494
|
ActionID: actionId,
|
|
@@ -3565,10 +4496,15 @@ export class TaskGraphDispatcher {
|
|
|
3565
4496
|
DependencyOutputs: dependencyOutputs,
|
|
3566
4497
|
Provider: provider,
|
|
3567
4498
|
ContextUser: executionUser,
|
|
4499
|
+
...(stepEnvelope ? { SecurityEnvelope: stepEnvelope } : {}),
|
|
3568
4500
|
});
|
|
3569
4501
|
if (actionOutcome.ActionLogID) {
|
|
3570
4502
|
lastActionLogID = actionOutcome.ActionLogID;
|
|
3571
4503
|
}
|
|
4504
|
+
if (actionOutcome.IsOutputTainted) {
|
|
4505
|
+
stepEnvelope = WithInputTaint(stepEnvelope, true);
|
|
4506
|
+
onIterationTainted?.();
|
|
4507
|
+
}
|
|
3572
4508
|
if (!actionOutcome.Success) {
|
|
3573
4509
|
const errMsg = actionOutcome.ErrorMessage || `Loop step "${stepKey}" (${step.name}) failed`;
|
|
3574
4510
|
iterationTrace.push({
|
|
@@ -3710,7 +4646,7 @@ export class TaskGraphDispatcher {
|
|
|
3710
4646
|
* Depth and provenance are read together because they come from the same row: the graph's parent
|
|
3711
4647
|
* task knows both how many continuation hops led here and which run submitted it.
|
|
3712
4648
|
*/
|
|
3713
|
-
async runAgentNode(task, provider, effectiveInput, dependencyOutputs, onProgress, resolvedContext) {
|
|
4649
|
+
async runAgentNode(task, provider, effectiveInput, dependencyOutputs, onProgress, resolvedContext, securityEnvelope) {
|
|
3714
4650
|
const context = resolvedContext ?? await this.graphContext(provider, task);
|
|
3715
4651
|
const presetName = task.ConfigurationObject?.agent?.presetName?.trim() || undefined;
|
|
3716
4652
|
return this.agentRunner.RunAgentForTask({
|
|
@@ -3725,6 +4661,7 @@ export class TaskGraphDispatcher {
|
|
|
3725
4661
|
Provider: provider,
|
|
3726
4662
|
ContextUser: context.ExecutionUser,
|
|
3727
4663
|
OnProgress: onProgress,
|
|
4664
|
+
...(securityEnvelope ? { SecurityEnvelope: securityEnvelope } : {}),
|
|
3728
4665
|
});
|
|
3729
4666
|
}
|
|
3730
4667
|
/**
|
|
@@ -3741,7 +4678,7 @@ export class TaskGraphDispatcher {
|
|
|
3741
4678
|
* and the call asks only the rest. If that call fails, or cannot be made, the step stays
|
|
3742
4679
|
* `Complete` with the same usable answers, and the questions it asked again hold with the reason.
|
|
3743
4680
|
*/
|
|
3744
|
-
async runDecisionNode(task, provider, payload,
|
|
4681
|
+
async runDecisionNode(task, provider, payload, context, onProgress) {
|
|
3745
4682
|
const config = ReadDecisionStepConfiguration(task.Configuration);
|
|
3746
4683
|
if (!config)
|
|
3747
4684
|
return this.decisionNotAsked(task, payload, 'it has no decision settings, so there is nothing to ask');
|
|
@@ -3758,7 +4695,9 @@ export class TaskGraphDispatcher {
|
|
|
3758
4695
|
const conflict = DecisionsPayloadConflict(payload);
|
|
3759
4696
|
if (conflict)
|
|
3760
4697
|
return notAsked(conflict);
|
|
3761
|
-
|
|
4698
|
+
if ('Refusal' in context.Security) {
|
|
4699
|
+
return this.refusedNode(task, context.Security.Refusal);
|
|
4700
|
+
}
|
|
3762
4701
|
const startedAt = new Date();
|
|
3763
4702
|
const result = await this.decisionRunner.RunDecisionForTask({
|
|
3764
4703
|
TaskID: task.ID,
|
|
@@ -4235,8 +5174,10 @@ export class TaskGraphDispatcher {
|
|
|
4235
5174
|
task.Configuration = JSON.stringify(merged);
|
|
4236
5175
|
tasksToSave.push(task);
|
|
4237
5176
|
}
|
|
5177
|
+
// In the dispatcher's scope: these in-memory rows can carry a status a guarded skip already wrote, and a
|
|
5178
|
+
// workflow step's status is the dispatcher's (`MJTaskEntityServer`).
|
|
4238
5179
|
await Promise.all(tasksToSave.map(async (task) => {
|
|
4239
|
-
if (!(await
|
|
5180
|
+
if (!(await this.saveWithRuntimeAuthority(task))) {
|
|
4240
5181
|
LogError(`[TaskGraphDispatcher] Could not save computed layout for ${task.ID}: ${task.LatestResult?.CompleteMessage ?? 'unknown error'}`);
|
|
4241
5182
|
}
|
|
4242
5183
|
}));
|
|
@@ -4274,8 +5215,8 @@ export class TaskGraphDispatcher {
|
|
|
4274
5215
|
* Returns `undefined` when there is nothing to record, so the guarded write omits the column
|
|
4275
5216
|
* rather than rewriting it with what it already held.
|
|
4276
5217
|
*/
|
|
4277
|
-
configurationWithRuntime(task, promptRunID, actionLogID, iterations, payloadAtStart) {
|
|
4278
|
-
if (!promptRunID && !actionLogID && !iterations?.length && !payloadAtStart)
|
|
5218
|
+
configurationWithRuntime(task, promptRunID, actionLogID, iterations, payloadAtStart, isOutputTainted, actionInput) {
|
|
5219
|
+
if (!promptRunID && !actionLogID && !iterations?.length && !payloadAtStart && isOutputTainted === undefined && !actionInput)
|
|
4279
5220
|
return undefined;
|
|
4280
5221
|
const existing = this.parseConfiguration(task);
|
|
4281
5222
|
const merged = {
|
|
@@ -4292,6 +5233,10 @@ export class TaskGraphDispatcher {
|
|
|
4292
5233
|
// against. NOT written to Task.InputPayload, which holds the AUTHORED input and
|
|
4293
5234
|
// round-trips back out as part of the spec.
|
|
4294
5235
|
...(payloadAtStart ? { payloadAtStart } : {}),
|
|
5236
|
+
// Written true OR false: "ran clean" must be told apart from "never ran" (UpstreamCarriesTaint).
|
|
5237
|
+
...(isOutputTainted !== undefined ? { isOutputTainted } : {}),
|
|
5238
|
+
// What the action was actually given, which its compensation's `input.*` reads.
|
|
5239
|
+
...(actionInput ? { actionInput } : {}),
|
|
4295
5240
|
},
|
|
4296
5241
|
};
|
|
4297
5242
|
return JSON.stringify(merged);
|