run-windows-e2e-shards.mjs 17 KB

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