Peach: Local-first video metadata scraper and media manager.
perf(test): 按实测耗时排程分片与浏览器文件,并逐条记录测试结果
longmeidao6adc86d53aac
diff --git a/docs/TESTING.md b/docs/TESTING.mdindex 1175cf681..83ed94323 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -94,11 +94,11 @@ GitGud 流水线(`.gitlab-ci.yml`)的 `verify-linux`、`verify-windows`、`vRelease 在媒体工具编译前核对同 SHA 主线 CI,缓存键绑定媒体工具源码清单与构建脚本,缓存内容同时含二进制和对应源码包;制品与独立开箱验收仍是发布前置。Docker 只在镜像相关主线改动、匹配 PR、版本标签或手动请求时运行,验收后推送同一个本地镜像。版本发布与覆盖升级验收不取消进行中的同目标运行;覆盖升级需明确选择目标版本及完整构建提交。-浏览器用例覆盖 `frontend/e2e` 下全部 `*.test.ts`,包括子目录。`setup.test.ts` 由 `SetupE2ETests` 在首次设置服务上执行,其余文件在已配置的演示库服务上按文件并发、文件内串行。并发数取 `PEACH_E2E_CONCURRENCY`;未设时本机取逻辑核数的四分之一、上限 4,CI(`GITHUB_ACTIONS=true`)为 1。并发批最多 12 个文件,串行批每批一个文件,各自取得完整 TAP 结果。测量动画、密度切换与等待态替换的文件(`tests/test_web_e2e.py` 的 `TIMING_SENSITIVE_SUITES`)在并发批之后串行;并发为 1 时按设计决定、交互回归和路由冒烟排序。每批限时 600 秒,任一批失败,整轮验证失败。并发的文件共用一个服务和演示库:用例触发的写请求只能落在别的用例不断言的状态上,否则用 `page.route` 拦下或归进串行批。控制台逐批输出文件名;完整 TAP 日志与服务访问日志 `serve.log` 保存在 `build/agent-verification/browser/`,CI 在测试结束后上传其中的 TAP 日志。+浏览器用例覆盖 `frontend/e2e` 下全部 `*.test.ts`,包括子目录。`setup.test.ts` 由 `SetupE2ETests` 在首次设置服务上执行,其余文件在已配置的演示库服务上按文件并发、文件内串行。并发数取 `PEACH_E2E_CONCURRENCY`;未设时本机取逻辑核数的四分之一、上限 4,CI(`GITHUB_ACTIONS=true`)为 1。每个文件单独起一次 Node,限时 600 秒,取得自己的完整 TAP;空出的通道马上领下一个文件,没有批与批之间的等待。并发时文件按 `scripts/ci-browser-timings.json` 的实测秒数先长后短排队(没测过的按 30 秒算),测量动画、密度切换与等待态替换的文件(`tests/test_web_e2e.py` 的 `TIMING_SENSITIVE_SUITES`)在并发文件全部结束后逐个串行;并发为 1 时按设计决定、交互回归和路由冒烟的顺序逐个执行。任一文件失败或超时,整轮验证失败。并发的文件共用一个服务和演示库:用例触发的写请求只能落在别的用例不断言的状态上,否则用 `page.route` 拦下或归进时序敏感的串行文件。控制台在每个文件结束时输出成败与耗时;每个文件的 TAP 日志 `e2e-<文件名>.tap`、首启的 `setup.tap` 与服务访问日志 `serve.log` 保存在 `build/agent-verification/browser/`,CI 在测试结束后上传其中的 TAP 日志。需要外部前置条件(Node、ffmpeg、Chrome 等)的用例,本机缺条件时跳过,在 CI(`GITHUB_ACTIONS=true`)里判失败,判定集中在 `tests/support/conditions.py` 的 `missing_prerequisite`。所以 `python` 矩阵里 `core` 以外的行也装 Node,Windows 行另装 ffmpeg 与 Chrome。-本机默认并行:入口传 `--jobs auto`(Windows `-Jobs`),运行器按同一套稳定分片切成并发数四倍的片,每个子进程各领一片、先完成的接着领下一片,父进程汇总成败、用例数与逐用例耗时后按原口径签发一份记录,一片红整轮红。`-Jobs 1` 退回串行。测试之间没有共享的端口或全局目录,账本与仓库夹具都在各自的临时目录里,并行才是安全的;新增测试保持这一点。运行器给每次运行建一个 `peach-test-run-<时间戳>-*` 目录,把 `TEMP`、`TMP`、`TMPDIR` 与 `tempfile.tempdir` 指向它,分片子进程沿用同一个,结束时整个删除;被强行结束的运行留下的目录,在下一次运行开始时超过一天就清扫。用例仍应回收自己的临时目录,运行目录只兜底。+本机默认并行:入口传 `--jobs auto`(Windows `-Jobs`),运行器切成并发数四倍的片,每个子进程各领一片、先完成的接着领下一片,父进程汇总成败、用例数与逐用例耗时后按原口径签发一份记录,一片红整轮红。`-Jobs 1` 退回串行。分片按实测耗时划分:每次运行把各测试文件的墙钟(含类级准备)并进共享记录目录的 `test-timings.json`,下一次按它先长后短把文件装进当前最空的一片(没测过的文件取中位数),总时长最长的片先派发;浏览器冒烟所在的 `test_web_e2e.py` 没有实测时也独占首片。父进程把划分写成文件交给子进程,父子用同一份;CI 的分片不带划分,仍按文件名轮转。测试之间没有共享的端口或全局目录,账本与仓库夹具都在各自的临时目录里,并行才是安全的;新增测试保持这一点。运行器给每次运行建一个 `peach-test-run-<时间戳>-*` 目录,把 `TEMP`、`TMP`、`TMPDIR` 与 `tempfile.tempdir` 指向它,分片子进程沿用同一个,结束时整个删除;被强行结束的运行留下的目录,在下一次运行开始时超过一天就清扫。用例仍应回收自己的临时目录,运行目录只兜底。Windows 的路径、挂载、托盘、证书、进程编码、更新、认证及迁移属于 `core`。构建和工作流修改选择 `packaging` 与 `tooling`;测试调度自身仍全量。仅 uv 工具版本或项目展示字段变化不算依赖图变化;无法解析时全量。@@ -170,7 +170,7 @@ ffmpeg 起不来是事实,但它不该挡住一次只改文档的 `checks`。Windows 的 `-Focus` 接受 Python 模块、类、方法或仓库相对路径,可传数组;macOS/Linux 对每个选择器重复传 `--focus`。入口准备隔离依赖并核对源码。选择器不存在、浏览器路径超出 `frontend/e2e` 或与分片混用时拒绝执行。浏览器用例只收单个 `frontend/e2e/*.test.ts` 文件,不收目录;要跑全部 e2e 时把文件逐个列进数组。-浏览器冒烟把 e2e 文件分成若干批,一批失败仍跑完其余批次,最后把各失败批次的输出与日志路径一起报出;一轮全量就能看到所有 e2e 失败,修完再起下一轮。+浏览器冒烟逐个文件执行,一个文件失败仍跑完其余文件,最后把各失败文件的输出与日志路径一起报出;一轮全量就能看到所有 e2e 失败,修完再起下一轮。定向调试 Python 回归:@@ -190,7 +190,7 @@ macOS/Linux 的相同入口:./scripts/test.sh auto --focus frontend/e2e/jav-detail.test.ts```-定向调试不签发记录,不能作为 `ready` / `integrate` 的验收证明。浏览器文件选择只在调试环境生效;正式入口拒绝残留的 `PEACH_TEST_FOCUS` / `PEACH_E2E_FILES`,防止局部运行被签成整域。某个浏览器批次失败或超时后立即结束该轮浏览器检查,保留完整 TAP 与服务日志。+定向调试不签发记录,不能作为 `ready` / `integrate` 的验收证明。浏览器文件选择只在调试环境生效;正式入口拒绝残留的 `PEACH_TEST_FOCUS` / `PEACH_E2E_FILES`,防止局部运行被签成整域。浏览器文件失败或超时时保留它的完整 TAP 与服务日志。浏览器沿用 Playwright 的默认进程模型与静音设置,不限制渲染进程数,也不把 GPU 或音频服务强制并入浏览器进程。原生浏览器启动限时 60 秒,页面主体等待限时 15 秒,每批限时 600 秒;进程启动与页面行为分别验收。需要任务状态桩的页面通过 `visit` 的准备回调在首次导航前安装响应,等对应的 React 主体出现后再检查任务状态;进行中的任务不作为主体等待态。页面主体等待失败时保留 URL、关闭状态、已收集的运行期问题与无障碍树,夹具关闭本次浏览器上下文。@@ -237,3 +237,28 @@ PowerShell 里解析到 `Git\cmd\git.exe`、在 Git Bash 里解析到 `Git\mingw& .\.venv\Scripts\python.exe -X utf8 <工作树>\scripts\agent_worktree.py `--repo <主检出> integrate --branch <分支>```++## 测试结果历史++正式入口与定向调试每次运行都把逐条结果追加进测试结果历史,用来统计每条测试抓到回归的比率,并区分抖动、期望过时与环境失败。实现在 `scripts/test_history.py`。++文件是 Git common directory 上一级的 `build/test-history/YYYY-MM.jsonl`:本机落在主检出的 `build/` 下,与测试记录 `build/agent-verification/` 同级,所有工作树共用;CI 上就是作业目录的 `build/test-history/`,由流水线作为 artifact 上传。JSON Lines 按月分文件、只追加,多个进程同时写时由旁边的 `.lock` 串行。++每次运行先写一行运行头:++| 字段 | 含义 |+| --- | --- |+| `type` | 固定为 `run` |+| `run` | 本次运行的编号,逐条结果用它关联 |+| `time` | 写入时刻 |+| `scope` | 请求与实际范围,如 `auto:catalog web`、`full:full`、`focus:<选择器>`;CI 独立分片带 `shard i/n` |+| `platform`、`python` | 平台与解释器版本 |+| `head`、`branch`、`worktree` | 提交、分支(分离头指针时取 CI 的分支变量)与工作树路径 |+| `ci` | `CI`、`GITLAB_CI`、`GITHUB_ACTIONS` 任一非空即为真 |+| `files`、`count` | 本次跑到的测试文件模块名与用例总数 |++之后逐条写 `type` 为 `test` 的行:`run`、`id`、`outcome`(`pass`、`fail`、`error`、`skip`)与 `seconds`,失败与报错另有 `message`,取最后一行异常,遮掉 `token=`、`password=` 一类的值,截断到 200 字。Python 用例名为 `模块.类.方法`,vitest 为 `vitest:文件 > 分组 > 标题`,浏览器用例为 `e2e:文件 > 分组 > 标题`。++为控制体积,只逐条写非通过的用例与耗时不少于 1 秒的通过用例。某条用例跑了几次,用运行头的 `files` 推算:文件在场、没被记成 `skip` 的用例都跑过。++写历史失败只打印一行告警,不改变测试判定。历史不经环境变量传递,也不在被快照的工作树里,测试记录的环境指纹与有效期不受影响。用例里调用运行器的那些测试不写真实历史,也不取走外层运行收集中的 vitest 与浏览器结果。diff --git a/scripts/test_focus.py b/scripts/test_focus.pyindex c6841380d..1492da726 100644--- a/scripts/test_focus.py+++ b/scripts/test_focus.py@@ -48,5 +48,9 @@ def run(runner, args) -> int:print("定向调试:只运行指定用例,不签发正式记录;提交前仍需 auto。", flush=True)flags = {"PEACH_TEST_FOCUS": "1", "PEACH_E2E_FILES": json.dumps(browsers)} if browsers else {}with mock.patch.dict(os.environ, flags):- result = unittest.TextTestRunner(verbosity=2, resultclass=runner.TimedResult).run(suite)+ with runner.test_history.running():+ result = unittest.TextTestRunner(verbosity=2, resultclass=runner.TimedResult).run(suite)+ runner.test_history.append(runner.ROOT, scope="focus:" + " ".join(args.focus),+ rows=result.results + runner.test_history.take_external(),+ files=sorted(result.files))return 0 if result.wasSuccessful() and result.testsRun > 0 else 1diff --git a/scripts/test_history.py b/scripts/test_history.pynew file mode 100644index 000000000..99d0c037d--- /dev/null+++ b/scripts/test_history.py@@ -0,0 +1,203 @@+"""逐条测试结果的历史:每次正式运行把结果追加到按月分的 JSON Lines,用来统计每条测试抓到回归的比率。++一次运行先写一行运行头(`type: run`:范围、平台、提交、分支、工作树、是否 CI、跑了哪些测试文件),+再按条写结果(`type: test`)。为控制体积,只逐条写非通过的用例与耗时不少于 `SLOW_SECONDS`+的通过用例;某条用例跑了几次,由运行头的文件清单推算。++写历史失败只告警,不改变测试判定;文件在测试记录同级、仓库之外(CI 上落在作业目录的+`build/test-history/`),不进代码快照,也不新增环境变量,不影响测试记录的环境指纹。+"""+from __future__ import annotations++import json+import os+import platform+import re+import subprocess+import sys+import time+import uuid+from contextlib import contextmanager+from pathlib import Path++from filelock import FileLock, Timeout++SLOW_SECONDS = 1.0+SUMMARY_CHARS = 200+OUTCOMES = frozenset({"pass", "fail", "error", "skip"})++#: 测试进程里由 vitest、浏览器用例交上来的逐条结果;分片子进程把它们连同自己的结果报给父进程。+_external: list[dict] = []++_SECRET = re.compile(r"(?i)\b(token|password|passwd|secret|api[_-]?key|authorization|cookie)\b(\s*[:=]\s*)\S+")+++def summary(text: str | None) -> str | None:+ """失败的首行摘要:取最后一个非空的异常行,遮掉形如 `token=…` 的值并截断。"""+ if not text:+ return None+ lines = [line.strip() for line in str(text).splitlines() if line.strip()]+ if not lines:+ return None+ errors = [line for line in lines if re.match(r"^[\w.]*(Error|Exception|Failure)\b", line)]+ line = (errors or lines)[-1]+ return _SECRET.sub(r"\1\2***", line)[:SUMMARY_CHARS]+++def result(test_id: str, outcome: str, seconds: float, message: str | None = None) -> dict:+ if outcome not in OUTCOMES:+ raise ValueError(f"未知的测试结果:{outcome}")+ row = {"id": test_id, "outcome": outcome, "seconds": round(float(seconds), 3)}+ if outcome in {"fail", "error"}:+ row["message"] = summary(message)+ return row+++#: 运行器正在执行用例的层数。用例里再调运行器(测运行器自己的那些用例)时不写真实历史,+#: 也不取走外层运行收集到一半的外部结果。+_running = 0+++@contextmanager+def running():+ global _running+ _running += 1+ try:+ yield+ finally:+ _running -= 1+++def nested() -> bool:+ """运行器正在执行用例:此刻调用运行器的是某条用例,不是正式运行。"""+ return _running > 0+++def record_external(rows: list[dict]) -> None:+ """vitest 与浏览器用例在测试进程里交上来的逐条结果。"""+ _external.extend(rows)+++def take_external() -> list[dict]:+ if _running:+ return []+ rows = list(_external)+ _external.clear()+ return rows+++def history_dir(root: Path) -> Path:+ """与测试记录同级:`<Git common directory 的上一级>/build/test-history`。"""+ common = subprocess.run(["git", "-c", f"safe.directory={root.as_posix()}", "-C", str(root),+ "rev-parse", "--path-format=absolute", "--git-common-dir"],+ capture_output=True, text=True, encoding="utf-8", check=True).stdout.strip()+ return Path(common).parent / "build" / "test-history"+++def _git(root: Path, *args: str) -> str:+ try:+ return subprocess.run(["git", "-c", f"safe.directory={root.as_posix()}", "-C", str(root), *args],+ capture_output=True, text=True, encoding="utf-8", check=True).stdout.strip()+ except (OSError, subprocess.CalledProcessError):+ return ""+++def is_ci() -> bool:+ return any(os.environ.get(name) for name in ("CI", "GITLAB_CI", "GITHUB_ACTIONS"))+++def run_header(root: Path, scope: str, files: list[str], count: int) -> dict:+ branch = _git(root, "rev-parse", "--abbrev-ref", "HEAD")+ if branch in {"", "HEAD"}:+ branch = os.environ.get("CI_COMMIT_REF_NAME") or os.environ.get("GITHUB_REF_NAME") or branch+ return {"type": "run", "run": uuid.uuid4().hex, "time": time.strftime("%Y-%m-%dT%H:%M:%S%z"),+ "scope": scope, "platform": platform.platform(), "python": platform.python_version(),+ "head": _git(root, "rev-parse", "HEAD"), "branch": branch, "worktree": str(root),+ "ci": is_ci(), "files": sorted(files), "count": count}+++def kept(rows: list[dict]) -> list[dict]:+ """逐条写哪些:非通过的全写,通过的只写慢的。"""+ return [row for row in rows if row["outcome"] != "pass" or row["seconds"] >= SLOW_SECONDS]+++def append(root: Path, *, scope: str, files: list[str], rows: list[dict],+ folder: Path | None = None) -> Path | None:+ """追加一次运行;多个进程同时写同一个月的文件时用旁边的锁串行。失败只告警,返回 None。"""+ if folder is None and _running:+ return None+ try:+ folder = history_dir(root) if folder is None else folder+ folder.mkdir(parents=True, exist_ok=True)+ path = folder / f"{time.strftime('%Y-%m')}.jsonl"+ header = run_header(root, scope, files, len(rows))+ lines = [json.dumps(header, ensure_ascii=False)]+ lines += [json.dumps({"type": "test", "run": header["run"], **row}, ensure_ascii=False)+ for row in kept(rows)]+ with FileLock(path.with_suffix(".lock"), timeout=30):+ with path.open("a", encoding="utf-8", newline="\n") as stream:+ stream.write("\n".join(lines) + "\n")+ return path+ except (OSError, ValueError, Timeout, subprocess.CalledProcessError) as error:+ print(f"测试结果历史没有写入(不影响本次判定):{error}", file=sys.stderr, flush=True)+ return None+++def vitest_rows(report: dict, frontend: Path) -> list[dict]:+ """vitest JSON 报告 → 逐条结果,用例名为「文件 > 分组 > 标题」。"""+ status = {"passed": "pass", "failed": "fail", "skipped": "skip", "pending": "skip", "todo": "skip"}+ rows = []+ for suite in report.get("testResults", []):+ name = Path(suite.get("name", ""))+ try:+ name = name.relative_to(frontend)+ except ValueError:+ pass+ for case in suite.get("assertionResults", []):+ title = " > ".join([name.as_posix(), *case.get("ancestorTitles", []), case.get("title", "")])+ rows.append(result(f"vitest:{title}", status.get(case.get("status"), "error"),+ (case.get("duration") or 0) / 1000,+ "\n".join(case.get("failureMessages") or [])))+ return rows+++_TAP_RESULT = re.compile(r"^(?P<indent>\s*)(?P<not>not )?ok \d+ - (?P<name>.*?)(?P<skip> # (?:SKIP|TODO)\b.*)?$")+++def tap_rows(path: str, output: str) -> list[dict]:+ """Node `--test-reporter=tap` 的输出 → 逐条叶子用例,用例名为「文件 > 分组 > 标题」。"""+ lines = output.splitlines()+ stack: dict[int, str] = {}+ rows = []+ for index, line in enumerate(lines):+ if line.lstrip().startswith("# Subtest: "):+ indent = len(line) - len(line.lstrip())+ stack[indent] = line.lstrip()[len("# Subtest: "):]+ stack = {level: name for level, name in stack.items() if level <= indent}+ continue+ match = _TAP_RESULT.match(line)+ if not match:+ continue+ indent = len(match["indent"])+ block, seconds, kind, message = [], 0.0, "test", None+ for following in lines[index + 1:]:+ stripped = following.strip()+ if stripped == "...":+ break+ block.append(following)+ for position, item in enumerate(block):+ stripped = item.strip()+ if stripped.startswith("duration_ms:"):+ seconds = float(stripped.split(":", 1)[1]) / 1000+ elif stripped.startswith("type:"):+ kind = stripped.split(":", 1)[1].strip().strip("'\"")+ elif stripped.startswith("error:") and message is None:+ value = stripped.split(":", 1)[1].strip()+ message = value.strip("'\"") if value not in {"|-", "|", ">-", ">"} \+ else next((rest.strip() for rest in block[position + 1:] if rest.strip()), "")+ if kind != "test":+ continue+ parents = [name for level, name in sorted(stack.items()) if level < indent]+ outcome = "skip" if match["skip"] else ("fail" if match["not"] else "pass")+ rows.append(result(" > ".join(["e2e:" + path, *parents, match["name"]]), outcome, seconds, message))+ return rowsdiff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex e43d34445..019762aa2 100644--- a/scripts/test_runner.py+++ b/scripts/test_runner.py@@ -27,7 +27,7 @@ TESTS = ROOT / "tests"if not __package__:sys.path.insert(0, str(ROOT))__package__ = "scripts"-from . import change_impact, test_evidence, test_progress+from . import change_impact, test_evidence, test_history, test_progressCOMMON_PATTERNS = ("test_context_budget.py", "test_test_collection.py", "test_complexity_ratchet.py","test_source_assertion_ratchet.py", "test_python_lint.py")@@ -110,7 +110,7 @@ SCOPES: dict[str, tuple[str, ...]] = {"test_seed_pack.py", "test_seed_followup.py", "test_seed_corrections.py"),"tooling": ("test_scripts.py", "test_trash_junk.py", "test_auth.py", "test_access.py", "test_cli.py", "test_server.py", "test_diagnostics.py", "test_error_reporting.py", "test_remote_reporting.py", "test_reporting_*.py", "test_library_sharing.py", "test_library_diagnostics.py", "test_script_policy.py","test_scan.py", "test_record_rehome.py", "test_wants.py", "test_push_discovery.py", "test_media_probe.py", "test_subtitles.py", "test_onboarding.py", "test_configuration_sources.py", "test_clouddrive_proxy.py", "test_folder_picker.py", "test_ledger_backups.py", "test_clear_camera_filename_codes.py",- "test_agent_worktree.py", "test_test_evidence.py", "test_test_environment.py", "test_dependency_policy.py",+ "test_agent_worktree.py", "test_test_evidence.py", "test_test_history.py", "test_test_environment.py", "test_dependency_policy.py","test_version_bump.py", "test_changelog.py", "test_release_due.py","test_restart_windows_tray.py", "test_deploy_windows_tray.py", "test_runtime_prepare.py","test_buildinfo.py", "test_versioning.py", "test_macos_standalone.py",@@ -371,7 +371,8 @@ AUTO_SCOPE_PREFIXES: tuple[tuple[str, str | tuple[str, ...]], ...] = (FULL_ONLY_PREFIXES: tuple[str, ...] = ("pyproject.toml","scripts/test_runner.py", "scripts/test_evidence.py", "scripts/test.ps1", "scripts/test.sh",- "scripts/ci_plan.py", "scripts/test_environment.py", "scripts/change_impact.py", "scripts/test_progress.py", "uv.lock",+ "scripts/ci_plan.py", "scripts/test_environment.py", "scripts/change_impact.py", "scripts/test_progress.py",+ "scripts/test_history.py", "uv.lock","migrations/","tests/support/","package.json",@@ -659,11 +660,18 @@ def without_ci_frontend_tests(suite: unittest.TestSuite) -> unittest.TestSuite:return selected-def build_suite(*scopes: str, shard_index: int = 0, shard_count: int = 1) -> unittest.TestSuite:+def build_suite(*scopes: str, shard_index: int = 0, shard_count: int = 1,+ assigned_names: Iterable[str] | None = None) -> unittest.TestSuite:+ """本片的用例。`assigned_names` 是父进程按耗时划好的文件名;不给时按文件名轮转(CI 分片)。"""loader = unittest.defaultTestLoadersuite = unittest.TestSuite()files = sorted({path for scope in scopes for path in selected_files(scope)})- assigned = set(files[shard_index::shard_count])+ if assigned_names is None:+ assigned = set(files[shard_index::shard_count])+ else:+ assigned = {TESTS / name for name in assigned_names}+ if not assigned <= set(files):+ raise ValueError(f"分片划分含本次范围以外的文件:{sorted(p.name for p in assigned - set(files))}")sys.path[:0] = [str(ROOT), str(TESTS)]try:for path in sorted(assigned):@@ -690,6 +698,8 @@ class TimedResult(unittest.TextTestResult):super().__init__(*args, **kwargs)self.timings = []self.files: dict[str, float] = {}+ self.results: list[dict] = []+ self.outcome: dict[str, tuple[str, str | None]] = {}self.last = time.monotonic()def startTestRun(self):@@ -703,11 +713,43 @@ class TimedResult(unittest.TextTestResult):def stopTest(self, test):now = time.monotonic()self.timings.append((round(now - self.started, 3), test.id()))+ outcome, message = self.outcome.pop(test.id(), ("pass", None))+ self.results.append(test_history.result(test.id(), outcome, now - self.started, message))module = type(test).__module__self.files[module] = round(self.files.get(module, 0.0) + now - self.last, 3)self.last = nowsuper().stopTest(test)+ def _mark(self, test, outcome: str, err=None) -> None:+ message = f"{err[0].__name__}: {err[1]}" if err else None+ if type(test).__name__ == "_ErrorHolder":+ # 类级或模块级准备失败:没有对应的 startTest/stopTest,直接记一条。+ self.results.append(test_history.result(test.id(), outcome, 0.0, message))+ return+ if self.outcome.get(test.id(), ("pass",))[0] in {"pass", "skip"}:+ self.outcome[test.id()] = (outcome, message)++ def addFailure(self, test, err):+ super().addFailure(test, err)+ self._mark(test, "fail", err)++ def addError(self, test, err):+ super().addError(test, err)+ self._mark(test, "error", err)++ def addSkip(self, test, reason):+ super().addSkip(test, reason)+ self._mark(test, "skip")++ def addUnexpectedSuccess(self, test):+ super().addUnexpectedSuccess(test)+ self._mark(test, "fail", (AssertionError, "预期失败的用例通过了"))++ def addSubTest(self, test, subtest, err):+ super().addSubTest(test, subtest, err)+ if err is not None:+ self._mark(test, "fail" if issubclass(err[0], test.failureException) else "error", err)+TIMINGS_FILE = "test-timings.json"@@ -729,7 +771,7 @@ def load_file_seconds(path: Path | None = None) -> dict[str, float]:def save_file_seconds(measured: dict[str, float], path: Path | None = None) -> None:"""把本次实测并进表里;没跑到的文件保留旧值。几个会话同时写时后到的覆盖,只影响排序。"""- if not measured:+ if not measured or (path is None and test_history.nested()):returntry:path = file_seconds_path() if path is None else path@@ -759,14 +801,44 @@ def resolve_jobs(value: str) -> int:return jobs-def shard_command(scopes: tuple[str, ...], index: int, count: int, timings: Path) -> list[str]:+def shard_command(scopes: tuple[str, ...], index: int, count: int, timings: Path,+ plan: Path | None = None) -> list[str]:command = [sys.executable, str(ROOT / "scripts" / "test_runner.py"),*(item for scope in scopes for item in ("--scope", scope)),"--shard-index", str(index), "--shard-count", str(count),"--timings", str(timings)]+ if plan is not None:+ command += ["--shard-plan", str(plan)]return command+#: 没有本机实测时的先验秒数。浏览器冒烟一条用例占十几分钟,必须独占一片并第一个派发,+#: 否则排在中间的那片开跑时其余分片已过半,它一个人拖尾。+PRIOR_SECONDS = {"test_web_e2e.py": 900.0}+++def shard_plan(names: Iterable[str], shard_count: int,+ seconds: dict[str, float]) -> list[list[str]]:+ """按预计秒数把测试文件装进分片:先长后短,每个文件放进当前最空的一片。++ 返回的分片按预计总时长降序排列,派发按这个顺序,最长的先开跑。实测表按模块名记,+ 没测过的文件取已测文件的中位数;表是空的时所有文件等重,相当于按个数均分。+ """+ names = sorted(names)+ known = sorted(value for value in seconds.values() if value > 0)+ default = known[len(known) // 2] if known else 1.0+ weight = {name: max(seconds.get(name.removesuffix(".py"), default), PRIOR_SECONDS.get(name, 0.0))+ for name in names}+ groups: list[list[str]] = [[] for _ in range(max(1, min(shard_count, len(names))))]+ totals = [0.0] * len(groups)+ for name in sorted(names, key=lambda item: (-weight[item], item)):+ slot = min(range(len(groups)), key=lambda index: (totals[index], index))+ groups[slot].append(name)+ totals[slot] += weight[name]+ order = sorted(range(len(groups)), key=lambda index: (-totals[index], index))+ return [sorted(groups[index]) for index in order]++@@ -776,12 +848,21 @@ def shard_command(scopes: tuple[str, ...], index: int, count: int, timings: Pathdef run_shards(scopes: tuple[str, ...], *, jobs: int, shard_count: int,- spawn=subprocess.Popen, measured: dict | None = None) -> tuple[bool, int, list]:+ spawn=subprocess.Popen, measured: dict | None = None,+ plan: list[list[str]] | None = None,+ outcomes: list | None = None) -> tuple[bool, int, list]:"""运行独立分片并汇总证明;并发取调用方的 jobs,取消时清理自己的子进程。- `measured` 收各片报回的逐文件墙钟。+ `plan` 是父进程定下的逐片文件名,写成文件交给每个子进程,父子用同一份划分;+ 片号即派发顺序。`measured` 收各片报回的逐文件墙钟,`outcomes` 收逐条结果。"""folder = Path(tempfile.mkdtemp(prefix="peach-shards-"))+ plan_path = None+ if plan is not None:+ if len(plan) != shard_count:+ raise ValueError("分片划分的片数与分片总数不符")+ plan_path = folder / "plan.json"+ plan_path.write_text(json.dumps(plan), encoding="utf-8")pending = list(range(shard_count))running = {}passed, count, timings = True, 0, []@@ -791,7 +872,8 @@ def run_shards(scopes: tuple[str, ...], *, jobs: int, shard_count: int,index = pending.pop(0)log = open(folder / f"{index}.log", "w+", encoding="utf-8", errors="replace")try:- process = spawn(shard_command(scopes, index, shard_count, folder / f"{index}.json"),+ process = spawn(shard_command(scopes, index, shard_count, folder / f"{index}.json",+ plan_path),stdout=log, stderr=subprocess.STDOUT, cwd=str(ROOT))except BaseException:log.close()@@ -816,6 +898,8 @@ def run_shards(scopes: tuple[str, ...], *, jobs: int, shard_count: int,timings.extend(tuple(item) for item in report.get("timings", []))if measured is not None:measured.update(report.get("files", {}))+ if outcomes is not None:+ outcomes.extend(report.get("results", []))print(f"分片 {index + 1}/{shard_count} {'通过' if ok else '失败'}"f"({report.get('count', 0)} 个用例)", flush=True)finally:@@ -886,21 +970,55 @@ def environment_preflight(scopes: tuple[str, ...], timings: Path | None = None,raise SystemExit(3)-def run_local_suite(scopes: tuple[str, ...], jobs: int) -> tuple[bool, int, list]:+def run_local_suite(scopes: tuple[str, ...], jobs: int, label: str | None = None) -> tuple[bool, int, list]:"""按调用方选择的并发运行,串行全量通过分片释放测试缓存。"""chosen = {path for scope in scopes for path in selected_files(scope)}if (jobs > 1 or "full" in scopes) and len(chosen) > 1:shard_count = min(len(chosen), 4 * jobs)- print(f"本机分片:{shard_count} 片、同时 {min(jobs, shard_count)} 个子进程", flush=True)+ print(f"本机分片:{shard_count} 片、同时 {min(jobs, shard_count)} 个子进程,按实测耗时先长后短", flush=True)+ plan = shard_plan((path.name for path in chosen), shard_count, load_file_seconds())measured: dict[str, float] = {}- outcome = run_shards(scopes, jobs=jobs, shard_count=shard_count, measured=measured)+ rows: list[dict] = []+ outcome = run_shards(scopes, jobs=jobs, shard_count=shard_count, measured=measured, plan=plan,+ outcomes=rows)save_file_seconds(measured)+ test_history.append(ROOT, scope=label or " ".join(scopes), rows=rows,+ files=[path.stem for path in sorted(chosen)])return outcome- result = unittest.TextTestRunner(verbosity=2, resultclass=TimedResult).run(build_suite(*scopes))+ suite = build_suite(*scopes)+ with test_history.running():+ result = unittest.TextTestRunner(verbosity=2, resultclass=TimedResult).run(suite)save_file_seconds(result.files)+ test_history.append(ROOT, scope=label or " ".join(scopes), rows=result.results + test_history.take_external(),+ files=[path.stem for path in sorted(chosen)])return result.wasSuccessful() and result.testsRun > 0, result.testsRun, result.timings+def run_shard_child(args, requested, scopes, files) -> int:+ """分片子进程:跑父进程(或 CI)分给本片的文件,把成败、耗时与逐条结果写给父进程。"""+ planned = {}+ if args.shard_plan is not None:+ planned["assigned_names"] = json.loads(+ args.shard_plan.read_text(encoding="utf-8"))[args.shard_index]+ suite = build_suite(*scopes, shard_index=args.shard_index, shard_count=args.shard_count, **planned)+ with test_history.running():+ result = unittest.TextTestRunner(verbosity=2, resultclass=TimedResult).run(suite)+ success = result.wasSuccessful() and result.testsRun > 0+ rows = result.results + test_history.take_external()+ if args.timings is not None:+ args.timings.write_text(json.dumps({"success": success, "count": result.testsRun,+ "timings": result.timings, "files": result.files,+ "results": rows}, ensure_ascii=False),+ encoding="utf-8")+ if args.shard_plan is None:+ # CI 的独立分片没有父进程替它汇总,自己写一次历史。+ names = [path.name for path in sorted(files)][args.shard_index::args.shard_count]+ test_history.append(ROOT, scope=f"{' '.join(requested)}:{' '.join(scopes)} "+ f"shard {args.shard_index + 1}/{args.shard_count}",+ rows=rows, files=[name.removesuffix(".py") for name in names])+ return 0 if success else 1++def main(argv: list[str] | None = None) -> int:parser = argparse.ArgumentParser()# `--scope` 可重复:本机并行的父进程把 `auto` 算出来的几个域原样交给每个分片子进程。@@ -915,6 +1033,8 @@ def main(argv: list[str] | None = None) -> int:parser.add_argument("--shard-count", type=int, default=1)parser.add_argument("--timings", type=Path, default=None,help="分片子进程把成败与逐用例耗时写到这个文件,供父进程汇总")+ parser.add_argument("--shard-plan", type=Path, default=None,+ help="父进程按耗时划好的逐片文件名;不给时按文件名轮转")parser.add_argument("--jobs", type=resolve_jobs, default=1,help="本机同时跑几个分片子进程;auto 按核数定。默认串行,正式入口传 auto")parser.add_argument("--list-scopes", action="store_true")@@ -949,17 +1069,10 @@ def main(argv: list[str] | None = None) -> int:print(f"Peach test scope: {' '.join(scopes)} ({len(files)} files)", flush=True)if args.shard_count > 1:# CI 的每片独立 runner;局部分片绝不签发本机全量证明。- result = unittest.TextTestRunner(verbosity=2, resultclass=TimedResult).run(- build_suite(*scopes, shard_index=args.shard_index, shard_count=args.shard_count))- success = result.wasSuccessful() and result.testsRun > 0- if args.timings is not None:- args.timings.write_text(json.dumps({"success": success, "count": result.testsRun,- "timings": result.timings, "files": result.files}),- encoding="utf-8")- return 0 if success else 1+ return run_shard_child(args, requested, scopes, files)if ci_frontend_delegated():print("CI 前端工具检查由 web-bundle 验证;本次不签发本机测试记录。", flush=True)- success, count, _ = run_local_suite(scopes, args.jobs)+ success, count, _ = run_local_suite(scopes, args.jobs, f"{' '.join(requested)}:{' '.join(scopes)}")return 0 if success and count > 0 else 1try:guard = test_evidence.held(test_evidence.evidence_dir(ROOT) / "full-suite.lock",@@ -1046,7 +1159,7 @@ def verified_run(args, requested, scopes, files) -> int:folder = test_evidence.evidence_dir(ROOT)(folder / f"{state}.json").unlink(missing_ok=True)started = time.monotonic()- passed, count, timings = run_local_suite(scopes, args.jobs) \+ passed, count, timings = run_local_suite(scopes, args.jobs, f"{' '.join(requested)}:{' '.join(scopes)}") \if scopes else (True, 0, [])stable = state == test_evidence.key(ROOT)success = passed and stablediff --git a/tests/test_frontend_build.py b/tests/test_frontend_build.pyindex b3689d9f0..afc3a1b10 100644--- a/tests/test_frontend_build.py+++ b/tests/test_frontend_build.py@@ -24,9 +24,11 @@ from pathlib import Pathimport reimport shutilimport subprocess+import tempfileimport unittestfrom peach.diagnostic_browser import BUNDLE_CHUNK_NAME+from scripts import test_historyfrom support.conditions import missing_prerequisiteROOT = Path(__file__).resolve().parents[1]@@ -408,10 +410,17 @@ class VitestTests(unittest.TestCase):def test_the_island_suite_passes(self):npm = self._npm("vitest", "vitest")- completed = subprocess.run(- [npm, "--prefix", str(FRONTEND), "test", "--silent"],- capture_output=True, text=True, encoding="utf-8", errors="replace",- cwd=str(FRONTEND), check=False)+ # 另挂一个 JSON 报告器,把逐条结果交给测试结果历史;控制台输出与判据不变。+ with tempfile.TemporaryDirectory() as folder:+ report = Path(folder) / "vitest.json"+ completed = subprocess.run(+ [npm, "--prefix", str(FRONTEND), "test", "--silent", "--",+ "--reporter=default", "--reporter=json", f"--outputFile.json={report}"],+ capture_output=True, text=True, encoding="utf-8", errors="replace",+ cwd=str(FRONTEND), check=False)+ if report.is_file():+ test_history.record_external(test_history.vitest_rows(+ json.loads(report.read_text(encoding="utf-8")), FRONTEND))output = f"{completed.stdout}\n{completed.stderr}"# vitest 的着色随宿主终端能力漂移,计数断言只认去码后的纯文本;# 退出码与用例数两道判据不受着色影响。diff --git a/tests/test_test_history.py b/tests/test_test_history.pynew file mode 100644index 000000000..bee11a419--- /dev/null+++ b/tests/test_test_history.py@@ -0,0 +1,187 @@+"""测试结果历史:逐条结果怎么记、写到哪、写不进去时不影响判定。"""+from __future__ import annotations++import contextlib+import io+import json+import tempfile+import unittest+from pathlib import Path+from unittest import mock++from scripts import test_history as history+from scripts import test_runner as runner++TAP = """TAP version 13+# Subtest: 跨页锚点定位+ # Subtest: desktop:内容就绪后定位+ ok 1 - desktop:内容就绪后定位+ ---+ duration_ms: 5528.0377+ type: 'test'+ ...+ # Subtest: mobile:内容就绪后定位+ not ok 2 - mobile:内容就绪后定位+ ---+ duration_ms: 2387.5+ type: 'test'+ error: |-+ locator.click: Timeout 15000ms exceeded.+ ...+ # Subtest: narrow 暂不支持+ ok 3 - narrow 暂不支持 # SKIP 没有窄屏夹具+ ---+ duration_ms: 0.1+ type: 'test'+ ...+ 1..3+not ok 1 - 跨页锚点定位+ ---+ duration_ms: 7916.0+ type: 'suite'+ ...+"""+++class ResultCollectionTests(unittest.TestCase):+ def run_cases(self, cases: dict) -> runner.TimedResult:+ case_class = type('Sample', (unittest.TestCase,), {'__module__': 'test_sample', **cases})+ suite = unittest.defaultTestLoader.loadTestsFromTestCase(case_class)+ with contextlib.redirect_stderr(io.StringIO()):+ return unittest.TextTestRunner(stream=io.StringIO(), verbosity=0,+ resultclass=runner.TimedResult).run(suite)++ def test_every_case_gets_one_row_with_its_outcome_and_a_failure_summary(self):+ def failing_subtest(self):+ for value in (1, 2):+ with self.subTest(value=value):+ self.assertEqual(value, 1)++ result = self.run_cases({+ 'test_a_pass': lambda self: None,+ 'test_b_fail': lambda self: self.assertEqual(1, 2, 'token=abc123 不该出现'),+ 'test_c_error': lambda self: {}['missing'],+ 'test_d_skip': unittest.skip('没有夹具')(lambda self: None),+ 'test_e_subtest': failing_subtest,+ })+ rows = {row['id'].rsplit('.', 1)[-1]: row for row in result.results}+ self.assertEqual({name: row['outcome'] for name, row in rows.items()},+ {'test_a_pass': 'pass', 'test_b_fail': 'fail', 'test_c_error': 'error',+ 'test_d_skip': 'skip', 'test_e_subtest': 'fail'})+ self.assertTrue(rows['test_b_fail']['message'].startswith('AssertionError: 1 != 2'))+ self.assertNotIn('abc123', rows['test_b_fail']['message'])+ self.assertEqual(rows['test_c_error']['message'], "KeyError: 'missing'")+ self.assertNotIn('message', rows['test_a_pass'])++ def test_a_class_setup_failure_is_recorded_once_as_an_error(self):+ def broken(cls):+ raise RuntimeError('建库失败')+ result = self.run_cases({'setUpClass': classmethod(broken), 'test_x': lambda self: None})+ self.assertEqual([row['outcome'] for row in result.results], ['error'])+ self.assertIn('建库失败', result.results[0]['message'])+++class HistoryFileTests(unittest.TestCase):+ def setUp(self):+ folder = tempfile.TemporaryDirectory()+ self.addCleanup(folder.cleanup)+ self.folder = Path(folder.name).resolve()++ def test_a_run_appends_its_header_and_only_failures_skips_and_slow_passes(self):+ rows = [history.result('test_a.T.test_fast', 'pass', 0.01),+ history.result('test_a.T.test_slow', 'pass', history.SLOW_SECONDS + 0.5),+ history.result('test_a.T.test_red', 'fail', 0.2, 'AssertionError: 1 != 2'),+ history.result('test_a.T.test_off', 'skip', 0.0)]+ path = history.append(runner.ROOT, scope='auto:catalog', files=['test_a'], rows=rows,+ folder=self.folder)+ history.append(runner.ROOT, scope='full:full', files=['test_a'], rows=rows[:1], folder=self.folder)+ self.assertRegex(path.name, r'^\d{4}-\d{2}\.jsonl$')+ lines = [json.loads(line) for line in path.read_text(encoding='utf-8').splitlines()]+ headers = [line for line in lines if line['type'] == 'run']+ self.assertEqual([header['scope'] for header in headers], ['auto:catalog', 'full:full'])+ first = headers[0]+ for field in ('time', 'platform', 'head', 'branch', 'worktree', 'ci', 'files', 'count'):+ self.assertIn(field, first)+ self.assertEqual(first['count'], 4)+ self.assertEqual(len(first['head']), 40)+ kept = [line['id'].rsplit('.', 1)[-1] for line in lines if line['type'] == 'test']+ self.assertEqual(kept, ['test_slow', 'test_red', 'test_off'])+ self.assertTrue(all(line['run'] == first['run'] for line in lines[1:4]))++ def test_a_history_that_cannot_be_written_only_warns(self):+ blocked = self.folder / 'not-a-directory'+ blocked.write_text('', encoding='utf-8')+ errors = io.StringIO()+ with contextlib.redirect_stderr(errors):+ self.assertIsNone(history.append(runner.ROOT, scope='full:full', files=[], rows=[],+ folder=blocked))+ self.assertIn('不影响本次判定', errors.getvalue())++ def test_runs_started_by_a_test_do_not_write_the_real_history_or_take_outer_rows(self):+ saved = list(history._external)+ self.addCleanup(history._external.__setitem__, slice(None), saved)+ outer = history.result('vitest:x.test.ts > a', 'pass', 2.0)+ history._external[:] = [outer]+ with history.running(), mock.patch.object(history, 'history_dir',+ side_effect=AssertionError('不该写真实历史')):+ self.assertTrue(history.nested())+ self.assertIsNone(history.append(runner.ROOT, scope='full:full', files=[], rows=[]))+ self.assertEqual(history.take_external(), [])+ self.assertEqual(history._external, [outer], '外层运行收集到一半的结果原样留着')++ def test_the_parent_collects_every_shards_rows(self):+ class Done:+ returncode = 0++ def poll(self):+ return 0++ def spawn(command, *, stdout, stderr, cwd):+ index = int(command[command.index('--shard-index') + 1])+ Path(command[command.index('--timings') + 1]).write_text(json.dumps({+ 'success': True, 'count': 1, 'timings': [],+ 'results': [history.result(f'test_{index}.T.test_x', 'fail', 0.1, 'boom')]}), encoding='utf-8')+ return Done()++ rows = []+ with contextlib.redirect_stdout(io.StringIO()):+ runner.run_shards(('checks',), jobs=2, shard_count=2, spawn=spawn, outcomes=rows,+ plan=[['test_a.py'], ['test_b.py']])+ self.assertCountEqual([row['id'] for row in rows], ['test_0.T.test_x', 'test_1.T.test_x'])+++class ExternalRowsTests(unittest.TestCase):+ def test_tap_leaves_become_rows_with_their_suite_path(self):+ rows = history.tap_rows('e2e/anchor-navigation.test.ts', TAP)+ self.assertEqual([(row['id'], row['outcome']) for row in rows], [+ ('e2e:e2e/anchor-navigation.test.ts > 跨页锚点定位 > desktop:内容就绪后定位', 'pass'),+ ('e2e:e2e/anchor-navigation.test.ts > 跨页锚点定位 > mobile:内容就绪后定位', 'fail'),+ ('e2e:e2e/anchor-navigation.test.ts > 跨页锚点定位 > narrow 暂不支持', 'skip'),+ ])+ self.assertAlmostEqual(rows[0]['seconds'], 5.528, places=3)+ self.assertEqual(rows[1]['message'], 'locator.click: Timeout 15000ms exceeded.')++ def test_vitest_json_rows_name_the_file_and_describe_path(self):+ frontend = Path(tempfile.gettempdir()).resolve() / 'frontend'+ report = {'testResults': [{'name': str(frontend / 'test' / 'card.test.tsx'), 'assertionResults': [+ {'ancestorTitles': ['卡片'], 'title': '显示标题', 'status': 'passed', 'duration': 1500},+ {'ancestorTitles': [], 'title': '空态', 'status': 'failed', 'duration': 3,+ 'failureMessages': ['AssertionError: expected 1 to be 2\n at card.test.tsx:4']},+ {'ancestorTitles': [], 'title': '待写', 'status': 'todo', 'duration': None}]}]}+ rows = history.vitest_rows(report, frontend)+ self.assertEqual([(row['id'], row['outcome']) for row in rows], [+ ('vitest:test/card.test.tsx > 卡片 > 显示标题', 'pass'),+ ('vitest:test/card.test.tsx > 空态', 'fail'),+ ('vitest:test/card.test.tsx > 待写', 'skip')])+ self.assertEqual(rows[0]['seconds'], 1.5)+ self.assertEqual(rows[1]['message'], 'AssertionError: expected 1 to be 2')++ def test_summaries_hide_credentials_and_stay_short(self):+ line = history.summary('Traceback\n File x\nValueError: password=hunter2 ' + 'x' * 400)+ self.assertNotIn('hunter2', line)+ self.assertLessEqual(len(line), history.SUMMARY_CHARS)+ self.assertTrue(line.startswith('ValueError: password=***'))+++if __name__ == '__main__':+ unittest.main()diff --git a/tests/test_test_planning.py b/tests/test_test_planning.pyindex bb3217337..47c6787c2 100644--- a/tests/test_test_planning.py+++ b/tests/test_test_planning.py@@ -380,6 +380,81 @@ class TestPlanningTests(unittest.TestCase):self.assertEqual(runner._imported_modules(nested / 'example.py'), {'beta', 'gamma'})self.assertEqual(runner._imported_modules(runner.ROOT / 'src' / 'peach' / 'example.py'), {'alpha'})+ def test_timed_shard_plan_covers_every_file_once_and_starts_with_the_longest(self):+ names = [f'test_{letter}.py' for letter in 'abcdefg'] + ['test_web_e2e.py']+ seconds = {'test_a': 300.0, 'test_b': 120.0, 'test_c': 100.0, 'test_d': 90.0, 'test_e': 10.0,+ 'test_f': 10.0, 'test_g': 50.0, 'test_web_e2e': 1000.0}+ plan = runner.shard_plan(names, 4, seconds)+ self.assertEqual(len(plan), 4)+ self.assertCountEqual([name for shard in plan for name in shard], names)+ self.assertEqual(plan[0], ['test_web_e2e.py'], '最重的文件独占一片并第一个派发')++ def total(shard):+ return sum(seconds[name.removesuffix('.py')] for name in shard)+ totals = [total(shard) for shard in plan]+ self.assertEqual(totals, sorted(totals, reverse=True))+ self.assertLessEqual(max(totals[1:]) - min(totals[1:]), 120.0)+ # 本机还没有实测表:按个数均分,浏览器冒烟照样独占首片。+ empty = runner.shard_plan(names, 4, {})+ self.assertEqual(empty[0], ['test_web_e2e.py'])+ self.assertEqual(sorted(len(shard) for shard in empty[1:]), [2, 2, 3])++ def test_planned_shards_cover_every_case_once_and_reject_foreign_files(self):+ def ids(suite):+ for case in suite:+ if isinstance(case, unittest.TestSuite):+ yield from ids(case)+ else:+ yield case.id()+ scopes = ('follow', 'tooling')+ serial = list(ids(runner.build_suite(*scopes)))+ names = {path.name for scope in scopes for path in runner.selected_files(scope)}+ plan = runner.shard_plan(names, 3, {'test_scripts': 500.0})+ shards = [list(ids(runner.build_suite(*scopes, shard_index=index, shard_count=3,+ assigned_names=plan[index]))) for index in range(3)]+ self.assertCountEqual(serial, [case for shard in shards for case in shard])+ with self.assertRaisesRegex(ValueError, '范围以外'):+ runner.build_suite('checks', assigned_names=['test_scripts.py'])++ def test_a_planned_shard_runs_the_files_its_parent_assigned(self):+ with tempfile.TemporaryDirectory() as directory:+ plan = Path(directory) / 'plan.json'+ plan.write_text(json.dumps([['test_scripts.py'], ['test_http.py', 'test_follow_web.py']]),+ encoding='utf-8')+ report = Path(directory) / 'shard.json'+ suite = unittest.TestSuite([unittest.FunctionTestCase(lambda: None)])+ with patch.object(runner, 'build_suite', return_value=suite) as build, \+ contextlib.redirect_stderr(io.StringIO()), contextlib.redirect_stdout(io.StringIO()):+ self.assertEqual(runner.main(['--scope', 'follow', '--scope', 'tooling',+ '--shard-index', '1', '--shard-count', '2',+ '--timings', str(report), '--shard-plan', str(plan)]), 0)+ build.assert_called_once_with('follow', 'tooling', shard_index=1, shard_count=2,+ assigned_names=['test_http.py', 'test_follow_web.py'])++ def test_parallel_shards_hand_every_child_the_same_plan_in_dispatch_order(self):+ class Done:+ returncode = 0++ def poll(self):+ return 0++ seen = []++ def spawn(command, *, stdout, stderr, cwd):+ index = int(command[command.index('--shard-index') + 1])+ plan = json.loads(Path(command[command.index('--shard-plan') + 1]).read_text(encoding='utf-8'))+ seen.append((index, plan[index]))+ Path(command[command.index('--timings') + 1]).write_text(+ json.dumps({'success': True, 'count': 1, 'timings': []}), encoding='utf-8')+ return Done()++ plan = [['test_web_e2e.py'], ['test_a.py', 'test_b.py'], ['test_c.py']]+ with contextlib.redirect_stdout(io.StringIO()):+ runner.run_shards(('full',), jobs=1, shard_count=3, spawn=spawn, plan=plan)+ self.assertEqual(seen, list(enumerate(plan)))+ with self.assertRaisesRegex(ValueError, '片数'):+ runner.run_shards(('full',), jobs=1, shard_count=2, spawn=spawn, plan=plan)+def test_partial_run_does_not_issue_verification_record(self):with patch.object(runner, 'build_suite', return_value=unittest.TestSuite([unittest.FunctionTestCase(lambda: None)])), \patch.object(runner.test_evidence, 'inputs', side_effect=AssertionError('分片不能签发证据')):diff --git a/tests/test_web_e2e.py b/tests/test_web_e2e.pyindex fa070b0a7..84ef13b84 100644--- a/tests/test_web_e2e.py+++ b/tests/test_web_e2e.py@@ -16,7 +16,9 @@ CI(`GITHUB_ACTIONS=true`)判失败,与 vitest 同一口径;浏览器不"""from __future__ import annotations+import contextlibimport importlib.util+import ioimport jsonimport osimport re@@ -31,6 +33,7 @@ import unittestimport urllib.errorimport urllib.parseimport urllib.request+from concurrent.futures import ThreadPoolExecutor, as_completedfrom contextlib import closingfrom pathlib import Pathfrom unittest import mock@@ -43,14 +46,17 @@ from peach.library_processing import process_libraryfrom support.conditions import missing_prerequisite, windows_ledger_rootsfrom support.ledger import fresh_ledgerfrom support.demo import seed_metadata_cache+from scripts import test_historyROOT = Path(__file__).resolve().parents[1]FRONTEND = ROOT / "frontend"BROWSER_LOGS = ROOT / "build" / "agent-verification" / "browser"SERVER_START_SECONDS = 60E2E_SECONDS = 600-E2E_BATCH_FILES = 12SETUP_SUITE = "e2e/setup.test.ts"+#: 浏览器文件的预计秒数,与 CI 浏览器矩阵共用同一份实测;没测过的文件按 30 秒算。+E2E_TIMINGS = ROOT / "scripts" / "ci-browser-timings.json"+E2E_DEFAULT_SECONDS = 30.0def chrome_executable() -> str | None:@@ -123,11 +129,22 @@ def e2e_command(node: str, concurrency: int, files: tuple[str, ...]) -> list[strreturn [node, "--test", f"--test-concurrency={concurrency}", "--test-reporter=tap", *files]-def e2e_batches(frontend: Path, concurrency: int, selected: tuple[str, ...] = ()) -> tuple[tuple[tuple[str, ...], int], ...]:- """把已配置服务的 `*.test.ts`(含子目录)分批,每批带自己的并发数,限时 600 秒。+def expected_seconds(path: Path = E2E_TIMINGS) -> dict[str, float]:+ """`frontend/e2e/x.test.ts` → 实测秒数,键去掉 `frontend/` 前缀;表缺失时为空。"""+ try:+ seconds = json.loads(path.read_text(encoding="utf-8"))["seconds"]+ except (OSError, ValueError, KeyError, TypeError):+ return {}+ return {name.removeprefix("frontend/"): float(value) for name, value in seconds.items()}- 并发批最多 12 个文件,串行批每批一个文件。并发批之后运行时序敏感的串行批;并发为 1 时,- 按设计决定、交互回归与路由冒烟分组。首启用例由 `SetupE2ETests` 在专用服务执行。++def e2e_pools(frontend: Path, concurrency: int, selected: tuple[str, ...] = (),+ seconds: dict[str, float] | None = None) -> tuple[tuple[tuple[str, ...], int], ...]:+ """把已配置服务的 `*.test.ts`(含子目录)排成依次执行的池,每个池带自己的并发数。++ 池里每个文件单独起一次 Node,限时 600 秒,空出的通道马上领下一个文件,没有批与批之间+ 的等待。并发池按预计秒数先长后短排队;时序敏感的文件在它之后单独串行。并发为 1 时,+ 按设计决定、交互回归与路由冒烟的顺序逐个执行。首启用例由 `SetupE2ETests` 在专用服务执行。"""files = tuple(sorted(path.relative_to(frontend).as_posix()for path in (frontend / "e2e").rglob("*.test.ts")))@@ -143,17 +160,19 @@ def e2e_batches(frontend: Path, concurrency: int, selected: tuple[str, ...] = ()design = tuple(path for path in files if path.startswith("e2e/design-"))routes = tuple(path for path in files if path == "e2e/smoke.test.ts")interactions = tuple(path for path in files if path not in design + routes)- groups = ((design, 1), (interactions, 1), (routes, 1))+ pools = ((design + interactions + routes, 1),)else:+ seconds = expected_seconds() if seconds is None else secondssensitive = tuple(path for path in files if path in TIMING_SENSITIVE_SUITES)- shared = tuple(path for path in files if path not in sensitive)- groups = ((shared, concurrency), (sensitive, 1))- batches = []- for group, lanes in groups:- size = E2E_BATCH_FILES if lanes > 1 else 1- batches.extend((group[start:start + size], lanes)- for start in range(0, len(group), size))- return tuple(batches)+ shared = tuple(sorted((path for path in files if path not in sensitive),+ key=lambda path: (-seconds.get(path, E2E_DEFAULT_SECONDS), path)))+ pools = ((shared, concurrency), (sensitive, 1))+ return tuple((group, lanes) for group, lanes in pools if group)+++def e2e_log_name(path: str) -> str:+ """`e2e/nested/feature.test.ts` → `e2e-nested-feature.tap`,与首启的 `setup.tap` 分开。"""+ return "e2e-" + path.removeprefix("e2e/").removesuffix(".test.ts").replace("/", "-") + ".tap"@windows_ledger_roots@@ -323,37 +342,55 @@ class WebE2ESmokeTests(unittest.TestCase):env = dict(os.environ, PEACH_E2E_ORIGIN=self.origin, PEACH_E2E_ITEM=str(self.item), PEACH_E2E_FFMPEG=self.ffmpeg,PEACH_E2E_CHROME=self.chrome, PEACH_E2E_NET_LOG_DIR=str(BROWSER_LOGS / "network"))BROWSER_LOGS.mkdir(parents=True, exist_ok=True)- for stale in BROWSER_LOGS.glob("batch-*.tap"):- stale.unlink()+ for pattern in ("batch-*.tap", "e2e-*.tap"):+ for stale in BROWSER_LOGS.glob(pattern):+ stale.unlink()concurrency = e2e_concurrency(os.environ.get("PEACH_E2E_CONCURRENCY", "").strip())selected = tuple(json.loads(os.environ.get("PEACH_E2E_FILES", "[]")))- batches = e2e_batches(FRONTEND, concurrency, selected)- # 一批红了也接着跑完后面的批次,最后一起报:停在第一批的话,一轮全量只露出一处失败,+ pools = e2e_pools(FRONTEND, concurrency, selected)+ total = sum(len(files) for files, _ in pools)+ # 一个文件红了也接着跑完其余文件,最后一起报:停在第一处的话,一轮全量只露出一处失败,# 修一处、再等一轮全量才看见下一处。- failures = []- for index, (batch, lanes) in enumerate(batches, 1):- print(f"浏览器批次 {index}/{len(batches)}:{', '.join(batch)}", flush=True)- log_path = BROWSER_LOGS / f"batch-{index}.tap"- try:- completed = subprocess.run(- e2e_command(self.node, lanes, batch),- capture_output=True, text=True, encoding="utf-8", errors="replace",- cwd=str(FRONTEND), env=env, timeout=E2E_SECONDS, check=False)- except subprocess.TimeoutExpired as expired:- partial = expired.stdout or ""- if isinstance(partial, bytes):- partial = partial.decode("utf-8", errors="replace")- log_path.write_text(partial, encoding="utf-8")- failures.append(f"批次 {index} 在 {E2E_SECONDS} 秒内没跑完,完整日志:{log_path}\n{partial[-4000:]}")- continue- output = f"{completed.stdout}\n{completed.stderr}"- log_path.write_text(output, encoding="utf-8")- if (completed.returncode != 0 or not re.search(r"# pass [1-9]\d*", output)- or not re.search(r"# fail 0\b", output)):- failures.append(f"批次 {index}({', '.join(batch)})退出码 {completed.returncode},日志:{log_path}\n{output}")+ failures, finished = [], 0+ for files, lanes in pools:+ print(f"浏览器文件 {len(files)} 个、同时 {lanes} 个:{', '.join(files)}", flush=True)+ with ThreadPoolExecutor(max_workers=lanes) as pool:+ running = [pool.submit(self._run_e2e_file, env, path) for path in files]+ for done in as_completed(running):+ finished += 1+ path, seconds, failure = done.result()+ print(f"浏览器文件 {finished}/{total} {'失败' if failure else '通过'}"+ f"({seconds:.1f}s):{path}", flush=True)+ if failure:+ failures.append(failure)if failures:self.fail("\n\n".join(failures) + f"\n--- serve.log ---\n{self._server_log()}")+ def _run_e2e_file(self, env: dict, path: str) -> tuple[str, float, str | None]:+ """单独起一次 Node 跑一个浏览器文件,完整 TAP 写到它自己的日志;返回失败说明或 None。"""+ log_path = BROWSER_LOGS / e2e_log_name(path)+ started = time.monotonic()+ try:+ completed = subprocess.run(+ e2e_command(self.node, 1, (path,)),+ capture_output=True, text=True, encoding="utf-8", errors="replace",+ cwd=str(FRONTEND), env=env, timeout=E2E_SECONDS, check=False)+ except subprocess.TimeoutExpired as expired:+ partial = expired.stdout or ""+ if isinstance(partial, bytes):+ partial = partial.decode("utf-8", errors="replace")+ log_path.write_text(partial, encoding="utf-8")+ return path, time.monotonic() - started, \+ f"{path} 在 {E2E_SECONDS} 秒内没跑完,完整日志:{log_path}\n{partial[-4000:]}"+ output = f"{completed.stdout}\n{completed.stderr}"+ log_path.write_text(output, encoding="utf-8")+ test_history.record_external(test_history.tap_rows(path, completed.stdout))+ if (completed.returncode != 0 or not re.search(r"# pass [1-9]\d*", output)+ or not re.search(r"# fail 0\b", output)):+ return path, time.monotonic() - started, \+ f"{path} 退出码 {completed.returncode},日志:{log_path}\n{output}"+ return path, time.monotonic() - started, None+class SetupE2ETests(unittest.TestCase):"""首次运行页跑在 `serve --setup` 上:临时 Peach 数据目录里还没有设置文件,提交成功后才有。@@ -446,6 +483,7 @@ class SetupE2ETests(unittest.TestCase):self.fail(f"首启 e2e {E2E_SECONDS} 秒内没跑完,完整日志:{log_path}\n{partial[-4000:]}")output = f"{completed.stdout}\n{completed.stderr}"log_path.write_text(output, encoding="utf-8")+ test_history.record_external(test_history.tap_rows(SETUP_SUITE, completed.stdout))self.assertEqual(completed.returncode, 0, f"{output}\n--- serve.log ---\n{self._server_log()}")self.assertRegex(output, r"# pass 1\b", output)self.assertRegex(output, r"# skipped 0\b", output)@@ -502,76 +540,73 @@ class MissingPrerequisiteTests(unittest.TestCase):PATHS = ("e2e/design-cards.test.ts", "e2e/design-detail.test.ts", "e2e/smoke.test.ts","e2e/nested/feature.test.ts", "e2e/sidebar-motion.test.ts")- def batches_for(self, concurrency: int, paths=None):+ def pools_for(self, concurrency: int, paths=None, seconds=None):with tempfile.TemporaryDirectory() as folder:frontend = Path(folder).resolve()for name in (*(self.PATHS if paths is None else paths), "e2e/harness.ts"):path = frontend / namepath.parent.mkdir(parents=True, exist_ok=True)path.touch()- return e2e_batches(frontend, concurrency)+ return e2e_pools(frontend, concurrency, seconds={} if seconds is None else seconds)- def assertEveryFileOnce(self, batches):- flattened = tuple(path for files, _ in batches for path in files)+ def assertEveryFileOnce(self, pools):+ flattened = tuple(path for files, _ in pools for path in files)self.assertCountEqual(flattened, self.PATHS)- def test_concurrent_run_puts_timing_sensitive_suites_in_a_trailing_serial_batch(self):- batches = self.batches_for(4)- self.assertEveryFileOnce(batches)- (shared, lanes), *serial = batches- self.assertEqual(lanes, 4)- self.assertEqual(serial, [(("e2e/design-cards.test.ts",), 1),- (("e2e/sidebar-motion.test.ts",), 1)])- self.assertIn("e2e/nested/feature.test.ts", shared)-- def test_serial_run_splits_design_interactions_and_routes_to_stay_within_the_time_limit(self):- batches = self.batches_for(1)- self.assertEveryFileOnce(batches)- self.assertEqual([files for files, _ in batches], [- ("e2e/design-cards.test.ts",), ("e2e/design-detail.test.ts",),- ("e2e/nested/feature.test.ts",), ("e2e/sidebar-motion.test.ts",),- ("e2e/smoke.test.ts",),- ])- self.assertEqual({lanes for _, lanes in batches}, {1})-- def test_serial_batches_bound_large_groups_and_run_each_file_once(self):+ def test_concurrent_pool_starts_the_longest_files_first_then_runs_timing_sensitive_suites_alone(self):+ pools = self.pools_for(4, seconds={"e2e/smoke.test.ts": 200.0, "e2e/nested/feature.test.ts": 5.0})+ self.assertEveryFileOnce(pools)+ self.assertEqual(pools, (+ (("e2e/smoke.test.ts", "e2e/design-detail.test.ts", "e2e/nested/feature.test.ts"), 4),+ (("e2e/design-cards.test.ts", "e2e/sidebar-motion.test.ts"), 1),+ ))++ def test_serial_run_keeps_design_interactions_and_routes_in_order(self):+ pools = self.pools_for(1)+ self.assertEveryFileOnce(pools)+ self.assertEqual(pools, ((("e2e/design-cards.test.ts", "e2e/design-detail.test.ts",+ "e2e/nested/feature.test.ts", "e2e/sidebar-motion.test.ts",+ "e2e/smoke.test.ts"), 1),))++ def test_large_groups_stay_in_one_pool_and_run_each_file_once(self):paths = (tuple(f"e2e/design-{index:02}.test.ts" for index in range(13))+ tuple(f"e2e/feature-{index:02}.test.ts" for index in range(25))- + ("e2e/smoke.test.ts",))- batches = self.batches_for(1, paths=paths)- self.assertCountEqual(tuple(path for files, _ in batches for path in files), paths)- self.assertEqual([len(files) for files, _ in batches], [1] * len(paths))- self.assertEqual({lanes for _, lanes in batches}, {1})-- def test_concurrent_batches_cover_large_groups_once_with_the_requested_concurrency(self):- paths = (tuple(f"e2e/feature-{index:02}.test.ts" for index in range(25))+ ("e2e/smoke.test.ts", "e2e/design-cards.test.ts", "e2e/sidebar-motion.test.ts"))- batches = self.batches_for(4, paths=paths)- self.assertCountEqual(tuple(path for files, _ in batches for path in files), paths)- self.assertEqual([len(files) for files, _ in batches], [12, 12, 2, 1, 1])- self.assertEqual([lanes for _, lanes in batches], [4, 4, 4, 1, 1])+ for concurrency, shape in ((1, [(41, 1)]), (4, [(39, 4), (2, 1)])):+ with self.subTest(concurrency=concurrency):+ pools = self.pools_for(concurrency, paths=paths)+ self.assertCountEqual(tuple(path for files, _ in pools for path in files), paths)+ self.assertEqual([(len(files), lanes) for files, lanes in pools], shape)++ def test_expected_seconds_follow_the_shared_browser_timings(self):+ with tempfile.TemporaryDirectory() as folder:+ table = Path(folder).resolve() / "timings.json"+ table.write_text(json.dumps({"seconds": {"frontend/e2e/smoke.test.ts": 120.5}}), encoding="utf-8")+ self.assertEqual(expected_seconds(table), {"e2e/smoke.test.ts": 120.5})+ self.assertEqual(expected_seconds(table.with_name("missing.json")), {})+ self.assertEqual(e2e_log_name("e2e/nested/feature.test.ts"), "e2e-nested-feature.tap")- def test_browser_batches_require_at_least_one_suite(self):+ def test_browser_pools_require_at_least_one_suite(self):with tempfile.TemporaryDirectory() as folder:with self.assertRaisesRegex(AssertionError, "没有浏览器用例"):- e2e_batches(Path(folder).resolve(), 4)+ e2e_pools(Path(folder).resolve(), 4)def test_setup_suite_is_owned_by_the_first_run_service(self):paths = (*self.PATHS, SETUP_SUITE)for concurrency in (1, 4):with self.subTest(concurrency=concurrency):- self.assertEveryFileOnce(self.batches_for(concurrency, paths=paths))+ self.assertEveryFileOnce(self.pools_for(concurrency, paths=paths))with tempfile.TemporaryDirectory() as folder:frontend = Path(folder).resolve()for name in paths:path = frontend / namepath.parent.mkdir(parents=True, exist_ok=True)path.touch()- self.assertEqual(e2e_batches(frontend, 1, (SETUP_SUITE,)), ())- self.assertEqual(e2e_batches(frontend, 1, (SETUP_SUITE, self.PATHS[0])),+ self.assertEqual(e2e_pools(frontend, 1, (SETUP_SUITE,)), ())+ self.assertEqual(e2e_pools(frontend, 1, (SETUP_SUITE, self.PATHS[0])),(((self.PATHS[0],), 1),))- def test_focused_batches_only_collect_named_browser_files(self):+ def test_focused_pools_only_collect_named_browser_files(self):with tempfile.TemporaryDirectory() as folder:frontend = Path(folder).resolve()for name in self.PATHS:@@ -579,29 +614,41 @@ class MissingPrerequisiteTests(unittest.TestCase):path.parent.mkdir(parents=True, exist_ok=True)path.touch()chosen = ("e2e/nested/feature.test.ts",)- self.assertEqual(e2e_batches(frontend, 1, chosen), ((chosen, 1),))+ self.assertEqual(e2e_pools(frontend, 1, chosen), ((chosen, 1),))with self.assertRaisesRegex(AssertionError, "不存在"):- e2e_batches(frontend, 1, ("e2e/missing.test.ts",))+ e2e_pools(frontend, 1, ("e2e/missing.test.ts",))- def test_failed_browser_batch_still_runs_later_batches_and_reports_every_failure(self):+ def test_each_browser_file_runs_alone_and_every_failure_is_reported(self):+ """每个文件单独起一次 Node、各自限时并留下自己的 TAP;一个红了,其余照跑,最后一起报。"""with tempfile.TemporaryDirectory() as folder:log_root = Path(folder).resolve()case = WebE2ESmokeTests("test_every_route_holds_the_layout_and_runtime_invariants")case.origin, case.item, case.chrome, case.node = "http://fixture", 1, "chrome", "node"case.ffmpeg = "ffmpeg"- failed = subprocess.CompletedProcess([], 1, "# pass 1\n# fail 1\n", "failure")- passed = subprocess.CompletedProcess([], 0, "# pass 2\n# fail 0\n", "")- batches = ((("e2e/first.test.ts",), 1), (("e2e/second.test.ts",), 1), (("e2e/third.test.ts",), 1))+ files = ("e2e/first.test.ts", "e2e/second.test.ts", "e2e/third.test.ts", "e2e/fourth.test.ts")+ calls = []++ def run(command, **options):+ calls.append((command, options))+ if command[-1] in {"e2e/first.test.ts", "e2e/third.test.ts"}:+ return subprocess.CompletedProcess(command, 1, "# pass 1\n# fail 1\n", "failure")+ return subprocess.CompletedProcess(command, 0, "# pass 2\n# fail 0\n", "")+with mock.patch.dict(os.environ, {"PEACH_E2E_FILES": "[]"}), \mock.patch(__name__ + ".BROWSER_LOGS", log_root), \- mock.patch(__name__ + ".e2e_batches", return_value=batches), \+ mock.patch(__name__ + ".e2e_pools", return_value=((files[:3], 2), (files[3:], 1))), \mock.patch.object(case, "_server_log", return_value="serve fixture"), \- mock.patch("subprocess.run", side_effect=[failed, passed, failed]) as run:+ mock.patch("subprocess.run", side_effect=run), \+ contextlib.redirect_stdout(io.StringIO()):with self.assertRaises(AssertionError) as raised:case.test_every_route_holds_the_layout_and_runtime_invariants()- self.assertEqual(run.call_count, 3)- for index in (1, 2, 3):- self.assertTrue((log_root / f"batch-{index}.tap").is_file())+ self.assertCountEqual([command[-1] for command, _ in calls], files)+ self.assertEqual(calls[-1][0][-1], "e2e/fourth.test.ts", "串行池在并发池全部结束后才开始")+ for command, options in calls:+ self.assertEqual(command[:3], ["node", "--test", "--test-concurrency=1"])+ self.assertEqual(options["timeout"], E2E_SECONDS)+ for path in files:+ self.assertTrue((log_root / e2e_log_name(path)).is_file())report = str(raised.exception)self.assertIn("e2e/first.test.ts", report)self.assertIn("e2e/third.test.ts", report)