Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix(jobs): 收尾摘 run id 与写结束同锁,紧跟着的手动重来不再撞互斥键

longmeidaoe3f9e9cf8670
diff --git a/src/peach/jobs.py b/src/peach/jobs.py
index 487f27aa6..cf1bca1fe 100644
--- a/src/peach/jobs.py
+++ b/src/peach/jobs.py
@@ -286,6 +286,9 @@ class BackgroundJob:
#: job_id → task_run id。结算读这一份而不是读状态:状态可能已经被下一轮顶掉,
#: 而被顶掉的那一轮同样要有人给它收尾。
self._run_ids: dict[str, int] = {}
+ #: 摘 run id 与把那一行写成结束是同一件事:只摘不写完就放手的话,另一个线程
+ #: 看见 id 没了以为已经收过尾,紧接着开的下一轮会撞上那一行还没释放的互斥键。
+ self._close_lock = threading.Lock()
def snapshot(self) -> dict | None:
"""当前状态的深拷贝;一次都没跑过返回 None。"""
@@ -428,10 +431,11 @@ class BackgroundJob:
def _close_run(self, job_id: str, status: str, *, error: str = "",
summary: dict | None = None) -> None:
- run_id = self._run_ids.pop(job_id, None)
- if self.runs is None or run_id is None:
- return
- self.runs.finish(run_id, status, summary=summary, error=error)
+ with self._close_lock:
+ run_id = self._run_ids.pop(job_id, None)
+ if self.runs is None or run_id is None:
+ return
+ self.runs.finish(run_id, status, summary=summary, error=error)
self.runs.prune(self.task_key)
def stop(self, timeout: float | None = 2.0) -> None:
diff --git a/tests/test_task_center_integration.py b/tests/test_task_center_integration.py
index 8900bdfc2..8b9bc9f59 100644
--- a/tests/test_task_center_integration.py
+++ b/tests/test_task_center_integration.py
@@ -135,6 +135,24 @@ class BackgroundJobTaskRunTests(unittest.TestCase):
self.assertEqual(self.store.get(first_id).status, "succeeded")
self.assertEqual(len(self.store.query(status="active")), 0)
+ def test_a_restart_right_after_a_round_returns_waits_for_its_row_to_close(self):
+ """上一轮的线程正在把表里那一行写成结束,紧跟着的手动重来不能撞它的互斥键。"""
+ job = self.job()
+ closing = threading.Event()
+ finish = self.store.finish
+
+ def slow_finish(run_id, status, **kwargs):
+ closing.set()
+ threading.Event().wait(0.3)
+ return finish(run_id, status, **kwargs)
+
+ with unittest.mock.patch.object(self.store, "finish", side_effect=slow_finish):
+ job.start(lambda job_id: job.update(job_id, status="complete"))
+ self.assertTrue(closing.wait(5))
+ job.start(lambda job_id: job.update(job_id, status="complete"), restart=True)
+ job.thread.join(5)
+ self.assertEqual([run.status for run in self.store.query()], ["succeeded", "succeeded"])
+
def test_shutdown_marks_the_round_cancelled_not_failed(self):
job = self.job()
release = threading.Event()