Peach: Local-first video metadata scraper and media manager.
fix(web_contract): 让 w_item_tag 走唯一的事务入口
longmeidaobda3061dc0d1
diff --git a/src/peach/web_contract.py b/src/peach/web_contract.pyindex cf191b23a..5e422ef2d 100644--- a/src/peach/web_contract.py+++ b/src/peach/web_contract.py@@ -165,7 +165,6 @@ class WebContract:self.db_path = self.database.db_pathself.snapshot_root = Path(snapshot_root) if snapshot_root is not None else Noneself.legacy_snapshot_roots = tuple(Path(path) for path in legacy_snapshot_roots)- self.write_lock = self.database.write_lockself.cache: dict[str, tuple[float, object]] = {}self.cache_lock = threading.Lock()self.follow_check_lock = threading.Lock()@@ -2391,10 +2390,12 @@ def w_item_tag(contract: WebContract, body):raise ValueError("tag must be 1 to 80 characters and cannot be a performer marker")normalized = normalize_entity_name(tag)stamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())- with contract.write_lock:- c = contract.db(write=True)+ # 事务边界只有一个入口:write_transaction 自己取 database.write_lock 并在异常时回滚。+ # 这里曾经手取同一把不可重入的锁再手动 commit/close,任何 execute 抛出都会漏掉+ # 回滚和关闭;也正因为那把锁是同一把,直接改调 write_transaction 而不撤掉外层+ # with 会自死锁。+ with contract.write_transaction() as c:if not c.execute("SELECT 1 FROM asset WHERE id=?", (aid,)).fetchone():- c.close()raise ValueError("asset not found")if operation == "remove":c.execute(@@ -2417,7 +2418,6 @@ def w_item_tag(contract: WebContract, body):source="web-user", confidence=1.0,metadata={"profile_id": DEFAULT_PROFILE_ID}, now=stamp,)- c.commit(); c.close()return {"ok": True, "operation": operation, "tag": tag,"tags": [item["k"] for item in q_item(contract, aid)["tags"]]}diff --git a/tests/test_rm_web.py b/tests/test_rm_web.pyindex f921d659e..8690bf9d3 100644--- a/tests/test_rm_web.py+++ b/tests/test_rm_web.py@@ -3,6 +3,7 @@ import jsonimport osimport sqlite3import tempfile+import threadingimport timeimport unittestfrom contextlib import contextmanager@@ -553,6 +554,55 @@ class WebDataTests(unittest.TestCase):)con.close()+ def test_item_tag_rolls_back_and_closes_when_the_entity_write_fails(self):+ """加标签是一个事务:实体那步失败时 asset_tag 不能留下半条记录,连接也要关掉。++ 改用 write_transaction 之前这里是手动 commit/close,只有「资产不存在」那条+ 路径会关连接,任何 execute 抛出都既不回滚也不关闭。"""+ opened = []+ real_connect = self.contract.database.connect++ def capture(*, write=False):+ connection = real_connect(write=write)+ opened.append(connection)+ return connection++ with mock.patch.object(self.contract.database, "connect", side_effect=capture):+ with mock.patch.object(rm_web, "upsert_asset_entity",+ side_effect=RuntimeError("entity write failed")):+ with self.assertRaisesRegex(RuntimeError, "entity write failed"):+ rm_web.w_item_tag(self.contract, {+ "id": 1, "operation": "add", "tag": "回滚标签",+ })++ con = sqlite3.connect(self.db_path)+ self.assertIsNone(+ con.execute(+ "SELECT 1 FROM asset_tag WHERE asset_id=1 AND tag='回滚标签'").fetchone(),+ "事务中途失败后不能把标签行留在账本里",+ )+ con.close()+ self.assertTrue(opened, "没有取到写连接,测试本身失效")+ with self.assertRaises(sqlite3.ProgrammingError):+ opened[-1].execute("SELECT 1")++ def test_item_tag_releases_the_write_lock_between_calls(self):+ """写事务只能取一次 database.write_lock:那是把不可重入锁。++ 谁把外层的手动取锁加回来(或在 write_transaction 里再取一次),第二次写入+ 就会永远等自己已经持有的锁。这个断言就是那个陷阱的守卫。"""+ rm_web.w_item_tag(self.contract, {"id": 1, "operation": "add", "tag": "第一次"})+ finished = threading.Event()++ def second_write():+ rm_web.w_item_tag(self.contract, {"id": 1, "operation": "add", "tag": "第二次"})+ finished.set()++ worker = threading.Thread(target=second_write, daemon=True)+ worker.start()+ worker.join(timeout=10)+ self.assertTrue(finished.is_set(), "第二次写入没能在 10 秒内拿到写锁,写锁没被释放")+def stage_media(self, aid, name="clip.mp4"):"""把某条资产指向真实的临时文件,物理删除才有东西可删。"""path = Path(self.tmp.name) / name