Peach: Local-first video metadata scraper and media manager.
perf(test): 缓存恢复规划并按阶段执行验证
longmeidaoe0b8b3850fe0
diff --git a/docs/REUSE.md b/docs/REUSE.mdindex d072f80b7..0086947e8 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -1,5 +1,9 @@# 复用清单+## 测试规划与阶段计时++`scripts/test_resume.py` 的 `ImpactPlan` 在一次恢复规划内缓存域集合、测试导入图与路径影响;调用方用当前快照创建计划,检查点输入改变时重新计算。`scripts/test_runner.py` 的 `local_batches` 统一快速检查、普通分片和内部并行容器的执行顺序,`scripts/test_run_progress.py` 的 `phase` 将阶段墙钟写入正式测试记录。沿用标准库与现有单项证明协议,不改变证明有效期、环境身份或完整批次要求。使用范围与计时口径见 [测试与 CI](TESTING.md)。+## 首次设置分步框架首次设置、已有数据恢复与完成态共用 `frontend/src/react/pages/setup/setup-scene.tsx` 的分栏框架。媒体库卡片复用配置页的图标、来源色、处理方式及目录控件,访问范围使用 `ConfigurationChoice`。场景布局参考和来源见 [取证记录](reference-snapshots/arion-onboarding.md),设备素材见 [素材说明](../resources/setup/README.md)。没有新增运行时依赖;提交、校验和源码文案编辑沿用现有入口。步骤标题、场景说明和操作区随步骤独立挂载,防止文案草稿映射串到其他步骤。diff --git a/docs/TESTING.md b/docs/TESTING.mdindex 02962fe15..b8148ffea 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -98,7 +98,11 @@ Release 在媒体工具编译前核对同 SHA 主线 CI,缓存键绑定媒体需要外部前置条件(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` 退回串行。分片按实测耗时划分:每次运行把各测试文件的墙钟(含类级准备)并进共享记录目录的 `test-timings.json`,下一次按它先长后短把文件装进当前最空的一片(没测过的文件取中位数),总时长最长的片先派发;浏览器冒烟所在的 `test_web_e2e.py` 没有实测时也独占首片。父进程把划分写成文件交给子进程,父子用同一份;CI 的分片不带划分,仍按文件名轮转。测试之间没有共享的端口或全局目录,账本与仓库夹具都在各自的临时目录里,并行才是安全的;新增测试保持这一点。运行器给每次运行建一个 `peach-test-run-<时间戳>-*` 目录,把 `TEMP`、`TMP`、`TMPDIR` 与 `tempfile.tempdir` 指向它,分片子进程沿用同一个,结束时整个删除;被强行结束的运行留下的目录,在下一次运行开始时超过一天就清扫。用例仍应回收自己的临时目录,运行目录只兜底。+本机默认并行:入口传 `--jobs auto`(Windows `-Jobs`)。选中的快速检查先执行,包含仓库与资源位置、参考资料登记,以及前端类型、样式和文案检查;失败时不启动后续测试。普通测试切成并发数四倍的片,按实测耗时分配,每个子进程各领一片、先完成的接着领下一片。内部已并行的 Vitest 与浏览器容器分别独立执行,不与普通分片或彼此重叠。`-Jobs 1` 使用同一阶段顺序,普通分片串行运行。父进程汇总成败、用例数与耗时后签发一份记录,一片红整轮红。++每次运行把各测试文件的墙钟(含类级准备)并进共享记录目录的 `test-timings.json`,普通分片按它先长后短装进当前最空的一片(没测过的文件取中位数)。父进程把划分交给子进程,父子用同一份;CI 的独立分片仍按文件名轮转。测试账本、仓库夹具与端口须彼此隔离。运行器为每次运行创建 `peach-test-run-<时间戳>-*` 目录,`TEMP`、`TMP`、`TMPDIR` 与 `tempfile.tempdir` 指向它,分片子进程沿用同一目录,结束时删除;中断遗留超过一天的运行目录在下次启动时清扫。用例仍负责回收自己的临时资源。++正式记录的 `phases` 保存输入快照、历史记录读取、恢复规划、测试执行和结束核验耗时;测试执行内另列快速门槛、普通测试及各前端容器。父子阶段有包含关系,不能相加。`elapsed` 从取得输入快照前开始计时,不包含入口安装依赖、工具预检与取得全量锁前的等待。恢复规划在同一输入快照内复用域集合、测试导入图与路径影响;检查点发现输入改变时重新规划,不沿用旧图。Windows 的路径、挂载、托盘、证书、进程编码、更新、认证及迁移属于 `core`。构建和工作流修改选择 `packaging` 与 `tooling`;测试调度自身仍全量。仅 uv 工具版本或项目展示字段变化不算依赖图变化;无法解析时全量。@@ -242,6 +246,8 @@ GitGud 的三平台验证使用正式恢复入口,通过 GitLab 原生缓存运行中输入改变时,无论该批次是否全部通过,都按差异保留未受影响的成功结果和原时间;退出 `4`,随后 `auto` 补齐缺少项。独立 Python 测试文件的逻辑变化使该文件、直接或间接导入它的测试及公共门槛失效;浏览器测试文件变化使该文件及相应容器检查失效。共享设施、未知范围、执行模式或环境变化仍按完整影响范围重新验证。+首次设置目录 `frontend/src/react/pages/setup/`、素材 `resources/setup/` 和独立页面产物 `web/dist/peach-pages.js`、`web/dist/peach-pages.css` 的补测保留主应用浏览器结果,仍检查首次设置浏览器流程、全部相关 Python 契约、组件与打包。首次设置浏览器用例集中在 `frontend/e2e/setup.test.ts`;新增独立页面浏览器容器时须同步扩充这份对应关系。主应用产物、共享样式或公共组件同时改变时,主应用浏览器结果照常失效。+测试记录格式升级时,主检出的入口可能无法识别新格式。先在工作树通过 `ready`,再由主检出调用该工作树中已验收的 `scripts/agent_worktree.py`,用 `--repo` 指定主检出并执行 `integrate`。该方式仍检查测试记录、README 声明、目标分支和集成锁;不要手工改写记录或跳过门槛。集成后主检出使用同一版本的入口。PR 的浏览器 CI 根据界面、Web API、认证与浏览器用例选择;普通后端单测不单独触发浏览器任务。工作流按职责选测,发布工作流触发打包验证,看板等管理工作流只触发工具检查。主线推送与手动完整验证继续覆盖全部 CI 任务。diff --git a/scripts/test_evidence.py b/scripts/test_evidence.pyindex 585112e97..b0971946d 100644--- a/scripts/test_evidence.py+++ b/scripts/test_evidence.py@@ -332,7 +332,7 @@ def write(root: Path, state: str, scopes: tuple[str, ...], *, success: bool,elapsed: float, slowest: list, count: int, previous: dict | None = None,context: dict | None = None, baseline: dict | None = None,cohort: str | None = None, coverage: dict | None = None, flaky: list | None = None,- units: dict | None = None) -> None:+ units: dict | None = None, phases: dict | None = None) -> None:folder = evidence_dir(root)folder.mkdir(parents=True, exist_ok=True)prior = previous if previous is not None else read(root, state)@@ -354,7 +354,7 @@ def write(root: Path, state: str, scopes: tuple[str, ...], *, success: bool,'units': ({} if scopes else prior.get('units', {})) if units is None else units,"baseline": baseline.get("state") if baseline else None,"failed_scopes": sorted(failed),- "elapsed": elapsed, "count": count, "slowest": slowest,+ "elapsed": elapsed, "count": count, "slowest": slowest, "phases": dict(phases or {}),# 全量里失败、单独重跑通过的用例;记录照样算通过,但名字留在这里可查。"flaky": list(flaky or [])}temporary = folder / f"{state}.{os.getpid()}.tmp"diff --git a/scripts/test_resume.py b/scripts/test_resume.pyindex bdac7b0fd..69e0e952b 100644--- a/scripts/test_resume.py+++ b/scripts/test_resume.py@@ -19,6 +19,8 @@ CONTAINERS = {'test_frontend_build.VitestTests.test_the_island_suite_passes': 'frontend/test/',}OUTCOMES = frozenset({'pass', 'fail', 'unknown'})+SETUP_PREFIXES = ('frontend/src/react/pages/setup/', 'resources/setup/')+PAGE_BUNDLES = frozenset({'web/dist/peach-pages.js', 'web/dist/peach-pages.css'})def external_files(root: Path, module: str) -> set[str]:@@ -54,7 +56,7 @@ def scope_units(root: Path, scope: str, select, supplements=None) -> set[str]:return units-def test_importers(root: Path, module: str) -> set[str]:+def import_graph(root: Path) -> dict[str, set[str]]:graph = {}for path in (root / 'tests').glob('test_*.py'):try:@@ -70,35 +72,69 @@ def test_importers(root: Path, module: str) -> set[str]:if node.module in (None, 'tests'):imports.update(alias.name for alias in node.names)graph[path.name] = {name + '.py' for name in imports if name.startswith('test_')}+ return graph+++def test_importers(root: Path, module: str, graph=None) -> set[str]:+ graph = import_graph(root) if graph is None else graphfound = {module}while additions := {name for name, imports in graph.items() if imports & found} - found:found.update(additions)return found-def affected(root: Path, record: dict, context: dict, all_units: set[str], resolve, select) -> set[str]:+class ImpactPlan:+ """一次输入快照内复用域、测试依赖和路径影响;跨快照重新规划。"""++ def __init__(self, root, all_units, resolve, select):+ self.root, self.all_units, self.resolve, self.select = root, all_units, resolve, select+ self.scopes, self.paths = {}, {}+ self.graph = None++ def scope(self, name):+ if name not in self.scopes:+ self.scopes[name] = scope_units(self.root, name, self.select)+ return self.scopes[name]++ def path(self, path, kind):+ key = (path, kind)+ if key not in self.paths:+ invalid = self.calculate(path, kind)+ invalid.update(name for name in self.all_units if name.startswith('case:') and owner(name) in invalid)+ if kind != 'unsafe' and (path.startswith(SETUP_PREFIXES) or path in PAGE_BUNDLES):+ # 独立页面不加载主应用;Python 契约、打包、组件与 setup 浏览器检查仍执行。+ invalid.difference_update(name for name in self.all_units+ if name.startswith('frontend/e2e/') and name != 'frontend/e2e/setup.test.ts')+ invalid.discard('case:test_web_e2e.WebE2ESmokeTests.test_every_route_holds_the_layout_and_runtime_invariants')+ self.paths[key] = invalid+ return self.paths[key]++ def calculate(self, path, kind):+ if kind not in {'unsafe', 'prose'} and path.startswith('tests/test_') and path.endswith('.py'):+ if self.graph is None:+ self.graph = import_graph(self.root)+ modules = test_importers(self.root, Path(path).name, self.graph)+ return {unit for unit in self.all_units if owner(unit) in modules} | self.scope('checks')+ if kind != 'unsafe' and path.startswith(tuple(EXTERNAL)) and path.endswith(('.test.ts', '.test.tsx')):+ return ({path, owner(path), 'test_frontend_build.py'} | self.scope('checks')+ | {'case:' + case for case in CONTAINERS if path in container_files(self.root, case)})+ scopes, _ = self.resolve([path], kinds={path: kind} if kind else {})+ return set().union(*(self.scope(scope) for scope in scopes))+++def affected(root: Path, record: dict, context: dict, all_units: set[str], resolve, select, *, plan=None) -> set[str]:if record.get('environment') != context['environment']:return set(all_units)paths, kinds = change_impact.delta(record['manifest'], context['manifest'])+ plan = plan or ImpactPlan(root, all_units, resolve, select)invalid = set()for path in paths:- if kinds.get(path) not in {'unsafe', 'prose'} and path.startswith('tests/test_') and path.endswith('.py'):- modules = test_importers(root, Path(path).name)- invalid.update(unit for unit in all_units if owner(unit) in modules)- invalid.update(scope_units(root, 'checks', select))- elif kinds.get(path) != 'unsafe' and path.startswith(tuple(EXTERNAL)) and path.endswith(('.test.ts', '.test.tsx')):- invalid.update({path, owner(path), 'test_frontend_build.py'})- invalid.update('case:' + case for case in CONTAINERS if path in container_files(root, case))- invalid.update(scope_units(root, 'checks', select))- else:- scopes, _ = resolve([path], kinds={path: kinds[path]} if path in kinds else {})- invalid.update(unit for scope in scopes for unit in scope_units(root, scope, select))- invalid.update(name for name in all_units if name.startswith('case:') and owner(name) in invalid)+ invalid.update(plan.path(path, kinds.get(path)))return invalid & all_units-def eligible(root: Path, record: dict, context: dict, all_units: set[str], resolve, select) -> dict:- invalid = affected(root, record, context, all_units, resolve, select)+def eligible(root: Path, record: dict, context: dict, all_units: set[str], resolve, select, *, plan=None) -> dict:+ invalid = affected(root, record, context, all_units, resolve, select, plan=plan)units = dict(record.get('units', {}))if not units:cohort = record.get('cohort')@@ -128,8 +164,9 @@ def recorded_scope(root, scope, select):def combine(root: Path, records, context: dict, all_units: set[str], resolve, select) -> dict:merged = {}+ plan = ImpactPlan(root, all_units, resolve, select)for record in records:- for name, row in eligible(root, record, context, all_units, resolve, select).items():+ for name, row in eligible(root, record, context, all_units, resolve, select, plan=plan).items():previous = merged.get(name)rank = (row['at'], row['outcome'] != 'pass')if previous is None or rank > (previous['at'], previous['outcome'] != 'pass'):diff --git a/scripts/test_run_progress.py b/scripts/test_run_progress.pyindex 2e987ebbe..71369d154 100644--- a/scripts/test_run_progress.py+++ b/scripts/test_run_progress.py@@ -2,15 +2,26 @@from __future__ import annotationsimport time+from contextlib import contextmanagerfrom pathlib import Pathfrom . import test_evidence as evidence, test_resume as resume+@contextmanager+def phase(timings, name):+ started = time.monotonic()+ try:+ yield+ finally:+ timings[name] = timings.get(name, 0) + time.monotonic() - started++class RunProgress:def __init__(self, root, context, scopes, select, resolve, scope_names, *, supplements=None,force=False, records=(), previous=None, cohort=None):self.root, self.context, self.scopes = root, context, scopes+ self.phases = {}self.select, self.resolve = select, resolveself.scope_names, self.supplements = tuple(scope_names), supplements or {}records = list(records)@@ -104,7 +115,7 @@ class RunProgress:prior = {**self.previous, 'validated': validated, 'failed_scopes': sorted(failed)}evidence.write(self.root, self.context['state'], (), success=final and success, previous=prior,context=self.context, cohort=self.cohort, coverage=coverage, units=self.units,- elapsed=elapsed, slowest=slowest or [], count=count, flaky=flaky,+ elapsed=elapsed, slowest=slowest or [], count=count, flaky=flaky, phases=self.phases,baseline={'state': self.sources[0], 'validated': {}} if self.sources else None)def child_plan(self, scopes=None):@@ -117,15 +128,16 @@ class RunProgress:proof = self.units.get('case:' + case, self.units.get(resume.owner('case:' + case), {}))if proof.get('outcome') == 'pass':case_cached[case] = proof- expected = {module: sorted(resume.external_files(self.root, module)) for module in self.external}+ external = resume.external_plan(self.root, self.external, self.units)+ expected = {module: sorted(resume.external_files(self.root, module)) for module in external}cached = {name: self.units[name] for names in expected.values() for name in namesif name in resume.passed_units(self.units)}containers = {case: proof for case, proof in case_cached.items() if case in resume.CONTAINERS}- active = set().union(*map(set, self.external.values())) if self.external else set()+ active = set().union(*map(set, external.values())) if external else set()skipped = [case for case in containers if resume.container_files(self.root, case)and resume.container_files(self.root, case) <= cached.keys()and not resume.container_files(self.root, case) & active]- return {'state': self.context['state'], 'external': self.external, 'expected': expected,+ return {'state': self.context['state'], 'external': external, 'expected': expected,'cached': cached, 'containers': containers, 'skip_cases': skipped, 'case_universe': sorted(cases),'case_cached': case_cached, 'cases': sorted(cases - case_cached.keys())}diff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex 08acca61e..4694f0a66 100644--- a/scripts/test_runner.py+++ b/scripts/test_runner.py@@ -32,7 +32,7 @@ from . import change_impact, test_evidence, test_history, test_resume, test_run_COMMON_PATTERNS = ("test_context_budget.py", "test_test_collection.py", "test_complexity_ratchet.py","test_source_assertion_ratchet.py", "test_python_lint.py")SCOPES: dict[str, tuple[str, ...]] = {- "checks": ("test_copy_final_state.py", "test_dependency_policy.py", "test_repo_hygiene.py", "test_test_planning.py",+ "checks": ("test_copy_final_state.py", "test_dependency_policy.py", "test_repo_hygiene.py", "test_test_planning.py", "test_reference_updates.py","test_complexity_ratchet.py", "test_source_assertion_ratchet.py", "test_python_lint.py"),"follow": ("test_follow*.py", "test_http.py", "test_migrations.py", "test_wants_web.py"),"catalog": ("test_ad_judgement.py", "test_composite_name_split.py", "test_media_libraries.py", "test_media_folders.py",@@ -136,7 +136,7 @@ SCOPES: dict[str, tuple[str, ...]] = {# 后面七个文件的主体不在这一层,但各有一段断言读 `web/` 或 `frontend/` 的源码,# 所以本域也要登记它们:改了 `web/app.js` 却漏跑读它的测试,`test_test_planning.py`# 的域映射门槛会在本地就红。- "web": ("test_frontend_build.py", "test_web_ui.py", "test_web_js.py", "test_web_e2e.py",+ "web": ("test_frontend_build.py", "test_frontend_preflight.py", "test_web_ui.py", "test_web_js.py", "test_web_e2e.py","test_tag_management.py","test_subtitle_search.py", "test_subtitle_memory.py","test_legacy_shell_routes.py",@@ -152,7 +152,7 @@ SCOPES: dict[str, tuple[str, ...]] = {"test_folder_picker.py", "test_fsutil.py", "test_runtime_consistency.py","test_subprocess_encoding.py", "test_outbound_proxy_policy.py", "test_windows_update.py", "test_buildinfo.py"),"packaging": ("test_dependency_policy.py", "test_buildinfo.py", "test_onboarding.py", "test_macos_standalone.py",- "test_cli.py", "test_server.py", "test_versioning.py", "test_frontend_build.py",+ "test_cli.py", "test_server.py", "test_versioning.py", "test_frontend_build.py", "test_frontend_preflight.py","test_cloudflared_packaging.py", "test_desktop_installer.py","test_ffmpeg_build.py", "test_ffmpeg_bundle.py", "test_untrunc_build.py", "test_macos_media.py","test_face_models_bundle.py", "test_metadata_amane_bridge.py"),@@ -360,6 +360,7 @@ AUTO_SCOPE_PREFIXES: tuple[tuple[str, str | tuple[str, ...]], ...] = (("resources/licenses/", ("packaging", "tooling")),# 应用图标:页面站标(web)、托盘与菜单栏(sync)、安装包与 DMG(packaging),# `test_scripts.py` 读 `peach-logo.png`(tooling)。+ ("resources/setup/", ("web", "packaging")),("resources/", ("sync", "tooling", "web", "packaging")),("web/", "web"),("frontend/", "web"),@@ -636,8 +637,8 @@ def resolve_auto_scope() -> tuple[tuple[str, ...], str]:CI_FRONTEND_TESTS = frozenset({- "test_frontend_build.VitestTests.test_the_frontend_sources_typecheck",- "test_frontend_build.VitestTests.test_frontend_sources_and_tests_pass_lint",+ "test_frontend_preflight.FrontendPreflightTests.test_the_frontend_sources_typecheck",+ "test_frontend_preflight.FrontendPreflightTests.test_frontend_sources_and_tests_pass_lint","test_frontend_build.VitestTests.test_the_island_suite_passes",})@@ -1001,6 +1002,7 @@ GATE_TESTS = frozenset({"test_script_policy", "test_subprocess_encoding", "test_copy_final_state", "test_context_budget","test_source_assertion_ratchet", "test_complexity_ratchet", "test_python_lint","test_outbound_proxy_policy", "test_repo_hygiene", "test_dependency_policy",+ "test_reference_updates", "test_frontend_preflight",})#: 失败后单独重跑的文件数上限。失败面更大多半是真回归,重跑只会再白等一轮。RERUN_LIMIT = 6@@ -1055,6 +1057,18 @@ def rerun_failures(rows: list[dict], spawn=subprocess.run) -> bool:return True+def local_batches(names, jobs):+ """快速检查、普通分片和内部并行的容器分别执行,文件只分配一次。"""+ gate = sorted(name for name in names if name.removesuffix('.py') in GATE_TESTS)+ heavy = sorted(name for name in names if name.removesuffix('.py') in HEAVY_FILES and name not in gate)+ light = sorted(set(names) - set(gate) - set(heavy))+ batches = [('快速门槛', [gate], 1)] if gate else []+ if light:+ batches.append(('普通测试', shard_plan(light, min(len(light), 4 * jobs), load_file_seconds()), jobs))+ batches.extend((name.removesuffix('.py'), [[name]], 1) for name in heavy)+ return batches++def run_local_suite(scopes: tuple[str, ...], jobs: int, label: str | None = None,*, progress=None) -> tuple[bool, int, list]:"""按调用方选择的并发运行,串行全量通过分片释放测试缓存。"""@@ -1065,36 +1079,34 @@ def run_local_suite(scopes: tuple[str, ...], jobs: int, label: str | None = Nonechosen = {path for path in chosen if path.name in progress.modules}progress_args = {'checkpoint': progress.checkpoint, 'resume_plan': progress.child_plan(scopes)}FLAKY.clear()- if (jobs > 1 or "full" in scopes) and len(chosen) > 1:- names = sorted(path.name for path in chosen)- gate = [name for name in names if name.removesuffix(".py") in GATE_TESTS]- rest = [name for name in names if name not in gate] if gate and len(gate) < len(names) else names+ if len(chosen) > 1:measured: dict[str, float] = {}rows: list[dict] = []- count, timings = 0, []- if rest is not names:- print(f"快速门槛:先跑 {len(gate)} 个秒级检查,有一项不过就不起其余分片", flush=True)- passed, count, timings = run_shards(scopes, jobs=1, shard_count=1, measured=measured,- plan=[gate], outcomes=rows, **progress_args)- if not passed:+ passed, count, timings = True, 0, []+ for stage, plan, concurrency in local_batches([path.name for path in chosen], jobs):+ print(f'{stage}:{len(plan)} 片、同时 {min(concurrency, len(plan))} 个子进程', flush=True)+ with test_run_progress.phase(progress.phases if progress is not None else {}, stage):+ if jobs == 1 and 'full' not in scopes:+ assigned = {path for path in chosen if path.name in {name for group in plan for name in group}}+ ok, more, slow = run_serial_suite(scopes, assigned, original, progress, label)+ else:+ ok, more, slow = run_shards(scopes, jobs=concurrency, shard_count=len(plan), measured=measured,+ plan=plan, outcomes=rows, **progress_args)+ passed, count, timings = passed and ok, count + more, [*timings, *slow]+ if not ok and stage == '快速门槛':print("快速门槛未通过,其余测试本轮不跑。", flush=True)save_file_seconds(measured)test_history.append(ROOT, scope=label or " ".join(scopes), rows=rows,- files=[name.removesuffix(".py") for name in gate])+ files=[name.removesuffix(".py") for name in plan[0]])return False, count, timingsif progress is not None:progress_args['resume_plan'] = progress.child_plan(scopes)- shard_count = min(len(rest), 4 * jobs)- print(f"本机分片:{shard_count} 片、同时 {min(jobs, shard_count)} 个子进程,按实测耗时先长后短", flush=True)- plan = shard_plan(rest, shard_count, load_file_seconds())- passed, more, slow = run_shards(scopes, jobs=jobs, shard_count=shard_count, measured=measured, plan=plan,- outcomes=rows, **progress_args)save_file_seconds(measured)test_history.append(ROOT, scope=label or " ".join(scopes), rows=rows,files=[path.stem for path in sorted(chosen)])- if not passed:+ if not passed and rows:passed = rerun_failures(rows)- return passed, count + more, [*timings, *slow]+ return passed, count, timingsreturn run_serial_suite(scopes, chosen, original, progress, label)@@ -1276,38 +1288,47 @@ def busy(error) -> int:def verified_run(args, requested, scopes, files) -> int:"""在调用方持有的全量锁内取得快照、验证并签发记录。"""+ started = time.monotonic()+ phases = {}force = args.fresh or ('full' in requested and not args.resume)- context = test_evidence.inputs(ROOT)+ with test_run_progress.phase(phases, '输入快照'):+ context = test_evidence.inputs(ROOT)state = context["state"]with test_evidence.run_lock(ROOT, state, scope=" ".join(scopes), root=str(ROOT)):if not force and test_evidence.covers(test_evidence.read(ROOT, state), scopes):print("复用本机测试记录:代码、依赖环境和范围匹配(24 小时内)。", flush=True)return 0- previous = test_evidence.read(ROOT, state)- records = list(test_evidence.candidates(ROOT, context))- progress = test_run_progress.RunProgress(ROOT, context, scopes, selected_files, scopes_for_changes, SCOPES,- supplements=SCOPE_TEST_IDS, records=records, previous=previous,- force=force)- if requested == ('auto',) and not force:- choices = ('full', *SCOPES) if 'full' in scopes else scopes- scopes = test_resume.choose_scopes(progress.pending, progress.requirements, choices)+ with test_run_progress.phase(phases, '历史记录'):+ previous = test_evidence.read(ROOT, state)+ records = list(test_evidence.candidates(ROOT, context))+ with test_run_progress.phase(phases, '恢复规划'):+ progress = test_run_progress.RunProgress(ROOT, context, scopes, selected_files, scopes_for_changes, SCOPES,+ supplements=SCOPE_TEST_IDS, records=records, previous=previous,+ force=force)+ if requested == ('auto',) and not force:+ choices = ('full', *SCOPES) if 'full' in scopes else scopes+ scopes = test_resume.choose_scopes(progress.pending, progress.requirements, choices)+ progress.phases = phasesactual = len(progress.modules)print(f"实际运行:{' '.join(scopes) or '无需补测'}({actual} 个测试文件)", flush=True)if records and not force:print(f'单项覆盖:复用 {len(progress.required) - len(progress.pending)} 项,待验证 {len(progress.pending)} 项。', flush=True)progress.start()FLAKY.clear()- started = time.monotonic()- passed, count, timings = run_local_suite(scopes, args.jobs, f"{' '.join(requested)}:{' '.join(scopes)}",- progress=progress) if progress.pending else (True, 0, [])+ with test_run_progress.phase(phases, '测试执行'):+ passed, count, timings = run_local_suite(scopes, args.jobs, f"{' '.join(requested)}:{' '.join(scopes)}",+ progress=progress) if progress.pending else (True, 0, [])if passed:progress.accept_success(FLAKY)- stable = state == test_evidence.key(ROOT)- success = passed and stable and progress.complete()+ with test_run_progress.phase(phases, '结束核验'):+ stable = state == test_evidence.key(ROOT)+ success = passed and stable and progress.complete()slowest = sorted(timings, reverse=True)[:20]progress.persist(final=True, success=success, elapsed=time.monotonic() - started,slowest=slowest, count=count, flaky=FLAKY if success else None)+ print('分阶段耗时(测试执行包含各测试阶段):' + ';'.join(+ f'{name} {seconds:.2f}s' for name, seconds in phases.items()), flush=True)for seconds, name in slowest[:5]:print(f"慢测试 {seconds:.3f}s:{name}", flush=True)if not stable:diff --git a/tests/test_frontend_build.py b/tests/test_frontend_build.pyindex 465d79b3c..b2f982d2c 100644--- a/tests/test_frontend_build.py+++ b/tests/test_frontend_build.py@@ -23,14 +23,13 @@ import jsonimport osfrom pathlib import Pathimport re-import shutilimport subprocessimport tempfileimport unittestfrom peach.diagnostic_browser import BUNDLE_CHUNK_NAMEfrom scripts import test_history-from support.conditions import missing_prerequisite+from test_frontend_preflight import frontend_npmROOT = Path(__file__).resolve().parents[1]FRONTEND = ROOT / "frontend"@@ -366,51 +365,14 @@ class SharedStateContractTests(unittest.TestCase):class VitestTests(unittest.TestCase):- """vitest、tsc 与 lint 走同一个测试入口,但缺 Node 时跳过而不是红。-- 三者互不覆盖:vitest 经 Vite 转译时只剥掉类型、不做检查,类型错误照样跑绿;- 裸色值、任意值和在 BoardUI 组件上改样式,类型和行为测试都看不见。- """-- def _npm(self, tool: str, package: str) -> str:- npm = shutil.which("npm")- if npm is None:- missing_prerequisite(f"跳过 {tool}:本机没有 npm。装 Node 24+ 后 `-Scope web` 会带上它")- if not (FRONTEND / "node_modules" / package).is_dir():- missing_prerequisite(f"跳过 {tool}:frontend/node_modules 还没装,先 `npm --prefix frontend ci`")- return npm-- def test_the_frontend_sources_typecheck(self):- npm = self._npm("tsc", "typescript")- completed = subprocess.run(- [npm, "--prefix", str(FRONTEND), "run", "typecheck", "--silent"],- capture_output=True, text=True, encoding="utf-8", errors="replace",- cwd=str(FRONTEND), check=False)- self.assertEqual(completed.returncode, 0, f"{completed.stdout}\n{completed.stderr}")+ """Vitest 的行为回归与独立的类型、样式检查共同构成前端验收。"""def test_the_island_suite_has_a_bounded_worker_pool(self):config = (FRONTEND / "vitest.config.ts").read_text(encoding="utf-8")self.assertIn("maxWorkers: 4", config)- def test_frontend_sources_and_tests_pass_lint(self):- """`@shadcn/lint` 挡住裸色值、任意值、内联样式和在 BoardUI 组件上改样式(ADR-0031)。"""- npm = self._npm("lint", "oxlint")- completed = subprocess.run(- [npm, "--prefix", str(FRONTEND), "run", "lint", "--silent", "--", "--format=json"],- capture_output=True, text=True, encoding="utf-8", errors="replace",- cwd=str(FRONTEND), check=False)- output = f"{completed.stdout}\n{completed.stderr}"- self.assertEqual(completed.returncode, 0, output)- report = json.loads(completed.stdout)- self.assertEqual(report["diagnostics"], [], output)- # 没有问题时 Oxlint 什么都不打印,路径写错查了 0 个文件也照样退出 0。- self.assertGreater(report["number_of_files"], 0, output)- copy = subprocess.run([npm, "--prefix", str(FRONTEND), "run", "check:copy"],- capture_output=True, text=True, encoding="utf-8", errors="replace", cwd=FRONTEND)- self.assertEqual(copy.returncode, 0, copy.stdout + copy.stderr)-def test_the_island_suite_passes(self):- npm = self._npm("vitest", "vitest")+ npm = frontend_npm("vitest", "vitest")# 定向入口(含全量失败后的单独重跑)只跑指定的几个文件,路径相对 frontend/。selected = json.loads(os.environ.get("PEACH_VITEST_FILES", "[]"))# 另挂一个 JSON 报告器,把逐条结果交给测试结果历史;控制台输出与判据不变。diff --git a/tests/test_frontend_preflight.py b/tests/test_frontend_preflight.pynew file mode 100644index 000000000..c4433c93a--- /dev/null+++ b/tests/test_frontend_preflight.py@@ -0,0 +1,42 @@+"""前端类型、样式和文案检查,在行为测试之前执行。"""+import json+from pathlib import Path+import shutil+import subprocess+import unittest++from support.conditions import missing_prerequisite++FRONTEND = Path(__file__).resolve().parents[1] / 'frontend'+++def frontend_npm(tool: str, package: str) -> str:+ npm = shutil.which('npm')+ if npm is None:+ missing_prerequisite(f'跳过 {tool}:本机没有 npm。装 Node 24+ 后 `-Scope web` 会带上它')+ if not (FRONTEND / 'node_modules' / package).is_dir():+ missing_prerequisite(f'跳过 {tool}:frontend/node_modules 还没装,先 `npm --prefix frontend ci`')+ return npm+++class FrontendPreflightTests(unittest.TestCase):+ def test_the_frontend_sources_typecheck(self):+ npm = frontend_npm('tsc', 'typescript')+ completed = subprocess.run(+ [npm, '--prefix', str(FRONTEND), 'run', 'typecheck', '--silent'],+ capture_output=True, text=True, encoding='utf-8', errors='replace', cwd=FRONTEND, check=False)+ self.assertEqual(completed.returncode, 0, f'{completed.stdout}\n{completed.stderr}')++ def test_frontend_sources_and_tests_pass_lint(self):+ npm = frontend_npm('lint', 'oxlint')+ completed = subprocess.run(+ [npm, '--prefix', str(FRONTEND), 'run', 'lint', '--silent', '--', '--format=json'],+ capture_output=True, text=True, encoding='utf-8', errors='replace', cwd=FRONTEND, check=False)+ output = f'{completed.stdout}\n{completed.stderr}'+ self.assertEqual(completed.returncode, 0, output)+ report = json.loads(completed.stdout)+ self.assertEqual(report['diagnostics'], [], output)+ self.assertGreater(report['number_of_files'], 0, output)+ copy = subprocess.run([npm, '--prefix', str(FRONTEND), 'run', 'check:copy'],+ capture_output=True, text=True, encoding='utf-8', errors='replace', cwd=FRONTEND)+ self.assertEqual(copy.returncode, 0, copy.stdout + copy.stderr)diff --git a/tests/test_test_evidence.py b/tests/test_test_evidence.pyindex c4ff50571..f6b7aa3b4 100644--- a/tests/test_test_evidence.py+++ b/tests/test_test_evidence.py@@ -37,6 +37,43 @@ def fixture_process(command, root, env):class ParallelShardTests(unittest.TestCase):+ def test_nested_parallel_containers_have_separate_batches_without_losing_files(self):+ names = ['test_frontend_preflight.py', 'test_reference_updates.py', 'test_frontend_build.py',+ 'test_web_e2e.py', 'test_catalog.py', 'test_media.py']+ with mock.patch.object(runner, 'load_file_seconds', return_value={}):+ batches = runner.local_batches(names, 7)+ self.assertCountEqual([name for _, plan, _ in batches for shard in plan for name in shard], names)+ self.assertEqual(set(batches[0][1][0]), {'test_frontend_preflight.py', 'test_reference_updates.py'})+ self.assertEqual(batches[1][2], 7)+ for _, plan, jobs in batches[2:]:+ self.assertEqual((len(plan), len(plan[0]), jobs), (1, 1, 1))++ def test_failed_gate_stops_serial_and_parallel_behavior_tests(self):+ names = [Path('test_frontend_preflight.py'), Path('test_web_e2e.py')]+ for jobs in (1, 4):+ with self.subTest(jobs=jobs), mock.patch.object(runner, 'selected_files', return_value=names), \+ mock.patch.object(runner, 'run_shards', return_value=(False, 2, [])) as execute, \+ mock.patch.object(runner, 'run_serial_suite', return_value=(False, 2, [])) as serial, \+ mock.patch.object(runner, 'save_file_seconds'), mock.patch.object(runner.test_history, 'append'), \+ redirect_stdout(io.StringIO()):+ self.assertEqual(runner.run_local_suite(('web',), jobs), (False, 2, []))+ if jobs == 1:+ serial.assert_called_once()+ self.assertEqual(serial.call_args.args[1], {Path('test_frontend_preflight.py')})+ execute.assert_not_called()+ else:+ execute.assert_called_once()+ self.assertEqual(execute.call_args.kwargs['plan'], [['test_frontend_preflight.py']])++ def test_phase_timings_include_failed_work(self):+ timings = {}+ with mock.patch.object(test_run_progress.time, 'monotonic', side_effect=[10, 12, 20, 23]):+ with test_run_progress.phase(timings, '规划'):+ pass+ with self.assertRaises(ValueError), test_run_progress.phase(timings, '规划'):+ raise ValueError('失败仍计时')+ self.assertEqual(timings, {'规划': 5})+def test_checkpoint_exit_status_must_match_the_report(self):def exercise(success, code):observed = []@@ -261,6 +298,52 @@ class ReceiptFixture:class ReceiptTests(ReceiptFixture, unittest.TestCase):+ def test_history_planning_parses_each_test_once_and_rebuilds_for_new_inputs(self):+ tests = self.root / 'tests'+ tests.mkdir()+ (tests / 'test_catalog.py').write_text('VALUE = 1\n', encoding='utf8')+ consumer = tests / 'test_web.py'+ consumer.write_text('VALUE = 2\n', encoding='utf8')+ old = {'files': {'tests/test_catalog.py': [1, 'old', '100644']}, 'signatures': {}}+ current = {'files': {'tests/test_catalog.py': [1, 'new', '100644']}, 'signatures': {}}+ records = [self.record({'test_catalog.py': self.unit(), 'test_web.py': self.unit()}, manifest=old)] * 30+ with mock.patch.object(test_resume.ast, 'parse', wraps=test_resume.ast.parse) as parse:+ kept = test_resume.combine(self.root, records, {**self.context, 'manifest': current},+ {'test_catalog.py', 'test_web.py'}, self.resolve, self.mapping.__getitem__)+ self.assertEqual(parse.call_count, 2)+ self.assertEqual(set(kept), {'test_web.py'})+ consumer.write_text('import test_catalog\n', encoding='utf8')+ kept = test_resume.combine(self.root, records, {**self.context, 'manifest': current},+ {'test_catalog.py', 'test_web.py'}, self.resolve, self.mapping.__getitem__)+ self.assertEqual(kept, {})++ def test_isolated_pages_keep_main_browser_proof_and_shared_changes_invalidate_it(self):+ for name in ('setup', 'smoke'):+ path = self.root / 'frontend/e2e' / f'{name}.test.ts'+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text('', encoding='utf8')+ mapping = {'web': (Path('test_web_e2e.py'), Path('test_frontend_build.py')), 'checks': ()}+ units = test_resume.scope_units(self.root, 'web', mapping.__getitem__)+ main = 'case:test_web_e2e.WebE2ESmokeTests.test_every_route_holds_the_layout_and_runtime_invariants'+ resolve = lambda *args, **kwargs: (('web',), '')+ setup = 'frontend/src/react/pages/setup/setup.css'+ for paths, mode, environment, preserved in (+ ([setup], '100644', 'same', True),+ (['resources/setup/macbook.png', 'web/dist/peach-pages.js'], '100644', 'same', True),+ ([setup, 'web/dist/peach-app.css'], '100644', 'same', False),+ ([setup], '100755', 'same', False),+ ([setup], '100644', 'changed', False)):+ with self.subTest(paths=paths, mode=mode, environment=environment):+ old = {'files': {path: [1, 'old', '100644'] for path in paths}, 'signatures': {}}+ current = {'files': {path: [1, 'new', mode] for path in paths}, 'signatures': {}}+ record = self.record({unit: self.unit() for unit in units}, manifest=old)+ kept = test_resume.combine(self.root, [record], {**self.context, 'manifest': current,+ 'environment': environment}, units, resolve, mapping.__getitem__)+ self.assertEqual('frontend/e2e/smoke.test.ts' in kept, preserved)+ self.assertEqual(main in kept, preserved)+ self.assertNotIn('frontend/e2e/setup.test.ts', kept)+ self.assertNotIn('test_frontend_build.py', kept)+def test_a_failed_file_preserves_successful_sibling_files(self):report = {'success': False, 'count': 2, 'results': [{'id': 'test_catalog.Suite.test_value', 'outcome': 'pass'},@@ -495,6 +578,28 @@ class CheckpointTests(ReceiptFixture, unittest.TestCase):with self.subTest(plan=bad), self.assertRaises(ValueError):test_resume.validate_child_plan(self.root, bad, state=self.context['state'], valid_seconds=86400)+ def test_completed_container_updates_the_next_stage_plan_without_refreshing_its_proof(self):+ for name in ('frontend/test/component.test.ts', 'frontend/e2e/smoke.test.ts', 'frontend/e2e/setup.test.ts'):+ path = self.root / name+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text('export {};', encoding='utf8')+ self.mapping['full'] = self.mapping['web'] = (Path('test_frontend_build.py'), Path('test_web_e2e.py'))+ progress = self.progress()+ progress.start()+ for module in ('test_frontend_build.py', 'test_web_e2e.py'):+ plan = progress.child_plan()+ test_resume.validate_child_plan(self.root, plan, state=self.context['state'], valid_seconds=86400)+ report = {'complete': True, 'success': True, 'count': 1, 'results': [+ {'id': case, 'outcome': 'pass'} for case in test_resume.CONTAINERS+ if test_resume.owner('case:' + case) == module]}+ self.assertTrue(progress.checkpoint([module], report, True))+ stamp = progress.units['frontend/test/component.test.ts']['at']+ updated = progress.child_plan()+ test_resume.validate_child_plan(self.root, updated, state=self.context['state'], valid_seconds=86400)+ self.assertEqual(updated['external'][module], [])+ self.assertEqual(updated['cached']['frontend/test/component.test.ts']['at'], stamp)+ self.assertTrue(progress.complete())+def test_unrelated_python_failure_survives_browser_aggregation(self):smoke = next(case for case in runner.CI_BROWSER_TESTS if '.WebE2E' in case)ids = ['e2e:e2e/smoke.test.ts > failure', smoke,@@ -1338,8 +1443,10 @@ class VerificationTests(unittest.TestCase):mock.patch.object(runner, "ROOT", self.repo), \mock.patch.object(runner, "build_suite", side_effect=self.scope_suite) as build:self.assertEqual(runner.main(["--scope", "checks"]), 0)+ calls = build.call_countself.assertEqual(runner.main(["--scope", "checks"]), 0)- self.assertEqual(build.call_count, 1)+ self.assertGreater(calls, 0)+ self.assertEqual(build.call_count, calls)def failing(*scopes, **planned):return self.scope_suite(*scopes, fail=True, **planned)build.side_effect = failing@@ -1380,12 +1487,16 @@ class VerificationTests(unittest.TestCase):mock.patch.object(runner, "GATE_TESTS", frozenset()), \mock.patch.object(runner, "run_shards", return_value=(True, 7, [])) as shards:self.assertEqual(runner.main(["--scope", "full", "--jobs", "1"]), 0)- shards.assert_called_once()- self.assertEqual(shards.call_args.kwargs["jobs"], 1)- self.assertEqual(shards.call_args.kwargs["shard_count"], 4)+ self.assertEqual([call.kwargs['shard_count'] for call in shards.call_args_list], [4, 1, 1])+ self.assertTrue(all(call.kwargs['jobs'] == 1 for call in shards.call_args_list))+ self.assertCountEqual([name for call in shards.call_args_list for group in call.kwargs['plan'] for name in group],+ [path.name for path in runner.selected_files('full')])record = evidence.read(self.repo, evidence.key(self.repo))self.assertTrue(evidence.covers(record, ("full",)))- self.assertEqual(record["count"], 7)+ self.assertEqual(record["count"], 21)+ self.assertLessEqual({'输入快照', '历史记录', '恢复规划', '测试执行', '结束核验'}, record['phases'].keys())+ self.assertGreaterEqual(record['elapsed'], sum(record['phases'][name] for name in+ ('输入快照', '历史记录', '恢复规划', '测试执行', '结束核验')))def test_a_failure_that_passes_alone_signs_the_record_and_names_the_flaky_file(self):"""全量里挂、单独重跑过的:记录照样算通过,偶发的文件名留在记录里;单独也挂就没有记录。"""@@ -1418,7 +1529,8 @@ class VerificationTests(unittest.TestCase):mock.patch.object(runner, "resolve_auto_scope", return_value=(("full",), "fixture")), \mock.patch.object(runner, "build_suite", side_effect=self.scope_suite) as build:self.assertEqual(runner.main(["--scope", "auto"]), 0)- build.assert_called_once_with("checks", "tooling")+ self.assertTrue(build.called)+ self.assertTrue(all(call.args == ('checks', 'tooling') for call in build.call_args_list))record = evidence.read(self.repo, evidence.key(self.repo))self.assertEqual(record["baseline"], original)self.assertEqual(record["validated"]["full"], stamp)@@ -1443,10 +1555,11 @@ class VerificationTests(unittest.TestCase):mock.patch.object(runner, "resolve_auto_scope", return_value=(("checks",), "fixture")), \mock.patch.object(runner, "build_suite", side_effect=self.scope_suite) as build:self.assertEqual(runner.main(["--scope", "auto"]), 0)- self.assertEqual(build.call_count, 1)- self.assertEqual(build.call_args.args, ('checks',))- self.assertLessEqual(set(build.call_args.kwargs.get('assigned_names', ())),- {path.name for path in runner.selected_files('checks')})+ self.assertTrue(build.called)+ for call in build.call_args_list:+ self.assertEqual(call.args, ('checks',))+ self.assertLessEqual(set(call.kwargs.get('assigned_names', ())),+ {path.name for path in runner.selected_files('checks')})def test_baseline_distinguishes_version_assignment_and_package_logic(self):self.certify(self.repo, ("full",))diff --git a/tests/test_test_planning.py b/tests/test_test_planning.pyindex de124e9be..f788470f1 100644--- a/tests/test_test_planning.py+++ b/tests/test_test_planning.py@@ -28,14 +28,15 @@ class CIFrontendOwnershipTests(unittest.TestCase):def frontend_ids(self, environment, **shard):with patch.dict(os.environ, environment, clear=True), \- patch.object(runner, 'selected_files', return_value=(runner.TESTS / 'test_frontend_build.py',)):+ patch.object(runner, 'selected_files', return_value=(runner.TESTS / 'test_frontend_build.py',+ runner.TESTS / 'test_frontend_preflight.py')):return list(self.ids(runner.build_suite('web', **shard)))def test_only_known_ci_jobs_delegate_exactly_three_frontend_tools(self):local = set(self.frontend_ids({}))- delegated = {f'test_frontend_build.VitestTests.{name}' for name in (- 'test_the_frontend_sources_typecheck', 'test_frontend_sources_and_tests_pass_lint',- 'test_the_island_suite_passes')}+ delegated = {'test_frontend_build.VitestTests.test_the_island_suite_passes',+ 'test_frontend_preflight.FrontendPreflightTests.test_the_frontend_sources_typecheck',+ 'test_frontend_preflight.FrontendPreflightTests.test_frontend_sources_and_tests_pass_lint'}self.assertLessEqual(delegated, local)for job in ('python', 'web-e2e'):with self.subTest(job=job):