run-windows-e2e-shards.mjs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. #!/usr/bin/env node
  2. /* eslint-disable max-lines -- Windows E2E 父 runner 需要集中维护构建、分片、取消和 summary 完整性门禁。 */
  3. import { randomBytes } from "node:crypto";
  4. import { existsSync, readdirSync, readFileSync } from "node:fs";
  5. import { mkdir, writeFile } from "node:fs/promises";
  6. import { cpus, totalmem } from "node:os";
  7. import { dirname, join, resolve } from "node:path";
  8. import process from "node:process";
  9. import { fileURLToPath } from "node:url";
  10. import { spawnCancellableStep, startStepExecution } from "./e2e-step-process.mjs";
  11. import { normalizeE2EDesktopBuildEnv } from "./ensure-e2e-desktop-build.mjs";
  12. import { PREINSTALLED_ENTRY_SHIM_PROCESS_TIMEOUT_MS } from "./build-windows-preinstalled-entry-shim.mjs";
  13. import { isFormalSpecAdmittedByEnvironment } from "./e2e-formal-spec-selection.mjs";
  14. const RUNNER_SHARD_ARG_PREFIX = "--shards=";
  15. const DEFAULT_SPEC_DURATION_PROFILE_PATH = "test/e2e/spec-duration-weights.json";
  16. function readPositiveInteger(value, source) {
  17. if (!/^\d+$/u.test(value ?? "") || Number(value) <= 0) {
  18. throw new Error(`${source} must be a positive integer, received: ${value || "<empty>"}`);
  19. }
  20. return Number(value);
  21. }
  22. function splitRunnerArgs(args) {
  23. const shardArgs = args.filter((arg) => arg.startsWith(RUNNER_SHARD_ARG_PREFIX));
  24. if (shardArgs.length > 1) {
  25. throw new Error("--shards may only be specified once");
  26. }
  27. const explicitShardTotal = shardArgs[0]
  28. ? readPositiveInteger(shardArgs[0].slice(RUNNER_SHARD_ARG_PREFIX.length), "--shards")
  29. : undefined;
  30. return {
  31. explicitShardTotal,
  32. wdioArgs: args.filter((arg) => !arg.startsWith(RUNNER_SHARD_ARG_PREFIX)),
  33. };
  34. }
  35. function isTargetedRun(args, env) {
  36. const requestedSpec = env.ZCODE_E2E_SPEC?.trim();
  37. return (
  38. Boolean(requestedSpec) ||
  39. args.some(
  40. (arg, index) =>
  41. arg === "--spec" ||
  42. arg.startsWith("--spec=") ||
  43. (index > 0 && args[index - 1] === "--spec"),
  44. )
  45. );
  46. }
  47. function isManualReviewRun(args, env) {
  48. return (
  49. env.ZCODE_E2E_MANUAL_REVIEW?.trim() === "1" ||
  50. args.concat(env.ZCODE_E2E_SPEC ?? "").some((arg) => arg.includes("/manual-review/"))
  51. );
  52. }
  53. export function resolveWindowsE2EShardTotal({
  54. args,
  55. env,
  56. platform,
  57. logicalCpuCount = cpus().length,
  58. totalMemoryBytes = totalmem(),
  59. }) {
  60. const { explicitShardTotal } = splitRunnerArgs(args);
  61. const hasNativeShard = args.some((arg) => arg === "--shard" || arg.startsWith("--shard="));
  62. const isCaptureRun = env.E2E_PROVIDER_HTTP_MODE?.trim() === "capture";
  63. // 修复原因:性能入口固定携带 --shards=10;若显式分片先返回,定向、人工复核、
  64. // capture 或上层 native shard 会被重复启动。特殊模式必须先锁定单 child。
  65. if (hasNativeShard || isTargetedRun(args, env) || isManualReviewRun(args, env) || isCaptureRun) {
  66. return 1;
  67. }
  68. if (explicitShardTotal !== undefined) {
  69. return explicitShardTotal;
  70. }
  71. const envShardTotal = env.ZCODE_E2E_SHARD_TOTAL?.trim();
  72. if (envShardTotal) {
  73. return readPositiveInteger(envShardTotal, "ZCODE_E2E_SHARD_TOTAL");
  74. }
  75. // 修复原因:按机器资源自动启用多 shard 会让无参数命令产生隐式并发,既不便于
  76. // 本地复现,也会放大 session/清理竞争;默认固定单 shard,并行必须由调用方显式选择。
  77. void platform;
  78. void logicalCpuCount;
  79. void totalMemoryBytes;
  80. return 1;
  81. }
  82. export function listDefaultFormalE2ESpecs(desktopDir, env = process.env) {
  83. const e2eDir = join(desktopDir, "test/e2e");
  84. const specs = [];
  85. const visit = (directory, relativeDirectory = "") => {
  86. for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) =>
  87. a.name.localeCompare(b.name),
  88. )) {
  89. const relativePath = relativeDirectory ? `${relativeDirectory}/${entry.name}` : entry.name;
  90. if (entry.isDirectory()) {
  91. if (entry.name === "manual-review") continue;
  92. visit(join(directory, entry.name), relativePath);
  93. continue;
  94. }
  95. if (
  96. entry.isFile() &&
  97. entry.name.endsWith(".test.ts") &&
  98. entry.name !== "upstream-provider.test.ts" &&
  99. isFormalSpecAdmittedByEnvironment(`./test/e2e/${relativePath}`, env)
  100. ) {
  101. specs.push(`./test/e2e/${relativePath}`);
  102. }
  103. }
  104. };
  105. visit(e2eDir);
  106. return specs;
  107. }
  108. export function partitionE2ESpecsByWeight(specs, shardTotal, profile) {
  109. const defaultWeightMs = readPositiveInteger(
  110. String(profile.defaultWeightMs),
  111. "spec duration defaultWeightMs",
  112. );
  113. const buckets = Array.from({ length: shardTotal }, () => ({
  114. estimatedWeightMs: 0,
  115. specs: [],
  116. }));
  117. const weightedSpecs = specs
  118. .map((spec) => ({
  119. spec,
  120. weightMs: Number(profile.weights?.[spec]) || defaultWeightMs,
  121. }))
  122. .sort((left, right) => right.weightMs - left.weightMs || left.spec.localeCompare(right.spec));
  123. for (const weightedSpec of weightedSpecs) {
  124. let targetIndex = 0;
  125. for (let index = 1; index < buckets.length; index += 1) {
  126. if (buckets[index].estimatedWeightMs < buckets[targetIndex].estimatedWeightMs) {
  127. targetIndex = index;
  128. }
  129. }
  130. buckets[targetIndex].specs.push(weightedSpec.spec);
  131. buckets[targetIndex].estimatedWeightMs += weightedSpec.weightMs;
  132. }
  133. // 修复原因:历史权重只决定 shard 归属;每个 shard 内恢复稳定路径顺序,
  134. // 避免权重更新改变 fixture/mock 的执行顺序并制造无意义的快照差异。
  135. for (const bucket of buckets) bucket.specs.sort((a, b) => a.localeCompare(b));
  136. return buckets;
  137. }
  138. function formatRunId(date = new Date()) {
  139. return `desktop-e2e-${date.toISOString().replace(/[-:.TZ]/gu, "")}`;
  140. }
  141. export function createWindowsE2ERunId({ timestamp, processId, entropy }) {
  142. return `${formatRunId(timestamp)}-p${processId}-${entropy}`;
  143. }
  144. function createBuildEnv(env) {
  145. const { NODE_OPTIONS: _nodeOptions, ...buildEnv } = env;
  146. // 修复原因:从 ZCode 客户端 shell 运行时,构建会继承 ZCODE_ENV=production / ZCODE_BASE_URL,
  147. // 把它们固化进 agent 与桌面包,导致 E2E 打生产域、fixture endpoint 失效。
  148. return normalizeE2EDesktopBuildEnv({
  149. ...buildEnv,
  150. PNPM_CONFIG_VERIFY_DEPS_BEFORE_RUN: "false",
  151. VITE_ZCODE_E2E_STORE_BRIDGE: "1",
  152. // Windows full E2E 反复执行时复用 Turbo 内容缓存;冷缓存仍按依赖图构建,
  153. // targeted/non-Windows 路径不会经过父 runner 的 sharded build env。
  154. ZCODE_DESKTOP_AGENT_BUILD_MODE: env.ZCODE_DESKTOP_AGENT_BUILD_MODE ?? "turbo",
  155. });
  156. }
  157. export function createWindowsE2EShardPlan({
  158. args,
  159. desktopDir,
  160. env,
  161. platform,
  162. processId = process.pid,
  163. repoRoot,
  164. runIdEntropy,
  165. runIdTimestamp = new Date(),
  166. weightedSpecBuckets,
  167. }) {
  168. const { wdioArgs } = splitRunnerArgs(args);
  169. const shardTotal = resolveWindowsE2EShardTotal({ args, env, platform });
  170. // 修复原因:只有 ISO 毫秒的自动 ID 会让同毫秒启动的 runner 共享 HOME/artifact/network。
  171. // 显式 ID 保持原语义;自动 ID 同时加入 PID 和随机熵,测试可注入固定值稳定验证。
  172. const runId =
  173. env.ZCODE_E2E_RUN_ID?.trim() ||
  174. createWindowsE2ERunId({
  175. entropy: runIdEntropy ?? randomBytes(8).toString("hex"),
  176. processId,
  177. timestamp: runIdTimestamp,
  178. });
  179. const artifactRoot = resolve(
  180. env.ZCODE_E2E_ARTIFACT_DIR?.trim() || join(desktopDir, ".e2e-artifacts", runId),
  181. );
  182. const explicitHomeRoot = env.ZCODE_E2E_HOME_DIR?.trim();
  183. // 修复原因:单 shard runner 也可能并发启动;默认 HOME 若固定为 `.e2e-home`,
  184. // 不同 runId 会互相清理进程和状态。显式 HOME 保持调用方语义,默认 HOME 才追加 runId。
  185. const homeRoot = resolve(explicitHomeRoot || join(desktopDir, `.e2e-home-${runId}`));
  186. const sharded = shardTotal > 1;
  187. const useWeightedSpecBuckets =
  188. sharded &&
  189. weightedSpecBuckets?.length === shardTotal &&
  190. weightedSpecBuckets.every((bucket) => bucket.specs.length > 0) &&
  191. !wdioArgs.some((arg) => arg === "--exclude" || arg.startsWith("--exclude="));
  192. const buildEnv = createBuildEnv(env);
  193. const buildSteps = [
  194. ...(platform === "win32"
  195. ? [
  196. {
  197. id: "prepare-windows-entry-shim",
  198. kind: "build",
  199. command: process.execPath,
  200. args: [
  201. join(desktopDir, "scripts/build-windows-preinstalled-entry-shim.mjs"),
  202. "--ensure",
  203. ],
  204. cwd: repoRoot,
  205. env: buildEnv,
  206. timeoutMs: PREINSTALLED_ENTRY_SHIM_PROCESS_TIMEOUT_MS,
  207. killProcessTree: true,
  208. killSignal: "SIGKILL",
  209. },
  210. ]
  211. : []),
  212. ...(sharded
  213. ? [
  214. {
  215. id: "build-desktop",
  216. kind: "build",
  217. command: process.execPath,
  218. args: [join(desktopDir, "scripts/ensure-e2e-desktop-build.mjs")],
  219. cwd: repoRoot,
  220. env: buildEnv,
  221. },
  222. {
  223. id: "build-agent",
  224. kind: "build",
  225. command: process.execPath,
  226. args: [join(repoRoot, "scripts/build-desktop-agent-cli.mjs")],
  227. cwd: repoRoot,
  228. env: buildEnv,
  229. },
  230. ]
  231. : []),
  232. ];
  233. const children = Array.from({ length: shardTotal }, (_, offset) => {
  234. const shardIndex = offset + 1;
  235. const shardId = `${shardIndex}/${shardTotal}`;
  236. const shardName = `shard-${shardIndex}-of-${shardTotal}`;
  237. const childRunId = sharded ? `${runId}-${shardName}` : runId;
  238. const artifactDir = sharded ? join(artifactRoot, shardName) : artifactRoot;
  239. // 修复原因:默认并发度从多 shard 收敛为单 child 后,旧逻辑会让并发 runner
  240. // 重新共享 .e2e-home 并互相清理进程;自动 HOME 必须始终携带 runId。
  241. // 显式单 child HOME 保持原路径兼容,只有显式多 shard 才继续追加 run/shard 身份。
  242. const childHomeDir = explicitHomeRoot
  243. ? sharded
  244. ? join(homeRoot, runId, shardName)
  245. : homeRoot
  246. : sharded
  247. ? join(desktopDir, `.e2e-home-${runId}-shard-${shardIndex}`)
  248. : join(desktopDir, `.e2e-home-${runId}`);
  249. const childEnv = {
  250. ...env,
  251. ZCODE_E2E_HOME_DIR: childHomeDir,
  252. ZCODE_E2E_RUN_ID: childRunId,
  253. ZCODE_E2E_ARTIFACT_DIR: artifactDir,
  254. ZCODE_E2E_NETWORK_CAPTURE_DIR: sharded
  255. ? join(artifactDir, "network-capture")
  256. : resolve(
  257. env.ZCODE_E2E_NETWORK_CAPTURE_DIR?.trim() || join(artifactDir, "network-capture"),
  258. ),
  259. ...(sharded
  260. ? {
  261. ZCODE_E2E_SKIP_BUILD: "1",
  262. ZCODE_E2E_SKIP_AGENT_BUILD: "1",
  263. }
  264. : {}),
  265. ...(useWeightedSpecBuckets
  266. ? { ZCODE_E2E_SPEC: weightedSpecBuckets[offset].specs.join(",") }
  267. : {}),
  268. };
  269. return {
  270. id: shardName,
  271. kind: "child",
  272. shardId,
  273. shardIndex,
  274. shardTotal,
  275. command: "pnpm",
  276. args: [
  277. "exec",
  278. "wdio",
  279. "run",
  280. "wdio.conf.ts",
  281. ...wdioArgs,
  282. ...(sharded && !useWeightedSpecBuckets ? [`--shard=${shardId}`] : []),
  283. ],
  284. cwd: desktopDir,
  285. env: childEnv,
  286. artifactDir,
  287. summaryPath: join(artifactDir, "summary.json"),
  288. ...(useWeightedSpecBuckets
  289. ? {
  290. specs: weightedSpecBuckets[offset].specs,
  291. estimatedWeightMs: weightedSpecBuckets[offset].estimatedWeightMs,
  292. }
  293. : {}),
  294. };
  295. });
  296. return {
  297. runId,
  298. shardTotal,
  299. wdioArgs,
  300. artifactRoot,
  301. distributionKind: useWeightedSpecBuckets ? "historical-lpt" : "wdio-native",
  302. manifestPath: join(artifactRoot, "shard-manifest.json"),
  303. buildSteps,
  304. children,
  305. };
  306. }
  307. async function writeShardManifest(path, manifest) {
  308. await mkdir(dirname(path), { recursive: true });
  309. await writeFile(path, `${JSON.stringify(manifest, null, 2)}\n`, "utf-8");
  310. }
  311. function printShardManifest(manifest) {
  312. console.log(`[e2e-shards] ${JSON.stringify(manifest, null, 2)}`);
  313. }
  314. export class WindowsE2EShardRunError extends Error {
  315. constructor(message, manifest) {
  316. super(message);
  317. this.name = "WindowsE2EShardRunError";
  318. this.manifest = manifest;
  319. }
  320. }
  321. export async function executeWindowsE2EShardPlan(
  322. plan,
  323. {
  324. now = Date.now,
  325. signalSource = process,
  326. spawnStep: runStep = spawnCancellableStep,
  327. summaryExists = existsSync,
  328. writeManifest = writeShardManifest,
  329. printManifest = printShardManifest,
  330. } = {},
  331. ) {
  332. const startedAtMs = now();
  333. const activeExecutions = new Set();
  334. const terminationRequestedExecutions = new WeakSet();
  335. let interruptedBySignal;
  336. const terminateActiveExecutions = (excludedExecution) => {
  337. for (const execution of activeExecutions) {
  338. if (
  339. execution === excludedExecution ||
  340. terminationRequestedExecutions.has(execution) ||
  341. typeof execution.terminate !== "function"
  342. ) {
  343. continue;
  344. }
  345. terminationRequestedExecutions.add(execution);
  346. try {
  347. execution.terminate();
  348. } catch {
  349. // 等待对应 result 进入 close/error 终态,不能因清理调用失败提前跳出。
  350. }
  351. }
  352. };
  353. const runTrackedStep = (step, { terminatePeersOnStartFailure = false } = {}) => {
  354. const execution = startStepExecution(runStep, step);
  355. activeExecutions.add(execution);
  356. const result = execution.result
  357. .then((stepResult) => {
  358. if (terminatePeersOnStartFailure && stepResult.error) {
  359. terminateActiveExecutions(execution);
  360. }
  361. return stepResult;
  362. })
  363. .finally(() => activeExecutions.delete(execution));
  364. return result;
  365. };
  366. const signalHandlers = new Map(
  367. ["SIGINT", "SIGTERM"].map((signal) => [
  368. signal,
  369. () => {
  370. interruptedBySignal ??= signal;
  371. terminateActiveExecutions();
  372. },
  373. ]),
  374. );
  375. for (const [signal, handler] of signalHandlers) signalSource.on(signal, handler);
  376. try {
  377. for (const buildStep of plan.buildSteps) {
  378. const result = await runTrackedStep(buildStep);
  379. if (interruptedBySignal) {
  380. throw new Error(`parent received ${interruptedBySignal} during ${buildStep.id}`);
  381. }
  382. if (result.error) {
  383. throw new Error(`${buildStep.id} failed to start: ${result.error}`);
  384. }
  385. if (result.exitCode !== 0) {
  386. throw new Error(`${buildStep.id} exited with code ${result.exitCode}`);
  387. }
  388. }
  389. // 每项内部吸收 reject,保证所有已启动 shard 都进入 close/error 终态后才写 manifest。
  390. const childResults = await Promise.all(
  391. plan.children.map(async (child) => ({
  392. child,
  393. result: await runTrackedStep(child, { terminatePeersOnStartFailure: true }),
  394. })),
  395. );
  396. for (const childResult of childResults) {
  397. if (childResult.result.exitCode === 0 && !summaryExists(childResult.child.summaryPath)) {
  398. // 修复原因:onPrepare 的 unref timer 曾让 shard 在未运行任何 spec 时静默退出 0;
  399. // summary 是执行覆盖的权威证据,缺失时必须让父 runner 失败。
  400. childResult.result = {
  401. exitCode: 1,
  402. error: `missing shard summary: ${childResult.child.summaryPath}`,
  403. };
  404. }
  405. }
  406. const finishedAtMs = now();
  407. const manifest = {
  408. runId: plan.runId,
  409. shardTotal: plan.shardTotal,
  410. distributionKind: plan.distributionKind,
  411. wallDurationMs: finishedAtMs - startedAtMs,
  412. manifestPath: plan.manifestPath,
  413. ...(interruptedBySignal ? { interruptedBySignal } : {}),
  414. children: childResults.map(({ child, result }) => ({
  415. shardId: child.shardId,
  416. exitCode: result.exitCode,
  417. ...(result.signal ? { signal: result.signal } : {}),
  418. ...(result.error ? { error: result.error } : {}),
  419. artifactDir: child.artifactDir,
  420. summaryPath: child.summaryPath,
  421. ...(child.specs ? { specs: child.specs } : {}),
  422. ...(child.estimatedWeightMs ? { estimatedWeightMs: child.estimatedWeightMs } : {}),
  423. })),
  424. };
  425. await writeManifest(plan.manifestPath, manifest);
  426. printManifest(manifest);
  427. const failures = manifest.children.filter(
  428. (child) => child.exitCode !== 0 || child.error || child.signal,
  429. );
  430. if (interruptedBySignal || failures.length > 0) {
  431. const failureMessages = failures.map((child) => {
  432. if (child.error) return `shard ${child.shardId} failed to start: ${child.error}`;
  433. if (child.signal) return `shard ${child.shardId} terminated by signal ${child.signal}`;
  434. return `shard ${child.shardId} exited with code ${child.exitCode}`;
  435. });
  436. if (interruptedBySignal) failureMessages.unshift(`parent received ${interruptedBySignal}`);
  437. throw new WindowsE2EShardRunError(failureMessages.join("; "), manifest);
  438. }
  439. return manifest;
  440. } finally {
  441. for (const [signal, handler] of signalHandlers) signalSource.off(signal, handler);
  442. }
  443. }
  444. export async function runWindowsE2EShards({
  445. args = process.argv.slice(2),
  446. desktopDir = resolve(dirname(fileURLToPath(import.meta.url)), ".."),
  447. env = process.env,
  448. platform = process.platform,
  449. repoRoot = resolve(desktopDir, "../.."),
  450. } = {}) {
  451. const shardTotal = resolveWindowsE2EShardTotal({ args, env, platform });
  452. const useHistoricalWeights =
  453. shardTotal > 1 &&
  454. !isTargetedRun(args, env) &&
  455. !isManualReviewRun(args, env) &&
  456. env.E2E_PROVIDER_HTTP_MODE?.trim() !== "capture";
  457. let weightedSpecBuckets;
  458. if (useHistoricalWeights) {
  459. const durationProfile = JSON.parse(
  460. readFileSync(join(desktopDir, DEFAULT_SPEC_DURATION_PROFILE_PATH), "utf-8"),
  461. );
  462. weightedSpecBuckets = partitionE2ESpecsByWeight(
  463. listDefaultFormalE2ESpecs(desktopDir, env),
  464. shardTotal,
  465. durationProfile,
  466. );
  467. }
  468. const plan = createWindowsE2EShardPlan({
  469. args,
  470. desktopDir,
  471. env,
  472. platform,
  473. repoRoot,
  474. weightedSpecBuckets,
  475. });
  476. return await executeWindowsE2EShardPlan(plan);
  477. }
  478. const isEntrypoint =
  479. typeof process.argv[1] === "string" &&
  480. resolve(process.argv[1]) === fileURLToPath(import.meta.url);
  481. if (isEntrypoint) {
  482. try {
  483. await runWindowsE2EShards();
  484. } catch (error) {
  485. console.error(`[e2e-shards] ${error instanceof Error ? error.message : String(error)}`);
  486. process.exitCode = 1;
  487. }
  488. }