Peach: Local-first video metadata scraper and media manager.
fix(web): 任务中心的第一份进度、顶替收尾与同步等待
longmeidao555581428eea
diff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex 10902c47f..d0c097c7e 100644--- a/scripts/test_runner.py+++ b/scripts/test_runner.py@@ -38,11 +38,15 @@ SCOPES: dict[str, tuple[str, ...]] = {"test_brand_marks.py", "test_studio_icon_variants.py","test_review_csv.py", "test_related.py","test_search_suggest.py", "test_subtitles.py",+ "test_task_runs.py", "test_task_center_integration.py","test_jav_code_domain.py","test_taste_history.py", "test_web_ui.py", "test_web_js.py","test_web_perf.py", "test_web_resource_sync.py","test_web_review.py", "test_web_settings.py"),+ # 任务中心的两个文件跟着 `test_jobs.py` 走:`jobs.py` 与 `task_runs.py` 是同一条+ # 接线的两端,改哪一端都要两边一起验。"media": ("test_runtime_consistency.py", "test_endcard.py", "test_fastapi_api.py", "test_jobs.py",+ "test_task_runs.py", "test_task_center_integration.py","test_interaction.py", "test_media.py", "test_previews.py","test_providers.py", "test_segments.py", "test_streaming.py","test_subtitles.py", "test_transcodes.py"),@@ -77,7 +81,8 @@ SCOPES: dict[str, tuple[str, ...]] = {"test_buildinfo.py", "test_versioning.py","test_windows_update.py", "test_release_updates.py", "test_automatic_updates.py", "test_standalone_update.py", "test_certs.py", "test_config.py","test_fsutil.py", "test_desktop_settings.py",- "test_job_status.py", "test_jobs.py", "test_reference_updates.py",+ "test_job_status.py", "test_jobs.py", "test_task_runs.py",+ "test_task_center_integration.py", "test_reference_updates.py","test_repo_hygiene.py","test_review_csv.py", "test_jav_code_domain.py","test_subprocess_encoding.py", "test_module_layering.py",diff --git a/src/peach/jobs.py b/src/peach/jobs.pyindex a2a44c4a4..dd512a6d1 100644--- a/src/peach/jobs.py+++ b/src/peach/jobs.py@@ -315,11 +315,14 @@ class BackgroundJob:returncurrent = state.get("checked")total = state.get("total")- self.runs.progress(- run_id,- current=int(current) if isinstance(current, (int, float)) else None,- total=int(total) if isinstance(total, (int, float)) else None,- label=self._progress_label(state) or None)+ counts = (int(current) if isinstance(current, (int, float)) else None,+ int(total) if isinstance(total, (int, float)) else None)+ label = self._progress_label(state) or None+ if counts == (None, None) and label is None:+ # 这一次改的是别的字段(`run_id` 本身就是一例),没有进度可报。不往下走:+ # 空写一次会白占掉节流窗口,真正的第一份计数要等两秒才进得去表。+ return+ self.runs.progress(run_id, current=counts[0], total=counts[1], label=label)@staticmethoddef _progress_label(state: dict) -> str:@@ -362,6 +365,7 @@ class BackgroundJob:job_id = ""with self.lock:state = self.state+ previous = stateif state is None or (restart and state["status"] != "running"):job_id = uuid.uuid4().hexstate = {self.id_key: job_id, "status": "running", "run_id": None,@@ -380,6 +384,10 @@ class BackgroundJob:mutex_key=self.mutex_key, conflict="skip")return snapshot# 开 task_run 与起线程都在锁外:前者要拿数据库的写锁,后者是这个类的老约定。+ # 先给被顶掉的那一轮收尾再开新的:它占着同一把互斥键,不收就是新的一轮开不了,+ # 而它自己的线程要等到 `fn` 返回才走到结算,那可能是几分钟以后。+ if previous is not None and previous[self.id_key] != job_id:+ self._settle_from(previous[self.id_key], previous, superseded=True)try:self._open_run(job_id, trigger, snapshot)except TaskRunConflict:@@ -464,13 +472,27 @@ class BackgroundJob:"""state = self.snapshot() or {}if state.get(self.id_key) != job_id:+ # 已经被 `start` 在顶替的那一刻收过尾了,这里再收一次是空操作。self._close_run(job_id, "cancelled", error="这一轮已被新的任务顶替")return+ self._settle_from(job_id, state)++ def _settle_from(self, job_id: str, state: dict, *,+ superseded: bool = False) -> None:+ """按给定的那份状态结算。`superseded` 是「被下一轮顶替」的那条路。++ 顶替发生在 `start` 里,那时旧状态已经被换掉,`snapshot()` 讲的是新一轮的事,+ 所以这里收的是调用方手上那一份,不重新读。+ """status = state.get("status")if status == "failed":self._close_run(job_id, "failed", error=str(state.get("error") or "任务失败"),summary=self._summary(state))return+ if superseded and status == "running":+ # 还在跑就被顶掉:它的结果没人要了,记成取消而不是成功。+ self._close_run(job_id, "cancelled", error="这一轮已被新的任务顶替")+ return# `fn` 正常返回就是跑完了。域没有把状态推到 `complete` 只说明它不靠状态报结果# (`w_links` 这类直接返回 payload),不代表这一轮失败。self._close_run(job_id, "succeeded", summary=self._summary(state))diff --git a/src/peach/task_runs.py b/src/peach/task_runs.pyindex 669abf1ee..8276eaf63 100644--- a/src/peach/task_runs.py+++ b/src/peach/task_runs.py@@ -241,8 +241,8 @@ class TaskRunStore:task_key, blocking.id if blocking else None) from Noneself._record_skip(task_key, trigger, mutex_key, blocking)return None- with self._lock:- self._last_write[run_id] = time.monotonic()+ # 这里刻意不给节流打时间戳:开工那一刻还不知道要做多少件,第一次进度报上来的+ # 才是真正能看的那一行。把它一起节流掉,活动页开头两秒只有一句「进行中」。return self.get(run_id)def _record_skip(self, task_key: str, trigger: str, mutex_key: str,@@ -309,11 +309,10 @@ class TaskRunStore:return donedef _due(self, run_id: int, throttle: float) -> bool:- if throttle <= 0:- return True+ """节流闸门。放行的那一次也记时间——不记的话下一次拿 0 当基准,节流形同虚设。"""now = time.monotonic()with self._lock:- if now - self._last_write.get(run_id, 0.0) < throttle:+ if throttle > 0 and now - self._last_write.get(run_id, 0.0) < throttle:return Falseself._last_write[run_id] = nowreturn Truediff --git a/src/peach/web_follow.py b/src/peach/web_follow.pyindex 4b9481cb0..a5e1bf136 100644--- a/src/peach/web_follow.py+++ b/src/peach/web_follow.py@@ -815,6 +815,12 @@ def w_follow_check(contract, body) -> dict:if started["request_id"] != request_id:return {"ok": False, "busy": True, "checked": 0, "results": []}finished.wait()+ # `finished` 只说正文跑完了;线程回到 `BackgroundJob` 之后还要给这一轮结算。+ # 同步调用等它落完再回话:否则端点已经答复而账本还在写,紧跟着读活动页会看到+ # 一轮停在「进行中」的检查,关停时也会误判成被打断。+ worker = contract.follow_job.thread+ if worker is not None and worker is not threading.current_thread():+ worker.join(5)if "error" in outcome:raise outcome["error"]return outcome["result"]diff --git a/tests/test_rm_web.py b/tests/test_rm_web.pyindex 3464ef77b..d713da87e 100644--- a/tests/test_rm_web.py+++ b/tests/test_rm_web.py@@ -853,6 +853,7 @@ class WebDataTests(unittest.TestCase):def test_contract_handler_registries_are_complete_and_unknown_routes_fail(self):self.assertEqual(set(rm_web.GET_HANDLERS), {+ "/api/tasks","/api/library-processing","/api/library-processing/issues","/api/scraping", "/api/scraping/cover",diff --git a/tests/test_task_center_integration.py b/tests/test_task_center_integration.pyindex e6ba9271e..5cbc2c530 100644--- a/tests/test_task_center_integration.py+++ b/tests/test_task_center_integration.py@@ -174,10 +174,15 @@ class ContractWiringTests(unittest.TestCase):self.assertEqual(len({job.task_key for job in jobs}), len(jobs))def test_a_batch_operation_leaves_one_row(self):- with sqlite3.connect(self.db) as connection:- connection.execute(- "INSERT INTO asset(id,location,path,name,medium) "- "VALUES(1,'local','R:\\Media\\a.mp4','a.mp4','video')")+ # `with` 只提交,不关连接:Windows 上那个还开着的句柄会让临时目录删不掉。+ connection = sqlite3.connect(self.db)+ try:+ with connection:+ connection.execute(+ "INSERT INTO asset(id,location,path,name,medium) "+ "VALUES(1,'local','R:\\Media\\a.mp4','a.mp4','video')")+ finally:+ connection.close()web_contract.w_batch(self.contract, {"ids": [1], "operation": "like"})run = self.contract.task_runs.query(task_key="batch")[0]self.assertEqual(run.status, "succeeded")