Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat(test): 等测试锁与集成锁时打印持锁方的 pid、开始时间与范围

longmeidaobd914e676da8
diff --git a/.claude/skills/peach-worktree/SKILL.md b/.claude/skills/peach-worktree/SKILL.md
index 617af9916..d714686e8 100644
--- a/.claude/skills/peach-worktree/SKILL.md
+++ b/.claude/skills/peach-worktree/SKILL.md
@@ -29,7 +29,7 @@ description: 在用户说并行、工作树、暂存、提交、ready、集成
差异补测不延长全量基线有效期;版本号行单独变化归 tooling,包内其他逻辑变化仍按源码判断。
相同状态复用记录;Windows `-Fresh`、POSIX 第二参数 `--fresh` 强制重跑;显式 `full` 总是实际执行。
4. `ready` 前将当前 `master` 纳入工作树并运行 `auto`。相同内容可复用记录;目标变化重算影响域。`ready` / `integrate` 拒绝缺记录、范围不足或目标分支未纳入的提交。
-5. 协调者统一运行 `integrate`:锁内复查、合并固定提交。锁忙就等待后重试,禁止直接 merge。同一批任务由协调者整理 `STATUS`,工作者按文件分工;共享文件安排顺序。
+5. 协调者统一运行 `integrate`:锁内复查、合并固定提交。锁忙就等待后重试,禁止直接 merge;测试锁与集成锁被占时提示里带持锁方的 pid、开始时间与范围,看那一行判断,不要数进程。同一批任务由协调者整理 `STATUS`,工作者按文件分工;共享文件安排顺序。
版本号不在这里动,`integrate` 只报当前值:推进与打标签都走 `scripts/release_tag.py`,
它是唯一入口。`--bump auto --apply` 推版本、定版变更日志并把那一节带在输出里给人确认,
确认后 `--ship --apply` 一次做完提交、推送、等 Test 转绿、打标签(ADR-0012 修订)。
diff --git a/scripts/agent_worktree.py b/scripts/agent_worktree.py
index 7af284d16..ecfa60ddd 100644
--- a/scripts/agent_worktree.py
+++ b/scripts/agent_worktree.py
@@ -130,10 +130,13 @@ def integrate(repo: Path, worker_branch: str, target_branch: str = "master") ->
folder = test_evidence.evidence_dir(repo)
folder.mkdir(parents=True, exist_ok=True)
try:
- with test_evidence.FileLock(folder / "integration.lock", timeout=0):
+ with test_evidence.held(folder / "integration.lock",
+ branch=worker_branch, root=str(repo)):
return _integrate_locked(repo, worker_branch, target_branch)
except test_evidence.Timeout as error:
- raise WorkspaceError("另一任务正在集成;本次未修改分支,请等待后重试") from error
+ raise WorkspaceError(
+ f"另一任务正在集成({test_evidence.describe_holder(Path(error.lock_file))});"
+ "本次未修改分支,请等待后重试") from error
def _integrate_locked(repo: Path, worker_branch: str,
diff --git a/scripts/test_evidence.py b/scripts/test_evidence.py
index 8970def1b..d80298b46 100644
--- a/scripts/test_evidence.py
+++ b/scripts/test_evidence.py
@@ -12,6 +12,7 @@ import stat
import subprocess
import sys
import time
+from contextlib import contextmanager
from functools import lru_cache
from pathlib import Path
@@ -205,7 +206,42 @@ def write(root: Path, state: str, scopes: tuple[str, ...], *, success: bool,
temporary.replace(folder / f"{state}.json")
-def run_lock(root: Path, state: str) -> FileLock:
- folder = evidence_dir(root)
- folder.mkdir(parents=True, exist_ok=True)
- return FileLock(folder / f"{state}.lock", timeout=0)
+def holder_path(lock_path: Path) -> Path:
+ return lock_path.with_name(lock_path.name + ".holder.json")
+
+
+@contextmanager
+def held(lock_path: Path, **note: object):
+ """拿锁,并在旁边留下「谁在持有」的记录,让等锁的人知道在等什么。
+
+ 互斥只靠 filelock:锁是操作系统层面的句柄,只能被活着的进程持有,进程退出就释放。
+ 记录是旁证,不参与互斥。持有者正常退出就删掉它;异常退出留下的旧记录会被下一位
+ 持有者进门时覆盖,而等锁那一侧只在锁真的被占着时才去读,所以读到的总是当前持有者。
+ """
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
+ with FileLock(lock_path, timeout=0):
+ record = holder_path(lock_path)
+ record.write_text(json.dumps({
+ "pid": os.getpid(),
+ "started_at": time.strftime("%Y-%m-%d %H:%M:%S"),
+ **note,
+ }, ensure_ascii=False), encoding="utf-8")
+ try:
+ yield
+ finally:
+ record.unlink(missing_ok=True)
+
+
+def describe_holder(lock_path: Path) -> str:
+ """等锁时打印用:`pid 8772、01:54:39 起、scope full、root C:\\…`。"""
+ try:
+ note = json.loads(holder_path(lock_path).read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return "持有者刚退出或没留记录"
+ parts = [f"pid {note.get('pid')}", f"{note.get('started_at')} 起"]
+ parts.extend(f"{key} {note[key]}" for key in ("scope", "branch", "root") if note.get(key))
+ return "、".join(parts)
+
+
+def run_lock(repo: Path, state: str, **note: object):
+ return held(evidence_dir(repo) / f"{state}.lock", **note)
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index 93f736dba..063370141 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -372,7 +372,7 @@ def main(argv: list[str] | None = None) -> int:
context = test_evidence.inputs(ROOT)
state = context["state"]
try:
- with test_evidence.run_lock(ROOT, state):
+ 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(
test_evidence.read(ROOT, state), scopes):
print("复用本机测试记录:代码、依赖环境和范围匹配(24 小时内)。", flush=True)
@@ -393,7 +393,8 @@ def main(argv: list[str] | None = None) -> int:
_, baseline, scopes = min(choices, key=lambda item: item[0])
print(f"复用全量基线 {baseline['state'][:12]};新增差异补测:{' '.join(scopes)}", flush=True)
folder = test_evidence.evidence_dir(ROOT)
- full_lock = test_evidence.FileLock(folder / "full-suite.lock", timeout=0) \
+ full_lock = test_evidence.held(folder / "full-suite.lock",
+ scope=" ".join(scopes), root=str(ROOT)) \
if "full" in scopes else nullcontext()
with full_lock:
(folder / f"{state}.json").unlink(missing_ok=True)
@@ -410,8 +411,11 @@ def main(argv: list[str] | None = None) -> int:
if not stable:
print("验证期间代码或依赖环境改变,本次记录无效。", flush=True)
return 0 if success else 1
- except test_evidence.Timeout:
- print("相同状态的验证或本仓库全量测试正在运行,请等待该次结果。", flush=True)
+ except test_evidence.Timeout as error:
+ lock = Path(error.lock_file)
+ what = "本仓库全量测试" if lock.name == "full-suite.lock" else "相同状态的验证"
+ print(f"{what}正在运行({test_evidence.describe_holder(lock)}),请等待该次结果。",
+ flush=True)
return 2
diff --git a/tests/test_test_evidence.py b/tests/test_test_evidence.py
index b77be01ff..7d836dff1 100644
--- a/tests/test_test_evidence.py
+++ b/tests/test_test_evidence.py
@@ -189,14 +189,41 @@ class VerificationTests(unittest.TestCase):
before = self.git("rev-parse", "HEAD")
command = [sys.executable, str(Path(coordinator.__file__)), "--repo", str(self.repo),
"integrate", "--branch", branch]
- with evidence.FileLock(folder / "integration.lock"):
+ with evidence.held(folder / "integration.lock", branch="agent/x/other"):
result = subprocess.run(command, capture_output=True, text=True,
encoding="utf-8", timeout=15,
env={**os.environ, "PYTHONIOENCODING": "gbk"})
self.assertEqual(result.returncode, 2, result.stderr)
- self.assertIn("另一任务正在集成", json.loads(result.stdout)["error"])
+ error = json.loads(result.stdout)["error"]
+ self.assertIn("另一任务正在集成", error)
+ self.assertIn(f"pid {os.getpid()}", error, "被拒的一方要能看到在等谁")
+ self.assertIn("branch agent/x/other", error)
self.assertEqual(self.git("rev-parse", "HEAD"), before)
+ def test_a_held_lock_leaves_a_holder_note_only_while_it_is_held(self):
+ """三个会话同时在等锁时,光看进程列表判断不出谁在测;记录要说清 pid、时间和范围。"""
+ lock = evidence.evidence_dir(self.repo) / "full-suite.lock"
+ with evidence.held(lock, scope="full"):
+ note = json.loads(evidence.holder_path(lock).read_text(encoding="utf-8"))
+ self.assertEqual(note["pid"], os.getpid())
+ self.assertEqual(note["scope"], "full")
+ self.assertIn("pid", evidence.describe_holder(lock))
+ self.assertIn("scope full", evidence.describe_holder(lock))
+ self.assertFalse(evidence.holder_path(lock).exists())
+ self.assertIn("刚退出或没留记录", evidence.describe_holder(lock))
+
+ 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()
+ with evidence.held(lock, scope="full", root="elsewhere"), \
+ 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", "full"]), 2)
+ self.assertIn("本仓库全量测试正在运行", output.getvalue())
+ self.assertIn(f"pid {os.getpid()}", output.getvalue())
+ self.assertIn("root elsewhere", output.getvalue())
+
def test_empty_active_worktree_survives_prune(self):
item = coordinator.create(self.repo, "codex", "active", self.root / "worktrees")
report = coordinator.prune(self.repo, apply=True)