windows-e2e-shards.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. import { readFileSync } from "node:fs";
  2. import { EventEmitter } from "node:events";
  3. import { join, resolve } from "node:path";
  4. import { describe, expect, it, vi } from "vitest";
  5. import {
  6. createWindowsE2EShardPlan,
  7. executeWindowsE2EShardPlan,
  8. listDefaultFormalE2ESpecs,
  9. partitionE2ESpecsByWeight,
  10. resolveWindowsE2EShardTotal,
  11. } from "../scripts/run-windows-e2e-shards.mjs";
  12. const repoRoot = resolve("C:/repo");
  13. const desktopDir = join(repoRoot, "packages/desktop");
  14. function createPlan(overrides: Record<string, unknown> = {}) {
  15. return createWindowsE2EShardPlan({
  16. args: [],
  17. desktopDir,
  18. env: { ZCODE_E2E_RUN_ID: "local-full", ZCODE_E2E_SHARD_TOTAL: "2" },
  19. platform: "win32",
  20. repoRoot,
  21. ...overrides,
  22. });
  23. }
  24. describe("Windows E2E shard runner", () => {
  25. it("derives disjoint paths from automatic run IDs while preserving an explicit run ID", () => {
  26. const timestamp = new Date("2026-07-11T00:30:00.123Z");
  27. vi.useFakeTimers();
  28. vi.setSystemTime(timestamp);
  29. try {
  30. const firstPlan = createPlan({
  31. // 修复原因:默认 full run 已改为单 shard;路径隔离断言必须显式进入并发分片场景。
  32. env: { ZCODE_E2E_SHARD_TOTAL: "2" },
  33. processId: 4242,
  34. runIdEntropy: "entropy-a",
  35. runIdTimestamp: timestamp,
  36. });
  37. const secondPlan = createPlan({
  38. env: { ZCODE_E2E_SHARD_TOTAL: "2" },
  39. processId: 4242,
  40. runIdEntropy: "entropy-b",
  41. runIdTimestamp: timestamp,
  42. });
  43. expect(firstPlan.runId).not.toBe(secondPlan.runId);
  44. for (const key of [
  45. "ZCODE_E2E_HOME_DIR",
  46. "ZCODE_E2E_ARTIFACT_DIR",
  47. "ZCODE_E2E_NETWORK_CAPTURE_DIR",
  48. ] as const) {
  49. const firstPaths = new Set(firstPlan.children.map((child) => child.env[key]));
  50. const secondPaths = new Set(secondPlan.children.map((child) => child.env[key]));
  51. expect([...firstPaths].filter((path) => secondPaths.has(path))).toEqual([]);
  52. }
  53. const explicitPlan = createPlan({
  54. env: { ZCODE_E2E_RUN_ID: "explicit-compatible-run" },
  55. processId: 4242,
  56. runIdEntropy: "ignored-entropy",
  57. runIdTimestamp: timestamp,
  58. });
  59. expect(explicitPlan.runId).toBe("explicit-compatible-run");
  60. } finally {
  61. vi.useRealTimers();
  62. }
  63. });
  64. it("plans a default full Windows run as a single shard", () => {
  65. const plan = createPlan({
  66. env: { ZCODE_E2E_RUN_ID: "default-single" },
  67. });
  68. expect(plan.shardTotal).toBe(1);
  69. expect(plan.children).toHaveLength(1);
  70. expect(plan.children[0]?.args.some((arg) => arg.startsWith("--shard"))).toBe(false);
  71. expect(plan.children[0]?.env.ZCODE_E2E_HOME_DIR).toBe(
  72. join(desktopDir, ".e2e-home-default-single"),
  73. );
  74. });
  75. it("lists the default formal specs without manual-review or live provider cases", () => {
  76. const specs = listDefaultFormalE2ESpecs(resolve(process.cwd(), "packages/desktop"));
  77. // Bug 根因:formal case 由目录动态发现,固定总数会让新增或删除合法 case 误伤 pre-push。
  78. // 用稳定的 smoke 包含关系确认发现结果非空,其余断言只校验默认集合的语义边界。
  79. expect(specs).toContain("./test/e2e/smoke.test.ts");
  80. expect(specs).not.toContain("./test/e2e/upstream-provider.test.ts");
  81. expect(specs.some((spec) => spec.includes("/manual-review/"))).toBe(false);
  82. expect(specs.some((spec) => spec.includes("conversation-session-ssh-remote"))).toBe(false);
  83. const sshSpecs = listDefaultFormalE2ESpecs(resolve(process.cwd(), "packages/desktop"), {
  84. ZCODE_E2E_SSH_HOST: "ssh.example.test",
  85. ZCODE_E2E_SSH_USERNAME: "root",
  86. ZCODE_E2E_SSH_PASSWORD: "secret-from-test-env",
  87. });
  88. expect(sshSpecs).toContain(
  89. "./test/e2e/conversation-session/conversation-session-ssh-remote-connection-p0.test.ts",
  90. );
  91. });
  92. it("uses deterministic LPT weights and a fallback for new specs", () => {
  93. const buckets = partitionE2ESpecsByWeight(
  94. ["./a.test.ts", "./b.test.ts", "./c.test.ts", "./new.test.ts"],
  95. 2,
  96. {
  97. defaultWeightMs: 40,
  98. weights: {
  99. "./a.test.ts": 100,
  100. "./b.test.ts": 80,
  101. "./c.test.ts": 20,
  102. },
  103. },
  104. );
  105. expect(buckets).toEqual([
  106. { estimatedWeightMs: 120, specs: ["./a.test.ts", "./c.test.ts"] },
  107. { estimatedWeightMs: 120, specs: ["./b.test.ts", "./new.test.ts"] },
  108. ]);
  109. });
  110. it("passes weighted spec groups explicitly instead of native contiguous shards", () => {
  111. const weightedSpecBuckets = [
  112. { estimatedWeightMs: 100, specs: ["./test/e2e/smoke.test.ts"] },
  113. { estimatedWeightMs: 90, specs: ["./test/e2e/container-boot.test.ts"] },
  114. ];
  115. const plan = createPlan({ weightedSpecBuckets });
  116. expect(plan.distributionKind).toBe("historical-lpt");
  117. expect(plan.children.map((child) => child.env.ZCODE_E2E_SPEC)).toEqual([
  118. "./test/e2e/smoke.test.ts",
  119. "./test/e2e/container-boot.test.ts",
  120. ]);
  121. expect(
  122. plan.children.every((child) => child.args.every((arg) => !arg.startsWith("--shard"))),
  123. ).toBe(true);
  124. });
  125. it("plans two isolated shards for an explicit two-shard run", () => {
  126. const plan = createPlan();
  127. expect(plan.shardTotal).toBe(2);
  128. expect(plan.children).toHaveLength(2);
  129. expect(plan.children.map((child) => child.shardId)).toEqual(["1/2", "2/2"]);
  130. expect(plan.children.map((child) => child.args.at(-1))).toEqual(["--shard=1/2", "--shard=2/2"]);
  131. for (const key of [
  132. "ZCODE_E2E_HOME_DIR",
  133. "ZCODE_E2E_RUN_ID",
  134. "ZCODE_E2E_ARTIFACT_DIR",
  135. "ZCODE_E2E_NETWORK_CAPTURE_DIR",
  136. ] as const) {
  137. expect(new Set(plan.children.map((child) => child.env[key])).size).toBe(2);
  138. }
  139. for (const child of plan.children) {
  140. expect(child.env.ZCODE_E2E_SKIP_BUILD).toBe("1");
  141. expect(child.env.ZCODE_E2E_SKIP_AGENT_BUILD).toBe("1");
  142. expect(child.summaryPath).toBe(join(child.artifactDir, "summary.json"));
  143. }
  144. });
  145. it("keeps every default HOME disjoint across concurrent runner run IDs", () => {
  146. const firstPlan = createPlan({
  147. // 修复原因:覆盖 env 会同时移除 createPlan 默认的 shard 数,需保留显式分片前提。
  148. env: {
  149. ZCODE_E2E_RUN_ID: "concurrent-run-a",
  150. ZCODE_E2E_SHARD_TOTAL: "2",
  151. },
  152. });
  153. const secondPlan = createPlan({
  154. env: {
  155. ZCODE_E2E_RUN_ID: "concurrent-run-b",
  156. ZCODE_E2E_SHARD_TOTAL: "2",
  157. },
  158. });
  159. const firstHomes = new Set(firstPlan.children.map((child) => child.env.ZCODE_E2E_HOME_DIR));
  160. const secondHomes = new Set(secondPlan.children.map((child) => child.env.ZCODE_E2E_HOME_DIR));
  161. expect([...firstHomes].filter((home) => secondHomes.has(home))).toEqual([]);
  162. expect([...firstHomes].every((home) => home.includes("concurrent-run-a"))).toBe(true);
  163. expect([...secondHomes].every((home) => home.includes("concurrent-run-b"))).toBe(true);
  164. });
  165. it("preserves an explicit HOME for a single-child run", () => {
  166. const explicitHomeRoot = resolve("C:/e2e-homes/single");
  167. const plan = createPlan({
  168. env: {
  169. ZCODE_E2E_HOME_DIR: explicitHomeRoot,
  170. ZCODE_E2E_RUN_ID: "explicit-single-home-run",
  171. },
  172. });
  173. expect(plan.shardTotal).toBe(1);
  174. expect(plan.children[0]?.env.ZCODE_E2E_HOME_DIR).toBe(explicitHomeRoot);
  175. });
  176. it("adds run and shard identity below an explicit sharded HOME base", () => {
  177. const explicitHomeRoot = resolve("C:/e2e-homes");
  178. const plan = createPlan({
  179. env: {
  180. ZCODE_E2E_HOME_DIR: explicitHomeRoot,
  181. ZCODE_E2E_RUN_ID: "explicit-home-run",
  182. ZCODE_E2E_SHARD_TOTAL: "2",
  183. },
  184. });
  185. expect(plan.children.map((child) => child.env.ZCODE_E2E_HOME_DIR)).toEqual([
  186. join(explicitHomeRoot, "explicit-home-run", "shard-1-of-2"),
  187. join(explicitHomeRoot, "explicit-home-run", "shard-2-of-2"),
  188. ]);
  189. });
  190. it("builds desktop and agent once before starting both children concurrently", async () => {
  191. const plan = createPlan();
  192. expect(plan.buildSteps[1]?.env.ZCODE_DESKTOP_AGENT_BUILD_MODE).toBe("turbo");
  193. const events: string[] = [];
  194. const childResolvers: Array<(result: { exitCode: number }) => void> = [];
  195. const execution = executeWindowsE2EShardPlan(plan, {
  196. now: (() => {
  197. let value = 1_000;
  198. return () => (value += 50);
  199. })(),
  200. summaryExists: () => true,
  201. spawnStep: vi.fn(async (step) => {
  202. events.push(`start:${step.id}`);
  203. if (step.kind === "build") {
  204. events.push(`finish:${step.id}`);
  205. return { exitCode: 0 };
  206. }
  207. return await new Promise<{ exitCode: number }>((resolveChild) => {
  208. childResolvers.push(resolveChild);
  209. });
  210. }),
  211. writeManifest: vi.fn(),
  212. printManifest: vi.fn(),
  213. });
  214. await vi.waitFor(() => expect(childResolvers).toHaveLength(2));
  215. expect(events).toEqual([
  216. "start:build-desktop",
  217. "finish:build-desktop",
  218. "start:build-agent",
  219. "finish:build-agent",
  220. "start:shard-1-of-2",
  221. "start:shard-2-of-2",
  222. ]);
  223. childResolvers[1]?.({ exitCode: 0 });
  224. childResolvers[0]?.({ exitCode: 0 });
  225. const manifest = await execution;
  226. expect(manifest.wallDurationMs).toBe(50);
  227. expect(manifest.children.map((child) => child.exitCode)).toEqual([0, 0]);
  228. });
  229. it.each([
  230. {
  231. label: "targeted CLI",
  232. args: ["--spec=./test/e2e/container-boot.test.ts", "--shards=10"],
  233. env: { ZCODE_E2E_SHARD_TOTAL: "4" },
  234. },
  235. {
  236. label: "targeted env",
  237. args: ["--shards=10"],
  238. env: {
  239. ZCODE_E2E_SPEC: "./test/e2e/container-boot.test.ts",
  240. ZCODE_E2E_SHARD_TOTAL: "4",
  241. },
  242. },
  243. {
  244. label: "capture",
  245. args: ["--shards=10"],
  246. env: { E2E_PROVIDER_HTTP_MODE: "capture", ZCODE_E2E_SHARD_TOTAL: "4" },
  247. },
  248. {
  249. label: "manual review",
  250. args: ["--shards=10"],
  251. env: { ZCODE_E2E_MANUAL_REVIEW: "1", ZCODE_E2E_SHARD_TOTAL: "4" },
  252. },
  253. ])("keeps $label runs single despite explicit shard overrides", ({ args, env }) => {
  254. const plan = createPlan({ args, env });
  255. expect(plan.shardTotal).toBe(1);
  256. expect(plan.children).toHaveLength(1);
  257. });
  258. it("keeps non-Windows runs single by default", () => {
  259. expect(resolveWindowsE2EShardTotal({ args: [], env: {}, platform: "darwin" })).toBe(1);
  260. });
  261. it("validates explicit overrides and strips the runner-only option", () => {
  262. const plan = createPlan({
  263. args: ["--logLevel=warn", "--shards=3", "--mochaOpts.timeout=9000"],
  264. env: { ZCODE_E2E_SHARD_TOTAL: "4", ZCODE_E2E_RUN_ID: "override" },
  265. });
  266. expect(plan.shardTotal).toBe(3);
  267. expect(plan.wdioArgs).toEqual(["--logLevel=warn", "--mochaOpts.timeout=9000"]);
  268. expect(plan.children.map((child) => child.args.at(-1))).toEqual([
  269. "--shard=1/3",
  270. "--shard=2/3",
  271. "--shard=3/3",
  272. ]);
  273. expect(() =>
  274. resolveWindowsE2EShardTotal({ args: ["--shards=0"], env: {}, platform: "win32" }),
  275. ).toThrow("positive integer");
  276. expect(() =>
  277. resolveWindowsE2EShardTotal({
  278. args: [],
  279. env: { ZCODE_E2E_SHARD_TOTAL: "two" },
  280. platform: "win32",
  281. }),
  282. ).toThrow("positive integer");
  283. });
  284. it("does not reshard a native WDIO shard from any override", () => {
  285. expect(
  286. resolveWindowsE2EShardTotal({
  287. args: ["--shard=1/2"],
  288. env: { ZCODE_E2E_SHARD_TOTAL: "4" },
  289. platform: "win32",
  290. }),
  291. ).toBe(1);
  292. expect(
  293. resolveWindowsE2EShardTotal({
  294. args: ["--shard=1/2", "--shards=3"],
  295. env: { ZCODE_E2E_SHARD_TOTAL: "4" },
  296. platform: "win32",
  297. }),
  298. ).toBe(1);
  299. });
  300. it("waits for every child, writes one manifest, and fails when any shard fails", async () => {
  301. const plan = createPlan();
  302. const completed: string[] = [];
  303. const writeManifest = vi.fn();
  304. const printManifest = vi.fn();
  305. let caught: unknown;
  306. try {
  307. await executeWindowsE2EShardPlan(plan, {
  308. now: () => 2_000,
  309. summaryExists: () => true,
  310. spawnStep: async (step) => {
  311. if (step.kind === "build") return { exitCode: 0 };
  312. completed.push(step.id);
  313. return { exitCode: step.shardIndex === 1 ? 7 : 0 };
  314. },
  315. writeManifest,
  316. printManifest,
  317. });
  318. } catch (error) {
  319. caught = error;
  320. }
  321. expect(completed).toEqual(["shard-1-of-2", "shard-2-of-2"]);
  322. expect(writeManifest).toHaveBeenCalledOnce();
  323. expect(printManifest).toHaveBeenCalledOnce();
  324. expect(caught).toMatchObject({
  325. message: expect.stringContaining("shard 1/2 exited with code 7"),
  326. manifest: {
  327. runId: "local-full",
  328. shardTotal: 2,
  329. wallDurationMs: 0,
  330. children: [
  331. {
  332. shardId: "1/2",
  333. exitCode: 7,
  334. artifactDir: plan.children[0]?.artifactDir,
  335. summaryPath: plan.children[0]?.summaryPath,
  336. },
  337. {
  338. shardId: "2/2",
  339. exitCode: 0,
  340. artifactDir: plan.children[1]?.artifactDir,
  341. summaryPath: plan.children[1]?.summaryPath,
  342. },
  343. ],
  344. },
  345. });
  346. });
  347. it("rejects a zero-exit shard that produced no summary", async () => {
  348. const plan = createPlan();
  349. await expect(
  350. executeWindowsE2EShardPlan(plan, {
  351. now: () => 2_000,
  352. spawnStep: async () => ({ exitCode: 0 }),
  353. summaryExists: () => false,
  354. writeManifest: vi.fn(),
  355. printManifest: vi.fn(),
  356. }),
  357. ).rejects.toMatchObject({
  358. message: expect.stringContaining("missing shard summary"),
  359. manifest: {
  360. children: expect.arrayContaining([
  361. expect.objectContaining({ exitCode: 1, error: expect.stringContaining("summary.json") }),
  362. ]),
  363. },
  364. });
  365. });
  366. it("records a rejected shard start, waits for the delayed shard, and writes one manifest", async () => {
  367. const plan = createPlan();
  368. const writeManifest = vi.fn();
  369. const printManifest = vi.fn();
  370. let finishDelayedShard: (() => void) | undefined;
  371. const execution = executeWindowsE2EShardPlan(plan, {
  372. now: () => 2_000,
  373. summaryExists: () => true,
  374. spawnStep: (step) => {
  375. if (step.kind === "build") return Promise.resolve({ exitCode: 0 });
  376. if (step.shardIndex === 1) return Promise.reject(new Error("spawn pnpm EAGAIN"));
  377. return new Promise<{ exitCode: number }>((resolveChild) => {
  378. finishDelayedShard = () => resolveChild({ exitCode: 0 });
  379. });
  380. },
  381. writeManifest,
  382. printManifest,
  383. });
  384. await vi.waitFor(() => expect(finishDelayedShard).toBeTypeOf("function"));
  385. await Promise.resolve();
  386. expect(writeManifest).not.toHaveBeenCalled();
  387. finishDelayedShard?.();
  388. await expect(execution).rejects.toMatchObject({
  389. message: expect.stringContaining("shard 1/2 failed to start: spawn pnpm EAGAIN"),
  390. manifest: {
  391. children: [
  392. expect.objectContaining({
  393. shardId: "1/2",
  394. exitCode: 1,
  395. error: "spawn pnpm EAGAIN",
  396. }),
  397. expect.objectContaining({ shardId: "2/2", exitCode: 0 }),
  398. ],
  399. },
  400. });
  401. expect(writeManifest).toHaveBeenCalledOnce();
  402. expect(printManifest).toHaveBeenCalledOnce();
  403. });
  404. it("terminates another cancellable shard after an unrecoverable start error", async () => {
  405. const plan = createPlan();
  406. let finishSecondShard: ((result: { exitCode: number; signal?: string }) => void) | undefined;
  407. const terminateSecondShard = vi.fn(() => {
  408. finishSecondShard?.({ exitCode: 1, signal: "SIGTERM" });
  409. });
  410. const execution = executeWindowsE2EShardPlan(plan, {
  411. now: () => 2_000,
  412. summaryExists: () => true,
  413. spawnStep: (step) => {
  414. if (step.kind === "build") return Promise.resolve({ exitCode: 0 });
  415. if (step.shardIndex === 1) return Promise.reject(new Error("spawn pnpm ENOMEM"));
  416. return {
  417. result: new Promise<{ exitCode: number; signal?: string }>((resolveChild) => {
  418. finishSecondShard = resolveChild;
  419. }),
  420. terminate: terminateSecondShard,
  421. };
  422. },
  423. writeManifest: vi.fn(),
  424. printManifest: vi.fn(),
  425. });
  426. await expect(execution).rejects.toMatchObject({
  427. manifest: {
  428. children: [
  429. expect.objectContaining({ error: "spawn pnpm ENOMEM" }),
  430. expect.objectContaining({ signal: "SIGTERM" }),
  431. ],
  432. },
  433. });
  434. expect(terminateSecondShard).toHaveBeenCalledOnce();
  435. });
  436. it("terminates active shards on a parent signal and reports the interrupted run", async () => {
  437. const plan = createPlan();
  438. const signalSource = new EventEmitter();
  439. const childResolvers = new Map<
  440. number,
  441. (result: { exitCode: number; signal?: string }) => void
  442. >();
  443. const terminates: Array<ReturnType<typeof vi.fn>> = [];
  444. const execution = executeWindowsE2EShardPlan(plan, {
  445. now: () => 2_000,
  446. summaryExists: () => true,
  447. signalSource,
  448. spawnStep: (step) => {
  449. if (step.kind === "build") return Promise.resolve({ exitCode: 0 });
  450. const terminate = vi.fn(() => {
  451. childResolvers.get(step.shardIndex)?.({ exitCode: 1, signal: "SIGTERM" });
  452. });
  453. terminates.push(terminate);
  454. return {
  455. result: new Promise<{ exitCode: number; signal?: string }>((resolveChild) => {
  456. childResolvers.set(step.shardIndex, resolveChild);
  457. }),
  458. terminate,
  459. };
  460. },
  461. writeManifest: vi.fn(),
  462. printManifest: vi.fn(),
  463. });
  464. await vi.waitFor(() => expect(childResolvers.size).toBe(2));
  465. signalSource.emit("SIGTERM");
  466. await expect(execution).rejects.toMatchObject({
  467. message: expect.stringContaining("parent received SIGTERM"),
  468. manifest: expect.objectContaining({ interruptedBySignal: "SIGTERM" }),
  469. });
  470. expect(terminates).toHaveLength(2);
  471. expect(terminates.every((terminate) => terminate.mock.calls.length === 1)).toBe(true);
  472. expect(signalSource.listenerCount("SIGINT")).toBe(0);
  473. expect(signalSource.listenerCount("SIGTERM")).toBe(0);
  474. });
  475. it("separates the single-shard default from the fixed 10-shard performance entry", () => {
  476. const desktopPackage = JSON.parse(
  477. readFileSync(resolve(process.cwd(), "packages/desktop/package.json"), "utf-8"),
  478. ) as { scripts: Record<string, string> };
  479. const rootPackage = JSON.parse(
  480. readFileSync(resolve(process.cwd(), "package.json"), "utf-8"),
  481. ) as { scripts: Record<string, string> };
  482. expect(desktopPackage.scripts["pretest:e2e"]).toBe(
  483. "pnpm --filter @zcode/e2e-report build:node",
  484. );
  485. expect(desktopPackage.scripts["test:e2e"]).toBe("node scripts/run-windows-e2e-shards.mjs");
  486. expect(rootPackage.scripts["test:e2e"]).toBe("pnpm --filter @zcode/desktop test:e2e");
  487. expect(desktopPackage.scripts["test:e2e:windows:sharded"]).toBe("pnpm test:e2e -- --shards=10");
  488. expect(rootPackage.scripts["test:e2e:windows:sharded"]).toBe(
  489. "pnpm --filter @zcode/desktop test:e2e:windows:sharded",
  490. );
  491. });
  492. });