@gobing-ai/ts-dual-workflow-engine 0.5.12 → 0.5.15
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/README.md +23 -22
- package/dist/action-step.d.ts +1 -0
- package/dist/action-step.d.ts.map +1 -1
- package/dist/action-step.js +1 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +137 -3
- package/dist/dag.d.ts +25 -0
- package/dist/dag.d.ts.map +1 -0
- package/dist/dag.js +215 -0
- package/dist/events.d.ts +33 -0
- package/dist/events.d.ts.map +1 -1
- package/dist/host.d.ts.map +1 -1
- package/dist/host.js +4 -3
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/persistence.d.ts +24 -1
- package/dist/persistence.d.ts.map +1 -1
- package/dist/persistence.js +91 -0
- package/dist/run-lifecycle.d.ts +8 -0
- package/dist/run-lifecycle.d.ts.map +1 -1
- package/dist/run-lifecycle.js +71 -2
- package/dist/schema-sql.d.ts.map +1 -1
- package/dist/schema-sql.js +20 -0
- package/dist/schema.d.ts +180 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +101 -14
- package/dist/service.d.ts.map +1 -1
- package/dist/service.js +17 -3
- package/dist/transition-flow.d.ts.map +1 -1
- package/dist/transition-flow.js +191 -0
- package/dist/types.d.ts +90 -2
- package/dist/types.d.ts.map +1 -1
- package/package.json +4 -4
- package/schemas/dag-workflow.schema.json +93 -0
- package/schemas/transition-flow-workflow.schema.json +34 -0
- package/src/action-step.ts +2 -0
- package/src/config.ts +152 -5
- package/src/dag.ts +297 -0
- package/src/events.ts +33 -0
- package/src/host.ts +4 -2
- package/src/index.ts +6 -0
- package/src/persistence.ts +155 -0
- package/src/run-lifecycle.ts +75 -2
- package/src/schema-sql.ts +20 -0
- package/src/schema.ts +104 -16
- package/src/service.ts +24 -7
- package/src/transition-flow.ts +271 -0
- package/src/types.ts +109 -2
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
|
+
"$id": "https://raw.githubusercontent.com/gobing-ai/ts-libs/main/packages/dual-workflow-engine/schemas/dag-workflow.schema.json",
|
|
4
|
+
"title": "@gobing-ai/ts-dual-workflow-engine Static Dependency DAG Workflow",
|
|
5
|
+
"type": "object",
|
|
6
|
+
"additionalProperties": false,
|
|
7
|
+
"required": ["kind", "name", "nodes"],
|
|
8
|
+
"properties": {
|
|
9
|
+
"$schema": { "type": "string" },
|
|
10
|
+
"kind": { "const": "dag" },
|
|
11
|
+
"name": { "type": "string", "minLength": 1 },
|
|
12
|
+
"version": { "type": "string" },
|
|
13
|
+
"description": { "type": "string" },
|
|
14
|
+
"iterationBound": { "type": "integer", "exclusiveMinimum": 0 },
|
|
15
|
+
"defaultOnError": { "enum": ["fail", "continue"] },
|
|
16
|
+
"vars": {
|
|
17
|
+
"type": "object",
|
|
18
|
+
"propertyNames": { "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" },
|
|
19
|
+
"additionalProperties": { "type": "string" }
|
|
20
|
+
},
|
|
21
|
+
"env": {
|
|
22
|
+
"type": "object",
|
|
23
|
+
"additionalProperties": false,
|
|
24
|
+
"properties": {
|
|
25
|
+
"allow": { "type": "array", "items": { "type": "string", "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" } }
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
"nodes": {
|
|
29
|
+
"type": "array",
|
|
30
|
+
"items": {
|
|
31
|
+
"type": "object",
|
|
32
|
+
"additionalProperties": false,
|
|
33
|
+
"required": ["id"],
|
|
34
|
+
"properties": {
|
|
35
|
+
"id": { "type": "string", "minLength": 1 },
|
|
36
|
+
"description": { "type": "string" },
|
|
37
|
+
"action": { "$ref": "#/$defs/action" },
|
|
38
|
+
"dependsOn": {
|
|
39
|
+
"type": "array",
|
|
40
|
+
"items": { "type": "string", "minLength": 1 }
|
|
41
|
+
},
|
|
42
|
+
"dependencyPolicy": { "enum": ["all", "any"] },
|
|
43
|
+
"condition": { "$ref": "#/$defs/guard" },
|
|
44
|
+
"pause": { "type": "boolean" },
|
|
45
|
+
"resumeRerun": { "type": "boolean" }
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
"extensions": { "$ref": "#/$defs/extensions" }
|
|
50
|
+
},
|
|
51
|
+
"$defs": {
|
|
52
|
+
"action": {
|
|
53
|
+
"type": "object",
|
|
54
|
+
"additionalProperties": false,
|
|
55
|
+
"required": ["kind"],
|
|
56
|
+
"properties": {
|
|
57
|
+
"kind": { "type": "string", "minLength": 1 },
|
|
58
|
+
"options": { "type": "object", "additionalProperties": true },
|
|
59
|
+
"onError": { "enum": ["fail", "continue"] }
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
"guard": {
|
|
63
|
+
"type": "object",
|
|
64
|
+
"additionalProperties": false,
|
|
65
|
+
"required": ["kind"],
|
|
66
|
+
"properties": {
|
|
67
|
+
"kind": { "type": "string", "minLength": 1 },
|
|
68
|
+
"options": { "type": "object", "additionalProperties": true }
|
|
69
|
+
}
|
|
70
|
+
},
|
|
71
|
+
"relativeExtensionPath": {
|
|
72
|
+
"type": "string",
|
|
73
|
+
"minLength": 1,
|
|
74
|
+
"description": "Relative module path; absolute paths and '..' traversal are forbidden.",
|
|
75
|
+
"not": {
|
|
76
|
+
"anyOf": [
|
|
77
|
+
{ "pattern": "^[/\\\\]" },
|
|
78
|
+
{ "pattern": "^[A-Za-z]:[/\\\\]" },
|
|
79
|
+
{ "pattern": "(^|[/\\\\])\\.\\.([/\\\\]|$)" }
|
|
80
|
+
]
|
|
81
|
+
}
|
|
82
|
+
},
|
|
83
|
+
"extensions": {
|
|
84
|
+
"type": "object",
|
|
85
|
+
"additionalProperties": false,
|
|
86
|
+
"description": "Rule-style relative extension module paths (actions / guards).",
|
|
87
|
+
"properties": {
|
|
88
|
+
"actions": { "type": "array", "items": { "$ref": "#/$defs/relativeExtensionPath" } },
|
|
89
|
+
"guards": { "type": "array", "items": { "$ref": "#/$defs/relativeExtensionPath" } }
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
@@ -40,6 +40,40 @@
|
|
|
40
40
|
"pause": {
|
|
41
41
|
"type": "boolean",
|
|
42
42
|
"description": "When true, the engine pauses the run at this node instead of auto-advancing."
|
|
43
|
+
},
|
|
44
|
+
"resumeRerun": {
|
|
45
|
+
"type": "boolean",
|
|
46
|
+
"description": "Author declaration that re-running this node's action after an interruption is safe."
|
|
47
|
+
},
|
|
48
|
+
"branches": {
|
|
49
|
+
"type": "array",
|
|
50
|
+
"items": {
|
|
51
|
+
"type": "object",
|
|
52
|
+
"additionalProperties": false,
|
|
53
|
+
"required": ["id", "startNode"],
|
|
54
|
+
"properties": {
|
|
55
|
+
"id": { "type": "string", "minLength": 1 },
|
|
56
|
+
"startNode": { "type": "string", "minLength": 1 },
|
|
57
|
+
"description": { "type": "string" }
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
"join": {
|
|
62
|
+
"type": "string",
|
|
63
|
+
"minLength": 1,
|
|
64
|
+
"description": "Target join node ID where branches converge for parallel fork nodes."
|
|
65
|
+
},
|
|
66
|
+
"joinPolicy": {
|
|
67
|
+
"type": "string",
|
|
68
|
+
"enum": ["all"]
|
|
69
|
+
},
|
|
70
|
+
"failurePolicy": {
|
|
71
|
+
"type": "string",
|
|
72
|
+
"enum": ["collect", "fail-fast"]
|
|
73
|
+
},
|
|
74
|
+
"concurrencyLimit": {
|
|
75
|
+
"type": "integer",
|
|
76
|
+
"exclusiveMinimum": 0
|
|
43
77
|
}
|
|
44
78
|
}
|
|
45
79
|
}
|
package/src/action-step.ts
CHANGED
|
@@ -58,6 +58,7 @@ export interface ActionStepDeps {
|
|
|
58
58
|
readonly env: Record<string, string>;
|
|
59
59
|
readonly options: WorkflowRunOptions;
|
|
60
60
|
readonly defaultOnError: OnErrorPolicy | undefined;
|
|
61
|
+
readonly signal?: AbortSignal;
|
|
61
62
|
}
|
|
62
63
|
|
|
63
64
|
/**
|
|
@@ -106,6 +107,7 @@ export async function runActionStep(
|
|
|
106
107
|
env: deps.env,
|
|
107
108
|
metadata: deps.options.metadata,
|
|
108
109
|
events: deps.options.events,
|
|
110
|
+
signal: deps.signal ?? deps.options.signal,
|
|
109
111
|
});
|
|
110
112
|
} catch (error) {
|
|
111
113
|
result = { ok: false, error: error instanceof Error ? error.message : String(error) };
|
package/src/config.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { loadStructuredConfig, parseYamlObject, type StructuredConfigLoadOptions } from '@gobing-ai/ts-runtime';
|
|
2
2
|
import { WorkflowValidationError } from './errors';
|
|
3
3
|
import { RUNTIME_BUILTIN_KEYS } from './run-lifecycle';
|
|
4
|
-
import { StateMachineWorkflowDefSchema, TransitionFlowWorkflowDefSchema } from './schema';
|
|
5
|
-
import type { WorkflowDef } from './types';
|
|
4
|
+
import { DagWorkflowDefSchema, StateMachineWorkflowDefSchema, TransitionFlowWorkflowDefSchema } from './schema';
|
|
5
|
+
import type { DagWorkflowDef, WorkflowDef } from './types';
|
|
6
6
|
|
|
7
7
|
/** Loading options for {@link loadWorkflowDef}. */
|
|
8
8
|
export interface WorkflowLoadOptions {
|
|
@@ -41,6 +41,8 @@ export async function loadWorkflowDef(path: string, options: WorkflowLoadOptions
|
|
|
41
41
|
export function validateWorkflowDef(workflow: WorkflowDef): void {
|
|
42
42
|
if (workflow.kind === 'transition-flow') {
|
|
43
43
|
validateTransitionFlow(workflow);
|
|
44
|
+
} else if (workflow.kind === 'dag') {
|
|
45
|
+
validateDagWorkflowDef(workflow);
|
|
44
46
|
} else {
|
|
45
47
|
validateStateMachine(workflow);
|
|
46
48
|
}
|
|
@@ -132,10 +134,13 @@ function parseWorkflowDef(parsed: unknown, source: string): WorkflowDef {
|
|
|
132
134
|
/** Pick the dialect schema by the shape of the input so diagnostics are field-precise. */
|
|
133
135
|
function selectWorkflowSchema(
|
|
134
136
|
parsed: unknown,
|
|
135
|
-
): typeof StateMachineWorkflowDefSchema | typeof TransitionFlowWorkflowDefSchema {
|
|
137
|
+
): typeof StateMachineWorkflowDefSchema | typeof TransitionFlowWorkflowDefSchema | typeof DagWorkflowDefSchema {
|
|
136
138
|
if (parsed !== null && typeof parsed === 'object') {
|
|
137
139
|
const value = parsed as Record<string, unknown>;
|
|
138
|
-
if (value.kind === '
|
|
140
|
+
if (value.kind === 'dag') {
|
|
141
|
+
return DagWorkflowDefSchema;
|
|
142
|
+
}
|
|
143
|
+
if (value.kind === 'transition-flow' || 'edges' in value || 'initialNode' in value) {
|
|
139
144
|
return TransitionFlowWorkflowDefSchema;
|
|
140
145
|
}
|
|
141
146
|
}
|
|
@@ -180,6 +185,7 @@ function validateTransitionFlow(workflow: Extract<WorkflowDef, { kind: 'transiti
|
|
|
180
185
|
}
|
|
181
186
|
}
|
|
182
187
|
for (const node of workflow.nodes) {
|
|
188
|
+
if (node.type === 'parallel') continue;
|
|
183
189
|
const outbound = workflow.edges.filter((edge) => edge.from === node.id);
|
|
184
190
|
const unconditional = outbound.findIndex((edge) => edge.condition === undefined);
|
|
185
191
|
if (unconditional !== -1 && unconditional < outbound.length - 1) {
|
|
@@ -187,12 +193,151 @@ function validateTransitionFlow(workflow: Extract<WorkflowDef, { kind: 'transiti
|
|
|
187
193
|
}
|
|
188
194
|
}
|
|
189
195
|
|
|
196
|
+
// Parallel fork-join validation
|
|
197
|
+
const nodeMap = new Map(workflow.nodes.map((n) => [n.id, n]));
|
|
198
|
+
const outboundByFrom = new Map<string, string[]>();
|
|
199
|
+
for (const edge of workflow.edges) {
|
|
200
|
+
const list = outboundByFrom.get(edge.from) ?? [];
|
|
201
|
+
list.push(edge.to);
|
|
202
|
+
outboundByFrom.set(edge.from, list);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
for (const node of workflow.nodes) {
|
|
206
|
+
if (node.type === 'parallel') {
|
|
207
|
+
if (!node.branches || node.branches.length < 2) {
|
|
208
|
+
errors.push(`Parallel node "${node.id}" must declare at least 2 branches`);
|
|
209
|
+
}
|
|
210
|
+
if (node.branches) {
|
|
211
|
+
for (const dupe of duplicates(node.branches.map((b) => b.id))) {
|
|
212
|
+
errors.push(`Parallel node "${node.id}" declares duplicate branch id "${dupe}"`);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
if (node.join !== undefined) {
|
|
216
|
+
if (!nodes.has(node.join)) {
|
|
217
|
+
errors.push(`Parallel node "${node.id}" references undeclared join node "${node.join}"`);
|
|
218
|
+
} else if (node.join === node.id) {
|
|
219
|
+
errors.push(`Parallel node "${node.id}" cannot have join set to itself`);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
if (node.branches && node.join && nodes.has(node.join) && node.join !== node.id) {
|
|
224
|
+
for (const branch of node.branches) {
|
|
225
|
+
if (!nodes.has(branch.startNode)) {
|
|
226
|
+
errors.push(
|
|
227
|
+
`Branch "${branch.id}" in parallel node "${node.id}" references undeclared startNode "${branch.startNode}"`,
|
|
228
|
+
);
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
if (branch.startNode === node.join) {
|
|
232
|
+
errors.push(
|
|
233
|
+
`Branch "${branch.id}" in parallel node "${node.id}" has startNode equal to join node "${node.join}"`,
|
|
234
|
+
);
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// Check for nested parallel nodes and cycles within branch before reaching join
|
|
239
|
+
const visiting = new Set<string>();
|
|
240
|
+
const visited = new Set<string>();
|
|
241
|
+
let hasCycle = false;
|
|
242
|
+
|
|
243
|
+
const walk = (currentId: string) => {
|
|
244
|
+
if (currentId === node.join) return;
|
|
245
|
+
if (visiting.has(currentId)) {
|
|
246
|
+
hasCycle = true;
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
if (visited.has(currentId)) return;
|
|
250
|
+
|
|
251
|
+
const currentNode = nodeMap.get(currentId);
|
|
252
|
+
if (currentNode && currentNode.id !== node.id && currentNode.type === 'parallel') {
|
|
253
|
+
errors.push(
|
|
254
|
+
`Parallel node "${currentNode.id}" is nested inside parallel node "${node.id}" (nested parallel regions are forbidden)`,
|
|
255
|
+
);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
visiting.add(currentId);
|
|
259
|
+
const nextIds = outboundByFrom.get(currentId) ?? [];
|
|
260
|
+
for (const nextId of nextIds) {
|
|
261
|
+
walk(nextId);
|
|
262
|
+
}
|
|
263
|
+
visiting.delete(currentId);
|
|
264
|
+
visited.add(currentId);
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
walk(branch.startNode);
|
|
268
|
+
|
|
269
|
+
if (hasCycle) {
|
|
270
|
+
errors.push(`Parallel branch "${branch.id}" in node "${node.id}" contains a cycle`);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
190
277
|
// Template variable references must resolve.
|
|
191
278
|
errors.push(...checkVariableReferences(collectActionOptions(workflow), workflow.vars, workflow.env));
|
|
192
279
|
|
|
193
280
|
throwIfErrors(workflow, errors);
|
|
194
281
|
}
|
|
195
282
|
|
|
283
|
+
function validateDagWorkflowDef(workflow: DagWorkflowDef): void {
|
|
284
|
+
const errors: string[] = [];
|
|
285
|
+
const ids = workflow.nodes.map((node) => node.id);
|
|
286
|
+
const nodes = new Set(ids);
|
|
287
|
+
|
|
288
|
+
// Duplicate node IDs
|
|
289
|
+
for (const id of duplicates(ids)) {
|
|
290
|
+
errors.push(`Node "${id}" is declared more than once`);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// Validate dependsOn references and self-dependencies
|
|
294
|
+
for (const node of workflow.nodes) {
|
|
295
|
+
for (const dep of node.dependsOn ?? []) {
|
|
296
|
+
if (dep === node.id) {
|
|
297
|
+
errors.push(`Node "${node.id}" cannot depend on itself`);
|
|
298
|
+
} else if (!nodes.has(dep)) {
|
|
299
|
+
errors.push(`Node "${node.id}" references undeclared dependency "${dep}"`);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// Cycle detection via Kahn's algorithm (topological sort)
|
|
305
|
+
const inDegree = new Map<string, number>();
|
|
306
|
+
const adjList = new Map<string, string[]>();
|
|
307
|
+
for (const id of ids) {
|
|
308
|
+
inDegree.set(id, 0);
|
|
309
|
+
adjList.set(id, []);
|
|
310
|
+
}
|
|
311
|
+
for (const node of workflow.nodes) {
|
|
312
|
+
for (const dep of node.dependsOn ?? []) {
|
|
313
|
+
if (nodes.has(dep) && dep !== node.id) {
|
|
314
|
+
adjList.get(dep)?.push(node.id);
|
|
315
|
+
inDegree.set(node.id, (inDegree.get(node.id) ?? 0) + 1);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
const queue = ids.filter((id) => (inDegree.get(id) ?? 0) === 0);
|
|
320
|
+
let visitedCount = 0;
|
|
321
|
+
while (queue.length > 0) {
|
|
322
|
+
const curr = queue.shift();
|
|
323
|
+
if (curr === undefined) break;
|
|
324
|
+
visitedCount++;
|
|
325
|
+
for (const neighbor of adjList.get(curr) ?? []) {
|
|
326
|
+
const newDeg = (inDegree.get(neighbor) ?? 1) - 1;
|
|
327
|
+
inDegree.set(neighbor, newDeg);
|
|
328
|
+
if (newDeg === 0) queue.push(neighbor);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
if (visitedCount < ids.length && errors.length === 0) {
|
|
332
|
+
errors.push('Cycle detected in DAG dependencies');
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// Variable template references in actions
|
|
336
|
+
errors.push(...checkVariableReferences(collectActionOptions(workflow), workflow.vars, workflow.env));
|
|
337
|
+
|
|
338
|
+
throwIfErrors(workflow, errors);
|
|
339
|
+
}
|
|
340
|
+
|
|
196
341
|
/** Return the ids that appear more than once, in first-seen order. */
|
|
197
342
|
function duplicates(ids: readonly string[]): string[] {
|
|
198
343
|
const seen = new Set<string>();
|
|
@@ -210,7 +355,9 @@ function collectActionOptions(workflow: WorkflowDef): Record<string, unknown>[]
|
|
|
210
355
|
const actions =
|
|
211
356
|
workflow.kind === 'transition-flow'
|
|
212
357
|
? workflow.nodes.flatMap((node) => (node.action ? [node.action] : []))
|
|
213
|
-
: workflow.
|
|
358
|
+
: workflow.kind === 'dag'
|
|
359
|
+
? workflow.nodes.flatMap((node) => (node.action ? [node.action] : []))
|
|
360
|
+
: workflow.states.flatMap((state) => [...(state.onEnter ?? []), ...(state.onExit ?? [])]);
|
|
214
361
|
for (const action of actions) {
|
|
215
362
|
if (action.options) optionSets.push(action.options);
|
|
216
363
|
}
|
package/src/dag.ts
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
import { runActionStep } from './action-step';
|
|
2
|
+
import type { WorkflowEngineHost } from './host';
|
|
3
|
+
import { allowedEnv, RunLifecycle, snapshotTransitions } from './run-lifecycle';
|
|
4
|
+
import type {
|
|
5
|
+
DagNodeDef,
|
|
6
|
+
DagWorkflowDef,
|
|
7
|
+
Vars,
|
|
8
|
+
WorkflowPersistenceAdapter,
|
|
9
|
+
WorkflowRunOptions,
|
|
10
|
+
WorkflowRunResult,
|
|
11
|
+
} from './types';
|
|
12
|
+
import { mergeSetVars, mergeVars, resolveShellCommandTemplates, resolveTemplates } from './variables';
|
|
13
|
+
|
|
14
|
+
/** Dependencies required by the static dependency DAG driver. */
|
|
15
|
+
export interface DagDriverOptions {
|
|
16
|
+
readonly host: WorkflowEngineHost;
|
|
17
|
+
readonly persistence: WorkflowPersistenceAdapter;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Execution status of a single DAG node within a run. */
|
|
21
|
+
export type DagNodeStatus = 'pending' | 'ready' | 'running' | 'done' | 'failed' | 'skipped' | 'paused';
|
|
22
|
+
|
|
23
|
+
// Reserved parallel_node namespace reusing the 0094 branch ledger for per-node DAG execution records.
|
|
24
|
+
const DAG_LEDGER_NAMESPACE = '__dag__';
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Static dependency DAG workflow driver (task 0100, ADR-034).
|
|
28
|
+
* Manages an in-process ready queue of runnable nodes, dispatching them as upstream
|
|
29
|
+
* dependencies complete, propagating skips on conditional branches, and supporting
|
|
30
|
+
* pause, resume, and durable recovery.
|
|
31
|
+
*/
|
|
32
|
+
export class DagDriver {
|
|
33
|
+
constructor(private readonly options: DagDriverOptions) {}
|
|
34
|
+
|
|
35
|
+
/** Run a DAG workflow to completion, pause, or failure. */
|
|
36
|
+
async run(workflow: DagWorkflowDef, options: WorkflowRunOptions = {}): Promise<WorkflowRunResult> {
|
|
37
|
+
return await RunLifecycle.run(
|
|
38
|
+
workflow.name,
|
|
39
|
+
'dag',
|
|
40
|
+
{ persistence: this.options.persistence, events: options.events },
|
|
41
|
+
options,
|
|
42
|
+
(lifecycle) => this.loop(workflow, options, lifecycle),
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Resume a paused DAG workflow run. */
|
|
47
|
+
async resume(
|
|
48
|
+
workflow: DagWorkflowDef,
|
|
49
|
+
runId: string,
|
|
50
|
+
externalKey: string | undefined,
|
|
51
|
+
options: WorkflowRunOptions = {},
|
|
52
|
+
): Promise<WorkflowRunResult> {
|
|
53
|
+
return await RunLifecycle.resume(
|
|
54
|
+
workflow.name,
|
|
55
|
+
'dag',
|
|
56
|
+
{ persistence: this.options.persistence, events: options.events },
|
|
57
|
+
runId,
|
|
58
|
+
externalKey,
|
|
59
|
+
(lifecycle) => this.loop(workflow, options, lifecycle),
|
|
60
|
+
options.resumeOwner?.attemptId,
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
private async loop(
|
|
65
|
+
workflow: DagWorkflowDef,
|
|
66
|
+
options: WorkflowRunOptions,
|
|
67
|
+
lifecycle: RunLifecycle,
|
|
68
|
+
): Promise<WorkflowRunResult> {
|
|
69
|
+
const runId = lifecycle.runId;
|
|
70
|
+
let vars = mergeVars(workflow.vars, options.vars);
|
|
71
|
+
const env = allowedEnv(workflow.env?.allow ?? [], options.env);
|
|
72
|
+
const defaultOnError = workflow.defaultOnError;
|
|
73
|
+
|
|
74
|
+
// Restore snapshot if resuming
|
|
75
|
+
const snapshot = await this.options.persistence.loadLatestStateSnapshot(runId);
|
|
76
|
+
let transitionsTaken = snapshotTransitions(snapshot?.data);
|
|
77
|
+
if (snapshot?.data?.effectiveVars && typeof snapshot.data.effectiveVars === 'object') {
|
|
78
|
+
vars = mergeVars(vars, snapshot.data.effectiveVars as Vars);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const nodeStatuses = new Map<string, DagNodeStatus>();
|
|
82
|
+
// If resuming, determine if any node was already paused or completed
|
|
83
|
+
const pausedNodeId = snapshot?.state;
|
|
84
|
+
|
|
85
|
+
// Seed from the durable per-node ledger (task 0101): settled nodes are never
|
|
86
|
+
// re-dispatched. 'cancelled' rows are condition-skipped nodes; 'paused'/'running'/
|
|
87
|
+
// 'pending' rows fall through to the dependsOn rule so interrupted nodes re-run.
|
|
88
|
+
const priorRows = await this.options.persistence.listRunBranches(runId, DAG_LEDGER_NAMESPACE);
|
|
89
|
+
const priorByNode = new Map(priorRows.map((r) => [r.branch_id, r.status]));
|
|
90
|
+
|
|
91
|
+
for (const node of workflow.nodes) {
|
|
92
|
+
const deps = node.dependsOn ?? [];
|
|
93
|
+
const prior = priorByNode.get(node.id);
|
|
94
|
+
if (prior === 'done') {
|
|
95
|
+
nodeStatuses.set(node.id, 'done');
|
|
96
|
+
} else if (prior === 'cancelled') {
|
|
97
|
+
nodeStatuses.set(node.id, 'skipped');
|
|
98
|
+
} else if (prior === 'failed') {
|
|
99
|
+
nodeStatuses.set(node.id, 'failed');
|
|
100
|
+
} else if (pausedNodeId && node.id === pausedNodeId) {
|
|
101
|
+
nodeStatuses.set(node.id, 'done');
|
|
102
|
+
} else {
|
|
103
|
+
nodeStatuses.set(node.id, deps.length === 0 ? 'ready' : 'pending');
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const checkDependenciesSatisfied = (node: DagNodeDef): { ready: boolean; shouldSkip: boolean } => {
|
|
108
|
+
const deps = node.dependsOn ?? [];
|
|
109
|
+
if (deps.length === 0) return { ready: true, shouldSkip: false };
|
|
110
|
+
|
|
111
|
+
const policy = node.dependencyPolicy ?? 'all';
|
|
112
|
+
const depStatuses = deps.map((d) => nodeStatuses.get(d) ?? 'pending');
|
|
113
|
+
|
|
114
|
+
if (policy === 'any') {
|
|
115
|
+
const anyDone = depStatuses.some((s) => s === 'done');
|
|
116
|
+
if (anyDone) return { ready: true, shouldSkip: false };
|
|
117
|
+
const allSettled = depStatuses.every((s) => s === 'done' || s === 'skipped' || s === 'failed');
|
|
118
|
+
const allSkipped = depStatuses.every((s) => s === 'skipped');
|
|
119
|
+
return { ready: false, shouldSkip: allSettled && allSkipped };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// policy === 'all'
|
|
123
|
+
const allDone = depStatuses.every((s) => s === 'done');
|
|
124
|
+
if (allDone) return { ready: true, shouldSkip: false };
|
|
125
|
+
|
|
126
|
+
// Skip propagation: if all parents have settled, and none failed, but some are skipped
|
|
127
|
+
const allSettled = depStatuses.every((s) => s === 'done' || s === 'skipped');
|
|
128
|
+
const hasSkipped = depStatuses.some((s) => s === 'skipped');
|
|
129
|
+
if (allSettled && hasSkipped) {
|
|
130
|
+
// If every dependent branch was skipped, skip this node too
|
|
131
|
+
const allSkipped = depStatuses.every((s) => s === 'skipped');
|
|
132
|
+
if (allSkipped) {
|
|
133
|
+
return { ready: false, shouldSkip: true };
|
|
134
|
+
}
|
|
135
|
+
// If some are done and some are skipped, join proceeds with completed branches!
|
|
136
|
+
return { ready: true, shouldSkip: false };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
return { ready: false, shouldSkip: false };
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
let pausedNode: string | undefined;
|
|
143
|
+
let failureError: string | undefined;
|
|
144
|
+
|
|
145
|
+
while (true) {
|
|
146
|
+
// Find nodes ready to run
|
|
147
|
+
const readyNodes: DagNodeDef[] = [];
|
|
148
|
+
for (const node of workflow.nodes) {
|
|
149
|
+
const status = nodeStatuses.get(node.id);
|
|
150
|
+
if (status === 'pending') {
|
|
151
|
+
const check = checkDependenciesSatisfied(node);
|
|
152
|
+
if (check.shouldSkip) {
|
|
153
|
+
nodeStatuses.set(node.id, 'skipped');
|
|
154
|
+
} else if (check.ready) {
|
|
155
|
+
nodeStatuses.set(node.id, 'ready');
|
|
156
|
+
readyNodes.push(node);
|
|
157
|
+
}
|
|
158
|
+
} else if (status === 'ready') {
|
|
159
|
+
readyNodes.push(node);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
if (readyNodes.length === 0) {
|
|
164
|
+
break;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// Dispatch ready nodes concurrently
|
|
168
|
+
const results = await Promise.all(
|
|
169
|
+
readyNodes.map(async (node) => {
|
|
170
|
+
nodeStatuses.set(node.id, 'running');
|
|
171
|
+
// Ledger rows make per-node completion durable; dryRun executes nothing and records nothing.
|
|
172
|
+
const nodeStartMs = Date.now();
|
|
173
|
+
if (!options.dryRun) {
|
|
174
|
+
await this.options.persistence.saveBranchStart(runId, DAG_LEDGER_NAMESPACE, node.id, node.id);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// Check condition if declared
|
|
178
|
+
if (node.condition) {
|
|
179
|
+
const resolvedOptions =
|
|
180
|
+
node.condition.kind === 'shell'
|
|
181
|
+
? resolveShellCommandTemplates(node.condition.options ?? {}, { vars, env })
|
|
182
|
+
: resolveTemplates(node.condition.options ?? {}, { vars, env });
|
|
183
|
+
const passed = await this.options.host.evaluateGuard(node.condition.kind, resolvedOptions, {
|
|
184
|
+
runId,
|
|
185
|
+
current: node.id,
|
|
186
|
+
vars,
|
|
187
|
+
env,
|
|
188
|
+
workdir: options.workdir,
|
|
189
|
+
});
|
|
190
|
+
if (!passed) {
|
|
191
|
+
nodeStatuses.set(node.id, 'skipped');
|
|
192
|
+
// BranchStatus has no 'skipped'; 'cancelled' marks settled-without-running.
|
|
193
|
+
if (!options.dryRun) {
|
|
194
|
+
await this.options.persistence.saveBranchFinalize(
|
|
195
|
+
runId,
|
|
196
|
+
node.id,
|
|
197
|
+
'cancelled',
|
|
198
|
+
Date.now() - nodeStartMs,
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
return { id: node.id, status: 'skipped' as const };
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
if (node.pause === true) {
|
|
206
|
+
nodeStatuses.set(node.id, 'paused');
|
|
207
|
+
if (!options.dryRun) {
|
|
208
|
+
await this.options.persistence.saveBranchFinalize(
|
|
209
|
+
runId,
|
|
210
|
+
node.id,
|
|
211
|
+
'paused',
|
|
212
|
+
Date.now() - nodeStartMs,
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
return { id: node.id, status: 'paused' as const };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
if (!options.dryRun && node.action) {
|
|
219
|
+
const step = await runActionStep(node.action, vars, {
|
|
220
|
+
host: this.options.host,
|
|
221
|
+
persistence: this.options.persistence,
|
|
222
|
+
lifecycle,
|
|
223
|
+
workflowName: workflow.name,
|
|
224
|
+
stateOrNodeId: node.id,
|
|
225
|
+
runId,
|
|
226
|
+
mode: 'dag',
|
|
227
|
+
transitionsTaken,
|
|
228
|
+
env,
|
|
229
|
+
options,
|
|
230
|
+
defaultOnError,
|
|
231
|
+
});
|
|
232
|
+
if (step.outcome === 'fail') {
|
|
233
|
+
nodeStatuses.set(node.id, 'failed');
|
|
234
|
+
if (!options.dryRun) {
|
|
235
|
+
await this.options.persistence.saveBranchFinalize(
|
|
236
|
+
runId,
|
|
237
|
+
node.id,
|
|
238
|
+
'failed',
|
|
239
|
+
Date.now() - nodeStartMs,
|
|
240
|
+
undefined,
|
|
241
|
+
step.result?.error ?? 'failed',
|
|
242
|
+
);
|
|
243
|
+
}
|
|
244
|
+
return { id: node.id, status: 'failed' as const, error: step.result?.error ?? 'failed' };
|
|
245
|
+
}
|
|
246
|
+
if (step.result?.setVars) {
|
|
247
|
+
vars = mergeSetVars(vars, step.result.setVars);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
nodeStatuses.set(node.id, 'done');
|
|
252
|
+
transitionsTaken++;
|
|
253
|
+
if (!options.dryRun) {
|
|
254
|
+
await this.options.persistence.saveBranchFinalize(
|
|
255
|
+
runId,
|
|
256
|
+
node.id,
|
|
257
|
+
'done',
|
|
258
|
+
Date.now() - nodeStartMs,
|
|
259
|
+
);
|
|
260
|
+
}
|
|
261
|
+
return { id: node.id, status: 'done' as const };
|
|
262
|
+
}),
|
|
263
|
+
);
|
|
264
|
+
|
|
265
|
+
// Check if any failed or paused
|
|
266
|
+
for (const res of results) {
|
|
267
|
+
if (res.status === 'failed') {
|
|
268
|
+
failureError = res.error;
|
|
269
|
+
} else if (res.status === 'paused') {
|
|
270
|
+
pausedNode = res.id;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
if (failureError) {
|
|
275
|
+
return await lifecycle.fail('dag', transitionsTaken, failureError);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
if (pausedNode) {
|
|
279
|
+
return await lifecycle.pause(pausedNode, transitionsTaken, vars);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// Final completion check
|
|
284
|
+
const anyFailed = Array.from(nodeStatuses.values()).some((s) => s === 'failed');
|
|
285
|
+
if (anyFailed) {
|
|
286
|
+
return await lifecycle.fail('dag', transitionsTaken, failureError ?? 'dag-failed');
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// Never report done while a node is stranded (task 0101 R3): unreachable = loud failure.
|
|
290
|
+
const stuck = workflow.nodes.filter((n) => nodeStatuses.get(n.id) === 'pending').map((n) => n.id);
|
|
291
|
+
if (stuck.length > 0) {
|
|
292
|
+
return await lifecycle.fail('dag', transitionsTaken, `dag-unreachable-nodes: ${stuck.join(',')}`);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
return await lifecycle.done('dag', transitionsTaken);
|
|
296
|
+
}
|
|
297
|
+
}
|