workflow-scheduler.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. deriveWorkflowSchedulerState,
  4. type WorkflowEvent,
  5. type WorkflowGraph,
  6. type WorkflowGraphRecord,
  7. type WorkflowRunSnapshot,
  8. } from "@zcode/contracts";
  9. import { WorkflowGraphScheduler } from "../src/workflow/scheduler.js";
  10. import { DEFAULT_EXPERT_WORKFLOW_STRATEGY } from "../src/workflow/expert.js";
  11. describe("WorkflowGraphScheduler", () => {
  12. it("derives ready and blocked nodes from graph dependencies", () => {
  13. const state = deriveWorkflowSchedulerState({
  14. edges: [{ from: "a", to: "b" }],
  15. nodes: [
  16. { dependsOn: [], id: "a", kind: "task", status: "completed", title: "A" },
  17. { dependsOn: ["a"], id: "b", kind: "task", status: "pending", title: "B" },
  18. { dependsOn: ["missing"], id: "c", kind: "task", status: "pending", title: "C" },
  19. ],
  20. });
  21. expect(state.readyNodeIds).toEqual(["b"]);
  22. expect(state.blockedNodes).toEqual([{ blockedBy: ["missing"], nodeId: "c" }]);
  23. expect(state.counts).toMatchObject({
  24. blocked: 1,
  25. completed: 1,
  26. pending: 2,
  27. ready: 1,
  28. total: 3,
  29. });
  30. });
  31. it("dispatches independent ready nodes concurrently and waits for dependencies", async () => {
  32. const events: WorkflowEvent[] = [];
  33. const graphRecords: WorkflowGraphRecord[] = [];
  34. const started: string[] = [];
  35. const completed: string[] = [];
  36. let inFlight = 0;
  37. let maxInFlight = 0;
  38. let now = 0;
  39. const scheduler = new WorkflowGraphScheduler({
  40. appendEvent: async (event) => {
  41. events.push(event);
  42. },
  43. appendGraphRecord: async (_runId, record) => {
  44. graphRecords.push(record);
  45. },
  46. createActivityId: () => `act_${events.length}_${started.length}`,
  47. now: () => new Date(1_700_000_000_000 + now++),
  48. runner: {
  49. run: async ({ node }) => {
  50. started.push(node.id);
  51. inFlight++;
  52. maxInFlight = Math.max(maxInFlight, inFlight);
  53. await new Promise((resolve) => setTimeout(resolve, node.id === "c" ? 1 : 10));
  54. inFlight--;
  55. completed.push(node.id);
  56. return {
  57. response: `# ${node.id}`,
  58. sessionId: `sess_${node.id}`,
  59. };
  60. },
  61. },
  62. writeArtifact: async (_runId, relativePath) => ({
  63. path: relativePath,
  64. relativePath,
  65. }),
  66. writeSnapshot: async () => {},
  67. });
  68. const result = await scheduler.run({
  69. cwd: "/repo",
  70. executableNodeIds: ["a", "b", "c"],
  71. phase: "exec",
  72. snapshot: createSnapshot({
  73. edges: [
  74. { from: "a", to: "c" },
  75. { from: "b", to: "c" },
  76. ],
  77. nodes: [
  78. { dependsOn: [], id: "a", kind: "task", status: "pending", title: "A" },
  79. { dependsOn: [], id: "b", kind: "task", status: "pending", title: "B" },
  80. { dependsOn: ["a", "b"], id: "c", kind: "task", status: "pending", title: "C" },
  81. ],
  82. }),
  83. });
  84. expect(result.status).toBe("completed");
  85. expect(maxInFlight).toBe(2);
  86. expect(started.slice(0, 2).sort()).toEqual(["a", "b"]);
  87. expect(started.at(-1)).toBe("c");
  88. expect(completed.sort()).toEqual(["a", "b", "c"]);
  89. expect(result.snapshot.graph.nodes.map((node) => [node.id, node.status])).toEqual([
  90. ["a", "completed"],
  91. ["b", "completed"],
  92. ["c", "completed"],
  93. ]);
  94. expect(events.map((event) => event.type)).toEqual(
  95. expect.arrayContaining([
  96. "frontier_changed",
  97. "node_started",
  98. "node_completed",
  99. "executor_completed",
  100. ]),
  101. );
  102. expect(
  103. graphRecords.some(
  104. (record) =>
  105. record.recordType === "op" && record.nodeId === "c" && record.status === "completed",
  106. ),
  107. ).toBe(true);
  108. });
  109. it("retries failed nodes and pauses at the consecutive error threshold", async () => {
  110. const events: WorkflowEvent[] = [];
  111. const scheduler = new WorkflowGraphScheduler({
  112. appendEvent: async (event) => {
  113. events.push(event);
  114. },
  115. appendGraphRecord: async () => {},
  116. createActivityId: () => `act_${events.length}`,
  117. now: () => new Date("2026-05-05T00:00:00Z"),
  118. runner: {
  119. run: async () => {
  120. throw new Error("node failed");
  121. },
  122. },
  123. writeArtifact: async (_runId, relativePath) => ({
  124. path: relativePath,
  125. relativePath,
  126. }),
  127. writeSnapshot: async () => {},
  128. });
  129. const result = await scheduler.run({
  130. cwd: "/repo",
  131. executableNodeIds: ["flaky"],
  132. phase: "exec",
  133. snapshot: createSnapshot(
  134. {
  135. edges: [],
  136. nodes: [
  137. {
  138. dependsOn: [],
  139. id: "flaky",
  140. kind: "task",
  141. status: "pending",
  142. title: "Flaky",
  143. },
  144. ],
  145. },
  146. { maxConsecutiveErrors: 2 },
  147. ),
  148. });
  149. expect(result.status).toBe("paused");
  150. expect(result.reason).toBe("error_threshold");
  151. expect(result.snapshot.graph.nodes[0]).toMatchObject({
  152. attempts: 2,
  153. error: "node failed",
  154. status: "failed",
  155. });
  156. expect(events.filter((event) => event.type === "node_failed")).toHaveLength(2);
  157. expect(events.at(-1)).toMatchObject({
  158. type: "executor_paused",
  159. });
  160. });
  161. it("runs collection planners, expands the graph, and schedules new nodes", async () => {
  162. const events: WorkflowEvent[] = [];
  163. const graphRecords: WorkflowGraphRecord[] = [];
  164. const started: string[] = [];
  165. const plannerCollections: string[] = [];
  166. let now = 0;
  167. const scheduler = new WorkflowGraphScheduler({
  168. appendEvent: async (event) => {
  169. events.push(event);
  170. },
  171. appendGraphRecord: async (_runId, record) => {
  172. graphRecords.push(record);
  173. },
  174. createActivityId: () => `act_${events.length}_${started.length}_${plannerCollections.length}`,
  175. now: () => new Date(1_700_000_000_000 + now++),
  176. plannerRunner: {
  177. run: async ({ collection }) => {
  178. plannerCollections.push(collection.collectionId);
  179. if (plannerCollections.length === 1) {
  180. return {
  181. edges: [{ from: "seed", to: "follow_up" }],
  182. nodes: [
  183. {
  184. dependsOn: ["seed"],
  185. id: "follow_up",
  186. title: "Follow Up",
  187. },
  188. ],
  189. response:
  190. '{"nodes":[{"id":"follow_up","title":"Follow Up","dependsOn":["seed"]}],"edges":[{"from":"seed","to":"follow_up"}]}',
  191. sessionId: "planner-one",
  192. };
  193. }
  194. return {
  195. edges: [],
  196. exhausted: true,
  197. nodes: [],
  198. response: '{"nodes":[],"edges":[],"exhausted":true}',
  199. sessionId: "planner-two",
  200. };
  201. },
  202. },
  203. runner: {
  204. run: async ({ node }) => {
  205. started.push(node.id);
  206. return {
  207. response: `# ${node.id}`,
  208. sessionId: `sess_${node.id}`,
  209. };
  210. },
  211. },
  212. writeArtifact: async (_runId, relativePath) => ({
  213. path: relativePath,
  214. relativePath,
  215. }),
  216. writeSnapshot: async () => {},
  217. });
  218. const result = await scheduler.run({
  219. cwd: "/repo",
  220. executableNodeIds: ["seed"],
  221. phase: "exec",
  222. snapshot: createSnapshot(
  223. {
  224. collections: [
  225. {
  226. collectionId: "research",
  227. explorable: true,
  228. frontierTarget: 1,
  229. nodeIds: ["seed"],
  230. },
  231. ],
  232. edges: [],
  233. nodes: [
  234. {
  235. collectionId: "research",
  236. dependsOn: [],
  237. id: "seed",
  238. kind: "task",
  239. status: "completed",
  240. title: "Seed",
  241. },
  242. ],
  243. },
  244. { maxPlannerRuns: 3 },
  245. ),
  246. });
  247. expect(result.status).toBe("completed");
  248. expect(plannerCollections).toEqual(["research", "research"]);
  249. expect(started).toEqual(["follow_up"]);
  250. expect(result.snapshot.graph.nodes.map((node) => [node.id, node.status])).toEqual([
  251. ["seed", "completed"],
  252. ["follow_up", "completed"],
  253. ]);
  254. expect(result.snapshot.graph.collections?.[0]).toMatchObject({
  255. analyzedNodeIds: ["seed", "follow_up"],
  256. collectionId: "research",
  257. exhausted: true,
  258. nodeIds: ["seed", "follow_up"],
  259. plannerRuns: 2,
  260. status: "exhausted",
  261. });
  262. expect(events.map((event) => event.type)).toEqual(
  263. expect.arrayContaining([
  264. "planner_started",
  265. "planner_completed",
  266. "graph_expanded",
  267. "node_completed",
  268. "collection_exhausted",
  269. ]),
  270. );
  271. expect(
  272. graphRecords.some(
  273. (record) =>
  274. record.recordType === "op" &&
  275. record.type === "graph_expanded" &&
  276. record.collectionId === "research",
  277. ),
  278. ).toBe(true);
  279. });
  280. it("does not run a collection planner before seeded frontier has a completion", async () => {
  281. const plannerCalls: string[] = [];
  282. const started: string[] = [];
  283. const scheduler = new WorkflowGraphScheduler({
  284. appendEvent: async () => {},
  285. appendGraphRecord: async () => {},
  286. createActivityId: () => `act_${plannerCalls.length}_${started.length}`,
  287. now: () => new Date("2026-05-05T00:00:00Z"),
  288. plannerRunner: {
  289. run: async ({ collection }) => {
  290. plannerCalls.push(collection.collectionId);
  291. return {
  292. edges: [],
  293. exhausted: true,
  294. nodes: [],
  295. response: '{"nodes":[],"edges":[],"exhausted":true}',
  296. sessionId: "planner",
  297. };
  298. },
  299. },
  300. runner: {
  301. run: async ({ node }) => {
  302. expect(plannerCalls).toEqual([]);
  303. started.push(node.id);
  304. return {
  305. response: `# ${node.id}`,
  306. sessionId: `sess_${node.id}`,
  307. };
  308. },
  309. },
  310. writeArtifact: async (_runId, relativePath) => ({
  311. path: relativePath,
  312. relativePath,
  313. }),
  314. writeSnapshot: async () => {},
  315. });
  316. const result = await scheduler.run({
  317. cwd: "/repo",
  318. executableNodeIds: ["seed"],
  319. phase: "exec",
  320. snapshot: createSnapshot({
  321. collections: [
  322. {
  323. collectionId: "research",
  324. explorable: true,
  325. frontierTarget: 2,
  326. nodeIds: ["seed"],
  327. },
  328. ],
  329. edges: [],
  330. nodes: [
  331. {
  332. collectionId: "research",
  333. dependsOn: [],
  334. id: "seed",
  335. kind: "task",
  336. status: "pending",
  337. title: "Seed",
  338. },
  339. ],
  340. }),
  341. });
  342. expect(result.status).toBe("completed");
  343. expect(started).toEqual(["seed"]);
  344. expect(plannerCalls).toEqual(["research"]);
  345. });
  346. it("exhausts a collection instead of running past maxPlannerRuns", async () => {
  347. const events: WorkflowEvent[] = [];
  348. const scheduler = new WorkflowGraphScheduler({
  349. appendEvent: async (event) => {
  350. events.push(event);
  351. },
  352. appendGraphRecord: async () => {},
  353. createActivityId: () => `act_${events.length}`,
  354. now: () => new Date("2026-05-05T00:00:00Z"),
  355. plannerRunner: {
  356. run: async () => {
  357. throw new Error("planner should not run");
  358. },
  359. },
  360. runner: {
  361. run: async ({ node }) => ({
  362. response: `# ${node.id}`,
  363. sessionId: `sess_${node.id}`,
  364. }),
  365. },
  366. writeArtifact: async (_runId, relativePath) => ({
  367. path: relativePath,
  368. relativePath,
  369. }),
  370. writeSnapshot: async () => {},
  371. });
  372. const result = await scheduler.run({
  373. cwd: "/repo",
  374. executableNodeIds: ["seed"],
  375. phase: "exec",
  376. snapshot: createSnapshot(
  377. {
  378. collections: [
  379. {
  380. collectionId: "research",
  381. explorable: true,
  382. nodeIds: ["seed"],
  383. plannerRuns: 1,
  384. },
  385. ],
  386. edges: [],
  387. nodes: [
  388. {
  389. collectionId: "research",
  390. dependsOn: [],
  391. id: "seed",
  392. kind: "task",
  393. status: "completed",
  394. title: "Seed",
  395. },
  396. ],
  397. },
  398. { maxPlannerRuns: 1 },
  399. ),
  400. });
  401. expect(result.status).toBe("completed");
  402. expect(result.snapshot.graph.collections?.[0]).toMatchObject({
  403. collectionId: "research",
  404. exhausted: true,
  405. status: "exhausted",
  406. });
  407. expect(events.at(0)).toMatchObject({
  408. payload: {
  409. reason: "max_planner_runs",
  410. },
  411. type: "collection_exhausted",
  412. });
  413. });
  414. it("records planner failures without corrupting graph state", async () => {
  415. const events: WorkflowEvent[] = [];
  416. const scheduler = new WorkflowGraphScheduler({
  417. appendEvent: async (event) => {
  418. events.push(event);
  419. },
  420. appendGraphRecord: async () => {},
  421. createActivityId: () => `act_${events.length}`,
  422. now: () => new Date("2026-05-05T00:00:00Z"),
  423. plannerRunner: {
  424. run: async () => {
  425. throw new Error("planner failed");
  426. },
  427. },
  428. runner: {
  429. run: async ({ node }) => ({
  430. response: `# ${node.id}`,
  431. sessionId: `sess_${node.id}`,
  432. }),
  433. },
  434. writeArtifact: async (_runId, relativePath) => ({
  435. path: relativePath,
  436. relativePath,
  437. }),
  438. writeSnapshot: async () => {},
  439. });
  440. const result = await scheduler.run({
  441. cwd: "/repo",
  442. executableNodeIds: ["seed"],
  443. phase: "exec",
  444. snapshot: createSnapshot(
  445. {
  446. collections: [
  447. {
  448. collectionId: "research",
  449. explorable: true,
  450. nodeIds: ["seed"],
  451. },
  452. ],
  453. edges: [],
  454. nodes: [
  455. {
  456. collectionId: "research",
  457. dependsOn: [],
  458. id: "seed",
  459. kind: "task",
  460. status: "completed",
  461. title: "Seed",
  462. },
  463. ],
  464. },
  465. { maxConsecutiveErrors: 1 },
  466. ),
  467. });
  468. expect(result.status).toBe("completed");
  469. expect(result.snapshot.graph.nodes).toEqual([
  470. {
  471. collectionId: "research",
  472. dependsOn: [],
  473. id: "seed",
  474. kind: "task",
  475. status: "completed",
  476. title: "Seed",
  477. },
  478. ]);
  479. expect(result.snapshot.graph.collections?.[0]).toMatchObject({
  480. collectionId: "research",
  481. errorCount: 1,
  482. exhausted: true,
  483. status: "exhausted",
  484. });
  485. expect(events.map((event) => event.type)).toEqual(
  486. expect.arrayContaining(["planner_failed", "collection_exhausted"]),
  487. );
  488. });
  489. });
  490. function createSnapshot(
  491. graph: WorkflowGraph,
  492. options: { maxConsecutiveErrors?: number; maxPlannerRuns?: number } = {},
  493. ): WorkflowRunSnapshot {
  494. return {
  495. activities: [],
  496. artifacts: [],
  497. createdAt: "2026-05-05T00:00:00.000Z",
  498. cwd: "/repo",
  499. graph,
  500. kind: "expert",
  501. phaseOrder: ["exec"],
  502. phases: [{ phase: "exec", status: "pending" }],
  503. runId: "wf_scheduler_test",
  504. schemaVersion: 1,
  505. status: "running",
  506. strategy: {
  507. ...DEFAULT_EXPERT_WORKFLOW_STRATEGY,
  508. executor: {
  509. ...DEFAULT_EXPERT_WORKFLOW_STRATEGY.executor,
  510. maxConsecutiveErrors:
  511. options.maxConsecutiveErrors ??
  512. DEFAULT_EXPERT_WORKFLOW_STRATEGY.executor.maxConsecutiveErrors,
  513. maxPlannerRuns:
  514. options.maxPlannerRuns ?? DEFAULT_EXPERT_WORKFLOW_STRATEGY.executor.maxPlannerRuns,
  515. },
  516. },
  517. task: "ship workflow scheduler",
  518. updatedAt: "2026-05-05T00:00:00.000Z",
  519. };
  520. }