Peach: Local-first video metadata scraper and media manager.
test(tooling): 本机测试按分片并行跑
longmeidaof786e4496e00
diff --git a/docs/TESTING.md b/docs/TESTING.mdindex d6060e482..4cf8277e3 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -40,7 +40,9 @@ npm 的两份清单还有一层派生产物:根 `package.json` 对应 `web/ven| wheel | 每次独立最小安装,通常两组;完整矩阵四组 || Release | 复用同 SHA 主线成功 CI;构建后执行独立 EXE 冒烟 |-全量在两个独立 runner 按测试文件稳定分片;汇总任务要求所有分片和必需任务成功。分片不能签发本机全量记录。当前本机仍串行,避免共享资源竞争。+全量在两个独立 runner 按测试文件稳定分片;汇总任务要求所有分片和必需任务成功。分片子进程不签发记录。++本机默认并行:入口传 `--jobs auto`(Windows `-Jobs`),运行器按同一套稳定分片切成并发数四倍的片,最多四个子进程各领一片、先完成的接着领下一片,父进程汇总成败、用例数与逐用例耗时后按原口径签发一份记录,一片红整轮红。`-Jobs 1` 退回串行。测试之间没有共享的端口或全局目录,账本与仓库夹具都在各自的临时目录里,并行才是安全的;新增测试保持这一点。Windows 的路径、挂载、托盘、证书、进程编码、更新、认证及迁移属于 `core`。构建和工作流修改选择 `packaging` 与 `tooling`;测试调度自身仍全量。仅 uv 工具版本或项目展示字段变化不算依赖图变化;无法解析时全量。diff --git a/scripts/test.ps1 b/scripts/test.ps1index 726e97e60..6693098a8 100644--- a/scripts/test.ps1+++ b/scripts/test.ps1@@ -5,7 +5,9 @@ param([switch]$Fresh,[string]$Base = 'master',[int]$ShardIndex = 0,- [int]$ShardCount = 1+ [int]$ShardCount = 1,+ # 本机同时跑几个分片子进程:auto 按核数定;-Jobs 1 退回串行。CI 分片模式下运行器忽略它。+ [string]$Jobs = 'auto')$ErrorActionPreference = 'Stop'@@ -60,7 +62,7 @@ try {Write-Host "Peach source: $LoadedPath"$PeachTestExtra = @()if ($Fresh) { $PeachTestExtra += '--fresh' }- & $Python scripts\test_runner.py --scope $Scope --base $Base --shard-index $ShardIndex --shard-count $ShardCount @PeachTestExtra+ & $Python scripts\test_runner.py --scope $Scope --base $Base --shard-index $ShardIndex --shard-count $ShardCount --jobs $Jobs @PeachTestExtraexit $LASTEXITCODE} finally {Pop-Locationdiff --git a/scripts/test.sh b/scripts/test.shindex d07b202c0..9fa88ee08 100755--- a/scripts/test.sh+++ b/scripts/test.sh@@ -12,6 +12,12 @@ case "$SCOPE" inexit 2;;esac+# 本机默认并行:没显式给 `--jobs` 就传 auto,运行器按核数定并发;CI 分片模式下它被忽略。+# `${1+$*}` 是 bash 3.2 在 `set -u` 下读全部参数的写法,没有参数时安全地展开成空。+JOBS=(--jobs auto)+case " ${1+$*} " in+ *" --jobs "*) JOBS=() ;;+esacEXTRA=("${@:2}")# 展开必须写成 `${EXTRA[@]+...}`。macOS 自带的是 bash 3.2,`set -u` 下它把空数组的# `"${EXTRA[@]}"` 当未绑定变量报错(bash 4.4 起才不报),于是不带额外参数直接跑@@ -54,4 +60,4 @@ if [[ "$LOADED_MODULE" != "$SOURCE_ROOT/"* ]]; thenfiecho "Peach source: $LOADED_MODULE"-exec "$PYTHON" scripts/test_runner.py --scope "$SCOPE" ${EXTRA[@]+"${EXTRA[@]}"}+exec "$PYTHON" scripts/test_runner.py --scope "$SCOPE" ${JOBS[@]+"${JOBS[@]}"} ${EXTRA[@]+"${EXTRA[@]}"}diff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex edba3376d..83bd14e39 100644--- a/scripts/test_runner.py+++ b/scripts/test_runner.py@@ -4,9 +4,13 @@ from __future__ import annotationsimport argparseimport fnmatchimport importlib+import json+import osimport re+import shutilimport subprocessimport sys+import tempfileimport timeimport tomllibimport unittest@@ -353,22 +357,105 @@ class TimedResult(unittest.TextTestResult):super().stopTest(test)+#: 本机并行的上限。全量里最重的是 git 与 PowerShell 子进程型的 tooling 用例,四路已经+#: 把它们摊开;再多只是让每个子进程各自 import 一遍 peach 的固定开销变多。+MAX_JOBS = 4+#: 最多切多少片。CI 两片是因为每片一台 runner;本机每片只是一个子进程,切细一点+#: 才能让重文件(`test_agent_worktree.py` 一个就 80 秒)不把整片拖成长尾。+MAX_SHARDS = 16+++def resolve_jobs(value: str) -> int:+ """`--jobs` 的取值:正整数照收,`auto` 按核数定、不超过 `MAX_JOBS`。"""+ if value == "auto":+ return max(1, min(MAX_JOBS, (os.cpu_count() or 1) // 2))+ try:+ jobs = int(value)+ except ValueError:+ raise argparse.ArgumentTypeError("--jobs 只接受正整数或 auto") from None+ if jobs < 1:+ raise argparse.ArgumentTypeError("--jobs 至少为 1")+ return jobs+++def shard_command(scopes: tuple[str, ...], index: int, count: int, timings: Path) -> list[str]:+ return [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)]+++def run_shards(scopes: tuple[str, ...], *, jobs: int, shard_count: int,+ spawn=subprocess.Popen) -> tuple[bool, int, list]:+ """把选中的文件按 CI 同一套稳定分片切开,同时最多 `jobs` 个子进程各跑一片。++ 每片是一次 `--shard-count` 子进程:它自己从不签发记录,只把成败、用例数和逐个+ 用例的耗时写进 `--timings` 那个文件,父进程汇总后签发一份记录,口径与串行相同。+ 片数比并发数多,是为了让先跑完的进程接着领下一片,重文件不至于把墙钟拖成它+ 一家的长度。子进程的输出各自落盘,哪片结束就整段打印哪片,不交错。+ """+ folder = Path(tempfile.mkdtemp(prefix="peach-shards-"))+ pending = list(range(shard_count))+ running: dict[int, tuple[object, object]] = {}+ passed, count, timings = True, 0, []+ try:+ while pending or running:+ while pending and len(running) < jobs:+ index = pending.pop(0)+ log = open(folder / f"{index}.log", "w+", encoding="utf-8", errors="replace")+ process = spawn(shard_command(scopes, index, shard_count, folder / f"{index}.json"),+ stdout=log, stderr=subprocess.STDOUT, cwd=str(ROOT))+ running[index] = (process, log)+ finished = [index for index, (process, _) in running.items()+ if process.poll() is not None]+ if not finished:+ time.sleep(0.2)+ continue+ for index in finished:+ process, log = running.pop(index)+ log.flush()+ log.seek(0)+ sys.stdout.write(log.read())+ log.close()+ report_path = folder / f"{index}.json"+ report = json.loads(report_path.read_text(encoding="utf-8")) \+ if report_path.is_file() else {"success": False, "count": 0, "timings": []}+ ok = process.returncode == 0 and bool(report.get("success"))+ passed = passed and ok+ count += int(report.get("count", 0))+ timings.extend(tuple(item) for item in report.get("timings", []))+ print(f"分片 {index + 1}/{shard_count} {'通过' if ok else '失败'}"+ f"({report.get('count', 0)} 个用例)", flush=True)+ finally:+ shutil.rmtree(folder, ignore_errors=True)+ return passed, count, timings++def main(argv: list[str] | None = None) -> int:parser = argparse.ArgumentParser()- parser.add_argument("--scope", choices=("full", "auto", *SCOPES), default="auto")+ # `--scope` 可重复:本机并行的父进程把 `auto` 算出来的几个域原样交给每个分片子进程。+ parser.add_argument("--scope", action="append", dest="scopes",+ choices=("full", "auto", *SCOPES))parser.add_argument("--fresh", action="store_true", help="实际重跑,不复用本机记录")parser.add_argument("--base", default="master", help="CI 选测的已验证 Git 基线")parser.add_argument("--shard-index", type=int, default=0)parser.add_argument("--shard-count", type=int, default=1)+ parser.add_argument("--timings", 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")args = parser.parse_args(argv)- if not 1 <= args.shard_count <= 4 or not 0 <= args.shard_index < args.shard_count:- parser.error("分片总数为 1~4,编号从 0 开始且小于总数")+ if not 1 <= args.shard_count <= MAX_SHARDS or not 0 <= args.shard_index < args.shard_count:+ parser.error(f"分片总数为 1~{MAX_SHARDS},编号从 0 开始且小于总数")if args.list_scopes:print("\n".join(("full", "auto", *SCOPES)))return 0- scopes: tuple[str, ...] = (args.scope,)- if args.scope == "auto":+ requested: tuple[str, ...] = tuple(dict.fromkeys(args.scopes or ("auto",)))+ if "auto" in requested and len(requested) > 1:+ parser.error("auto 不能与别的域同时指定")+ scopes = requested+ if requested == ("auto",):if args.base == "master":scopes, explanation = resolve_auto_scope()else:@@ -381,18 +468,22 @@ def main(argv: list[str] | None = None) -> int:# CI 的每片独立 runner;局部分片绝不签发本机全量证明。result = unittest.TextTestRunner(verbosity=2, resultclass=TimedResult).run(build_suite(*scopes, shard_index=args.shard_index, shard_count=args.shard_count))- return 0 if result.wasSuccessful() and result.testsRun > 0 else 1+ 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}), encoding="utf-8")+ return 0 if success else 1context = test_evidence.inputs(ROOT)state = context["state"]try:with test_evidence.run_lock(ROOT, state, scope=" ".join(scopes), root=str(ROOT)):- if not args.fresh and args.scope != "full" and test_evidence.covers(+ if not args.fresh and "full" not in requested and test_evidence.covers(test_evidence.read(ROOT, state), scopes):print("复用本机测试记录:代码、依赖环境和范围匹配(24 小时内)。", flush=True)return 0previous = test_evidence.read(ROOT, state)baseline = None- if args.scope == "auto" and not args.fresh and not previous:+ if requested == ("auto",) and not args.fresh and not previous:choices = []for record, delta, version_only in test_evidence.baselines(ROOT, context):needed, _ = scopes_for_changes(delta)@@ -412,13 +503,26 @@ def main(argv: list[str] | None = None) -> int:with full_lock:(folder / f"{state}.json").unlink(missing_ok=True)started = time.monotonic()- result = unittest.TextTestRunner(verbosity=2, resultclass=TimedResult).run(build_suite(*scopes))+ chosen = {path for scope in scopes for path in selected_files(scope)}+ if args.jobs > 1 and len(chosen) > 1:+ # 片数取并发数的四倍:八片时最长一片 154 秒、最短 15 秒,墙钟被+ # 最重那片拖住;切细后先完成的进程接着领,长尾才摊得开。+ shard_count = min(len(chosen), 4 * args.jobs, MAX_SHARDS)+ print(f"本机并行:{shard_count} 片、同时 {min(args.jobs, shard_count)} 个子进程",+ flush=True)+ passed, count, timings = run_shards(scopes, jobs=args.jobs,+ shard_count=shard_count)+ else:+ result = unittest.TextTestRunner(verbosity=2, resultclass=TimedResult).run(+ build_suite(*scopes))+ passed, count, timings = (result.wasSuccessful() and result.testsRun > 0,+ result.testsRun, result.timings)stable = state == test_evidence.key(ROOT)- success = result.wasSuccessful() and stable and result.testsRun > 0- slowest = sorted(result.timings, reverse=True)[:20]+ success = passed and stable+ slowest = sorted(timings, reverse=True)[:20]test_evidence.write(ROOT, state, scopes, success=success, previous=previous,context=context, baseline=baseline,- elapsed=time.monotonic() - started, slowest=slowest, count=result.testsRun)+ elapsed=time.monotonic() - started, slowest=slowest, count=count)for seconds, name in slowest[:5]:print(f"慢测试 {seconds:.3f}s:{name}", flush=True)if not stable:diff --git a/tests/test_scripts.py b/tests/test_scripts.pyindex be5649c09..ccf6f70d2 100644--- a/tests/test_scripts.py+++ b/tests/test_scripts.py@@ -334,8 +334,9 @@ class OperationalScriptTests(unittest.TestCase):"""source = (ROOT / "scripts" / "test.sh").read_text(encoding="utf-8")self.assertIn("set -euo pipefail", source)- self.assertIn('scripts/test_runner.py --scope "$SCOPE" ${EXTRA[@]+"${EXTRA[@]}"}', source)- self.assertNotIn('--scope "$SCOPE" "${EXTRA[@]}"', source)+ self.assertIn('scripts/test_runner.py --scope "$SCOPE" ${JOBS[@]+"${JOBS[@]}"} ${EXTRA[@]+"${EXTRA[@]}"}',+ source)+ self.assertNotIn(' "${EXTRA[@]}"', source)# 真实脚本后半段要定位 venv 并跑整个测试套件,直接执行会递归。只取参数处理那一段,# 把 exec 的目标换成一个回显 argv 的桩,其余保持逐字一致。@@ -375,11 +376,13 @@ class OperationalScriptTests(unittest.TestCase):shells.append(path)self.assertTrue(shells)for shell in dict.fromkeys(shells):+ # 没显式给 `--jobs` 就补 auto,本机默认并行;给了就原样透传,不再补。for argv, expected in (- ([], ["--scope", "auto"]),- (["auto"], ["--scope", "auto"]),+ ([], ["--scope", "auto", "--jobs", "auto"]),+ (["auto"], ["--scope", "auto", "--jobs", "auto"]),(["web", "--fresh", "--base", "a b"],- ["--scope", "web", "--fresh", "--base", "a b"]),+ ["--scope", "web", "--jobs", "auto", "--fresh", "--base", "a b"]),+ (["web", "--jobs", "1"], ["--scope", "web", "--jobs", "1"]),):with self.subTest(shell=shell, argv=argv):done = subprocess.run(diff --git a/tests/test_test_evidence.py b/tests/test_test_evidence.pyindex a1edb7a12..e3977cb71 100644--- a/tests/test_test_evidence.py+++ b/tests/test_test_evidence.py@@ -250,6 +250,27 @@ class VerificationTests(unittest.TestCase):self.assertEqual(runner.main(["--scope", "checks", "--fresh"]), 1)self.assertFalse(evidence.covers(evidence.read(self.repo, evidence.key(self.repo)), ("checks",)))+ def test_a_parallel_run_signs_one_record_from_the_merged_shards(self):+ """并行时父进程不自己跑用例,只按分片汇总签一份记录;一片红就没有记录。"""+ with redirect_stderr(io.StringIO()), redirect_stdout(io.StringIO()), \+ mock.patch.object(runner, "ROOT", self.repo), \+ mock.patch.object(runner, "build_suite", side_effect=AssertionError("父进程不该自己跑")), \+ mock.patch.object(runner, "run_shards", return_value=(True, 3, [(0.5, "x"), (0.1, "y")])) as shards:+ self.assertEqual(runner.main(["--scope", "checks", "--jobs", "2"]), 0)+ shards.assert_called_once()+ self.assertEqual(shards.call_args.args, (("checks",),))+ self.assertEqual(shards.call_args.kwargs["jobs"], 2)+ self.assertGreater(shards.call_args.kwargs["shard_count"], 1)+ record = evidence.read(self.repo, evidence.key(self.repo))+ self.assertTrue(evidence.covers(record, ("checks",)))+ self.assertEqual(record["count"], 3)+ self.assertEqual(record["slowest"][0], [0.5, "x"])+ with redirect_stderr(io.StringIO()), redirect_stdout(io.StringIO()), \+ mock.patch.object(runner, "ROOT", self.repo), \+ mock.patch.object(runner, "run_shards", return_value=(False, 3, [])):+ self.assertEqual(runner.main(["--scope", "checks", "--jobs", "2", "--fresh"]), 1)+ self.assertFalse(evidence.covers(evidence.read(self.repo, evidence.key(self.repo)), ("checks",)))+def test_full_baseline_requires_only_new_scopes_without_extending_its_age(self):original = self.certify(self.repo, ("full",))stamp = evidence.read(self.repo, original)["validated"]["full"]diff --git a/tests/test_test_planning.py b/tests/test_test_planning.pyindex 1800b5ab3..1842ea99e 100644--- a/tests/test_test_planning.py+++ b/tests/test_test_planning.py@@ -2,6 +2,7 @@from pathlib import Pathimport contextlibimport io+import jsonimport sqlite3import subprocessimport sys@@ -86,6 +87,72 @@ class TestPlanningTests(unittest.TestCase):patch.object(runner.test_evidence, 'inputs', side_effect=AssertionError('分片不能签发证据')):self.assertEqual(runner.main(['--scope', 'full', '--shard-count', '2']), 0)+ def test_a_shard_writes_its_outcome_for_the_parent_to_merge(self):+ """分片子进程不签记录,只把成败、用例数和逐用例耗时写给父进程;域可以给多个。"""+ with tempfile.TemporaryDirectory() as directory:+ report = Path(directory) / 'shard.json'+ suite = unittest.TestSuite([unittest.FunctionTestCase(lambda: None)])+ with patch.object(runner, 'build_suite', return_value=suite) as build, \+ patch.object(runner.test_evidence, 'inputs', side_effect=AssertionError('分片不能签发证据')), \+ 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)]), 0)+ build.assert_called_once_with('follow', 'tooling', shard_index=1, shard_count=2)+ payload = json.loads(report.read_text(encoding='utf-8'))+ self.assertTrue(payload['success'])+ self.assertEqual(payload['count'], 1)+ self.assertEqual(len(payload['timings']), 1)++ def test_parallel_shards_are_merged_and_one_red_shard_fails_the_run(self):+ """父进程只汇总:每片的结论来自子进程写的文件,片数比并发多时先完成的接着领。"""+ class Done:+ def __init__(self, code):+ self.returncode = code++ def poll(self):+ return self.returncode++ def launcher(failing: int | None):+ launched = []++ def spawn(command, *, stdout, stderr, cwd):+ launched.append(command)+ index = int(command[command.index('--shard-index') + 1])+ report = Path(command[command.index('--timings') + 1])+ report.write_text(json.dumps({'success': index != failing, 'count': 10 + index,+ 'timings': [[0.5, f'test_{index}']]}), encoding='utf-8')+ stdout.write(f'分片 {index} 的输出\n')+ return Done(0 if index != failing else 1)+ return launched, spawn++ launched, spawn = launcher(failing=None)+ with contextlib.redirect_stdout(io.StringIO()) as output:+ passed, count, timings = runner.run_shards(('follow', 'tooling'), jobs=2, shard_count=3, spawn=spawn)+ self.assertTrue(passed)+ self.assertEqual(count, 10 + 11 + 12)+ self.assertEqual(sorted(name for _, name in timings), ['test_0', 'test_1', 'test_2'])+ self.assertEqual(sorted(int(c[c.index('--shard-index') + 1]) for c in launched), [0, 1, 2])+ for command in launched:+ self.assertEqual(command[:2], [sys.executable, str(runner.ROOT / 'scripts' / 'test_runner.py')])+ self.assertEqual(command[2:6], ['--scope', 'follow', '--scope', 'tooling'])+ self.assertEqual(command[command.index('--shard-count') + 1], '3')+ for index in range(3):+ self.assertIn(f'分片 {index} 的输出', output.getvalue())++ _, spawn = launcher(failing=2)+ with contextlib.redirect_stdout(io.StringIO()):+ passed, count, _ = runner.run_shards(('checks',), jobs=4, shard_count=3, spawn=spawn)+ self.assertFalse(passed)+ self.assertEqual(count, 10 + 11 + 12, '失败那片的用例数也要算进总数,记录里的 count 才是实跑数')++ def test_jobs_accepts_auto_or_a_positive_integer(self):+ self.assertEqual(runner.resolve_jobs('3'), 3)+ self.assertTrue(1 <= runner.resolve_jobs('auto') <= runner.MAX_JOBS)+ for bad in ('0', '-1', 'many'):+ with self.subTest(bad=bad), self.assertRaises(runner.argparse.ArgumentTypeError):+ runner.resolve_jobs(bad)+def test_a_test_reading_a_web_source_runs_when_that_source_changes(self):"""断言 `web/`、`frontend/` 文件的测试,必须登记在改那个文件会选到的域里。