child-entry-file.test.ts 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. /**
  2. * 沙箱入口文件的落盘契约(docs/dynamic-workflow/launch.md「Single-executable builds」)。
  3. *
  4. * Bug 根因:harness 原先把整份 lowered 脚本 base64 后放在子进程命令行上,Windows 的命令行上限是
  5. * 32,767 字符,脚本一过约 18 KB 就 `spawn ENAMETOOLONG`——Windows 上稍长的 run 一个都起不来。
  6. * 次生缺陷:这类 spawn 失败在 Node 里是**同步抛错**,绕过引擎,journal 行永远停在 running。
  7. *
  8. * 四件事钉住:
  9. * 1. 入口文件落在 `<cwd>/.zcode/workflow-runs/<runId>.mjs`,同目录有 `.gitignore`,run 结算后文件仍在;
  10. * 2. **回归护栏**:脚本再大,命令行长度也不变(与 200 KB 的 lowered 体无关);
  11. * 3. 项目 `.zcode` 写不进 → 回落 tmpdir + onWarning,run 照常;
  12. * 4. spawn 同步抛错 → 经引擎结算 failed,journal 行 status 是 failed 而不是 running。
  13. */
  14. import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
  15. import { tmpdir } from "node:os";
  16. import { join } from "node:path";
  17. import { afterEach, describe, expect, it, vi } from "vitest";
  18. import type { spawn as spawnType } from "node:child_process";
  19. import { InMemoryJournalStore } from "@zcode/dynamic-workflow";
  20. import {
  21. childEntryFileName,
  22. fallbackWorkflowRunsDir,
  23. runWorkflowScript,
  24. workflowRunsDir,
  25. writeChildEntryFile,
  26. type HarnessWarning,
  27. } from "../src/index.js";
  28. import { AutoDriver } from "./auto-driver.js";
  29. // 包一层真 spawn:截获 args,子进程照常启动;`spawnOverride` 存在时改为调用它(同步抛错用例)。
  30. const spawnCalls: Array<{ args: readonly string[] }> = [];
  31. let spawnOverride: ((...args: Parameters<typeof spawnType>) => ReturnType<typeof spawnType>) | undefined;
  32. vi.mock("node:child_process", async (importOriginal) => {
  33. const actual = await importOriginal<typeof import("node:child_process")>();
  34. const wrapped: typeof spawnType = ((...args: Parameters<typeof spawnType>) => {
  35. spawnCalls.push({ args: (args[1] ?? []) as readonly string[] });
  36. if (spawnOverride !== undefined) return spawnOverride(...args);
  37. return actual.spawn(...args);
  38. }) as typeof spawnType;
  39. return { ...actual, spawn: wrapped };
  40. });
  41. const roots: string[] = [];
  42. afterEach(async () => {
  43. spawnCalls.length = 0;
  44. spawnOverride = undefined;
  45. await Promise.all(roots.splice(0).map((root) => rm(root, { force: true, recursive: true })));
  46. });
  47. async function tempRoot(prefix: string): Promise<string> {
  48. const root = await mkdtemp(join(tmpdir(), prefix));
  49. roots.push(root);
  50. return root;
  51. }
  52. /** 跑一份手写 lowered 体(无 ask 站点),返回结算与 journal。 */
  53. async function runLowered(
  54. lowered: string,
  55. extra: Partial<Parameters<typeof runWorkflowScript>[0]> = {},
  56. ): Promise<{ settlement: Awaited<ReturnType<typeof runWorkflowScript>>; journal: InMemoryJournalStore }> {
  57. const journal = new InMemoryJournalStore();
  58. const driver = new AutoDriver(journal);
  59. const settlement = await runWorkflowScript({
  60. lowered,
  61. runId: "run",
  62. caps: { maxConcurrency: 4 },
  63. askSpecs: new Map(),
  64. validate: () => [],
  65. makeDriver: (sink) => {
  66. driver.attach(sink);
  67. return driver;
  68. },
  69. timeoutMs: 20000,
  70. ...extra,
  71. });
  72. return { settlement, journal };
  73. }
  74. describe("child entry file", () => {
  75. it("lands under <cwd>/.zcode/workflow-runs/<runId>.mjs with a .gitignore, and stays after the run settles", async () => {
  76. const cwd = await tempRoot("dwf-entry-cwd-");
  77. const { settlement } = await runLowered("return __host.args.x;", {
  78. cwd,
  79. runId: "dwfrun-1234",
  80. args: { x: 7 },
  81. });
  82. expect(settlement).toEqual({ status: "completed", artifact: 7 });
  83. const entryPath = join(cwd, ".zcode", "workflow-runs", "dwfrun-1234.mjs");
  84. expect(spawnCalls[0]!.args).toEqual(["--max-old-space-size=256", entryPath]);
  85. // 保留是裁决:目录兼作每次 run 实际执行体的存档。
  86. const text = await readFile(entryPath, "utf8");
  87. expect(text).toContain("// zcode dynamic workflow run dwfrun-1234");
  88. expect(text).toContain('export const payload = {"lowered":"return __host.args.x;","args":{"x":7},"maxOldSpaceSizeMb":256}');
  89. expect(text).toContain("export const start = ");
  90. // 只由 harness 写一份 `*`,绝不碰项目自己的 .gitignore。
  91. await expect(readFile(join(cwd, ".zcode", "workflow-runs", ".gitignore"), "utf8")).resolves.toBe("*\n");
  92. });
  93. it("keeps the command line short no matter how large the script is (Windows ENAMETOOLONG guard)", async () => {
  94. const cwd = await tempRoot("dwf-entry-big-");
  95. // 200 KB 的 lowered 体:远超 Windows 32,767 字符的命令行上限,也超过 Linux 128 KB 的单参数上限。
  96. const lowered = `const pad = ${JSON.stringify("x".repeat(200_000))};\nreturn pad.length;`;
  97. const { settlement } = await runLowered(lowered, { cwd });
  98. expect(settlement).toEqual({ status: "completed", artifact: 200_000 });
  99. const argvChars = spawnCalls[0]!.args.reduce((sum, arg) => sum + arg.length, 0);
  100. expect(argvChars).toBeLessThan(1_000);
  101. expect(spawnCalls[0]!.args.every((arg) => arg.length < 32_767)).toBe(true);
  102. });
  103. it("falls back to os.tmpdir() and warns when the project .zcode cannot be created", async () => {
  104. const cwd = await tempRoot("dwf-entry-fallback-");
  105. // `.zcode` 是个普通文件:mkdir 必然 ENOTDIR/EEXIST,正是「项目里写不进」的一种。
  106. await writeFile(join(cwd, ".zcode"), "not a directory", "utf8");
  107. const warnings: HarnessWarning[] = [];
  108. const { settlement } = await runLowered("return 1;", {
  109. cwd,
  110. runId: "dwfrun-fallback",
  111. onWarning: (warning) => warnings.push(warning),
  112. });
  113. expect(settlement).toEqual({ status: "completed", artifact: 1 });
  114. const expectedPath = join(fallbackWorkflowRunsDir(), "dwfrun-fallback.mjs");
  115. expect(spawnCalls[0]!.args[1]).toBe(expectedPath);
  116. await expect(stat(expectedPath)).resolves.toBeDefined();
  117. expect(warnings).toEqual([
  118. {
  119. kind: "entry_file_fallback",
  120. projectDir: join(cwd, ".zcode", "workflow-runs"),
  121. fallbackDir: fallbackWorkflowRunsDir(),
  122. error: expect.stringMatching(/ENOTDIR|EEXIST|ENOENT/),
  123. },
  124. ]);
  125. await rm(expectedPath, { force: true });
  126. });
  127. it("settles a synchronous spawn failure as stopped(interrupted) through the engine, so the journal row is not left running", async () => {
  128. const cwd = await tempRoot("dwf-entry-throw-");
  129. spawnOverride = () => {
  130. // Node 对 ENAMETOOLONG / E2BIG 正是这样同步抛的(只有 EACCES/EAGAIN/EMFILE/ENFILE/ENOENT 走 error 事件)。
  131. const error = new Error("spawn ENAMETOOLONG") as Error & { code: string };
  132. error.code = "ENAMETOOLONG";
  133. throw error;
  134. };
  135. const { settlement, journal } = await runLowered("return 1;", { cwd });
  136. expect(settlement.status).toBe("stopped");
  137. expect(settlement.status === "stopped" ? settlement.error?.message : "").toContain(
  138. "spawn ENAMETOOLONG",
  139. );
  140. // 引擎结算过:journal 行是 stopped(interrupted),不是永远 running 的孤儿(那会让 AmendWorkflow
  141. // 被「has not settled yet」拒绝);宿主侧故障可 resume。
  142. expect(journal.getRun("run")).toMatchObject({ status: "stopped", stopReason: "interrupted" });
  143. });
  144. });
  145. describe("writeChildEntryFile", () => {
  146. it("sanitises the run id into the file name", () => {
  147. expect(childEntryFileName("dwfrun-1234-abcd")).toBe("dwfrun-1234-abcd.mjs");
  148. expect(childEntryFileName("../evil/run id")).toBe(".._evil_run_id.mjs");
  149. });
  150. it("reports where it wrote", async () => {
  151. const cwd = await tempRoot("dwf-entry-unit-");
  152. const written = writeChildEntryFile({ cwd, runId: "r1", source: "export const x = 1;\n" });
  153. expect(written).toEqual({ path: join(workflowRunsDir(cwd), "r1.mjs"), location: "project" });
  154. await expect(readFile(written.path, "utf8")).resolves.toBe("export const x = 1;\n");
  155. });
  156. it("leaves an existing .gitignore alone", async () => {
  157. const cwd = await tempRoot("dwf-entry-gitignore-");
  158. writeChildEntryFile({ cwd, runId: "r1", source: "" });
  159. await writeFile(join(workflowRunsDir(cwd), ".gitignore"), "custom\n", "utf8");
  160. writeChildEntryFile({ cwd, runId: "r2", source: "" });
  161. await expect(readFile(join(workflowRunsDir(cwd), ".gitignore"), "utf8")).resolves.toBe("custom\n");
  162. });
  163. });