process-errors.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. import assert from "node:assert/strict";
  2. import { spawn } from "node:child_process";
  3. import { once } from "node:events";
  4. import test from "node:test";
  5. import { fileURLToPath } from "node:url";
  6. import { Writable } from "node:stream";
  7. import { parseZCodeProcessDiagnostic } from "@zcode/shared/process-diagnostic";
  8. import { isProtocolServerInvocation } from "../src/arguments.js";
  9. import { interceptKnownRuntimeWarnings } from "../src/runtime-warnings.js";
  10. import { installProtocolStderrBoundary } from "../src/protocol-stderr.js";
  11. import {
  12. installCliProcessErrorBoundary,
  13. type CliProcessErrorBoundaryTarget,
  14. } from "../src/process-errors.js";
  15. type Listener = (...args: never[]) => void;
  16. test("protocol stderr flush waits for the last diagnostic write callback", async () => {
  17. let release!: () => void;
  18. const stderr = new Writable({
  19. write(chunk, _encoding, callback) {
  20. if (chunk.length) release = callback;
  21. else callback();
  22. },
  23. });
  24. const restore = installProtocolStderrBoundary(stderr);
  25. const warnings = interceptKnownRuntimeWarnings(stderr as unknown as NodeJS.WriteStream);
  26. let flushed = false;
  27. try {
  28. stderr.write("last diagnostic");
  29. const flush = new Promise<void>((resolve) =>
  30. stderr.write("", () => {
  31. flushed = true;
  32. resolve();
  33. }),
  34. );
  35. await new Promise((resolve) => setImmediate(resolve));
  36. assert.equal(flushed, false);
  37. release();
  38. await flush;
  39. } finally {
  40. warnings.restore();
  41. restore();
  42. stderr.destroy();
  43. }
  44. });
  45. test("protocol lifecycle follows the command, not an option value", () => {
  46. assert.equal(isProtocolServerInvocation(["--prompt", "app-server"]), false);
  47. assert.equal(isProtocolServerInvocation(["--cwd", "app-server", "doctor"]), false);
  48. assert.equal(isProtocolServerInvocation(["--target", "agent-server"]), false);
  49. assert.equal(isProtocolServerInvocation(["__zcode-plugin-host", "app-server"]), false);
  50. assert.equal(isProtocolServerInvocation(["app-server", "--help"]), false);
  51. assert.equal(isProtocolServerInvocation(["--cwd", "/tmp", "app-server", "--stdio"]), true);
  52. assert.equal(isProtocolServerInvocation(["agent-server", "--stdio"]), true);
  53. });
  54. class FakeProcess implements CliProcessErrorBoundaryTarget {
  55. private readonly listeners = new Map<string, Set<Listener>>();
  56. on(event: string, listener: Listener): this {
  57. const listeners = this.listeners.get(event) ?? new Set<Listener>();
  58. listeners.add(listener);
  59. this.listeners.set(event, listeners);
  60. return this;
  61. }
  62. off(event: string, listener: Listener): this {
  63. this.listeners.get(event)?.delete(listener);
  64. return this;
  65. }
  66. emit(event: string, ...args: never[]): void {
  67. for (const listener of this.listeners.get(event) ?? []) {
  68. listener(...args);
  69. }
  70. }
  71. listenerCount(event: string): number {
  72. return this.listeners.get(event)?.size ?? 0;
  73. }
  74. }
  75. function createStderr(): { output: () => string; write: (chunk: string) => boolean } {
  76. let value = "";
  77. return {
  78. output: () => value,
  79. write: (chunk: string) => {
  80. value += chunk;
  81. return true;
  82. },
  83. };
  84. }
  85. test("process error boundary observes uncaught exceptions without throwing", () => {
  86. const target = new FakeProcess();
  87. const stderr = createStderr();
  88. const dispose = installCliProcessErrorBoundary({ target, stderr, onFatal: () => {} });
  89. const error = new Error("uncaught boom");
  90. target.emit("uncaughtExceptionMonitor", error, "uncaughtException");
  91. target.emit("uncaughtException", error);
  92. assert.match(stderr.output(), /kind=uncaughtException/);
  93. assert.match(stderr.output(), /uncaught boom/);
  94. const events = stderr.output().split("\n").map(parseZCodeProcessDiagnostic).filter(Boolean);
  95. assert.equal(events.length, 1);
  96. assert.equal(events[0]?.name, "Error");
  97. assert.equal(events[0]?.message, "uncaught boom");
  98. assert.equal(events[0]?.stack, error.stack);
  99. assert.equal(events[0]?.kind, "uncaughtException");
  100. assert.equal(target.listenerCount("uncaughtException"), 1);
  101. assert.equal(target.listenerCount("unhandledRejection"), 1);
  102. assert.equal(target.listenerCount("uncaughtExceptionMonitor"), 1);
  103. dispose();
  104. assert.equal(target.listenerCount("uncaughtException"), 0);
  105. assert.equal(target.listenerCount("unhandledRejection"), 0);
  106. assert.equal(target.listenerCount("uncaughtExceptionMonitor"), 0);
  107. });
  108. test("process error boundary observes non-Error promise rejection reasons", () => {
  109. const target = new FakeProcess();
  110. const stderr = createStderr();
  111. const dispose = installCliProcessErrorBoundary({ target, stderr, onFatal: () => {} });
  112. target.emit("unhandledRejection", "rejected value", Promise.resolve());
  113. assert.match(stderr.output(), /kind=unhandledRejection/);
  114. assert.match(stderr.output(), /rejected value/);
  115. const event = stderr.output().split("\n").map(parseZCodeProcessDiagnostic).find(Boolean);
  116. assert.equal(event?.kind, "unhandledRejection");
  117. assert.equal(event?.message, "rejected value");
  118. dispose();
  119. });
  120. test("fatal diagnostics are bounded and shutdown is requested only once", () => {
  121. const target = new FakeProcess();
  122. const stderr = createStderr();
  123. let fatalCount = 0;
  124. const dispose = installCliProcessErrorBoundary({
  125. target,
  126. stderr,
  127. onFatal: () => {
  128. fatalCount += 1;
  129. },
  130. });
  131. const error = new Error("x".repeat(20_000));
  132. target.emit("uncaughtExceptionMonitor", error, "uncaughtException");
  133. target.emit("uncaughtException", error);
  134. target.emit("uncaughtException", error);
  135. const events = stderr.output().split("\n").map(parseZCodeProcessDiagnostic).filter(Boolean);
  136. assert.equal(events.length, 1);
  137. assert.equal(fatalCount, 1);
  138. assert.equal(events[0]?.origin, "uncaughtException");
  139. assert.equal(events[0]?.message.length, 4000);
  140. assert.ok((events[0]?.stack?.length ?? 0) <= 16_000);
  141. dispose();
  142. });
  143. test("serialization and stderr failures cannot escape the exception boundary", () => {
  144. const target = new FakeProcess();
  145. const dispose = installCliProcessErrorBoundary({
  146. onFatal: () => {},
  147. target,
  148. stderr: {
  149. write() {
  150. throw new Error("closed pipe");
  151. },
  152. },
  153. });
  154. const hostile = {
  155. toJSON() {
  156. throw new Error("toJSON failed");
  157. },
  158. toString() {
  159. throw new Error("toString failed");
  160. },
  161. };
  162. assert.doesNotThrow(() => target.emit("unhandledRejection", hostile));
  163. assert.doesNotThrow(() => target.emit("uncaughtException", new Error("write failure")));
  164. dispose();
  165. });
  166. const fixture = fileURLToPath(new URL("./fixtures/protocol-lifecycle-child.ts", import.meta.url));
  167. function startChild(mode = "serving", rejectionMode = "throw") {
  168. const child = spawn(
  169. process.execPath,
  170. [`--unhandled-rejections=${rejectionMode}`, "--import", "tsx", fixture, mode],
  171. { stdio: ["pipe", "pipe", "pipe"] },
  172. );
  173. const stdout: string[] = [];
  174. const stderr: Buffer[] = [];
  175. let buffer = "";
  176. child.stdout.on("data", (chunk: Buffer) => {
  177. buffer += chunk.toString();
  178. const lines = buffer.split("\n");
  179. buffer = lines.pop()!;
  180. for (const line of lines) stdout.push((JSON.parse(line) as { id: string }).id);
  181. });
  182. child.stderr.on("data", (chunk: Buffer) => stderr.push(chunk));
  183. const exited = once(child, "close");
  184. const waitFor = async (id: string) => {
  185. const deadline = Date.now() + 5_000;
  186. while (!stdout.includes(id)) {
  187. assert.ok(
  188. Date.now() < deadline && child.exitCode === null,
  189. `missing ${id}: ${Buffer.concat(stderr)}`,
  190. );
  191. await new Promise((resolve) => setTimeout(resolve, 10));
  192. }
  193. };
  194. return { child, stdout, stderr, exited, waitFor };
  195. }
  196. for (const rejectionMode of ["throw", "strict"]) {
  197. for (const command of ["throw", "reject"]) {
  198. test(
  199. `fatal ${command} reports once and exits (${rejectionMode})`,
  200. { timeout: 10_000 },
  201. async (t) => {
  202. const probe = startChild("serving", rejectionMode);
  203. t.after(() => probe.child.kill("SIGKILL"));
  204. await probe.waitFor("ready");
  205. probe.child.stdin.write(command + "\n");
  206. const [code, signal] = await probe.exited;
  207. assert.equal(code, 1);
  208. assert.equal(signal, null);
  209. const events = Buffer.concat(probe.stderr)
  210. .toString()
  211. .split("\n")
  212. .map(parseZCodeProcessDiagnostic)
  213. .filter(Boolean);
  214. assert.equal(events.length, 1);
  215. assert.equal(
  216. events[0]?.kind,
  217. command === "throw" ? "uncaughtException" : "unhandledRejection",
  218. );
  219. },
  220. );
  221. }
  222. }
  223. test(
  224. "real broken stderr does not recurse or terminate a healthy protocol",
  225. { timeout: 10_000 },
  226. async (t) => {
  227. const probe = startChild();
  228. t.after(() => probe.child.kill("SIGKILL"));
  229. await probe.waitFor("ready");
  230. probe.child.stderr.destroy();
  231. probe.child.stdin.write("log\n");
  232. await probe.waitFor("healthy");
  233. probe.child.stdin.write("ping\n");
  234. await probe.waitFor("pong");
  235. probe.child.stdin.end();
  236. const [code, signal] = await probe.exited;
  237. assert.equal(code, 0);
  238. assert.equal(signal, null);
  239. },
  240. );
  241. for (const mode of ["startup-hung", "handler-hung", "serving"]) {
  242. test(
  243. `EOF bounds ${mode} even when the entrypoint never returns`,
  244. { timeout: 10_000 },
  245. async (t) => {
  246. const probe = startChild(mode);
  247. t.after(() => probe.child.kill("SIGKILL"));
  248. await probe.waitFor("ready");
  249. const started = Date.now();
  250. probe.child.stdin.end();
  251. const [code, signal] = await probe.exited;
  252. assert.equal(code, 0);
  253. assert.equal(signal, null);
  254. assert.ok(Date.now() - started < 2_000);
  255. },
  256. );
  257. }
  258. test("broken stdout stops the runtime", { timeout: 10_000 }, async (t) => {
  259. const probe = startChild();
  260. t.after(() => probe.child.kill("SIGKILL"));
  261. await probe.waitFor("ready");
  262. probe.child.stdout.destroy();
  263. probe.child.stdin.write("output\n");
  264. const [code, signal] = await probe.exited;
  265. assert.equal(code, 1);
  266. assert.equal(signal, null);
  267. });
  268. test(
  269. "repeated signals do not reset the first shutdown deadline or cause",
  270. { timeout: 10_000 },
  271. async (t) => {
  272. const probe = startChild("handler-hung");
  273. t.after(() => probe.child.kill("SIGKILL"));
  274. await probe.waitFor("ready");
  275. probe.child.stdin.end();
  276. await new Promise((resolve) => setTimeout(resolve, 150));
  277. if (process.platform !== "win32") {
  278. probe.child.kill("SIGTERM");
  279. probe.child.kill("SIGTERM");
  280. }
  281. const [code, signal] = await probe.exited;
  282. assert.equal(code, 0);
  283. assert.equal(signal, null);
  284. },
  285. );