regression.test.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. import { describe, expect, it } from "vitest";
  2. import { writeFile, readFile, rm } from "node:fs/promises";
  3. import { join } from "node:path";
  4. import { runRegression } from "#public";
  5. import { renderReport } from "#regression/report";
  6. import { readModelRequestBody } from "#regression/usage";
  7. import { fixture, chatResponse, secret, architectureAnswer } from "#test/fixture";
  8. describe("provider regression", () => {
  9. it("只解析模型请求,字节体与 Request 观测不消费原请求", async () => {
  10. const body = { model: "model-a", messages: [], max_tokens: 8192 };
  11. const json = JSON.stringify(body);
  12. const bytes = new TextEncoder().encode(json);
  13. const url = "https://provider.example.com/v1/messages";
  14. for (const input of [json, bytes, bytes.buffer]) {
  15. expect(await readModelRequestBody(url, { method: "POST", body: input })).toEqual(body);
  16. }
  17. const request = new Request(url, { method: "POST", body: json });
  18. expect(await readModelRequestBody(request)).toEqual(body);
  19. expect(await request.json()).toEqual(body);
  20. expect(
  21. await readModelRequestBody(url, { method: "POST", body: JSON.stringify({ apiKey: secret }) }),
  22. ).toBeUndefined();
  23. expect(await readModelRequestBody(url, { method: "GET" })).toBeUndefined();
  24. expect(
  25. await readModelRequestBody(url, {
  26. method: "POST",
  27. body: JSON.stringify({ model: "model-a" }),
  28. }),
  29. ).toBeUndefined();
  30. expect(
  31. await readModelRequestBody(url, {
  32. method: "POST",
  33. body: JSON.stringify({ model: "model-a", input: [] }),
  34. }),
  35. ).toEqual({ model: "model-a", input: [] });
  36. });
  37. it("省略 repetitions 时每个档位只运行一次", async () => {
  38. const f = await fixture();
  39. try {
  40. const { repetitions: _repetitions, ...list } = f.list;
  41. await writeFile(f.options.listFile, JSON.stringify(list));
  42. let calls = 0;
  43. const report = await runRegression({
  44. ...f.options,
  45. transport: async () => {
  46. calls++;
  47. return chatResponse();
  48. },
  49. });
  50. expect(calls).toBe(2);
  51. expect(report.rows.map((row) => [row.reasoningLevel, row.repetition])).toEqual([
  52. ["low", 1],
  53. ["high", 1],
  54. ]);
  55. } finally {
  56. await rm(f.dir, { recursive: true, force: true });
  57. }
  58. });
  59. it("并行实例有独立会话,入口所需会话头沿现有 Adapter 生成", async () => {
  60. const f = await fixture();
  61. const sessions: (string | null)[] = [];
  62. try {
  63. const providers = JSON.parse(await readFile(f.options.providersFile, "utf8"));
  64. providers.providerRules[0].config.api = {
  65. type: "openai-chat-completions",
  66. baseUrl: "https://opencode.ai/zen/go/v1",
  67. };
  68. await writeFile(f.options.providersFile, JSON.stringify(providers));
  69. await writeFile(
  70. f.options.listFile,
  71. JSON.stringify({ ...f.list, repetitions: 1, concurrency: { cases: 2 } }),
  72. );
  73. const report = await runRegression({
  74. ...f.options,
  75. transport: async (_url, init) => {
  76. const headers = new Headers(init?.headers);
  77. const session = headers.get("x-session-id");
  78. sessions.push(session);
  79. expect(session).toBeTruthy();
  80. expect(headers.get("x-opencode-session")).toBe(session);
  81. return chatResponse();
  82. },
  83. });
  84. expect(report.rows.every((row) => row.status === "passed")).toBe(true);
  85. expect(sessions).toHaveLength(2);
  86. expect(new Set(sessions).size).toBe(2);
  87. } finally {
  88. await rm(f.dir, { recursive: true, force: true });
  89. }
  90. });
  91. it("同题逐档重复,真实 Adapter 参数、缺失 usage 与中位数不混淆", async () => {
  92. const f = await fixture();
  93. const bodies: Record<string, unknown>[] = [];
  94. try {
  95. const transport: typeof fetch = async (_url, init) => {
  96. bodies.push(JSON.parse(String(init?.body)));
  97. return chatResponse(bodies.length === 1 ? 0 : undefined);
  98. };
  99. const report = await runRegression({ ...f.options, transport });
  100. expect(report.rows).toHaveLength(6);
  101. expect(
  102. report.rows.every((r) => r.status === "passed" && r.parameterCheck === "matched"),
  103. ).toBe(true);
  104. expect(new Set(bodies.map((b) => JSON.stringify(b.messages))).size).toBe(1);
  105. expect(bodies.map((b) => b.reasoning_effort)).toEqual([
  106. "low",
  107. "high",
  108. "low",
  109. "high",
  110. "low",
  111. "high",
  112. ]);
  113. expect(report.rows[0].reasoningTokens).toBe(0);
  114. expect(report.rows[1].reasoningTokens).toBeNull();
  115. expect(report.rows[0].reasoningCharacters).toBe(3);
  116. const saved = await readFile(join(f.dir, "report", report.runId!, "report.json"), "utf8");
  117. expect(saved).not.toContain(secret);
  118. expect(saved).not.toContain("思考😀");
  119. expect(renderReport(report)).toContain("中位数");
  120. expect(report.reasoningTask.id).toBe("task-platform-v1");
  121. expect(report.reasoningTask.prompt).toContain("跨地域");
  122. expect(report.reasoningTask.maxOutputTokens).toBe(1024);
  123. expect(report.rows[0].answer).toBe(architectureAnswer);
  124. expect(report.rows[0].detail).toContain("设计质量待人工评审");
  125. expect(renderReport(report)).toContain(
  126. architectureAnswer
  127. .split("\n")
  128. .map((line) => `> ${line}`)
  129. .join("\n"),
  130. );
  131. expect(JSON.stringify(bodies[0].messages)).toContain("外部接口");
  132. } finally {
  133. await rm(f.dir, { recursive: true, force: true });
  134. }
  135. });
  136. it("架构题只验证传输完成与非空回答,不评判内容或标题", async () => {
  137. const f = await fixture();
  138. try {
  139. for (const answer of ["80", architectureAnswer.replace("## 4. 故障推演", "缺失章节"), ""]) {
  140. const report = await runRegression({
  141. ...f.options,
  142. transport: async () =>
  143. new Response(
  144. (await chatResponse().text()).replace(
  145. JSON.stringify(architectureAnswer),
  146. JSON.stringify(answer),
  147. ),
  148. {
  149. headers: { "content-type": "text/event-stream" },
  150. },
  151. ),
  152. });
  153. expect(report.rows.every((r) => r.status === (answer ? "passed" : "failed"))).toBe(true);
  154. }
  155. } finally {
  156. await rm(f.dir, { recursive: true, force: true });
  157. }
  158. });
  159. it.each(["17 × 19 = 323", "已完成回答", ""])(
  160. "文本使用产品流式会话,不评判最终文风:%s",
  161. async (answer) => {
  162. const f = await fixture();
  163. try {
  164. await writeFile(f.options.listFile, JSON.stringify({ ...f.list, caseIds: ["TEXT-001"] }));
  165. const report = await runRegression({
  166. ...f.options,
  167. transport: async (_url, init) => {
  168. const body = JSON.parse(String(init?.body));
  169. if (body.stream)
  170. return new Response(
  171. (await chatResponse().text()).replace(
  172. JSON.stringify(architectureAnswer),
  173. JSON.stringify(answer),
  174. ),
  175. { headers: { "content-type": "text/event-stream" } },
  176. );
  177. return new Response(
  178. JSON.stringify({
  179. id: "text",
  180. object: "chat.completion",
  181. created: 1,
  182. model: "model-a",
  183. choices: [
  184. {
  185. index: 0,
  186. message: { role: "assistant", content: answer },
  187. finish_reason: "stop",
  188. },
  189. ],
  190. usage: { prompt_tokens: 1, completion_tokens: 1 },
  191. }),
  192. { headers: { "content-type": "application/json" } },
  193. );
  194. },
  195. });
  196. expect(report.rows[0].status).toBe(answer ? "passed" : "failed");
  197. } finally {
  198. await rm(f.dir, { recursive: true, force: true });
  199. }
  200. },
  201. );
  202. it.each(["当前口令是 blue-42。", "BLUE-420"])(
  203. "输入标记允许解释但不接受不同标记:%s",
  204. async (answer) => {
  205. const f = await fixture();
  206. try {
  207. await writeFile(f.options.listFile, JSON.stringify({ ...f.list, caseIds: ["SYSTEM-001"] }));
  208. const report = await runRegression({
  209. ...f.options,
  210. transport: async () =>
  211. new Response(
  212. (await chatResponse().text()).replace(
  213. JSON.stringify(architectureAnswer),
  214. JSON.stringify(answer),
  215. ),
  216. { headers: { "content-type": "text/event-stream" } },
  217. ),
  218. });
  219. expect(report.rows[0].status).toBe(answer === "BLUE-420" ? "review" : "passed");
  220. } finally {
  221. await rm(f.dir, { recursive: true, force: true });
  222. }
  223. },
  224. );
  225. it("失败继续下一项且报告移除错误回显的 Key", async () => {
  226. const f = await fixture();
  227. let calls = 0;
  228. try {
  229. const report = await runRegression({
  230. ...f.options,
  231. transport: async () => {
  232. if (++calls === 1) throw new Error(secret);
  233. return chatResponse();
  234. },
  235. });
  236. expect(calls).toBe(6);
  237. expect(report.rows[0].status).toBe("failed");
  238. expect(report.rows[1].status).toBe("passed");
  239. expect(JSON.stringify(report)).not.toContain(secret);
  240. } finally {
  241. await rm(f.dir, { recursive: true, force: true });
  242. }
  243. });
  244. it("预览不调用网络,不适用与缺 Key 保留为不同状态", async () => {
  245. const f = await fixture();
  246. try {
  247. await writeFile(
  248. f.options.listFile,
  249. JSON.stringify({ ...f.list, caseIds: ["IMAGE-001", "REASON-001"] }),
  250. );
  251. const cfg = JSON.parse(await readFile(f.options.providersFile, "utf8"));
  252. cfg.providerRules[0].config.access.apiKey = "";
  253. await writeFile(f.options.providersFile, JSON.stringify(cfg));
  254. const r = await runRegression({
  255. ...f.options,
  256. dryRun: true,
  257. transport: async () => {
  258. throw new Error("must not call");
  259. },
  260. });
  261. expect(r.rows.find((x) => x.caseId === "IMAGE-001")?.status).toBe("skipped");
  262. expect(
  263. r.rows.filter((x) => x.caseId === "REASON-001").every((x) => x.status === "untested"),
  264. ).toBe(true);
  265. } finally {
  266. await rm(f.dir, { recursive: true, force: true });
  267. }
  268. });
  269. it("未知用例和不存在的模型在发请求前报错", async () => {
  270. const f = await fixture();
  271. try {
  272. await writeFile(f.options.listFile, JSON.stringify({ ...f.list, caseIds: ["WRONG"] }));
  273. await expect(runRegression(f.options)).rejects.toThrow();
  274. await writeFile(
  275. f.options.listFile,
  276. JSON.stringify({ ...f.list, targets: [{ providerId: "test-a", modelIds: ["wrong"] }] }),
  277. );
  278. await expect(runRegression(f.options)).rejects.toThrow();
  279. } finally {
  280. await rm(f.dir, { recursive: true, force: true });
  281. }
  282. });
  283. it.each(["stop", "length", "error"])("输出预算只检查传参和合法结束:%s", async (finish) => {
  284. const f = await fixture();
  285. try {
  286. await writeFile(f.options.listFile, JSON.stringify({ ...f.list, caseIds: ["OUTPUT-001"] }));
  287. const report = await runRegression({
  288. ...f.options,
  289. transport: async () => chatResponse(0, finish),
  290. });
  291. expect(report.rows[0].status).toBe(finish === "error" ? "failed" : "passed");
  292. if (finish === "stop") expect(report.rows[0].detail).toContain("未观察到截断");
  293. } finally {
  294. await rm(f.dir, { recursive: true, force: true });
  295. }
  296. });
  297. it("截断不算成功", async () => {
  298. const f = await fixture();
  299. try {
  300. const r = await runRegression({
  301. ...f.options,
  302. transport: async () => chatResponse(20, "length"),
  303. });
  304. expect(r.rows.every((x) => x.status === "failed")).toBe(true);
  305. } finally {
  306. await rm(f.dir, { recursive: true, force: true });
  307. }
  308. });
  309. it("新档位自动展开,媒体用例按 property 选择", async () => {
  310. const f = await fixture();
  311. try {
  312. const path = join(f.dir, "builtin.json");
  313. const data = JSON.parse(await readFile(path, "utf8"));
  314. data.config.modelConfigRules.modelRules[0].config.optionSpecs.reasoningLevel.values.push(
  315. "max",
  316. );
  317. await writeFile(path, JSON.stringify(data));
  318. await writeFile(f.options.listFile, JSON.stringify({ ...f.list, caseIds: ["*"] }));
  319. const r = await runRegression({ ...f.options, dryRun: true });
  320. expect(r.rows.filter((x) => x.caseId === "REASON-001")).toHaveLength(9);
  321. expect(r.rows.find((x) => x.caseId === "IMAGE-001")?.status).toBe("skipped");
  322. } finally {
  323. await rm(f.dir, { recursive: true, force: true });
  324. }
  325. });
  326. it.each(["323", "17 × 19 = 323", "两项工具结果已收到", ""])(
  327. "工具闭环验证传输,不评判最终文风:%s",
  328. async (answer) => {
  329. const f = await fixture();
  330. const bodies: any[] = [];
  331. const sessions: (string | null)[] = [];
  332. try {
  333. await writeFile(f.options.listFile, JSON.stringify({ ...f.list, caseIds: ["TOOL-001"] }));
  334. const r = await runRegression({
  335. ...f.options,
  336. transport: async (_url, init) => {
  337. const body = JSON.parse(String(init?.body));
  338. bodies.push(body);
  339. sessions.push(new Headers(init?.headers).get("x-session-id"));
  340. const count = bodies.length;
  341. const message =
  342. count < 3
  343. ? {
  344. role: "assistant",
  345. content: null,
  346. tool_calls: [
  347. {
  348. id: `call-${count}`,
  349. type: "function",
  350. function: {
  351. name: "lookup_regression_value",
  352. arguments: JSON.stringify({
  353. query: { id: count === 1 ? "left" : "right" },
  354. }),
  355. },
  356. },
  357. ],
  358. }
  359. : { role: "assistant", content: answer };
  360. expect(body.stream).toBe(true);
  361. const delta = {
  362. ...message,
  363. ...(message.tool_calls
  364. ? { tool_calls: message.tool_calls.map((call, index) => ({ ...call, index })) }
  365. : {}),
  366. };
  367. return new Response(
  368. [
  369. { choices: [{ index: 0, delta, finish_reason: null }] },
  370. {
  371. choices: [
  372. { index: 0, delta: {}, finish_reason: count < 3 ? "tool_calls" : "stop" },
  373. ],
  374. usage: { prompt_tokens: 10, completion_tokens: 20 },
  375. },
  376. ]
  377. .map(
  378. (payload) =>
  379. `data: ${JSON.stringify({ id: "response", object: "chat.completion.chunk", created: 1, model: "model-a", ...payload })}\n\n`,
  380. )
  381. .join("") + "data: [DONE]\n\n",
  382. { headers: { "content-type": "text/event-stream" } },
  383. );
  384. },
  385. });
  386. expect(r.rows[0].status, r.rows[0].detail).toBe(answer ? "passed" : "failed");
  387. if (answer) expect(bodies).toHaveLength(3);
  388. else expect(bodies.length).toBeGreaterThanOrEqual(3);
  389. expect(sessions.every(Boolean)).toBe(true);
  390. expect(new Set(sessions).size).toBe(1);
  391. expect(
  392. bodies[2].messages.filter((m: any) => m.role === "tool").map((m: any) => m.tool_call_id),
  393. ).toEqual(["call-1", "call-2"]);
  394. } finally {
  395. await rm(f.dir, { recursive: true, force: true });
  396. }
  397. },
  398. );
  399. it("超时传入实际请求,后续用例仍有结果", async () => {
  400. const f = await fixture();
  401. try {
  402. await writeFile(
  403. f.options.listFile,
  404. JSON.stringify({ ...f.list, timeoutMs: 100, repetitions: 1 }),
  405. );
  406. const r = await runRegression({
  407. ...f.options,
  408. transport: async (_url, init) =>
  409. new Promise((_resolve, reject) => {
  410. if (init?.signal?.aborted) reject(new Error("aborted"));
  411. else
  412. init?.signal?.addEventListener("abort", () => reject(new Error("aborted")), {
  413. once: true,
  414. });
  415. }),
  416. });
  417. expect(r.rows).toHaveLength(2);
  418. expect(r.rows.every((x) => x.status === "failed" && x.detail.includes("超时"))).toBe(true);
  419. } finally {
  420. await rm(f.dir, { recursive: true, force: true });
  421. }
  422. });
  423. it("取消后停止发新请求,并保留未测项目", async () => {
  424. const f = await fixture();
  425. const abort = new AbortController();
  426. let calls = 0;
  427. try {
  428. const r = await runRegression({
  429. ...f.options,
  430. signal: abort.signal,
  431. transport: async () => {
  432. calls++;
  433. abort.abort();
  434. throw new Error("aborted");
  435. },
  436. });
  437. expect(calls).toBe(1);
  438. expect(r.rows.slice(1).every((x) => x.status === "untested")).toBe(true);
  439. } finally {
  440. await rm(f.dir, { recursive: true, force: true });
  441. }
  442. });
  443. it("Messages 路径保留可见思考长度,原始 usage 缺失不补零", async () => {
  444. const f = await fixture("anthropic-messages");
  445. try {
  446. await writeFile(f.options.listFile, JSON.stringify({ ...f.list, repetitions: 1 }));
  447. const r = await runRegression({
  448. ...f.options,
  449. transport: async () => {
  450. const events = [
  451. {
  452. type: "message_start",
  453. message: {
  454. id: "m1",
  455. type: "message",
  456. role: "assistant",
  457. model: "model-a",
  458. content: [],
  459. stop_reason: null,
  460. stop_sequence: null,
  461. usage: { input_tokens: 10, output_tokens: 0 },
  462. },
  463. },
  464. {
  465. type: "content_block_start",
  466. index: 0,
  467. content_block: { type: "thinking", thinking: "", signature: "" },
  468. },
  469. {
  470. type: "content_block_delta",
  471. index: 0,
  472. delta: { type: "thinking_delta", thinking: "thinking" },
  473. },
  474. { type: "content_block_stop", index: 0 },
  475. { type: "content_block_start", index: 1, content_block: { type: "text", text: "" } },
  476. {
  477. type: "content_block_delta",
  478. index: 1,
  479. delta: { type: "text_delta", text: architectureAnswer },
  480. },
  481. { type: "content_block_stop", index: 1 },
  482. {
  483. type: "message_delta",
  484. delta: { stop_reason: "end_turn", stop_sequence: null },
  485. usage: { output_tokens: 20 },
  486. },
  487. { type: "message_stop" },
  488. ];
  489. return new Response(
  490. events.map((e) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""),
  491. { headers: { "content-type": "text/event-stream" } },
  492. );
  493. },
  494. });
  495. expect(
  496. r.rows.every(
  497. (x) => x.status === "passed" && x.reasoningTokens === null && x.reasoningCharacters === 8,
  498. ),
  499. ).toBe(true);
  500. } finally {
  501. await rm(f.dir, { recursive: true, force: true });
  502. }
  503. });
  504. it("Responses 路径读取原始思考 usage,不把文本长度当 token", async () => {
  505. const f = await fixture("openai-responses");
  506. try {
  507. await writeFile(f.options.listFile, JSON.stringify({ ...f.list, repetitions: 1 }));
  508. const r = await runRegression({
  509. ...f.options,
  510. transport: async () => {
  511. const events = [
  512. { type: "response.created", response: { id: "r1", created_at: 1, model: "model-a" } },
  513. {
  514. type: "response.output_item.added",
  515. output_index: 0,
  516. item: { type: "message", id: "m1" },
  517. },
  518. { type: "response.output_text.delta", item_id: "m1", delta: architectureAnswer },
  519. {
  520. type: "response.output_item.done",
  521. output_index: 0,
  522. item: { type: "message", id: "m1" },
  523. },
  524. {
  525. type: "response.completed",
  526. response: {
  527. usage: {
  528. input_tokens: 10,
  529. output_tokens: 25,
  530. output_tokens_details: { reasoning_tokens: 20 },
  531. },
  532. },
  533. },
  534. ];
  535. return new Response(events.map((e) => `data: ${JSON.stringify(e)}\n\n`).join(""), {
  536. headers: { "content-type": "text/event-stream" },
  537. });
  538. },
  539. });
  540. expect(
  541. r.rows.every(
  542. (x) =>
  543. x.status === "passed" && x.reasoningTokens === 20 && x.reasoningCharacters === null,
  544. ),
  545. ).toBe(true);
  546. } finally {
  547. await rm(f.dir, { recursive: true, force: true });
  548. }
  549. });
  550. it("单个档位 Map 求值失败不会中断整轮", async () => {
  551. const f = await fixture();
  552. try {
  553. const path = join(f.dir, "builtin.json");
  554. const release = JSON.parse(await readFile(path, "utf8"));
  555. release.config.modelConfigRules.modelRules[0].config.optionSpecs.reasoningLevel.map =
  556. 'reasoningLevel == "low" ? {"reasoning_effort": "low"} : {"invalid": 1 / 0}';
  557. await writeFile(path, JSON.stringify(release));
  558. const r = await runRegression({ ...f.options, transport: async () => chatResponse() });
  559. expect(r.rows).toHaveLength(6);
  560. expect(
  561. r.rows.filter((x) => x.reasoningLevel === "low").every((x) => x.status === "passed"),
  562. ).toBe(true);
  563. expect(
  564. r.rows.filter((x) => x.reasoningLevel === "high").every((x) => x.status === "failed"),
  565. ).toBe(true);
  566. } finally {
  567. await rm(f.dir, { recursive: true, force: true });
  568. }
  569. });
  570. it("响应回显包含 JSON 转义字符的 Key 也必须脱敏", async () => {
  571. const f = await fixture();
  572. const key = 'private-"-key';
  573. try {
  574. const cfg = JSON.parse(await readFile(f.options.providersFile, "utf8"));
  575. cfg.providerRules[0].config.access.apiKey = key;
  576. await writeFile(f.options.providersFile, JSON.stringify(cfg));
  577. const r = await runRegression({
  578. ...f.options,
  579. transport: async () =>
  580. new Response(
  581. (await chatResponse().text()).replace(
  582. JSON.stringify(architectureAnswer),
  583. JSON.stringify(key),
  584. ),
  585. {
  586. headers: { "content-type": "text/event-stream" },
  587. },
  588. ),
  589. });
  590. expect(r.rows.every((x) => !x.answer.includes(key))).toBe(true);
  591. } finally {
  592. await rm(f.dir, { recursive: true, force: true });
  593. }
  594. });
  595. });