failures.test.ts 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. /**
  2. * 失败路径:错误是一等公民。墙钟超时 / abort / 脚本抛错 / 子进程输出损坏的 NDJSON 都必须被
  3. * 归一成清晰结算,绝不静默吞掉。见 docs/execution-engine.md 的"How the bridge settles the run"
  4. * 与 apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md:脚本之错 → errored;宿主侧故障(超时 / 崩溃 /
  5. * 协议损坏)→ stopped(interrupted);abort → stopped(user | model)。
  6. */
  7. import { describe, expect, it } from "vitest";
  8. import { InMemoryJournalStore, WorkflowError, type Caps, type RunSettlement } from "@zcode/dynamic-workflow";
  9. import { runWorkflowScript } from "../src/index.js";
  10. import { AutoDriver } from "./auto-driver.js";
  11. import { TEST_CWD } from "./helpers.js";
  12. interface LoweredOpts {
  13. timeoutMs?: number;
  14. signal?: AbortSignal;
  15. caps?: Caps;
  16. }
  17. async function runLowered(
  18. lowered: string,
  19. opts: LoweredOpts = {},
  20. ): Promise<{ settlement: RunSettlement; journal: InMemoryJournalStore }> {
  21. const journal = new InMemoryJournalStore();
  22. // HANG 的 ask 永不应答:空动作串让 driver 什么都不做,请求就一直在飞。
  23. const driver = new AutoDriver(journal, { asks: { "ask#1": () => [] } });
  24. const settlement = await runWorkflowScript({
  25. cwd: TEST_CWD,
  26. lowered,
  27. runId: "run",
  28. caps: opts.caps ?? { maxConcurrency: 4 },
  29. askSpecs: new Map([["ask#1", { typed: false }]]),
  30. validate: () => [],
  31. makeDriver: (sink) => {
  32. driver.attach(sink);
  33. return driver;
  34. },
  35. timeoutMs: opts.timeoutMs,
  36. signal: opts.signal,
  37. });
  38. return { settlement, journal };
  39. }
  40. /**
  41. * 永不结算的沙箱体(用于超时 / abort):一个 driver 永不应答的 ask。它是 run 「活着却无事可做」
  42. * 的唯一合法形态——一个裸的永不兑现的 promise如今是停滞,cell 会当场以 ScriptStalled 结束 run
  43. * (tests/streams.test.ts),再也等不到超时或 abort。
  44. */
  45. const HANG = 'await __host.ask("ask#1", __host.createActor("actor#1", "waiter"), "wait forever");';
  46. type Stopped = { status: "stopped"; reason: string; error?: WorkflowError };
  47. type Errored = { status: "errored"; error: WorkflowError };
  48. describe("failures — wall-clock timeout", () => {
  49. it("kills the child and stops the run as interrupted with a clear timeout error", async () => {
  50. const { settlement, journal } = await runLowered(HANG, { timeoutMs: 400 });
  51. expect(settlement.status).toBe("stopped");
  52. const stopped = settlement as Stopped;
  53. expect(stopped.reason).toBe("interrupted");
  54. expect(stopped.error).toBeInstanceOf(WorkflowError);
  55. expect(stopped.error?.code).toBe("Interrupted");
  56. expect(stopped.error?.message).toContain("wall-clock timeout of 400ms");
  57. // 引擎裁决落 journal:stopped(interrupted) + failure_json(可 resume),不伪装成用户取消。
  58. const run = journal.getRun("run");
  59. expect(run?.status).toBe("stopped");
  60. expect(run?.stopReason).toBe("interrupted");
  61. expect(run?.failure?.code).toBe("Interrupted");
  62. });
  63. });
  64. describe("failures — abort signal", () => {
  65. it("kills the child and settles stopped(user)", async () => {
  66. const controller = new AbortController();
  67. setTimeout(() => controller.abort(), 200);
  68. const { settlement, journal } = await runLowered(HANG, { signal: controller.signal });
  69. expect(settlement).toEqual({ status: "stopped", reason: "user" });
  70. // abort 是唯一的真取消:journal 记 stopped(user)(可 resume),不带 failure。
  71. expect(journal.getRun("run")).toMatchObject({ status: "stopped", stopReason: "user" });
  72. expect(journal.getRun("run")?.failure).toBeUndefined();
  73. });
  74. it('reads the initiator off the abort reason: "model" settles stopped(model)', async () => {
  75. const controller = new AbortController();
  76. setTimeout(() => controller.abort("model"), 200);
  77. const { settlement, journal } = await runLowered(HANG, { signal: controller.signal });
  78. expect(settlement).toEqual({ status: "stopped", reason: "model" });
  79. expect(journal.getRun("run")?.stopReason).toBe("model");
  80. });
  81. it('reads `{ superseded }` off the abort reason: settles stopped(superseded) with the successor', async () => {
  82. const controller = new AbortController();
  83. setTimeout(() => controller.abort({ superseded: "run-next" }), 200);
  84. const { settlement, journal } = await runLowered(HANG, { signal: controller.signal });
  85. expect(settlement).toEqual({ status: "stopped", reason: "superseded", supersededBy: "run-next" });
  86. // 后继 id 与原因同一笔落库(docs/execution-engine.md「Amend-resume」)。
  87. expect(journal.getRun("run")).toMatchObject({
  88. status: "stopped",
  89. stopReason: "superseded",
  90. supersededBy: "run-next",
  91. });
  92. expect(journal.getRun("run")?.failure).toBeUndefined();
  93. });
  94. // 宿主 App 关闭时停下自己拥有的 run(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Engine ownership」规则二):
  95. // run service 的 close() 以 "interrupted" abort 每个在飞条目,归一到与超时 / 沙箱崩溃同一族
  96. // 的 stopped(interrupted) + Interrupted——而不是 stopped(user),那在 UI 上读作用户按了停止。
  97. it('reads "interrupted" off the abort reason: settles stopped(interrupted) with an Interrupted failure', async () => {
  98. const controller = new AbortController();
  99. setTimeout(() => controller.abort("interrupted"), 200);
  100. const { settlement, journal } = await runLowered(HANG, { signal: controller.signal });
  101. expect(settlement.status).toBe("stopped");
  102. const stopped = settlement as Stopped;
  103. expect(stopped.reason).toBe("interrupted");
  104. expect(stopped.error).toBeInstanceOf(WorkflowError);
  105. expect(stopped.error?.code).toBe("Interrupted");
  106. // 文本指名 run 与成因:下一次激活时详情页据它解释这一行。
  107. expect(stopped.error?.message).toContain("run run was interrupted");
  108. expect(stopped.error?.message).toContain("the owning session closed");
  109. // 引擎自己写的那一笔:可 resume 的 stopped(interrupted) + failure_json。
  110. expect(journal.getRun("run")).toMatchObject({
  111. status: "stopped",
  112. stopReason: "interrupted",
  113. });
  114. expect(journal.getRun("run")?.failure?.code).toBe("Interrupted");
  115. });
  116. it("settles stopped(user) immediately when the signal is already aborted", async () => {
  117. const { settlement } = await runLowered(HANG, { signal: AbortSignal.abort() });
  118. expect(settlement).toEqual({ status: "stopped", reason: "user" });
  119. });
  120. });
  121. describe("failures — script error", () => {
  122. it("surfaces the script's thrown error as an errored run", async () => {
  123. const { settlement, journal } = await runLowered('throw new Error("boom from the script");');
  124. expect(settlement.status).toBe("errored");
  125. const error = (settlement as Errored).error;
  126. expect(error.code).toBe("DriverError");
  127. expect(error.message).toContain("boom from the script");
  128. expect(journal.getRun("run")?.status).toBe("errored");
  129. expect(journal.getRun("run")?.stopReason).toBeUndefined();
  130. });
  131. });
  132. describe("failures — malformed NDJSON from child", () => {
  133. it("surfaces a garbage line as interrupted rather than swallowing it", async () => {
  134. // 沙箱内经传输句柄 __send 直接吐一行非 JSON,模拟"子进程输出损坏"。
  135. const { settlement, journal } = await runLowered(
  136. 'globalThis.__send("this is not json"); await new Promise(() => {});',
  137. );
  138. expect(settlement.status).toBe("stopped");
  139. const stopped = settlement as Stopped;
  140. expect(stopped.reason).toBe("interrupted");
  141. expect(stopped.error?.code).toBe("Interrupted");
  142. expect(stopped.error?.message).toContain("NDJSON");
  143. // 引擎裁决落 journal。
  144. expect(journal.getRun("run")).toMatchObject({ status: "stopped", stopReason: "interrupted" });
  145. expect(journal.getRun("run")?.failure?.code).toBe("Interrupted");
  146. });
  147. });