streams.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. /**
  2. * 流水线原语 channel / future 与停滞检测在**真沙箱**里的行为(docs/dynamic-workflow/authoring.md
  3. * 「Streams」、execution-engine.md「The vm cell」)。跑真子进程而不是桩:channel 的实现、
  4. * `__checkStalled` 的调度点(setImmediate)与 error-complete 的收尾都只在这条链上成立。
  5. */
  6. import { describe, expect, it } from "vitest";
  7. import {
  8. InMemoryJournalStore,
  9. collectSitePhases,
  10. collectSites,
  11. createWorkflowProgram,
  12. interpret,
  13. type RunSettlement,
  14. } from "@zcode/dynamic-workflow";
  15. import { runWorkflowScript } from "../src/index.js";
  16. import { AutoDriver } from "./auto-driver.js";
  17. import { askSpecsFor, runScript, TEST_CWD } from "./helpers.js";
  18. /** 直接投喂手写 lowered 体(自由标识符仅 `__host`),返回结算。 */
  19. async function runLowered(lowered: string): Promise<RunSettlement> {
  20. const journal = new InMemoryJournalStore();
  21. const driver = new AutoDriver(journal);
  22. return runWorkflowScript({
  23. cwd: TEST_CWD,
  24. lowered,
  25. caps: { maxConcurrency: 4 },
  26. askSpecs: new Map(),
  27. validate: () => [],
  28. makeDriver: (sink) => {
  29. driver.attach(sink);
  30. return driver;
  31. },
  32. timeoutMs: 15000,
  33. });
  34. }
  35. function failureMessage(settlement: RunSettlement): string {
  36. expect(settlement.status).toBe("errored");
  37. return (settlement as { status: "errored"; error: { message: string } }).error.message;
  38. }
  39. describe("channel — a pipeline in the sandbox", () => {
  40. it("streams every item from three producers through two consumers exactly once", async () => {
  41. const script = [
  42. 'const facts = channel<string>("facts");',
  43. "const seen: string[] = [];",
  44. "const research = future(async () => {",
  45. " try {",
  46. ' await Promise.all(["a", "b", "c"].map(async (angle) => {',
  47. " const found = await agent(`researcher-${angle}`).ask<string[]>(`find ${angle}`);",
  48. " for (const fact of found) facts.send(fact);",
  49. " }));",
  50. " } finally {",
  51. " facts.close();",
  52. " }",
  53. "});",
  54. "const verify = future(async () => {",
  55. " await Promise.all([1, 2].map(async () => {",
  56. " for await (const fact of facts) {",
  57. " seen.push(await agent(`verifier-${fact}`).ask(`verify ${fact}`));",
  58. " }",
  59. " }));",
  60. "});",
  61. "await Promise.all([research, verify]);",
  62. "return seen.sort();",
  63. ].join("\n");
  64. const { settlement, journal } = await runScript(script, {
  65. asks: {
  66. "ask#1": ({ message }) => {
  67. const angle = message.instructions.slice("find ".length);
  68. return { type: "submit", payload: [`${angle}1`, `${angle}2`] };
  69. },
  70. "ask#2": ({ message }) => ({
  71. type: "text",
  72. finalText: message.instructions.slice("verify ".length),
  73. }),
  74. },
  75. });
  76. expect(settlement).toEqual({
  77. status: "completed",
  78. artifact: ["a1", "a2", "b1", "b2", "c1", "c2"],
  79. });
  80. // 六个 fact,六个 verifier ask;每个 fact 恰好被一个消费者拿到。
  81. expect(
  82. journal
  83. .listNodes("run", { kinds: "all", withResult: true })
  84. .filter((node) => node.siteId === "ask#2"),
  85. ).toHaveLength(6);
  86. });
  87. it("drains buffered items after close, then ends every receiver", async () => {
  88. const settlement = await runLowered(`
  89. const ch = __host.channel("buffered");
  90. for (let i = 0; i < 5000; i++) ch.send(i);
  91. ch.close();
  92. let sum = 0;
  93. let count = 0;
  94. for await (const n of ch) { sum += n; count += 1; }
  95. // 关闭后再迭代:立即结束,不挂起。
  96. for await (const n of ch) { sum += n; }
  97. return [count, sum];
  98. `);
  99. expect(settlement).toEqual({ status: "completed", artifact: [5000, (4999 * 5000) / 2] });
  100. });
  101. it("wakes parked receivers in arrival order and hands each item to exactly one of them", async () => {
  102. const settlement = await runLowered(`
  103. const ch = __host.channel("fifo");
  104. const got = [[], []];
  105. const consumers = [0, 1].map((w) => __host.future(async () => {
  106. for await (const n of ch) got[w].push(n);
  107. }));
  108. // 两个接收者都已停在空通道上;逐个 send 应轮流唤醒 0、1、0、1。
  109. await Promise.resolve();
  110. for (let i = 0; i < 4; i++) ch.send(i);
  111. ch.close();
  112. await Promise.all(consumers);
  113. return got;
  114. `);
  115. expect(settlement).toEqual({
  116. status: "completed",
  117. artifact: [
  118. [0, 2],
  119. [1, 3],
  120. ],
  121. });
  122. });
  123. it("send after close throws a catchable ChannelClosed naming the channel", async () => {
  124. const settlement = await runLowered(`
  125. const ch = __host.channel("facts");
  126. ch.close();
  127. ch.close();
  128. try { ch.send(1); return "NO-THROW"; } catch (e) { return [e.name, e.code, e.message]; }
  129. `);
  130. expect(settlement.status).toBe("completed");
  131. const [name, code, message] = (settlement as { status: "completed"; artifact: string[] })
  132. .artifact;
  133. expect(name).toBe("ChannelClosed");
  134. expect(code).toBe("ChannelClosed");
  135. expect(message).toContain('"facts"');
  136. });
  137. });
  138. describe("future — a named async IIFE", () => {
  139. it("runs the body to its first await before returning, and turns a sync throw into a rejection", async () => {
  140. const settlement = await runLowered(`
  141. const order = [];
  142. const f = __host.future(async () => { order.push("body"); await null; order.push("after"); return 7; });
  143. order.push("returned");
  144. const value = await f;
  145. let rejected = "no";
  146. try { await __host.future(() => { throw new Error("boom"); }); } catch (e) { rejected = e.message; }
  147. return [order, value, rejected];
  148. `);
  149. expect(settlement).toEqual({
  150. status: "completed",
  151. artifact: [["body", "returned", "after"], 7, "boom"],
  152. });
  153. });
  154. });
  155. describe("stall detection — a stuck run fails instead of hanging", () => {
  156. it("names the channel and the waiting receivers when nobody can send again", async () => {
  157. const settlement = await runLowered(`
  158. const facts = __host.channel("facts");
  159. const consumers = [1, 2].map(() => __host.future(async () => { for await (const f of facts) {} }));
  160. await Promise.all(consumers);
  161. return "unreachable";
  162. `);
  163. const message = failureMessage(settlement);
  164. expect(message).toContain("Deadlock");
  165. expect(message).toContain('2 on "facts"');
  166. expect(message).toContain("close()");
  167. });
  168. it("fires only once the last in-flight request has been answered", async () => {
  169. // 生产者的 ask 在飞时不能误报;它结算、发送、却忘了 close 之后,消费者停在空通道上——
  170. // 那一刻(最后一条 response 投递之后)才是死锁。
  171. const script = [
  172. 'const facts = channel<string>("facts");',
  173. "const seen: string[] = [];",
  174. "const research = future(async () => {",
  175. ' const found = await agent("researcher").ask<string[]>("find");',
  176. " for (const fact of found) facts.send(fact);",
  177. " // forgot facts.close()",
  178. "});",
  179. "const verify = future(async () => {",
  180. " for await (const fact of facts) seen.push(fact);",
  181. "});",
  182. "await Promise.all([research, verify]);",
  183. "return seen;",
  184. ].join("\n");
  185. const { settlement, journal } = await runScript(script, {
  186. asks: { "ask#1": () => ({ type: "submit", payload: ["x", "y"] }) },
  187. });
  188. const message = failureMessage(settlement);
  189. expect(message).toContain('1 on "facts"');
  190. // 生产者的 ask 正常结算了:检测没有抢在 response 前面。
  191. expect(journal.getNode("run", "ask#1", 1)?.status).toBe("completed");
  192. });
  193. it("reports a promise that can never settle as a stall", async () => {
  194. const settlement = await runLowered(`await new Promise(() => {}); return 1;`);
  195. expect(failureMessage(settlement)).toContain("Stalled");
  196. });
  197. it("rests on the cell having no timers of its own", async () => {
  198. const settlement = await runLowered(
  199. `return [typeof setTimeout, typeof setImmediate, typeof setInterval, typeof queueMicrotask];`,
  200. );
  201. expect(settlement).toEqual({
  202. status: "completed",
  203. artifact: ["undefined", "undefined", "undefined", "undefined"],
  204. });
  205. });
  206. });
  207. describe("lexical phases end to end", () => {
  208. it("stamps a producer's post-await ask with its own stage although the consumer's marker ran last", async () => {
  209. const script = [
  210. 'const facts = channel<string>("facts");',
  211. "const seen: string[] = [];",
  212. "const research = future(async () => {",
  213. ' phase("Gather facts");',
  214. " try {",
  215. ' const first = await agent("scout").ask<string[]>("scout");',
  216. " // 首次 await 之后再发一个 ask:动态戳会说 Verify(它的标记最后跑过),词法戳说 Gather。",
  217. ' const more = await agent("digger").ask<string[]>(`dig ${first.length}`);',
  218. " for (const fact of [...first, ...more]) facts.send(fact);",
  219. " } finally {",
  220. " facts.close();",
  221. " }",
  222. "});",
  223. "const verify = future(async () => {",
  224. ' phase("Verify facts");',
  225. " for await (const fact of facts) seen.push(await agent(`verifier-${fact}`).ask(`verify ${fact}`));",
  226. "});",
  227. "await Promise.all([research, verify]);",
  228. "return seen;",
  229. ].join("\n");
  230. const workflow = createWorkflowProgram(script);
  231. const sitePhases = collectSitePhases(interpret(workflow, collectSites(workflow)));
  232. expect(sitePhases.get("ask#2")).toBe("Gather facts");
  233. expect(sitePhases.get("ask#3")).toBe("Verify facts");
  234. const journal = new InMemoryJournalStore();
  235. const driver = new AutoDriver(journal, {
  236. asks: {
  237. "ask#1": () => ({ type: "submit", payload: ["a"] }),
  238. "ask#2": () => ({ type: "submit", payload: ["b"] }),
  239. "ask#3": ({ message }) => ({ type: "text", finalText: message.instructions }),
  240. },
  241. });
  242. const settlement = await runWorkflowScript({
  243. scriptText: script,
  244. cwd: TEST_CWD,
  245. runId: "run",
  246. caps: { maxConcurrency: 16 },
  247. askSpecs: askSpecsFor(script),
  248. sitePhases,
  249. validate: () => [],
  250. makeDriver: (sink) => {
  251. driver.attach(sink);
  252. return driver;
  253. },
  254. timeoutMs: 20000,
  255. });
  256. expect(settlement.status).toBe("completed");
  257. const phaseOf = new Map(
  258. driver
  259. .eventsOfType("node-queued")
  260. .map((e) => [`${e.instance.siteId}@${e.instance.ordinal}`, e.phaseName]),
  261. );
  262. expect(phaseOf.get("ask#1@1")).toBe("Gather facts");
  263. expect(phaseOf.get("ask#2@1")).toBe("Gather facts");
  264. expect(phaseOf.get("ask#3@1")).toBe("Verify facts");
  265. expect(phaseOf.get("ask#3@2")).toBe("Verify facts");
  266. });
  267. });