parallel.test.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. import { describe, expect, it } from "vitest";
  2. import { readFile, writeFile, readdir, rm, stat } from "node:fs/promises";
  3. import { join } from "node:path";
  4. import { setImmediate } from "node:timers/promises";
  5. import { runRegression } from "#public";
  6. import { fixture, chatResponse, secret } from "#test/fixture";
  7. import { renderHtmlReport, parseReport } from "#regression/html";
  8. function deferred() {
  9. let resolve!: () => void;
  10. const promise = new Promise<void>((done) => {
  11. resolve = done;
  12. });
  13. return { promise, resolve };
  14. }
  15. async function saved(root: string) {
  16. const runs = await readdir(root);
  17. expect(runs).toHaveLength(1);
  18. return JSON.parse(await readFile(join(root, runs[0], "report.json"), "utf8"));
  19. }
  20. describe("parallel regression and durable reports", () => {
  21. it("三级并行同时生效,Provider 覆盖逐字段继承,实例只执行一次", async () => {
  22. const f = await fixture();
  23. try {
  24. const cfg = JSON.parse(await readFile(f.options.providersFile, "utf8"));
  25. cfg.providerRules = ["a", "b", "c"].map((id) => ({
  26. ...cfg.providerRules[0],
  27. providerId: id,
  28. config: {
  29. ...cfg.providerRules[0].config,
  30. api: { type: "openai-chat-completions", baseUrl: `https://${id}.example.com/v1` },
  31. },
  32. }));
  33. await writeFile(f.options.providersFile, JSON.stringify(cfg));
  34. const builtinPath = join(f.dir, "builtin.json");
  35. const builtin = JSON.parse(await readFile(builtinPath, "utf8"));
  36. builtin.config.providerConfigRules.templateRules[0].config.builtinModelIds = [
  37. "model-a",
  38. "model-b",
  39. ];
  40. await writeFile(builtinPath, JSON.stringify(builtin));
  41. await writeFile(
  42. f.options.listFile,
  43. JSON.stringify({
  44. ...f.list,
  45. repetitions: 1,
  46. concurrency: { providers: 2, models: 2, cases: 2 },
  47. targets: [
  48. { providerId: "a", modelIds: ["*"], concurrency: { models: 1, cases: 1 } },
  49. { providerId: "b", modelIds: ["*"], concurrency: { cases: 2 } },
  50. { providerId: "c", modelIds: ["*"] },
  51. ],
  52. }),
  53. );
  54. const gate = deferred();
  55. const ready = deferred();
  56. const active = new Map<string, number>();
  57. const seen = new Set<string>();
  58. let count = 0;
  59. const running = runRegression({
  60. ...f.options,
  61. transport: async (url, init) => {
  62. const provider = new URL(String(url)).hostname.split(".")[0];
  63. const body = JSON.parse(String(init?.body));
  64. const key = `${provider}/${body.model}`;
  65. const identity = `${key}/${body.reasoning_effort}`;
  66. expect(seen.has(identity)).toBe(false);
  67. seen.add(identity);
  68. active.set(key, (active.get(key) ?? 0) + 1);
  69. expect(new Set([...active.keys()].map((k) => k.split("/")[0])).size).toBeLessThanOrEqual(
  70. 2,
  71. );
  72. expect(
  73. [...active.keys()].filter((k) => k.startsWith(provider + "/")).length,
  74. ).toBeLessThanOrEqual(provider === "a" ? 1 : 2);
  75. expect(active.get(key)).toBeLessThanOrEqual(provider === "a" ? 1 : 2);
  76. if (++count === 5) ready.resolve();
  77. await gate.promise;
  78. await setImmediate();
  79. const remaining = active.get(key)! - 1;
  80. if (remaining) active.set(key, remaining);
  81. else active.delete(key);
  82. return chatResponse();
  83. },
  84. });
  85. await Promise.race([
  86. ready.promise,
  87. running.then(() => {
  88. throw new Error("expected concurrent requests");
  89. }),
  90. ]);
  91. expect(count).toBe(5);
  92. gate.resolve();
  93. const report = await running;
  94. expect(report.rows).toHaveLength(12);
  95. expect(report.rows.every((r) => r.status === "passed")).toBe(true);
  96. expect(count).toBe(12);
  97. expect(report.execution?.targets[1].concurrency).toEqual({ models: 2, cases: 2 });
  98. } finally {
  99. await rm(f.dir, { recursive: true, force: true });
  100. }
  101. });
  102. it("开始前已有全计划,逐项保存,取消保留成功项并区分在途与未启动", async () => {
  103. const f = await fixture();
  104. const abort = new AbortController();
  105. let calls = 0;
  106. try {
  107. const report = await runRegression({
  108. ...f.options,
  109. signal: abort.signal,
  110. transport: async () => {
  111. const snapshot = await saved(f.options.outputDir);
  112. expect(snapshot.rows).toHaveLength(6);
  113. if (++calls === 1) {
  114. expect(snapshot.rows.map((r: { status: string }) => r.status)).toEqual([
  115. "running",
  116. ...Array(5).fill("pending"),
  117. ]);
  118. return chatResponse();
  119. }
  120. expect(snapshot.rows[0].status).toBe("passed");
  121. expect(snapshot.rows[1].status).toBe("running");
  122. expect(JSON.stringify(snapshot)).not.toContain(secret);
  123. abort.abort();
  124. throw new Error("aborted");
  125. },
  126. });
  127. expect(calls).toBe(2);
  128. expect(report.status).toBe("cancelled");
  129. expect(report.rows.map((r) => r.status)).toEqual([
  130. "passed",
  131. "cancelled",
  132. ...Array(4).fill("untested"),
  133. ]);
  134. expect((await saved(f.options.outputDir)).rows).toEqual(report.rows);
  135. if (process.platform !== "win32") {
  136. expect(
  137. (await stat(join(f.options.outputDir, report.runId!, "report.json"))).mode & 0o777,
  138. ).toBe(0o600);
  139. }
  140. } finally {
  141. await rm(f.dir, { recursive: true, force: true });
  142. }
  143. });
  144. it("默认预算使用模型上限,显式大预算不受旧 32768 上限限制", async () => {
  145. const f = await fixture();
  146. try {
  147. const builtinPath = join(f.dir, "builtin.json");
  148. const builtin = JSON.parse(await readFile(builtinPath, "utf8"));
  149. builtin.config.modelConfigRules.modelRules[0].config.optionSpecs.maxOutputTokens.max = 524288;
  150. await writeFile(builtinPath, JSON.stringify(builtin));
  151. for (const budget of [undefined, 100000, 600000]) {
  152. await writeFile(
  153. f.options.listFile,
  154. JSON.stringify({ ...f.list, repetitions: 1, maxOutputTokens: budget }),
  155. );
  156. const report = await runRegression({
  157. ...f.options,
  158. transport: async (_url, init) => {
  159. expect(JSON.parse(String(init?.body)).max_tokens).toBe(
  160. Math.min(budget ?? 524288, 524288),
  161. );
  162. return chatResponse();
  163. },
  164. });
  165. expect(report.rows.every((r) => r.status === "passed")).toBe(true);
  166. expect(report.rows[0].maxOutputTokens).toBe(Math.min(budget ?? 524288, 524288));
  167. }
  168. expect(await readdir(f.options.outputDir)).toHaveLength(3);
  169. } finally {
  170. await rm(f.dir, { recursive: true, force: true });
  171. }
  172. });
  173. it("输出限制用例仍使用小预算,普通用例使用模型预算", async () => {
  174. const f = await fixture();
  175. try {
  176. await writeFile(
  177. f.options.listFile,
  178. JSON.stringify({
  179. ...f.list,
  180. repetitions: 1,
  181. caseIds: ["OUTPUT-001"],
  182. maxOutputTokens: undefined,
  183. }),
  184. );
  185. const report = await runRegression({
  186. ...f.options,
  187. transport: async (_url, init) => {
  188. expect(JSON.parse(String(init?.body)).max_tokens).toBe(1024);
  189. return chatResponse(undefined, "length");
  190. },
  191. });
  192. expect(report.rows[0].status).toBe("passed");
  193. expect(report.rows[0].maxOutputTokens).toBe(1024);
  194. } finally {
  195. await rm(f.dir, { recursive: true, force: true });
  196. }
  197. });
  198. it("拒绝重复 Provider 与非法并行数,在请求前失败", async () => {
  199. const f = await fixture();
  200. try {
  201. for (const change of [
  202. { targets: [...f.list.targets, ...f.list.targets] },
  203. { concurrency: { cases: 0 } },
  204. { concurrency: { models: 1.5 } },
  205. { targets: [{ ...f.list.targets[0], concurrency: { providers: 2 } }] },
  206. ]) {
  207. await writeFile(f.options.listFile, JSON.stringify({ ...f.list, ...change }));
  208. await expect(runRegression(f.options)).rejects.toThrow();
  209. }
  210. } finally {
  211. await rm(f.dir, { recursive: true, force: true });
  212. }
  213. });
  214. it("离线 HTML 保留分组、失败和未完成状态,旧报告可读且不执行外部 HTML", async () => {
  215. const f = await fixture();
  216. try {
  217. const report = await runRegression({ ...f.options, dryRun: true });
  218. report.rows[0].answer = '<script>alert("x")</script><img src="https://example.com/track">';
  219. report.rows[0].status = "running";
  220. report.rows[1].status = "failed";
  221. report.rows[1].finishReason = "length";
  222. const html = renderHtmlReport(parseReport(JSON.parse(JSON.stringify(report))));
  223. expect(html).toContain("test-a");
  224. expect(html).toContain("model-a");
  225. expect(html).toContain("未完成");
  226. expect(html).toContain("length");
  227. expect(html).toContain("&lt;script&gt;");
  228. expect(html).not.toContain("<script>");
  229. expect(html).not.toContain("<img src=");
  230. expect(html).not.toContain(secret);
  231. const { schemaVersion: _v, runId: _id, status: _s, execution: _e, ...legacy } = report;
  232. expect(renderHtmlReport(parseReport(legacy))).toContain("未记录");
  233. expect(() => parseReport({ rows: [{}] })).toThrow();
  234. expect(() => parseReport({ ...report, schemaVersion: 99 })).toThrow();
  235. } finally {
  236. await rm(f.dir, { recursive: true, force: true });
  237. }
  238. });
  239. });