run-windows-e2e-shards.mjs 17 KB

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