streams.test.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. analyzeWorkflowScript,
  4. collectSitePhases,
  5. collectSites,
  6. createWorkflowProgram,
  7. interpret,
  8. lowerWorkflowScript,
  9. SNIPPET_FACADE_DTS,
  10. } from "../src/index.js";
  11. import { FACADE_SITING_CODE } from "../src/analysis/facade-misuse.js";
  12. import { corpusDiagnostics } from "./helpers/analysis-corpus.js";
  13. /**
  14. * 流水线原语 channel / future 的编译期行为(docs/dynamic-workflow/authoring.md「Streams」、
  15. * docs/analysis.md「Phases」):
  16. * - 两者无站点,但仍是 facade callable——别名逃逸走 9001;
  17. * - channel 是分析器「看穿」的容器:send 写入、for await 读出,生产者到消费者有数据边;
  18. * - future 体作为 entered strand 内联在调用点;
  19. * - collectSitePhases:唯一有名阶段进表,helper 被两处调用 / 首个标记之前的站点不进表。
  20. */
  21. const PIPELINE = `
  22. interface Fact { id: string; claim: string }
  23. interface Verdict { holds: boolean }
  24. const facts = channel<Fact>("facts");
  25. const verified: Fact[] = [];
  26. const research = future(async () => {
  27. phase("gather");
  28. try {
  29. const found = await agent("researcher").ask<Fact[]>("find facts");
  30. for (const fact of found) facts.send(fact);
  31. } finally {
  32. facts.close();
  33. }
  34. });
  35. const verify = future(async () => {
  36. phase("verify");
  37. for await (const fact of facts) {
  38. const v = await agent(\`verifier-\${fact.id}\`).ask<Verdict>(\`verify \${fact.claim}\`);
  39. if (v.holds) verified.push(fact);
  40. }
  41. });
  42. await Promise.all([research, verify]);
  43. phase("write");
  44. return agent("writer").ask<string>(\`write \${JSON.stringify(verified)}\`);
  45. `;
  46. function analyzeClean(source: string) {
  47. const result = analyzeWorkflowScript(source);
  48. expect(corpusDiagnostics(result.diagnostics)).toEqual([]);
  49. expect(result.ok).toBe(true);
  50. return result;
  51. }
  52. describe("streams — compile and lower", () => {
  53. it("compiles, analyzes and lowers a channel pipeline", () => {
  54. analyzeClean(PIPELINE);
  55. const lowered = lowerWorkflowScript(PIPELINE);
  56. expect(lowered.ok).toBe(true);
  57. const code = lowered.lowered?.code ?? "";
  58. expect(code).toContain('__host.channel("facts")');
  59. expect(code).toContain("__host.future(async () =>");
  60. // 无站点:站点 id 清单里没有 channel / future 的份。
  61. expect(
  62. lowered.lowered?.siteIds.some((id) => id.startsWith("channel") || id.startsWith("future")),
  63. ).toBe(false);
  64. });
  65. it("is present in the snippet facade too", () => {
  66. const snippet = [
  67. 'const ch = channel<number>("n");',
  68. "const producer = future(async () => { for (const n of [1, 2, 3]) ch.send(n); ch.close(); });",
  69. "let sum = 0;",
  70. "for await (const n of ch) sum += n;",
  71. "await producer;",
  72. "return sum;",
  73. ].join("\n");
  74. const workflow = createWorkflowProgram(snippet, { facadeDts: SNIPPET_FACADE_DTS });
  75. expect(workflow.program.getSemanticDiagnostics().map((d) => d.messageText)).toEqual([]);
  76. });
  77. });
  78. describe("streams — facade siting (9001)", () => {
  79. it("rejects aliasing Channel.send and future", () => {
  80. const source = [
  81. 'const ch = channel<string>("c");',
  82. "const send = ch.send;",
  83. "const spawn = future;",
  84. 'send("x");',
  85. 'await spawn(async () => { log("hi"); });',
  86. "return 1;",
  87. ].join("\n");
  88. const result = analyzeWorkflowScript(source);
  89. const codes = result.diagnostics.map((d) => d.code);
  90. expect(codes.filter((code) => code === FACADE_SITING_CODE).length).toBeGreaterThanOrEqual(2);
  91. expect(result.ok).toBe(false);
  92. });
  93. it("lets a channel value travel: stored, passed to a helper, retyped", () => {
  94. const source = [
  95. 'const ch = channel<number>("c");',
  96. "interface Sink { send(item: number): void }",
  97. "function feed(target: Channel<number>, n: number): void { target.send(n); }",
  98. "const sink: Sink = ch;",
  99. "feed(ch, 1);",
  100. "sink.send(2);",
  101. "ch.close();",
  102. "let total = 0;",
  103. "for await (const n of ch) total += n;",
  104. "return total;",
  105. ].join("\n");
  106. analyzeClean(source);
  107. });
  108. });
  109. describe("streams — the analyzer sees through the channel", () => {
  110. const result = analyzeClean(PIPELINE);
  111. const graph = result.graph!;
  112. it("draws a data edge from the producer ask to the consumer ask", () => {
  113. const edge = graph.edges.find(
  114. (e) => e.from === "ask#1" && e.to === "ask#2" && e.kind === "data",
  115. );
  116. expect(edge).toBeDefined();
  117. });
  118. it("inlines each future body as an entered strand region", () => {
  119. const strands = result.core!.trace.regions.filter(
  120. (region) => region.kind === "call" && region.strand === true && region.label === "future",
  121. );
  122. expect(strands.length).toBe(2);
  123. for (const strand of strands) expect(strand.entered).toBe(true);
  124. });
  125. it("places the consumer ask in the verify phase although the marker sits inside a future", () => {
  126. const steps = result.causality!.steps;
  127. const phases = new Map((result.causality!.phases ?? []).map((phase) => [phase.id, phase.name]));
  128. const phaseOf = (id: string) => phases.get(steps.find((step) => step.id === id)?.phase ?? "");
  129. expect(phaseOf("ask#1")).toBe("gather");
  130. expect(phaseOf("ask#2")).toBe("verify");
  131. expect(phaseOf("ask#3")).toBe("write");
  132. });
  133. });
  134. describe("collectSitePhases", () => {
  135. function sitePhasesOf(source: string): ReadonlyMap<string, string> {
  136. const workflow = createWorkflowProgram(source);
  137. const table = collectSites(workflow);
  138. return collectSitePhases(interpret(workflow, table));
  139. }
  140. it("lists every site with one named phase, actors included", () => {
  141. const phases = sitePhasesOf(PIPELINE);
  142. expect(Object.fromEntries(phases)).toEqual({
  143. "actor#1": "gather",
  144. "ask#1": "gather",
  145. "actor#2": "verify",
  146. "ask#2": "verify",
  147. "actor#3": "write",
  148. "ask#3": "write",
  149. });
  150. });
  151. it("leaves out a helper called from two phases and a call before the first marker", () => {
  152. const source = [
  153. 'const early = agent("early");',
  154. 'void early.ask("before any marker");',
  155. "async function check(what: string): Promise<string> {",
  156. " return agent(`checker-${what}`).ask(`check ${what}`);",
  157. "}",
  158. 'phase("first");',
  159. 'const a = await check("a");',
  160. 'phase("second");',
  161. 'const b = await check("b");',
  162. 'const late = await agent("late").ask(`${a} ${b}`);',
  163. "return late;",
  164. ].join("\n");
  165. const phases = sitePhasesOf(source);
  166. // 首个标记之前:unphased,不进表。
  167. expect(phases.has("actor#1")).toBe(false);
  168. expect(phases.has("ask#1")).toBe(false);
  169. // helper 里的站点被两个阶段各调一次:不唯一,不进表——引擎退回动态阶段。
  170. expect(phases.has("actor#2")).toBe(false);
  171. expect(phases.has("ask#2")).toBe(false);
  172. // 第二阶段独有的站点进表。
  173. expect(phases.get("actor#3")).toBe("second");
  174. expect(phases.get("ask#3")).toBe("second");
  175. });
  176. it("is empty for a script without markers", () => {
  177. expect(sitePhasesOf('return agent("a").ask("x");').size).toBe(0);
  178. });
  179. });