Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

fix(tests): 测试重任务限制改为仓库内两槽位

longmeidao1345d56448f0
diff --git a/.claude/skills/peach-shell-commands/SKILL.md b/.claude/skills/peach-shell-commands/SKILL.md
index 98b570e60..9509c6da1 100644
--- a/.claude/skills/peach-shell-commands/SKILL.md
+++ b/.claude/skills/peach-shell-commands/SKILL.md
@@ -50,8 +50,7 @@ Claude 与 Codex 会话记录里交给用户、被贴回报错截图的 39 条
不改断言、不跳过用例。`scripts/test.ps1` 会在分片前报告无法启动的外部工具。
- `danger-full-access` 是取消隔离,不是「提权沙箱」。除非用户明确要求承担全局风险,否则保留沙箱,
只给当前项目入口所需的命令授权。
-- Windows 全量测试若外套 `resource_run.py`,给 `scripts/test.ps1` 传 `-Jobs 1`;外层 Job Object
- 与入口的四路并发叠加会让 Git Bash、Python 和临时 Git 进程出现 I/O 或进程创建错误。
+- 测试入口自带机器级两槽位重任务限制(`docs/TESTING.md`「验证频率」),不要再外套资源守卫;
npm/PyInstaller、FFmpeg 与媒体批处理仍按资源预算使用外层守卫。
## 多行内容一律先写成文件
diff --git a/docs/TESTING.md b/docs/TESTING.md
index bc842243d..4d1abccfd 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -46,7 +46,7 @@ Dependabot 的 PR 一律在本地接管,不在网页上合:
## 验证频率
-Windows 长回归可设置 `PEACH_TEST_RESOURCE_RUNNER` 为本机 Python 资源入口的绝对路径,并使用 `-Jobs 1`。正式入口仍汇总所有分片与签发记录,每片独立取得资源互斥和 1800 秒限额;控制器只负责调度,不把多个分片合成一个超时窗口。取消时按已创建的 PID 清理子进程树。
+整台机器同时最多跑两个测试重任务:一个分片子进程,或不分片时的整轮测试,各占一个槽位。槽位是 `build/agent-verification/heavy-slot-*.lock` 文件锁,所有工作树与会话共用;槽位全忙时入口排队,等待上限同 `--lock-timeout`,超时以 `2` 退出且不开跑。槽位只限并发,不改变测试内容,不进记录指纹。取消时按已创建的 PID 清理子进程树并归还槽位。
Python 静态检查使用开发依赖 Ruff,随每个正式测试域扫描全仓自有 Python 文件,覆盖应用、脚本、测试和打包入口。规则为 Pyflakes(`F`)、Ruff 支持的 Pylint 错误规则(`PLE`),以及可变默认参数、`finally` 跳转、无效表达式和循环闭包规则(`B006`、`B012`、`B018`、`B023`)。生成的 `downloads_clouddrive_pb2.py` 排除;公开导出的导入用显式同名别名声明。命名、行数、空行和复杂度偏好不属于这套 lint 门槛。
@@ -72,7 +72,7 @@ Python 静态检查使用开发依赖 Ruff,随每个正式测试域扫描全
需要外部前置条件(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` 退回串行。测试之间没有共享的端口或全局目录,账本与仓库夹具都在各自的临时目录里,并行才是安全的;新增测试保持这一点。
+本机默认并行:入口传 `--jobs auto`(Windows `-Jobs`),运行器按同一套稳定分片切成并发数四倍的片,最多两个子进程各领一片、先完成的接着领下一片,父进程汇总成败、用例数与逐用例耗时后按原口径签发一份记录,一片红整轮红。`-Jobs 1` 退回串行。测试之间没有共享的端口或全局目录,账本与仓库夹具都在各自的临时目录里,并行才是安全的;新增测试保持这一点。
Windows 的路径、挂载、托盘、证书、进程编码、更新、认证及迁移属于 `core`。构建和工作流修改选择 `packaging` 与 `tooling`;测试调度自身仍全量。仅 uv 工具版本或项目展示字段变化不算依赖图变化;无法解析时全量。
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index cf26843cf..97c1ee68b 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -15,7 +15,7 @@ import time
import tomllib
import unittest
from collections.abc import Iterable
-from contextlib import nullcontext
+from contextlib import ExitStack, nullcontext
from pathlib import Path
@@ -507,9 +507,11 @@ class TimedResult(unittest.TextTestResult):
super().stopTest(test)
-#: 本机并行的上限。全量里最重的是 git 与 PowerShell 子进程型的 tooling 用例,四路已经
-#: 把它们摊开;再多只是让每个子进程各自 import 一遍 peach 的固定开销变多。
-MAX_JOBS = 4
+#: 整台机器同时跑的测试重任务上限。一个分片子进程、或不分片时的整轮测试,各占一个槽位;
+#: 槽位是共用 Git 目录下的文件锁,所有工作树、所有会话共用这几个,用户定的是两个。
+HEAVY_TASK_SLOTS = 2
+#: 一轮测试自己的并发上限,不超过机器的槽位数:多开的子进程只会排队等槽位。
+MAX_JOBS = HEAVY_TASK_SLOTS
#: 最多切多少片。CI 两片是因为每片一台 runner;本机每片只是一个子进程,切细一点
#: 才能让重文件(`test_agent_worktree.py` 一个就 80 秒)不把整片拖成长尾。
MAX_SHARDS = 16
@@ -533,45 +535,92 @@ def shard_command(scopes: tuple[str, ...], index: int, count: int, timings: Path
*(item for scope in scopes for item in ("--scope", scope)),
"--shard-index", str(index), "--shard-count", str(count),
"--timings", str(timings)]
- resource_runner = os.environ.get('PEACH_TEST_RESOURCE_RUNNER', '').strip()
- if not resource_runner:
- return command
- path = Path(resource_runner).resolve()
- if not path.is_file():
- raise ValueError('测试资源入口不存在')
- return [sys.executable, '-X', 'utf8', str(path), '--timeout', '1800', '--', *command]
+ return command
+
+
+def heavy_slot_paths(slots: Path | None = None) -> list[Path]:
+ """机器级重任务槽位的锁文件;默认在共用 Git 目录旁,所有工作树看到的是同一组。"""
+ folder = slots if slots is not None else test_evidence.evidence_dir(ROOT)
+ return [folder / f"heavy-slot-{index}.lock" for index in range(1, HEAVY_TASK_SLOTS + 1)]
+
+
+def try_heavy_slot(paths: list[Path], **note: object) -> ExitStack | None:
+ """不等待地拿一个空闲槽位;全忙返回 None。拿到的槽位随返回的 ExitStack 关闭而释放。"""
+ for path in paths:
+ stack = ExitStack()
+ try:
+ stack.enter_context(test_evidence.held(path, **note))
+ except test_evidence.Timeout:
+ stack.close()
+ continue
+ return stack
+ return None
+
+
+def wait_heavy_slot(paths: list[Path], *, wait_seconds: float, poll: float = 0.2,
+ **note: object) -> ExitStack:
+ """等到一个槽位空出来;超过 `wait_seconds` 抛 `Timeout`,锁文件取最后一个槽位。"""
+ deadline = time.monotonic() + wait_seconds
+ announced = False
+ while True:
+ slot = try_heavy_slot(paths, **note)
+ if slot is not None:
+ return slot
+ if time.monotonic() >= deadline:
+ raise test_evidence.Timeout(str(paths[-1]))
+ if not announced:
+ holders = ";".join(test_evidence.describe_holder(path) for path in paths)
+ print(f"{len(paths)} 个测试重任务槽位都在用({holders}),最长等待 {wait_seconds:g} 秒。",
+ flush=True)
+ announced = True
+ time.sleep(poll)
def run_shards(scopes: tuple[str, ...], *, jobs: int, shard_count: int,
- spawn=subprocess.Popen) -> tuple[bool, int, list]:
+ spawn=subprocess.Popen, slots: Path | None = None,
+ slot_wait: float = 1800) -> tuple[bool, int, list]:
"""把选中的文件按 CI 同一套稳定分片切开,同时最多 `jobs` 个子进程各跑一片。
每片是一次 `--shard-count` 子进程:它自己从不签发记录,只把成败、用例数和逐个
用例的耗时写进 `--timings` 那个文件,父进程汇总后签发一份记录,口径与串行相同。
片数比并发数多,是为了让先跑完的进程接着领下一片,重文件不至于把墙钟拖成它
一家的长度。子进程的输出各自落盘,哪片结束就整段打印哪片,不交错。
+
+ 每片启动前先拿一个机器级重任务槽位(`HEAVY_TASK_SLOTS`),该片结束就还。别的
+ 工作树或会话占着槽位时,这里排队,最长 `slot_wait` 秒。
"""
- if os.environ.get('PEACH_TEST_RESOURCE_RUNNER', '').strip() and jobs != 1:
- raise ValueError('受限分片必须使用 --jobs 1')
folder = Path(tempfile.mkdtemp(prefix="peach-shards-"))
+ paths = heavy_slot_paths(slots)
pending = list(range(shard_count))
- running: dict[int, tuple[object, object]] = {}
+ running: dict[int, tuple[object, object, ExitStack]] = {}
passed, count, timings = True, 0, []
try:
while pending or running:
while pending and len(running) < jobs:
+ if running:
+ slot = try_heavy_slot(paths, scope=" ".join(scopes), root=str(ROOT))
+ if slot is None:
+ break
+ else:
+ slot = wait_heavy_slot(paths, wait_seconds=slot_wait,
+ scope=" ".join(scopes), root=str(ROOT))
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()
+ try:
+ 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))
+ except BaseException:
+ slot.close()
+ raise
+ running[index] = (process, log, slot)
+ 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)
+ process, log, slot = running.pop(index)
+ slot.close()
log.flush()
log.seek(0)
sys.stdout.write(log.read())
@@ -586,15 +635,18 @@ def run_shards(scopes: tuple[str, ...], *, jobs: int, shard_count: int,
print(f"分片 {index + 1}/{shard_count} {'通过' if ok else '失败'}"
f"({report.get('count', 0)} 个用例)", flush=True)
finally:
- for process, log in running.values():
- if process.poll() is None:
- if os.name == 'nt':
- subprocess.run(['taskkill', '/PID', str(process.pid), '/T', '/F'],
- stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=15)
- else:
- process.terminate()
- process.wait(timeout=15)
- log.close()
+ for process, log, slot in running.values():
+ try:
+ if process.poll() is None:
+ if os.name == 'nt':
+ subprocess.run(['taskkill', '/PID', str(process.pid), '/T', '/F'],
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=15)
+ else:
+ process.terminate()
+ process.wait(timeout=15)
+ log.close()
+ finally:
+ slot.close()
shutil.rmtree(folder, ignore_errors=True)
return passed, count, timings
@@ -653,14 +705,20 @@ 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, *,
+ slot_wait: float = 1800) -> 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, MAX_SHARDS)
print(f"本机分片:{shard_count} 片、同时 {min(jobs, shard_count)} 个子进程", flush=True)
- return run_shards(scopes, jobs=jobs, shard_count=shard_count)
- result = unittest.TextTestRunner(verbosity=2, resultclass=TimedResult).run(build_suite(*scopes))
+ return run_shards(scopes, jobs=jobs, shard_count=shard_count, slot_wait=slot_wait)
+ with wait_heavy_slot(heavy_slot_paths(), wait_seconds=slot_wait,
+ scope=" ".join(scopes), root=str(ROOT)):
+ result = unittest.TextTestRunner(verbosity=2, resultclass=TimedResult).run(build_suite(*scopes))
return result.wasSuccessful() and result.testsRun > 0, result.testsRun, result.timings
@@ -720,6 +778,10 @@ def main(argv: list[str] | None = None) -> int:
return verified_run(args, requested, scopes, files)
except test_evidence.Timeout as error:
lock = Path(error.lock_file)
+ if lock.name.startswith("heavy-slot-"):
+ print(f"{HEAVY_TASK_SLOTS} 个测试重任务槽位一直被占用,本次未开跑;"
+ "等其他工作树或会话的测试结束后重试。", flush=True)
+ return 2
what = "本仓库全量测试" if lock.name == "full-suite.lock" else "相同状态的验证"
print(f"{what}正在运行({test_evidence.describe_holder(lock)}),请等待该次结果。",
flush=True)
@@ -760,7 +822,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, slot_wait=args.lock_timeout)
stable = state == test_evidence.key(ROOT)
success = passed and stable
slowest = sorted(timings, reverse=True)[:20]
diff --git a/tests/test_test_evidence.py b/tests/test_test_evidence.py
index c1b9e34d2..c2de8d016 100644
--- a/tests/test_test_evidence.py
+++ b/tests/test_test_evidence.py
@@ -19,25 +19,70 @@ from scripts import test_runner as runner
from support.gitrepo import seed_repository
-class ResourceShardCommandTests(unittest.TestCase):
- def test_resource_entry_keeps_shard_arguments_and_space_in_path(self):
- with tempfile.TemporaryDirectory() as temporary:
- resource = Path(temporary)/'resource entry.py'
- resource.write_text('', encoding='utf-8')
- with mock.patch.dict(os.environ, {'PEACH_TEST_RESOURCE_RUNNER': ''}):
- original = runner.shard_command(('full',), 2, 4, Path(temporary)/'timings.json')
- with mock.patch.dict(os.environ, {'PEACH_TEST_RESOURCE_RUNNER': str(resource)}):
- bounded = runner.shard_command(('full',), 2, 4, Path(temporary)/'timings.json')
- self.assertEqual(bounded[:7], [sys.executable, '-X', 'utf8', str(resource.resolve()), '--timeout', '1800', '--'])
- self.assertEqual(bounded[7:], original)
-
- def test_missing_resource_entry_and_parallel_resource_jobs_are_rejected(self):
- with tempfile.TemporaryDirectory() as temporary:
- with mock.patch.dict(os.environ, {'PEACH_TEST_RESOURCE_RUNNER': str(Path(temporary)/'missing.py')}):
- with self.assertRaisesRegex(ValueError, '不存在'):
- runner.shard_command(('full',), 0, 4, Path(temporary)/'timings.json')
- with self.assertRaisesRegex(ValueError, 'jobs 1'):
- runner.run_shards(('full',), jobs=2, shard_count=4)
+class HeavyTaskSlotTests(unittest.TestCase):
+ """机器级重任务槽位:别的会话占着的槽位,本轮分片不能再用。"""
+
+ def setUp(self):
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.slots = Path(temporary.name)
+
+ def launcher(self):
+ live, peak, commands = set(), [0], []
+
+ class Shard:
+ def __init__(self, command):
+ report = Path(command[command.index('--timings') + 1])
+ report.write_text(json.dumps({'success': True, 'count': 1, 'timings': []}),
+ encoding='utf-8')
+ self.polls, self.returncode = 0, None
+ live.add(self)
+ peak[0] = max(peak[0], len(live))
+
+ def poll(self):
+ self.polls += 1
+ if self.polls >= 2:
+ live.discard(self)
+ self.returncode = 0
+ return self.returncode
+
+ def spawn(command, *, stdout, stderr, cwd):
+ commands.append(command)
+ return Shard(command)
+ return spawn, peak, commands
+
+ def test_a_slot_held_elsewhere_leaves_this_run_one_shard_at_a_time(self):
+ spawn, peak, commands = self.launcher()
+ busy = runner.heavy_slot_paths(self.slots)[0]
+ with evidence.held(busy, scope='other session'), redirect_stdout(io.StringIO()), \
+ mock.patch.dict(os.environ, {'PEACH_TEST_RESOURCE_RUNNER': str(self.slots / 'gone.py')}):
+ passed, count, _ = runner.run_shards(('checks',), jobs=2, shard_count=3,
+ spawn=spawn, slots=self.slots)
+ self.assertTrue(passed)
+ self.assertEqual(count, 3)
+ self.assertEqual(peak[0], 1)
+ for command in commands:
+ self.assertEqual(command[:2], [sys.executable, str(runner.ROOT / 'scripts' / 'test_runner.py')])
+
+ def test_free_slots_let_the_run_use_both(self):
+ spawn, peak, _ = self.launcher()
+ with redirect_stdout(io.StringIO()):
+ passed, _, _ = runner.run_shards(('checks',), jobs=2, shard_count=4,
+ spawn=spawn, slots=self.slots)
+ self.assertTrue(passed)
+ self.assertEqual(peak[0], runner.HEAVY_TASK_SLOTS)
+ for path in runner.heavy_slot_paths(self.slots):
+ with evidence.held(path):
+ pass # 分片结束后每个槽位都还回去了,才能不等待地再拿到
+
+ def test_all_slots_busy_times_out_without_starting_a_shard(self):
+ spawn, _, commands = self.launcher()
+ paths = runner.heavy_slot_paths(self.slots)
+ with evidence.held(paths[0]), evidence.held(paths[1]), redirect_stdout(io.StringIO()):
+ with self.assertRaises(evidence.Timeout):
+ runner.run_shards(('checks',), jobs=2, shard_count=2, spawn=spawn,
+ slots=self.slots, slot_wait=0)
+ self.assertEqual(commands, [])
class VerificationTests(unittest.TestCase):
@@ -305,6 +350,17 @@ class VerificationTests(unittest.TestCase):
self.assertIn("scope full", reader.result(timeout=5))
self.assertFalse(note.exists())
+ def test_busy_heavy_slots_stop_an_unsharded_run_before_any_test(self):
+ first, second = runner.heavy_slot_paths(evidence.evidence_dir(self.repo))
+ output = io.StringIO()
+ with evidence.held(first), evidence.held(second), \
+ redirect_stderr(io.StringIO()), redirect_stdout(output), \
+ mock.patch.object(runner, "ROOT", self.repo), \
+ mock.patch.object(runner, "build_suite", side_effect=AssertionError("不该开跑")):
+ self.assertEqual(runner.main(["--scope", "checks", "--lock-timeout", "0"]), 2)
+ self.assertIn("测试重任务槽位一直被占用", output.getvalue())
+ self.assertFalse(evidence.covers(evidence.read(self.repo, evidence.key(self.repo)), ("checks",)))
+
def test_the_waiting_runner_names_the_holder_of_the_full_suite_lock(self):
lock = evidence.evidence_dir(self.repo) / "full-suite.lock"
output = io.StringIO()
@@ -479,7 +535,7 @@ class VerificationTests(unittest.TestCase):
mock.patch.object(runner, "resolve_auto_scope", return_value=(("full",), "fixture")), \
mock.patch.object(runner, "run_local_suite", return_value=(True, 1, [])) as run:
self.assertEqual(runner.main(["--scope", "auto"]), 0)
- run.assert_called_once_with(("full",), 1)
+ run.assert_called_once_with(("full",), 1, slot_wait=1800)
def test_baseline_does_not_expand_a_small_requested_scope(self):
self.certify(self.repo, ("full",))
diff --git a/tests/test_test_planning.py b/tests/test_test_planning.py
index b0c7c2927..7367c0d89 100644
--- a/tests/test_test_planning.py
+++ b/tests/test_test_planning.py
@@ -188,10 +188,12 @@ class TestPlanningTests(unittest.TestCase):
return Done(0 if index != failing else 1)
return launched, spawn
+ slots = tempfile.TemporaryDirectory()
+ self.addCleanup(slots.cleanup)
launched, spawn = launcher(failing=None)
- with patch.dict(os.environ, {'PEACH_TEST_RESOURCE_RUNNER': ''}), \
- contextlib.redirect_stdout(io.StringIO()) as output:
- passed, count, timings = runner.run_shards(('follow', 'tooling'), jobs=2, shard_count=3, spawn=spawn)
+ with contextlib.redirect_stdout(io.StringIO()) as output:
+ passed, count, timings = runner.run_shards(('follow', 'tooling'), jobs=2, shard_count=3,
+ spawn=spawn, slots=Path(slots.name))
self.assertTrue(passed)
self.assertEqual(count, 10 + 11 + 12)
self.assertEqual(sorted(name for _, name in timings), ['test_0', 'test_1', 'test_2'])
@@ -204,9 +206,9 @@ class TestPlanningTests(unittest.TestCase):
self.assertIn(f'分片 {index} 的输出', output.getvalue())
_, spawn = launcher(failing=2)
- with patch.dict(os.environ, {'PEACH_TEST_RESOURCE_RUNNER': ''}), \
- contextlib.redirect_stdout(io.StringIO()):
- passed, count, _ = runner.run_shards(('checks',), jobs=4, shard_count=3, spawn=spawn)
+ with contextlib.redirect_stdout(io.StringIO()):
+ passed, count, _ = runner.run_shards(('checks',), jobs=4, shard_count=3,
+ spawn=spawn, slots=Path(slots.name))
self.assertFalse(passed)
self.assertEqual(count, 10 + 11 + 12, '失败那片的用例数也要算进总数,记录里的 count 才是实跑数')