agent-crash-diagnostic.node.test.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. // perf_agent_crash 的退出诊断回归。App 业务单测已退役(docs/testing/unit-test-quality.md);
  2. // 这里是经评审同意的例外:Windows 退出码 0xE0000008 在 Linux 上无法用真实进程复现,
  3. // 只能对纯函数取样。使用 node:test,不进入工程 Vitest 清单和 pre-push;
  4. // 相关文件改动的 MR 上由 CI job test:agent-crash-diagnostic 自动执行(.gitlab/ci/23-agent-crash-diagnostic.yml)。
  5. // pnpm --filter @zcode/desktop test:agent-crash-diagnostic
  6. import assert from "node:assert/strict";
  7. import * as dns from "node:dns";
  8. import { readFileSync } from "node:fs";
  9. import { constants as osConstants } from "node:os";
  10. import { resolve } from "node:path";
  11. import { test } from "node:test";
  12. import { getSystemErrorMap } from "node:util";
  13. import {
  14. classifyAgentProcessExitCause,
  15. parseAgentProcessExitDiagnostic,
  16. redactAgentDiagnosticSecrets,
  17. } from "@zcode/shared/agent-crash-diagnostic";
  18. // 构造样本:长期运行的 Agent 在几小时前打印过一次 HTTP 429 失败对象,stderr 尾部 20 行
  19. // 只剩响应头逐行转储;值均为虚构。
  20. const STALE_HTTP_429_DUMP = [
  21. " connection: 'keep-alive',",
  22. " 'content-type': 'application/json',",
  23. " date: 'Mon, 02 Nov 2026 01:02:03 GMT',",
  24. " eagleid: '0123456789abcdef0123456789',",
  25. " server: 'ESA',",
  26. " 'set-cookie': ***REDACTED***,",
  27. " 'strict-transport-security': 'max-age=31536000; includeSubDomains',",
  28. " 'transfer-encoding': 'chunked',",
  29. " vary: 'Origin, Access-Control-Request-Method',",
  30. " via: 'cache-1.example[100,0,DP], cache-2.example[101,0]',",
  31. " 'x-content-type-options': 'nosniff',",
  32. " 'x-request-id': '20261102010203abcdef',",
  33. " 'x-site-cache-status': 'DYNAMIC'",
  34. " },",
  35. " responseStatus: 429,",
  36. " statusCode: undefined,",
  37. " code: undefined",
  38. "}",
  39. ];
  40. const NATIVE_OOM_EXIT_CODE = 3758096392; // 0xE0000008
  41. test("classifies the Windows native allocation failure exit code as out of memory", () => {
  42. assert.equal(classifyAgentProcessExitCause(NATIVE_OOM_EXIT_CODE), "native_out_of_memory");
  43. // 有符号 int32 形式的同一个 DWORD。
  44. assert.equal(classifyAgentProcessExitCause(-536870904), "native_out_of_memory");
  45. for (const exitCode of [null, undefined, 0, 1, 137, 0xc0000005, 0x40010004]) {
  46. assert.equal(classifyAgentProcessExitCause(exitCode), undefined, String(exitCode));
  47. }
  48. });
  49. test("reports exit 0xE0000008 as AgentOutOfMemory even when stderr ends with a stale HTTP 429 dump", () => {
  50. const diagnostic = parseAgentProcessExitDiagnostic({
  51. exitCode: NATIVE_OOM_EXIT_CODE,
  52. signal: null,
  53. stderrTail: STALE_HTTP_429_DUMP,
  54. workspacePath: "/Users/dev/project",
  55. });
  56. assert.equal(diagnostic.errorName, "AgentOutOfMemory");
  57. assert.equal(diagnostic.errorCode, "ERR_OUT_OF_MEMORY");
  58. assert.equal(diagnostic.diagnosticClass, "oom");
  59. assert.equal(diagnostic.errorMessage, "Native memory allocation failed (exit code 0xE0000008)");
  60. // stderr 仍随事件保留,便于排查,但不进入指纹:有无历史输出都聚合到同一类。
  61. assert.match(diagnostic.errorStack, /responseStatus: 429/);
  62. const withoutStderr = parseAgentProcessExitDiagnostic({
  63. exitCode: NATIVE_OOM_EXIT_CODE,
  64. signal: null,
  65. workspacePath: "/Users/dev/other",
  66. });
  67. assert.equal(diagnostic.errorFingerprint, withoutStderr.errorFingerprint);
  68. });
  69. test("does not take error code or summary from an HTTP response header dump", () => {
  70. const exit1 = parseAgentProcessExitDiagnostic({
  71. exitCode: 1,
  72. signal: null,
  73. stderrTail: STALE_HTTP_429_DUMP,
  74. workspacePath: "/Users/dev/project",
  75. });
  76. assert.equal(exit1.errorCode, "");
  77. assert.equal(exit1.errorName, "AgentProcessExit");
  78. assert.equal(exit1.diagnosticClass, "none");
  79. assert.equal(exit1.errorMessage, "Agent process exited unexpectedly (code=1, signal=null)");
  80. const exit2 = parseAgentProcessExitDiagnostic({
  81. exitCode: 2,
  82. signal: null,
  83. stderrTail: STALE_HTTP_429_DUMP,
  84. workspacePath: "/Users/dev/project",
  85. });
  86. // 指纹随退出码区分,而不是被同一段无关日志聚到一起。
  87. assert.notEqual(exit1.errorFingerprint, exit2.errorFingerprint);
  88. });
  89. test("only accepts real errno names when no explicit code is printed", () => {
  90. const diagnostic = parseAgentProcessExitDiagnostic({
  91. exitCode: 1,
  92. signal: null,
  93. stderrTail: ["Unexpected END of input while reading ENV file"],
  94. workspacePath: "/Users/dev/project",
  95. });
  96. assert.equal(diagnostic.errorCode, "");
  97. assert.equal(diagnostic.diagnosticClass, "generic");
  98. });
  99. test("keeps errno and V8 heap out-of-memory diagnostics from stderr", () => {
  100. const errno = parseAgentProcessExitDiagnostic({
  101. exitCode: 1,
  102. signal: null,
  103. stderrTail: [
  104. "node:events:497",
  105. " throw er; // Unhandled 'error' event",
  106. "Error: write EPIPE",
  107. " at afterWriteDispatched (node:internal/stream_base_commons:161:15)",
  108. " errno: -32,",
  109. " code: 'EPIPE',",
  110. " syscall: 'write'",
  111. "}",
  112. ],
  113. workspacePath: "/Users/dev/project",
  114. });
  115. assert.equal(errno.errorName, "Error");
  116. assert.equal(errno.errorCode, "EPIPE");
  117. assert.equal(errno.diagnosticClass, "errno");
  118. assert.equal(errno.errorMessage, "write EPIPE");
  119. const heap = parseAgentProcessExitDiagnostic({
  120. exitCode: 134,
  121. signal: null,
  122. stderrTail: [
  123. "<--- Last few GCs --->",
  124. "FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory",
  125. ],
  126. workspacePath: "/Users/dev/project",
  127. });
  128. assert.equal(heap.errorName, "AgentOutOfMemory");
  129. assert.equal(heap.errorCode, "ERR_OUT_OF_MEMORY");
  130. assert.equal(heap.diagnosticClass, "oom");
  131. });
  132. test("recognizes every errno and DNS error name Node reports, e.g. getaddrinfo ENOTFOUND", () => {
  133. // 名单手写,会漏:以运行时 Node 自己的 errno / dns 错误码为准逐个核对。
  134. // EOF、UNKNOWN 故意不收:普通文本里太常见,会重演 `ESA` 那类误报。
  135. const names = new Set([
  136. ...[...getSystemErrorMap().values()].map(([name]) => name),
  137. ...Object.keys(osConstants.errno),
  138. ...Object.values(dns).filter(
  139. (value): value is string => typeof value === "string" && /^E[A-Z]+$/.test(value),
  140. ),
  141. ]);
  142. names.delete("EOF");
  143. names.delete("UNKNOWN");
  144. // Windows 的 os.constants.errno 还含 `WSAEINTR` 这类 Winsock 常量;Node 报错用的是 libuv 的
  145. // 通用名(ECONNRESET 等),解析器也只认 E 开头的名字。只核对 E 开头的,避免在 Windows 上误报。
  146. for (const name of names) if (!/^E[A-Z0-9_]+$/.test(name)) names.delete(name);
  147. for (const code of names) {
  148. const diagnostic = parseAgentProcessExitDiagnostic({
  149. exitCode: 1,
  150. signal: null,
  151. stderrTail: [`Error: getaddrinfo ${code} api.example.com`],
  152. workspacePath: "/Users/dev/project",
  153. });
  154. assert.equal(diagnostic.errorCode, code, code);
  155. assert.equal(diagnostic.diagnosticClass, "errno", code);
  156. }
  157. });
  158. test("does not report Bearer tokens or later cookie segments", () => {
  159. const diagnostic = parseAgentProcessExitDiagnostic({
  160. exitCode: 1,
  161. signal: null,
  162. stderrTail: [
  163. "Error: request failed",
  164. " Authorization: Bearer fake-bearer-value-0001",
  165. " cookie: session=fake-cookie-a; refresh=fake-cookie-b",
  166. ],
  167. workspacePath: "/Users/dev/project",
  168. });
  169. for (const secret of ["fake-bearer-value-0001", "fake-cookie-a", "fake-cookie-b"]) {
  170. assert.doesNotMatch(diagnostic.errorStack, new RegExp(secret), secret);
  171. assert.doesNotMatch(diagnostic.errorMessage, new RegExp(secret), secret);
  172. }
  173. });
  174. // 真实链路:services 逐行收集 stderr 时先遮一遍,desktop main 上报前再遮一遍。
  175. const SERVICES_SOURCE = resolve(
  176. import.meta.dirname,
  177. "../../services/src/zcode-agent/zcodeAgentProcessManager.ts",
  178. );
  179. function parseThroughServicesAndMain(stderrTail: string[]) {
  180. return parseAgentProcessExitDiagnostic({
  181. exitCode: 1,
  182. signal: null,
  183. stderrTail: stderrTail.map(redactAgentDiagnosticSecrets),
  184. workspacePath: "/Users/dev/project",
  185. });
  186. }
  187. test("services stderr redaction delegates to the shared rules instead of keeping its own", () => {
  188. // 两层各维护一套时,services 先做赋值替换会破坏 main 的 Bearer 锚点,token 随 errorStack 上报。
  189. const source = readFileSync(SERVICES_SOURCE, "utf8");
  190. assert.match(source, /return redactAgentDiagnosticSecrets\(value\);/);
  191. assert.doesNotMatch(source, /Bearer\|Basic/);
  192. });
  193. test("does not report credentials after the services layer has already redacted each line", () => {
  194. const diagnostic = parseThroughServicesAndMain([
  195. "Error: request failed",
  196. " Authorization: Bearer fake-bearer-value-0002",
  197. " Proxy-Authorization: Basic fake-basic-value-0003",
  198. " cookie: session=fake-cookie-d; refresh=fake-cookie-e",
  199. ]);
  200. for (const secret of [
  201. "fake-bearer-value-0002",
  202. "fake-basic-value-0003",
  203. "fake-cookie-d",
  204. "fake-cookie-e",
  205. ]) {
  206. assert.doesNotMatch(diagnostic.errorStack, new RegExp(secret), secret);
  207. assert.doesNotMatch(diagnostic.errorMessage, new RegExp(secret), secret);
  208. }
  209. });
  210. test("redacting already-redacted text again changes nothing", () => {
  211. for (const line of [
  212. " Authorization: Bearer fake-bearer-value-0004",
  213. " cookie: a=fake-cookie-f; b=fake-cookie-g",
  214. '{"headers":{"cookie":"sid=fake-cookie-h"},"code":"ECONNRESET"}',
  215. " 'set-cookie': [ 'sid=fake-cookie-i; Path=/' ],",
  216. "password=fake-password-0005 token: 'fake-token-0006'",
  217. ]) {
  218. const once = redactAgentDiagnosticSecrets(line);
  219. assert.equal(redactAgentDiagnosticSecrets(once), once, line);
  220. }
  221. });
  222. test("keeps the error code that follows a quoted cookie on the same line", () => {
  223. const diagnostic = parseThroughServicesAndMain([
  224. '{"headers":{"cookie":"sid=fake-cookie-j; uid=fake-cookie-k"},"code":"ECONNRESET"}',
  225. ]);
  226. assert.doesNotMatch(diagnostic.errorStack, /fake-cookie-j|fake-cookie-k/);
  227. assert.equal(diagnostic.errorCode, "ECONNRESET");
  228. assert.equal(diagnostic.diagnosticClass, "errno");
  229. });