Peach: Local-first video metadata scraper and media manager.
feat(tasks): 统一本机任务与后继的暂停继续和取消
longmeidao16be7989b944
diff --git a/README.md b/README.mdindex 8657f956a..3b3c02433 100644--- a/README.md+++ b/README.md@@ -47,7 +47,7 @@ Movie demo data; see [asset credits and licenses](https://peach.video/en/credits- **Playback and history**: web and external players, subtitles, playback speed, rotation, resume and timeline previews.- **Follows and discovery**: track performer and creator updates, discover titles and manage a want list.- **Cloud download**: search by video code or submit a magnet link, then organize completed downloads into your library.-- **Library management**: manage tags, duplicates, versions and parts; metadata and watch history are stored locally.+- **Library management**: manage tags, duplicates, versions and parts; pause, resume or cancel local background tasks from the task center. Metadata and watch history are stored locally.## Download and usediff --git a/README.zh-CN.md b/README.zh-CN.mdindex a00751f51..c7fcaf980 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -47,7 +47,7 @@- **播放与记录**:网页与外部播放器、字幕、倍速、旋转、续播和时间轴预览。- **关注与发现**:订阅人物与创作者更新,发现作品,管理「想要」清单。- **云下载**:按影片编号查找或提交磁力,下载完成后整理入库。-- **馆藏管理**:管理标签、重复文件、多版本与分卷;资料和观看记录保存在本机。+- **馆藏管理**:管理标签、重复文件、多版本与分卷;在任务中心暂停、继续或取消本机后台任务。资料和观看记录保存在本机。## 下载与使用diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.mdindex e79dcc77b..b6e1d1f51 100644--- a/docs/OPERATIONS.md+++ b/docs/OPERATIONS.md@@ -210,6 +210,10 @@ Windows 测试包默认使用 `%LOCALAPPDATA%\Peach\peach-data`。首次设置### 长时任务断点续跑+任务中心为本机执行的任务提供「暂停」「继续」「取消」。暂停保留当前任务和已保存结果;在途步骤尚未停稳时显示「正在暂停」。继续沿用原任务,取消则等待所属线程和子进程退出,再显示「已取消」,保留已完成结果并停止后续工作。父任务的操作覆盖全部后继,包括列表中未展开的任务。文件替换等提交步骤先完整提交,再响应控制请求。云下载在远端执行,操作以渠道实际支持的能力为准。++播放触发的文件头修复、发现页资料读取和诊断导出同样登记在任务中心。媒体子进程可暂停、继续和取消,暂停时长不计入处理超时。支持断点恢复的任务在重启后保留暂停意图;没有恢复入口的即时任务在服务关闭后结算,不留下无法继续的排队任务。+后台任务把任务标识、处理范围、完成集合和计数保存在本机。服务重启时接回同一条任务记录,继续未完成的部分。用户暂停的任务保持暂停;明确停止会取消恢复。失败、限流或未取得的结果保留原有重试与冷却规则,不作为成功项目跳过。「停止任务」先显示正在停止,等当前在途步骤退出后结算。已登记影片、资料、预览和候选保留,停止的任务不会在重启后自动继续;可以重新发起一趟任务。命令行发起的馆藏处理被停止时返回退出码 130。diff --git a/docs/REUSE.md b/docs/REUSE.mdindex da4ca2250..29b8da98e 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -1071,6 +1071,8 @@ Python 源文件纳入 `src/peach/library_sharing.py` 与 `src/peach/library_pro## 馆藏处理控制与耗时预估+任务中心的本机控制复用 `task_run` 的运行身份、`job_recovery` 的请求和检查点、`filelock` 与原子 JSON。`task_control` 保存逐轮控制意图;`BackgroundJob`、后继和命令行执行段共用安全停点。父任务的意图沿父子关联传递,排队任务领取前核对暂停与取消。媒体子进程使用固定版本 psutil 7.2.2(BSD-3-Clause)的暂停、继续、进程身份检查和所属子进程枚举,Windows 沿用已有 kill-on-close Job Object,macOS/Linux 使用专属会话的进程组;平台语义见 [psutil API](https://psutil.readthedocs.io/stable/) 和 [Python 子进程说明](https://docs.python.org/3.14/library/subprocess.html)。psutil 从开发依赖调整为运行依赖,没有新增调度器。网络和文件提交在安全停点响应,任务只有在在途工作退出后才结算取消。+长时任务续跑复用 `job_recovery` 的本机原子记录、`BackgroundJob.checkpoint` 与 `TaskRunHandle.checkpoint`。主任务保留原 `job_id`、`run_id`、开始时间、处理范围和领域检查点;后继重排保留原进度。扫描复用现有 `os.scandir`、SQLite 批次提交、`filelock` 和 `fsutil.atomic_write_text`,保存遍历栈、文件名游标及字幕配对资料。本地资料按影片保存小份证据边车,候选成功落盘后才提交元数据完成集合;整理逐项原子保存同一批次的日志。`scrape_codes.py` 复用流式 CSV 与原始来源快照,续跑只保留已确认完成的番号,未完成番号可以重放。当前树、扫描与采集的 Git 历史,以及现有任务队列均已核对;不引入新的调度或工作流依赖。项目已固定的 APScheduler 3.11.3(MIT)负责派发,其持久 job store 记录调度任务,不能保存函数执行到哪一条影片或来源页,见[上游调度说明](https://apscheduler.readthedocs.io/en/3.x/userguide.html#adding-jobs)。结果替换沿用 Python 3.14 标准库 [`os.replace`](https://docs.python.org/3.14/library/os.html#os.replace)(PSF),锁沿用项目固定的 `filelock`,没有新增运行时体积或平台要求。隔离实证覆盖目录与目录内批次中断、关注回抓游标、固定来源集合、原任务标识与计数、候选 CSV 保留及同批整理日志;不读取真实媒体、不访问外部采集来源,也不写真实 ledger。diff --git a/pyproject.toml b/pyproject.tomlindex 3ca77977b..b7993773b 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -44,6 +44,7 @@ dependencies = ["m3u8==6.0.0","pillow==13.0.0","protobuf==7.36.2",+ "psutil==7.2.2","pystray==0.19.5","pydantic==2.14.2","resvg-py==0.5.0",@@ -68,11 +69,9 @@ peach = "peach.error_reporting:cli_main"peach-tray = "peach.error_reporting:tray_main"[project.optional-dependencies]-# psutil 给 `scripts/agent_worktree.py` 查工作树里的残留进程:当前目录、父进程、CPU 与内存。dev = ["filelock==4.2.4","httpx2==2.16.0",- "psutil==7.2.2","ruff==0.17.3","seiso==0.4.0",]diff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex ee27574d7..35d7a5916 100644--- a/scripts/test_runner.py+++ b/scripts/test_runner.py@@ -65,7 +65,7 @@ SCOPES: dict[str, tuple[str, ...]] = {# 任务中心的两个文件跟着 `test_jobs.py` 走:`jobs.py` 与 `task_runs.py` 是同一条# 接线的两端,改哪一端都要两边一起验。"media": ("test_external_playback.py", "test_runtime_consistency.py", "test_endcard.py", "test_fastapi_api.py", "test_jobs.py",- "test_task_runs.py", "test_followups.py", "test_task_center_integration.py", "test_face_models.py",+ "test_task_runs.py", "test_followups.py", "test_task_center_integration.py", "test_task_control.py", "test_face_models.py","test_frame_capture.py", "test_timeline_sheets.py", "test_processing_control.py", "test_processing_traffic.py", "test_processing_inventory.py","test_web_timeline_thumbnails.py", "test_timeline_sources.py", "test_bif.py","test_interaction.py", "test_media.py", "test_mp4repair.py",@@ -119,7 +119,7 @@ SCOPES: dict[str, tuple[str, ...]] = {"test_windows_update.py", "test_release_updates.py", "test_automatic_updates.py", "test_standalone_update.py", "test_upgrade_repairs.py", "test_certs.py", "test_config.py","test_fsutil.py", "test_desktop_settings.py", "test_desktop_installer.py", "test_data_storage.py","test_job_status.py", "test_jobs.py", "test_task_runs.py", "test_followups.py", "test_update_tasks.py",- "test_task_center_integration.py", "test_reference_updates.py",+ "test_task_center_integration.py", "test_task_control.py", "test_reference_updates.py","test_repo_hygiene.py", "test_seed_pack.py", "test_seed_followup.py","test_review_csv.py", "test_jav_code_domain.py", "test_organize.py","test_link_repair.py", "test_tag_management.py",@@ -206,6 +206,8 @@ AUTO_SCOPE_FILES: dict[str, tuple[str, ...]] = {"src/peach/menubar.py": ("sync", "tooling"),# 托盘子服务与隧道的 cloudflared 共用这份 Job Object;两边的测试都要跑到。"src/peach/process_job.py": ("tooling", "sync"),+ 'src/peach/task_control.py': ('catalog', 'media', 'metadata', 'follow', 'sync', 'tooling', 'web'),+ 'tests/test_task_control.py': ('media', 'tooling'),# 托盘重启的实现由 `test_restart_windows_tray.py` 验,模块名推不出来。"src/peach/windows_restart.py": ("tooling",),# 托盘「重启服务」按路径拉起这个脚本(`--source --force`),托盘测试也要跑到。diff --git a/src/peach/api.py b/src/peach/api.pyindex f7a0f70a4..0a35167c5 100644--- a/src/peach/api.py+++ b/src/peach/api.py@@ -407,7 +407,7 @@ def create_app(edge=COVER_SMALL_THUMB_EDGE,quality=COVER_SMALL_THUMB_QUALITY)transcode_service = TranscodeService(resolver, settings.transcode_root, state_root=settings.follow_state_root)- header_repairs = HeaderRepairStore(settings.transcode_root, resolver)+ header_repairs = HeaderRepairStore(settings.transcode_root, resolver, runs=contract.task_runs)hls_plan_executor = ThreadPoolExecutor(max_workers=2, thread_name_prefix="PeachHlsPlan",)@@ -553,6 +553,7 @@ def create_app(# 死链检查和资源对账的后台线程是 daemon,本来挡不住进程退出;这里显式收# 一下,免得在途的那一轮在解释器拆卸期间还继续查库、往没人读的状态里写。contract.stop_background_jobs()+ header_repairs.stop()from . import face_modelsface_models.detach(contract.task_runs)if mdns is not None:diff --git a/src/peach/diagnostic_exports.py b/src/peach/diagnostic_exports.pyindex dc5eaa1a4..4cdc72385 100644--- a/src/peach/diagnostic_exports.py+++ b/src/peach/diagnostic_exports.py@@ -9,10 +9,10 @@ from .scraping_diagnostics import ExportCancelled, selected_codesclass DiagnosticExports:- def __init__(self, config):+ def __init__(self, config, *, runs=None):self.config = configself.root = config.directory('generated') / 'diagnostic-exports'- self.job = BackgroundJob('PeachDiagnosticExport')+ self.job = BackgroundJob('PeachDiagnosticExport', task_key='diagnostic-export', runs=runs)self.lock = threading.Lock()self.cancelled = threading.Event()@@ -77,6 +77,8 @@ class DiagnosticExports:if state['status'] in ('running', 'cancelling'):self.cancelled.set()state.update(status='cancelling', stage='正在取消导出')+ if self.job.runs is not None:+ self.job.stop(resume=False)return self.snapshot()def download(self, identity):@@ -97,5 +99,6 @@ def manager(request):with _MANAGER_LOCK:state = request.app.stateif not hasattr(state, 'diagnostic_exports'):- state.diagnostic_exports = DiagnosticExports(settings_file.load_config())+ state.diagnostic_exports = DiagnosticExports(settings_file.load_config(),+ runs=state.web_contract.task_runs)return state.diagnostic_exportsdiff --git a/src/peach/follow_discovery.py b/src/peach/follow_discovery.pyindex 1dd864f0c..38353b9d8 100644--- a/src/peach/follow_discovery.py+++ b/src/peach/follow_discovery.py@@ -14,6 +14,7 @@ import reimport timeimport urllib.parsefrom concurrent.futures import ThreadPoolExecutor+from contextvars import copy_contextfrom dataclasses import dataclass, field, replacefrom pathlib import Path@@ -765,5 +766,7 @@ def _tag_types(connector, names: list[str]) -> dict[str, str]:if pending:with ThreadPoolExecutor(max_workers=min(TAG_TYPE_WORKERS,len(pending))) as pool:- list(pool.map(ask, pending))+ futures = [pool.submit(copy_context().run, ask, name) for name in pending]+ for future in futures:+ future.result()return {name: _TAG_TYPES[name] for name in names if name in _TAG_TYPES}diff --git a/src/peach/followups.py b/src/peach/followups.pyindex 4968697d4..9e1ea3ed1 100644--- a/src/peach/followups.py+++ b/src/peach/followups.py@@ -255,7 +255,13 @@ class FollowupRunner:handle.finish("failed", error=f"没有登记 {run.task_key} 这种后继")returntry:- summary = followup_type.run(self.contract, run.followup_key, handle)+ from .task_control import bind, checkpoint, Cancelled+ with bind(self.store, run.id, recoverable=True):+ summary = followup_type.run(self.contract, run.followup_key, handle)+ checkpoint()+ except Cancelled:+ handle.finish('cancelled', summary={'cancelled_by_user': True})+ returnexcept JobDeferred as error:self.store.suspend(run.id, label=str(error), paused_for_update=False)return errordiff --git a/src/peach/frame_capture.py b/src/peach/frame_capture.pyindex c3ef80417..257d7c18a 100644--- a/src/peach/frame_capture.py+++ b/src/peach/frame_capture.py@@ -12,7 +12,8 @@ import reimport subprocessimport timefrom pathlib import Path-from .processing_control import checkpoint, ffmpeg_options+from .processing_control import checkpoint, deadline_after, ffmpeg_options+from .task_control import run as run_task_processfrom PIL import Image@@ -64,7 +65,7 @@ def capture_frame(ffmpeg: str, path: str, timestamp: float, destination: Path, **ffmpeg_options(), str(destination),]try:- completed = subprocess.run(command, capture_output=True, timeout=timeout,+ completed = run_task_process(command, capture_output=True, timeout=timeout,creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0)except subprocess.TimeoutExpired as error:media_statistics(path, error.stderr)@@ -96,7 +97,7 @@ def capture_with_retry(ffmpeg: str, path: str, timestamp: float, destination: Pafrom .smb_media import input_urlpath = input_url(path)from .hardware_transcode import frame_decode_options- deadline = time.monotonic() + timeout+ deadline = deadline_after(timeout)hardware = frame_decode_options(ffmpeg, path) if decode_options is None else decode_optionsattempts, detail, ok = [], {}, Falsefor options in ((hardware, ()) if hardware else ((),)):@@ -140,7 +141,7 @@ def tile_frames(ffmpeg: str, pattern: str, columns: int, rows: int, destination:destination.unlink(missing_ok=True)from .error_reporting import subprocess_failuretry:- completed = subprocess.run(+ completed = run_task_process([ffmpeg, "-y", "-v", "error", *options, "-i", pattern,"-filter_complex", f"tile={int(columns)}x{int(rows)}", "-q:v", "4",*ffmpeg_options(), str(destination)],diff --git a/src/peach/http.py b/src/peach/http.pyindex 67bd01b26..1d3d7ec1f 100644--- a/src/peach/http.py+++ b/src/peach/http.py@@ -20,6 +20,7 @@ import httpxfrom curl_cffi import requests as curl_requestsfrom curl_cffi.requests.exceptions import CurlErrorfrom . import peach_proxy+from .task_control import controlled, checkpoint#: 只在本机或局域网里有意义的名字后缀。外面递进来的地址落到它们上,只可能是想让#: Peach 替人去探内网。@@ -212,6 +213,7 @@ class HttpxTransport:with self._client_lock:self._client = value+ @controlleddef __call__(self,request: HttpRequest,@@ -280,6 +282,7 @@ def _bounded_body(chunks, max_bytes: int) -> bytes:kept: list[bytes] = []total = 0for chunk in chunks:+ checkpoint()remaining = max_bytes + 1 - totalif remaining <= 0:break@@ -314,6 +317,7 @@ class CurlCffiTransport:**peach_proxy.curl_options())return self._session+ @controlleddef __call__(self,request: HttpRequest,@@ -334,6 +338,7 @@ class CurlCffiTransport:allow_redirects=True,) as response:for chunk in response.iter_content():+ checkpoint()remaining = max_bytes + 1 - totalif remaining <= 0:breakdiff --git a/src/peach/jav_discovery_metadata.py b/src/peach/jav_discovery_metadata.pyindex bb084416c..fdd98d3cd 100644--- a/src/peach/jav_discovery_metadata.py+++ b/src/peach/jav_discovery_metadata.py@@ -41,14 +41,14 @@ def source_number(value):class DiscoveryMetadata:- """缓存只承载来源资料;后台任务不写账本或 task_run。"""+ """缓存只承载来源资料;任务进度与控制沿用任务中心。"""- def __init__(self, path: Path, *, api=PUBLIC_API, clock=time.time):+ def __init__(self, path: Path, *, api=PUBLIC_API, clock=time.time, runs=None):path = Path(path)self.path = path.with_name(f'{path.stem}.javdb-{RULE}{path.suffix}')self.api, self.clock = api, clockself.lock = threading.RLock()- self.job = BackgroundJob("jav-discovery-metadata")+ self.job = BackgroundJob('jav-discovery-metadata', runs=runs)self.last_job = Noneself.records = OrderedDict()self._load()@@ -59,7 +59,7 @@ class DiscoveryMetadata:saved = {}if saved.get('javdb_rule') != RULE:saved = {}- if saved.get('status') == 'running':+ if saved.get('status') == 'running' and runs is None:self.ensure(saved.get('codes') or [], _resume=saved)elif saved.get('job_id'):self.last_job = saved@@ -172,7 +172,8 @@ class DiscoveryMetadata:from .job_recovery import current_job_idtoken = current_job_id.set(_resume.get('job_id')) if _resume else Nonetry:- result = self.job.start(work, initial=initial, restart=bool(snapshot))+ result = self.job.start(work, initial=initial, restart=bool(snapshot),+ recovery={'codes': codes, 'refresh': refresh})self._save_job()return resultfinally:@@ -181,6 +182,10 @@ class DiscoveryMetadata:def _run_batch(self, current_id, *, initial, pending, refresh, budget, previous_elapsed, started,successful, attempted, failures):+ from .task_control import CURRENT+ control = CURRENT.get()+ def elapsed():+ return previous_elapsed + time.monotonic() - started - (control.paused_seconds if control is not None else 0.0)completed = initial['completed']stop_reason = ""with public_cache_scope(self.path.parent / 'jav-public'), self.api.request_budget(budget):@@ -205,9 +210,9 @@ class DiscoveryMetadata:if code not in attempted:completed += 1attempted.add(code)- if not self.job.update(current_id, completed=completed, failed=len(failures),+ if not self.job.checkpoint(current_id, completed=completed, failed=len(failures),completed_codes=sorted(successful), attempted_codes=sorted(attempted), failed_codes=sorted(failures),- active_seconds=previous_elapsed + time.monotonic() - started,+ active_seconds=elapsed(),requests=budget.requests, bytes=budget.bytes, batch=(completed + 9) // 10):returnself._save_job()@@ -215,7 +220,7 @@ class DiscoveryMetadata:breakself.job.update(current_id, status="stopped" if stop_reason else "complete", stop_reason=stop_reason,completed=completed, failed=len(failures), requests=budget.requests, bytes=budget.bytes,- active_seconds=previous_elapsed + time.monotonic() - started)+ active_seconds=elapsed())self._save_job()def stop(self):@@ -226,8 +231,10 @@ class DiscoveryMetadata:snapshot = self.job.snapshot() or self.last_jobif not snapshot or (job_id and snapshot["job_id"] != job_id):return snapshot- self.job.stop()- snapshot.update(status="stopped", stop_reason="cancelled")+ self.job.stop(resume=False)+ live = self.job.snapshot() or snapshot+ snapshot.update(status='cancelled' if live.get('status') == 'cancelled' else 'cancelling',+ stop_reason='cancelled')self.last_job = snapshotwith self.lock:atomic_write_text(self.job_path, json.dumps(snapshot, ensure_ascii=False))@@ -237,5 +244,6 @@ class DiscoveryMetadata:def discovery_metadata(contract):with contract.cache_lock:if not hasattr(contract, "jav_discovery_metadata"):- contract.jav_discovery_metadata = DiscoveryMetadata(contract.cover_root.parent / "jav-discovery-metadata.json")+ contract.jav_discovery_metadata = DiscoveryMetadata(+ contract.cover_root.parent / 'jav-discovery-metadata.json', runs=contract.task_runs)return contract.jav_discovery_metadatadiff --git a/src/peach/javdb_public.py b/src/peach/javdb_public.pyindex db27958a6..c5c8adee1 100644--- a/src/peach/javdb_public.py+++ b/src/peach/javdb_public.py@@ -139,12 +139,16 @@ class PublicRequestBudget:bytes: int = 0started: float = 0stop_reason: str = ""+ paused_at_start: float = 0.0def check(self):+ from .task_control import CURRENT+ control = CURRENT.get()+ paused = control.paused_seconds - self.paused_at_start if control is not None else 0.0for reason, exhausted in (("request_budget", self.requests >= self.max_requests),("byte_budget", self.bytes >= self.max_bytes),- ("time_budget", time.monotonic() - self.started >= self.max_seconds)):+ ("time_budget", time.monotonic() - self.started - paused >= self.max_seconds)):if exhausted:self.stop_reason = reasonraise PublicBudgetExceeded("本轮作品资料预算已用完")@@ -183,6 +187,9 @@ class PublicAPI:@contextmanagerdef request_budget(self, budget: PublicRequestBudget):budget.started = time.monotonic()+ from .task_control import CURRENT+ control = CURRENT.get()+ budget.paused_at_start = control.paused_seconds if control is not None else 0.0token = self.request_context.set(budget)try:yield budgetdiff --git a/src/peach/jobs.py b/src/peach/jobs.pyindex 3b8d1abf3..d6de56d06 100644--- a/src/peach/jobs.py+++ b/src/peach/jobs.py@@ -375,6 +375,8 @@ class BackgroundJob:退出时把进度同步进 `task_run`,写库在锁外:那一步要拿数据库的写锁,套在本类的锁里面就多了一组取锁顺序,而进度本来不需要和状态原子。节流由 store 做。"""+ from .task_control import checkpoint+ checkpoint()if job_id in self._recoverable:from .update_tasks import check_pausecheck_pause(self._database_path())@@ -583,6 +585,17 @@ class BackgroundJob:"""from .update_tasks import _mutex, state_fordb = self._database_path()+ current = self.snapshot() or {}+ run_id = self._run_ids.get(current.get(self.id_key))+ if db is not None and run_id is not None:+ from . import task_control+ if not resume:+ task_control.request(self.runs, run_id, 'cancel')+ thread = self.thread+ if thread is not None and thread is not threading.current_thread():+ thread.join(timeout)+ return+ task_control.shutdown(db, run_id)with _mutex(state_for(db)) if db is not None else nullcontext():if not resume and db is not None:from .job_recovery import cancel@@ -633,10 +646,19 @@ class BackgroundJob:parent_run = current_run.set(None)parent_job = current_job_id.set(None)context = current_db.set(self._database_path() if job_id in self._recoverable else None)+ from .task_control import Cancelled as TaskCancelledtry:from .update_tasks import check_pause- check_pause(current_db.get())- fn(job_id)+ from .task_control import bind, checkpoint+ with bind(self.runs, self._run_ids.get(job_id), recoverable=job_id in self._recoverable) if self.runs is not None else nullcontext():+ check_pause(current_db.get())+ fn(job_id)+ checkpoint()+ except TaskCancelled:+ with self.lock:+ if self.state is not None and self.state.get(self.id_key) == job_id:+ self.state.update(status='cancelled', outcome='cancelled', error='',+ followups=[], completed_at=time.time())except JobPaused:with self.lock:if self.state is not None and self.state.get(self.id_key) == job_id:diff --git a/src/peach/local_poster.py b/src/peach/local_poster.pyindex 1b42ddbd3..ee47cca13 100644--- a/src/peach/local_poster.py+++ b/src/peach/local_poster.py@@ -10,6 +10,7 @@ import sysimport tempfilefrom PIL import Image+from .task_control import run as run_task_processTIMEOUT_SECONDS = 20.0MAX_BYTES = 32 * 1024 * 1024@@ -26,7 +27,7 @@ def read_jpeg(source: Path, *, isolated=True) -> tuple[bytes, tuple[int, int]]:else [sys.executable, '-m', 'peach.local_poster'])with tempfile.TemporaryDirectory(prefix='peach-local-poster-') as temporary:output = Path(temporary).resolve() / 'poster.jpg'- result = subprocess.run([*command, str(source), str(output)], stdin=subprocess.DEVNULL,+ result = run_task_process([*command, str(source), str(output)], stdin=subprocess.DEVNULL,stdout=subprocess.PIPE if CURRENT.get() is not None else subprocess.DEVNULL,stderr=subprocess.DEVNULL, timeout=TIMEOUT_SECONDS,creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0)diff --git a/src/peach/media_probe.py b/src/peach/media_probe.pyindex 825463035..f946c3eff 100644--- a/src/peach/media_probe.py+++ b/src/peach/media_probe.py@@ -58,12 +58,13 @@ def context_fields(width: int, height: int, duration: float) -> tuple[str | Nonedef probe_file(ffprobe: str, path: str, timeout: float = TIMEOUT_SECONDS) -> tuple:+ from .task_control import run as run_task_processfrom .processing_traffic import CURRENT as TRAFFIC, media_statisticsif skip_background_read(path):raise ValueError('STRM 和 ISO 不执行视频探测')from .smb_media import input_urlpath = input_url(path)- result = subprocess.run(+ result = run_task_process([ffprobe, "-v", "verbose" if TRAFFIC.get() is not None else "error", "-rw_timeout", "8000000","-select_streams", "v:0", "-show_entries",diff --git a/src/peach/metadata_amane.py b/src/peach/metadata_amane.pyindex 6e763ed8d..1d1145558 100644--- a/src/peach/metadata_amane.py+++ b/src/peach/metadata_amane.py@@ -36,6 +36,7 @@ from .sources.base import (COOLDOWN_ACTIONS, REASON_KINDS, FailureReason, SiteCoSourceFailure)from .user_agent import USER_AGENTfrom .settings_file import PROJECT_ROOT+from .task_control import run as run_task_processAMANE_REPOSITORY = "https://github.com/sqzw-x/amane"AMANE_LICENSE = "GPL-3.0"@@ -270,7 +271,7 @@ def bundle_problem(root: Path = BRIDGE_ROOT) -> str:return ""-def rebuild(tools_root: Path, *, runner: Runner = subprocess.run, timeout: int = 900,+def rebuild(tools_root: Path, *, runner: Runner = run_task_process, timeout: int = 900,root: Path = BRIDGE_ROOT, proxy_options: Mapping[str, object] | None = None,force: bool = True) -> dict:"""重建桥 venv,返回给设置页的回执。首次要下载约 98 MB,之后只校验。"""@@ -338,7 +339,7 @@ def _rebuild(tools_root, *, runner, timeout, root, proxy_options):**describe(tools_root, root=root)}-def ensure(tools_root: Path, *, runner: Runner = subprocess.run,+def ensure(tools_root: Path, *, runner: Runner = run_task_process,proxy_options: Mapping[str, object] | None = None, secrets_root: Path | None = None,progress=lambda: None) -> None:"""按锁准备一次独立运行环境;安装失败由调用方保留尚未处理的范围。"""@@ -446,11 +447,11 @@ class AmaneBridge:python: Pathscript: Path | None = BRIDGE_SCRIPTtimeout: int = DEFAULT_TIMEOUT- runner: Runner = subprocess.run+ runner: Runner = run_task_process@classmethoddef create(cls, tools_root: Path, *, timeout: int = DEFAULT_TIMEOUT,- runner: Runner = subprocess.run) -> "AmaneBridge":+ runner: Runner = run_task_process) -> "AmaneBridge":packaged = packaged_runtime()if packaged:return cls(packaged[0], script=None if packaged[1] == "executable" else BRIDGE_SCRIPT,diff --git a/src/peach/mp4recover.py b/src/peach/mp4recover.pyindex d8ef49cc8..3ac7ed920 100644--- a/src/peach/mp4recover.py+++ b/src/peach/mp4recover.py@@ -22,6 +22,7 @@ from pathlib import Path, PureWindowsPathfrom .mp4repair import RepairUnavailable, _top_levelfrom .ffmpeg import bundled_tools_root+from .task_control import run as run_task_processUNTRUNC_ENV = "PEACH_UNTRUNC"#: 一部坏片最多试几个参照。每试一个都要把坏片完整读一遍,网盘上是实打实的流量。@@ -89,7 +90,7 @@ def pick_references(broken: str, candidates: list[str], limit: int = REFERENCE_Ldef _run(command: list[str], timeout: float) -> subprocess.CompletedProcess:- return subprocess.run(command, capture_output=True, stdin=subprocess.DEVNULL, timeout=timeout,+ return run_task_process(command, capture_output=True, stdin=subprocess.DEVNULL, timeout=timeout,creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0)diff --git a/src/peach/mp4repair.py b/src/peach/mp4repair.pyindex cc94d6ff4..16bd18673 100644--- a/src/peach/mp4repair.py+++ b/src/peach/mp4repair.py@@ -22,6 +22,7 @@ from pathlib import Pathfrom .smb_media import input_urlfrom .mp4index import _iter_boxes+from .task_control import run as run_task_processLOGGER = logging.getLogger(__name__)@@ -155,7 +156,7 @@ def _display_order(ffprobe: Path, source: Path, decode_times: list[int]) -> list"-show_entries", "frame=pts", "-of", "csv=p=0", input_url(source),)try:- completed = subprocess.run(command, capture_output=True, timeout=PROBE_TIMEOUT_SECONDS,+ completed = run_task_process(command, capture_output=True, timeout=PROBE_TIMEOUT_SECONDS,creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0)except (OSError, subprocess.TimeoutExpired) as exc:raise RepairUnavailable(f"ffprobe 没跑完:{exc}") from exc@@ -532,7 +533,7 @@ class HeaderRepairStore:所以只在后台算、一次只算一部,算不出来就记下来别再试——调用方照旧走转码分片。"""- def __init__(self, root: Path, resolver, *, max_concurrent: int = 1, cached: int = 4):+ def __init__(self, root: Path, resolver, *, max_concurrent: int = 1, cached: int = 4, runs=None):self.root = Path(root)self.resolver = resolverself._slots = threading.Semaphore(max(1, max_concurrent))@@ -543,6 +544,8 @@ class HeaderRepairStore:self._cached: dict[str, RepairedHeader] = {}self._cache_size = max(1, cached)self._guard = threading.Lock()+ self.runs = runs+ self._jobs = {}def _name(self, asset_id: int, source: Path) -> str | None:try:@@ -584,10 +587,28 @@ class HeaderRepairStore:with self._guard:if name in self._running or name in self._failed:return- threading.Thread(- target=self.repair_now, args=(asset_id, source),- name=f"PeachMp4Header-{asset_id}", daemon=True,- ).start()+ previous = self._jobs.get(name)+ if previous is not None:+ state = previous.snapshot() or {}+ if state.get('status') in ('running', 'cancelled'):+ return+ from .jobs import BackgroundJob+ job = BackgroundJob(f'PeachMp4Header-{asset_id}', task_key='mp4-header-repair',+ mutex_key=f'mp4-header-repair:{name}', runs=self.runs)+ self._jobs[name] = job++ def work(job_id):+ made = self.repair_now(asset_id, source)+ job.update(job_id, status='complete' if made else 'failed',+ repaired=int(made), error='' if made else '播放文件头未能修复')++ job.start(work, initial={'stage': '读取帧时间戳', 'message': source.name, 'asset_id': asset_id})++ def stop(self):+ with self._guard:+ jobs = list(self._jobs.values())+ for job in jobs:+ job.stop()def repair_now(self, asset_id: int, source: Path) -> bool:"""当场算一份头并存下来。已经有、正在算或上次算不出来都返回 False。"""@@ -600,8 +621,14 @@ class HeaderRepairStore:return Falseself._running.add(name)try:- with self._slots:+ from .task_control import checkpoint+ while not self._slots.acquire(timeout=.1):+ checkpoint()+ try:+ checkpoint()write_sidecar(self.root / name, repaired_header(source, ffprobe.path))+ finally:+ self._slots.release()for stale in self.root.glob(f"{asset_id}-*{SIDECAR_SUFFIX}"):if stale.name != name:stale.unlink(missing_ok=True)diff --git a/src/peach/processing_control.py b/src/peach/processing_control.pyindex 5f171df2e..46a03be2d 100644--- a/src/peach/processing_control.py+++ b/src/peach/processing_control.py@@ -102,6 +102,8 @@ def resume_fields(state, values):def checkpoint(kind='work'):+ from .task_control import checkpoint as task_checkpoint+ task_checkpoint()control = CURRENT.get()if control is not None:control.checkpoint(kind)@@ -163,11 +165,22 @@ class ActiveDeadline(float):def deadline_after(seconds):- value, control = time.monotonic() + seconds, CURRENT.get()+ from .task_control import CURRENT as TASK_CONTROL+ value, control = time.monotonic() + seconds, CURRENT.get() or TASK_CONTROL.get()return ActiveDeadline(value, control) if control is not None else valueclass ProcessingControl:+ @property+ def paused_seconds(self):+ from .task_control import CURRENT as TASK_CONTROL+ control = TASK_CONTROL.get() if CURRENT.get() is self else None+ return self._paused_seconds + (control.paused_seconds if control is not None else 0.0)++ @paused_seconds.setter+ def paused_seconds(self, value):+ self._paused_seconds = value+def __init__(self, path):self.path = pathself.lock = threading.RLock()@@ -267,8 +280,13 @@ class ProcessingControl:def checkpoint(self, kind='work'):from .update_tasks import check_pause+ from .task_control import CURRENT as TASK_CONTROL+ task = TASK_CONTROL.get()started = None+ generic_started = 0.0while True:+ from .task_control import checkpoint as task_checkpoint+ task_checkpoint()check_pause(self.db_path)self.refresh()self.check_item()@@ -280,12 +298,14 @@ class ProcessingControl:if paused:if started is None:started = time.monotonic()+ generic_started = task.paused_seconds if task is not None else 0.0self.publish(status='paused', speed_mode=mode)self.event.wait(0.25)continueif started is not None:spent = time.monotonic() - started- self.paused_seconds += spent+ generic_spent = task.paused_seconds - generic_started if task is not None else 0.0+ self._paused_seconds += max(0.0, spent - generic_spent)self.publish(status='running', speed_mode=mode, resumed_after=spent)started = None# 控制只作用于当前馆藏任务;在单项 I/O 之间留出空档。diff --git a/src/peach/repository.py b/src/peach/repository.pyindex 3f8df0bac..617887467 100644--- a/src/peach/repository.py+++ b/src/peach/repository.py@@ -2,7 +2,7 @@ from __future__ import annotationsimport sqlite3import threading-from contextlib import contextmanager+from contextlib import contextmanager, nullcontextfrom dataclasses import dataclassfrom pathlib import Path@@ -67,6 +67,13 @@ class LedgerDatabase:等不到抛 `sqlite3.OperationalError`,与 SQLite 自己等超时是同一种异常。不传则进程内一直排队、SQLite 等 30 秒。"""+ from .task_control import operation+ with operation() if notify else nullcontext():+ with self._write_transaction(notify=notify, timeout=timeout) as connection:+ yield connection++ @contextmanager+ def _write_transaction(self, *, notify: bool, timeout: float | None):if not self.write_lock.acquire(timeout=-1 if timeout is None else timeout):raise sqlite3.OperationalError("database is locked")try:diff --git a/src/peach/routes_api.py b/src/peach/routes_api.pyindex eefcc1498..3756249cd 100644--- a/src/peach/routes_api.py+++ b/src/peach/routes_api.py@@ -35,6 +35,7 @@ from .platform import is_unmapped, translate_ledger_pathfrom .providers import ProviderUnavailablefrom .routes_auth import require_authfrom .task_runs import task_label+from .task_control import Cancelled as TaskCancelledfrom .taste_history import analyze_history, import_history_exports, write_manifestrouter = APIRouter()@@ -248,6 +249,33 @@ def task_run_detail(request: Request, run_id: int,return JSONResponse({"error": str(exc.args[0])}, status_code=404)[email protected]('/api/tasks/{run_id}/control')+def task_run_control(request: Request, run_id: int, body: dict = Body(default_factory=dict),+ _args: dict[str, str] = Depends(require_auth)):+ from . import task_control+ contract = request.app.state.web_contract+ try:+ run = contract.task_runs.get(run_id)+ if run is not None and run.active and run.task_key == 'library-processing':+ from .web_library_processing import _current, w_library_processing+ current = _current(contract)+ if current.get('run_id') != run_id:+ raise ValueError('任务已变化,请刷新后重试')+ if not contract.task_runs.enabled or run.host != contract.task_runs.host:+ raise PermissionError('请在执行这轮任务的写入端操作')+ w_library_processing(contract, {'action': body.get('action'), 'job_id': current.get('job_id')})+ else:+ task_control.request(contract.task_runs, run_id, body.get('action'))+ contract.followups.wake()+ return web_tasks.q_task(contract, run_id)+ except KeyError as exc:+ return JSONResponse({'error': str(exc.args[0])}, status_code=404)+ except PermissionError as exc:+ return JSONResponse({'error': str(exc)}, status_code=403)+ except ValueError as exc:+ return JSONResponse({'error': str(exc)}, status_code=409)++@router.post(push_discovery.WEBHOOK_PATH, status_code=204)def clouddrive_inbox(request: Request, body: dict[str, Any] = Body(default_factory=dict)):"""CloudDrive2 的文件变更通知。@@ -330,6 +358,8 @@ def api_get(request: Request, route: str, args: dict[str, str] = Depends(requirereturn payloadexcept TaskRunConflict as exc:return _conflict(exc)+ except TaskCancelled:+ return JSONResponse({'error': '任务已取消,已保存的结果保留'}, status_code=409)except UpdateBusy as exc:return JSONResponse({'error': 'update in progress', 'message': str(exc)}, status_code=409)except FolderRuleConflict as exc:@@ -370,6 +400,8 @@ def api_post(try:return web_contract.dispatch_api_post(request.app.state.web_contract, route_path, body)+ except TaskCancelled:+ return JSONResponse({'error': '任务已取消,已保存的结果保留'}, status_code=409)except TaskRunConflict as exc:return _conflict(exc)except UpdateBusy as exc:diff --git a/src/peach/scraping_access.py b/src/peach/scraping_access.pyindex d5ef465f1..567525495 100644--- a/src/peach/scraping_access.py+++ b/src/peach/scraping_access.py@@ -413,6 +413,11 @@ class SourceTransport:self.requests = self.bytes = 0def __call__(self, request: HttpRequest, timeout: float, max_bytes: int):+ from .task_control import operation+ with operation():+ return self._controlled_request(request, timeout, max_bytes)++ def _controlled_request(self, request: HttpRequest, timeout: float, max_bytes: int):for _ in range(6):from .processing_control import checkpointcheckpoint('network')diff --git a/src/peach/task_control.py b/src/peach/task_control.pynew file mode 100644index 000000000..2324307f4--- /dev/null+++ b/src/peach/task_control.py@@ -0,0 +1,380 @@+"""任务中心的本机控制意图、安全停点和所属媒体子进程。"""+from __future__ import annotations++import json+import os+import signal+import subprocess+import threading+import time+import uuid+from functools import wraps+from contextlib import contextmanager+from contextvars import ContextVar++import psutil++from .fsutil import atomic_write_text+from .update_tasks import state_for++CURRENT = ContextVar('peach_task_control', default=None)+_LIVE = {}+_LOCK = threading.RLock()+++class Cancelled(KeyboardInterrupt):+ """用户取消整轮任务;领域内的单项失败处理不能吞掉取消。"""+++def _root(db):+ return state_for(db).parent / 'task-controls'+++def _read(path):+ try:+ return json.loads(path.read_text(encoding='utf-8'))+ except FileNotFoundError:+ return {}+++def _key(db, run_id):+ return (str(db.resolve()), run_id)+++def intent(db, run_id, ancestors=()):+ commands = [_read(_root(db) / f'{identity}.request.json')+ for identity in dict.fromkeys((run_id, *ancestors)) if identity is not None]+ cancelled = [command for command in commands if command.get('action') == 'cancel']+ if cancelled:+ commands = cancelled+ return max(commands, key=lambda value: value.get('at', 0), default={})+++def requested(db, run_id, ancestors=()):+ return intent(db, run_id, ancestors).get('action', 'resume')+++def projection(store, run):+ if not store.enabled or run.host != store.host:+ return None+ children = []+ if not run.active:+ with store.database.read_connection() as connection:+ rows = connection.execute(+ 'WITH RECURSIVE family(id) AS (SELECT id FROM task_run WHERE parent_run_id=? '+ 'UNION ALL SELECT t.id FROM task_run t JOIN family f ON t.parent_run_id=f.id) '+ "SELECT id FROM task_run WHERE id IN (SELECT id FROM family) AND status IN ('pending','running')",+ (run.id,)).fetchall()+ children = [store.get(row[0]) for row in rows]+ if not children:+ return None+ command = intent(store.database.db_path, run.id, (run.parent_run_id, run.root_run_id))+ action = command.get('action', 'resume')+ observed = _read(_root(store.database.db_path) / f'{run.id}.observed.json')+ if action == 'cancel':+ state, actions = 'cancelling', []+ elif action == 'pause':+ acknowledged = observed.get('command') == command.get('id') and observed.get('state') == 'paused'+ if not run.active:+ acknowledged = bool(children) and all(+ (projection(store, child) or {}).get('state') == 'paused' for child in children)+ state = 'paused' if run.status == 'pending' or acknowledged else 'pausing'+ actions = ['resume', 'cancel']+ else:+ state, actions = 'running', ['pause', 'cancel']+ return {'state': state, 'actions': actions}+++def request(store, run_id, action):+ from .update_tasks import _mutex+ with _mutex(state_for(store.database.db_path)):+ return _request(store, run_id, action)+++def _request(store, run_id, action):+ if action not in ('pause', 'resume', 'cancel'):+ raise ValueError('请选择暂停、继续或取消')+ run = store.get(run_id)+ if run is None:+ raise KeyError('任务未取得,请刷新后重试')+ if not store.enabled or run.host != store.host:+ raise PermissionError('请在执行这轮任务的写入端操作')+ if projection(store, run) is None:+ raise ValueError('这轮任务已经结束')+ db = store.database.db_path+ current = requested(db, run.id, (run.parent_run_id, run.root_run_id))+ if current == 'cancel':+ if action != 'cancel':+ raise ValueError('任务正在取消,不能再暂停或继续')+ return run+ if current == action:+ return run+ # 父任务的控制覆盖已经派出的后继;尚未派出的工作在父任务结算前经过停点。+ with store.database.read_connection() as connection:+ descendants = connection.execute(+ 'WITH RECURSIVE family(id) AS (SELECT ? UNION ALL '+ 'SELECT t.id FROM task_run t JOIN family f ON t.parent_run_id=f.id) '+ "SELECT id FROM task_run WHERE id IN (SELECT id FROM family) AND status IN ('pending','running')",+ (run_id,)).fetchall()+ command = {'id': uuid.uuid4().hex, 'action': action, 'at': time.time_ns()}+ atomic_write_text(_root(db) / f'{run.id}.request.json', json.dumps(command))+ for row in descendants:+ identity = int(row[0])+ child = store.get(identity)+ if child is None or child.host != store.host:+ continue+ if action != 'cancel' and requested(db, child.id, (child.parent_run_id, child.root_run_id)) == 'cancel':+ continue+ atomic_write_text(_root(db) / f'{identity}.request.json', json.dumps(command))+ if child.status == 'pending' and action == 'cancel':+ store.finish(identity, 'cancelled', summary={'cancelled_by_user': True})+ from .job_recovery import read, cancel+ saved = read(db, child.task_key)+ if saved.get('run_id') == identity:+ cancel(db, child.task_key)+ return store.get(run_id)+++class Control:+ def __init__(self, store, run_id, *, recoverable=False):+ self.store, self.run_id = store, run_id+ self.recoverable = recoverable+ self.db = store.database.db_path+ self.stopping = threading.Event()+ self.lock = threading.RLock()+ self.operations = {}+ self.owners = {}+ self._paused_seconds = 0.0+ self._paused_at = None+ run = store.get(run_id)+ self.ancestors = (run.parent_run_id, run.root_run_id)+ self._observed = None++ @property+ def paused_seconds(self):+ with self.lock:+ return self._paused_seconds + (time.monotonic() - self._paused_at+ if self._paused_at is not None else 0.0)++ def _publish(self, command, state):+ value = {'command': command.get('id'), 'state': state, 'pid': os.getpid()}+ with self.lock:+ if value != self._observed:+ atomic_write_text(_root(self.db) / f'{self.run_id}.observed.json', json.dumps(value))+ self._observed = value++ def check_item(self):+ self.checkpoint()++ def checkpoint(self, process=None):+ started = None+ suspended = []+ parked = []+ try:+ while True:+ from .update_tasks import check_pause+ check_pause(self.db if self.recoverable else None)+ if self.stopping.is_set():+ from .jobs import JobPaused+ if self.recoverable:+ raise JobPaused('服务正在关闭,已保存的进度留待恢复')+ raise Cancelled()+ command = intent(self.db, self.run_id, self.ancestors)+ action = command.get('action', 'resume')+ if action == 'cancel':+ raise Cancelled()+ if action != 'pause':+ with self.lock:+ if self._paused_at is not None:+ self._paused_seconds += time.monotonic() - self._paused_at+ self._paused_at = None+ self._publish(command, 'running')+ return time.monotonic() - started if started is not None else 0.0+ if started is None:+ started = time.monotonic()+ with self.lock:+ if self._paused_at is None:+ self._paused_at = started+ if process is not None and process.poll() is None:+ try:+ owner = psutil.Process(process.pid)+ except psutil.NoSuchProcess:+ return+ try:+ children = owner.children(recursive=True)+ except psutil.NoSuchProcess:+ children = []+ for child in [owner, *children]:+ try:+ child.suspend()+ suspended.append(child)+ except psutil.NoSuchProcess:+ pass+ with self.lock:+ parked = [key for key, owner in self.owners.items()+ if owner == threading.get_ident()]+ for key in parked:+ self.operations[key] = True+ with self.lock:+ quiet = all(self.operations.values())+ self._publish(command, 'paused' if quiet else 'pausing')+ self.store.heartbeat(self.run_id)+ self.stopping.wait(.1)+ finally:+ for child in reversed(suspended):+ try:+ child.resume()+ except psutil.NoSuchProcess:+ pass+ with self.lock:+ for key in parked:+ if key in self.operations:+ self.operations[key] = False+++@contextmanager+def bind(store, run_id, *, recoverable=False):+ if run_id is None or not store.enabled:+ yield None+ return+ control = Control(store, run_id, recoverable=recoverable)+ key = _key(control.db, run_id)+ with _LOCK:+ _LIVE[key] = control+ token = CURRENT.set(control)+ try:+ control.checkpoint()+ yield control+ finally:+ CURRENT.reset(token)+ with _LOCK:+ _LIVE.pop(key, None)+++def shutdown(db, run_id):+ with _LOCK:+ control = _LIVE.get(_key(db, run_id))+ if control is not None:+ control.stopping.set()+++def checkpoint():+ control = CURRENT.get()+ if control is not None:+ control.checkpoint()+++def controlled(function):+ @wraps(function)+ def call(*args, **kwargs):+ with operation():+ result = function(*args, **kwargs)+ checkpoint()+ return result+ return call+++@contextmanager+def operation():+ """有界网络请求等在途步骤退出后,才确认整轮已经暂停。"""+ control = CURRENT.get()+ if control is None:+ yield+ return+ marker = object()+ with control.lock:+ control.operations[id(marker)] = False+ control.owners[id(marker)] = threading.get_ident()+ try:+ checkpoint()+ yield+ finally:+ with control.lock:+ control.operations.pop(id(marker), None)+ control.owners.pop(id(marker), None)+++@contextmanager+def committing():+ """已进入文件替换等短提交步骤时,先完整提交,再响应下一次控制请求。"""+ checkpoint()+ with operation():+ token = CURRENT.set(None)+ try:+ yield+ finally:+ CURRENT.reset(token)+++@controlled+def run(command, *, capture_output=False, timeout=None, check=False, input=None, **kwargs):+ """执行当前任务拥有的子进程;暂停保留进程,取消回收后才向外结算。"""+ control = CURRENT.get()+ if control is None:+ return subprocess.run(command, capture_output=capture_output, timeout=timeout,+ check=check, input=input, **kwargs)+ checkpoint()+ if capture_output:+ kwargs.update(stdout=subprocess.PIPE, stderr=subprocess.PIPE)+ if input is not None:+ kwargs['stdin'] = subprocess.PIPE+ if os.name != 'nt':+ kwargs['start_new_session'] = True+ from .process_job import assign_to_job, close_job, create_kill_on_close_job+ job = create_kill_on_close_job()+ try:+ process = subprocess.Popen(command, **kwargs)+ except BaseException:+ close_job(job)+ raise+ assign_to_job(job, process)+ with control.lock:+ control.operations[id(process)] = False+ control.owners[id(process)] = threading.get_ident()+ started = time.monotonic()+ paused = 0.0+ try:+ while True:+ paused += control.checkpoint(process) or 0.0+ try:+ stdout, stderr = process.communicate(input=input, timeout=.1)+ break+ except subprocess.TimeoutExpired as error:+ input = None+ elapsed = time.monotonic() - started - paused+ if timeout is not None and elapsed >= timeout:+ raise subprocess.TimeoutExpired(command, timeout, output=error.output, stderr=error.stderr) from None+ checkpoint()+ result = subprocess.CompletedProcess(command, process.returncode, stdout, stderr)+ if check:+ result.check_returncode()+ return result+ finally:+ try:+ if process.poll() is None:+ try:+ children = psutil.Process(process.pid).children(recursive=True)+ except psutil.NoSuchProcess:+ children = []+ for child in reversed(children):+ try:+ child.kill()+ except psutil.NoSuchProcess:+ pass+ try:+ process.kill()+ except ProcessLookupError:+ pass+ finally:+ if os.name != 'nt':+ try:+ os.killpg(process.pid, signal.SIGKILL)+ except ProcessLookupError:+ pass+ close_job(job)+ try:+ process.communicate()+ finally:+ with control.lock:+ control.operations.pop(id(process), None)+ control.owners.pop(id(process), None)diff --git a/src/peach/task_runs.py b/src/peach/task_runs.pyindex b6707249b..9731f6e64 100644--- a/src/peach/task_runs.py+++ b/src/peach/task_runs.py@@ -93,6 +93,9 @@ TASK_LABELS = {"resource-apply": "资源同步清理","scraping-cover": "封面采集","media-repair": "媒体修复",+ "mp4-header-repair": "播放文件头修复",+ 'jav-discovery-metadata': '发现页资料读取',+ 'diagnostic-export': '诊断导出',"upgrade-repairs": "自动修复","upgrade-library": "自动修复资料","organize": "按模板整理",@@ -546,13 +549,24 @@ class TaskRunStore:return Noneahead = tuple(dict.fromkeys(str(key) for key in first or ())) or ("",)marks = ",".join("?" * len(keys))+ from .task_control import requestedmoment = stamp()with self.database.write_transaction(notify=False) as connection:- row = connection.execute(- f"SELECT id FROM task_run WHERE followup_key IS NOT NULL "+ rows = connection.execute(+ f"SELECT id,parent_run_id,root_run_id FROM task_run WHERE followup_key IS NOT NULL "f"AND status='pending' AND task_key IN ({marks}) "- f"ORDER BY task_key IN ({','.join('?' * len(ahead))}) DESC, id LIMIT 1",- (*keys, *ahead)).fetchone()+ f"ORDER BY task_key IN ({','.join('?' * len(ahead))}) DESC, id",+ (*keys, *ahead)).fetchall()+ row = None+ for candidate in rows:+ action = requested(self.database.db_path, candidate['id'],+ (candidate['parent_run_id'], candidate['root_run_id']))+ if action == 'cancel':+ connection.execute("UPDATE task_run SET status='cancelled',finished_at=?,heartbeat_at=? "+ "WHERE id=? AND status='pending'", (moment, moment, candidate['id']))+ elif action != 'pause':+ row = candidate+ breakif row is None:return Nonerun_id = int(row["id"])@@ -813,9 +827,14 @@ class TaskRunStore:conflict=conflict, total=total, label=label)handle = TaskRunHandle(self, run.id if run else None)try:- yield handle+ from .task_control import bind, checkpoint+ with bind(self, handle.run_id):+ yield handle+ checkpoint()except BaseException as error:- handle.finish("failed", error=f"{type(error).__name__}: {error}")+ from .task_control import Cancelled+ handle.finish('cancelled' if isinstance(error, Cancelled) else 'failed',+ error='' if isinstance(error, Cancelled) else f"{type(error).__name__}: {error}")raiseelse:handle.finish("succeeded")@@ -885,6 +904,8 @@ class TaskRunHandle:def checkpoint(self, **fields) -> None:"""领域结果提交后保存完成集合;后继重新领取时沿用。"""+ from .task_control import checkpoint+ checkpoint()if self.run_id is None or not self.store.enabled:returnwith self.store.database.write_transaction(notify=False) as connection:@@ -899,10 +920,14 @@ class TaskRunHandle:def progress(self, current: int | None = None, total: int | None = None,label: str | None = None, *,throttle: float = PROGRESS_INTERVAL) -> None:+ from .task_control import checkpoint+ checkpoint()self.store.progress(self.run_id, current=current, total=total,label=label, throttle=throttle)def heartbeat(self) -> None:+ from .task_control import checkpoint+ checkpoint()self.store.heartbeat(self.run_id)def finish(self, status: str, *, summary: dict | None = None,diff --git a/src/peach/web_batch.py b/src/peach/web_batch.pyindex 51fe7a16c..47011626c 100644--- a/src/peach/web_batch.py+++ b/src/peach/web_batch.py@@ -544,70 +544,77 @@ def w_batch(contract: WebContract, body):run = contract.task_runs.start("batch", trigger="manual", total=len(ids),label=BATCH_LABELS.get(operation, operation))handle = TaskRunHandle(contract.task_runs, run.id if run else None)+ from .task_control import bind, Cancelledtry:- with contract.write_transaction() as connection:- found = connection.execute(- f"SELECT id,path,snapshot_path,disposal,disposal_reason,location FROM asset WHERE id IN ({marks})", ids,- ).fetchall()- valid_ids = [row["id"] for row in found]- if not valid_ids:- raise ValueError("assets not found")- _reject_ineligible_targets(operation, found)- now = time.time()- if operation in {"restore", "seen", "dispose"}:- state_receipt = _write_batch_state(connection, found, operation, now, disposal_reason)- elif operation == "delete":- # 已消失的行文件本来就不在了,只删账本行;文件又回到盘上的那几条留着,- # 下一轮扫描会把它们接回在库。选中里有一条已消失的,整批都按这条口径删。- purge_outcome = purge_assets(- connection, found, missing_only=any(row["disposal"] == VANISHED for row in found))- elif operation == "dismiss-junk":- connection.executemany(- "INSERT INTO review_decision(category,item_key,status,note,updated_at) "- "VALUES('junk_file',?,'rejected','用户确认不是垃圾',?) "- "ON CONFLICT(category,item_key) DO UPDATE SET "- "status='rejected',note=excluded.note,updated_at=excluded.updated_at",- [(str(asset_id), time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(now)))- for asset_id in valid_ids],- )- elif operation == "reconsider-junk":- connection.executemany(- "DELETE FROM review_decision WHERE category='junk_file' AND item_key=?",- [(str(asset_id),) for asset_id in valid_ids],- )- elif operation == "region":- # 走 `write_owned_fields` 而不是直接 UPDATE:产地是真相字段,用户这一- # 笔要压得住后面每一轮刮削与推断,归属列是它唯一的凭据。- write_owned_fields(connection, valid_ids,- {"region": region_value}, USER_MANUAL)- elif operation == "later":- connection.executemany(- "INSERT OR IGNORE INTO watch_queue(profile_id,asset_id,added_at,source) "- f"VALUES('{DEFAULT_PROFILE_ID}',?,strftime('%Y-%m-%dT%H:%M:%fZ','now'),'web-batch')",- [(asset_id,) for asset_id in valid_ids],- )- else:- connection.executemany(- "INSERT INTO asset_preference(profile_id,asset_id,liked,reason,source,updated_at) "- f"VALUES('{DEFAULT_PROFILE_ID}',?,1,'','web-batch',strftime('%Y-%m-%dT%H:%M:%fZ','now')) "- "ON CONFLICT(profile_id,asset_id) DO UPDATE SET liked=1,source='web-batch',"- "updated_at=excluded.updated_at",- [(asset_id,) for asset_id in valid_ids],- )- except BaseException as error:- if purge_outcome is not None:- _restore_staged_media(purge_outcome["_staged"])- handle.finish("failed", error=f"{type(error).__name__}: {error}")+ with bind(contract.task_runs, handle.run_id):+ try:+ with contract.write_transaction() as connection:+ found = connection.execute(+ f"SELECT id,path,snapshot_path,disposal,disposal_reason,location FROM asset WHERE id IN ({marks})", ids,+ ).fetchall()+ valid_ids = [row["id"] for row in found]+ if not valid_ids:+ raise ValueError("assets not found")+ _reject_ineligible_targets(operation, found)+ now = time.time()+ if operation in {"restore", "seen", "dispose"}:+ state_receipt = _write_batch_state(connection, found, operation, now, disposal_reason)+ elif operation == "delete":+ # 已消失的行文件本来就不在了,只删账本行;文件又回到盘上的那几条留着,+ # 下一轮扫描会把它们接回在库。选中里有一条已消失的,整批都按这条口径删。+ purge_outcome = purge_assets(+ connection, found, missing_only=any(row["disposal"] == VANISHED for row in found))+ elif operation == "dismiss-junk":+ connection.executemany(+ "INSERT INTO review_decision(category,item_key,status,note,updated_at) "+ "VALUES('junk_file',?,'rejected','用户确认不是垃圾',?) "+ "ON CONFLICT(category,item_key) DO UPDATE SET "+ "status='rejected',note=excluded.note,updated_at=excluded.updated_at",+ [(str(asset_id), time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(now)))+ for asset_id in valid_ids],+ )+ elif operation == "reconsider-junk":+ connection.executemany(+ "DELETE FROM review_decision WHERE category='junk_file' AND item_key=?",+ [(str(asset_id),) for asset_id in valid_ids],+ )+ elif operation == "region":+ # 走 `write_owned_fields` 而不是直接 UPDATE:产地是真相字段,用户这一+ # 笔要压得住后面每一轮刮削与推断,归属列是它唯一的凭据。+ write_owned_fields(connection, valid_ids,+ {"region": region_value}, USER_MANUAL)+ elif operation == "later":+ connection.executemany(+ "INSERT OR IGNORE INTO watch_queue(profile_id,asset_id,added_at,source) "+ f"VALUES('{DEFAULT_PROFILE_ID}',?,strftime('%Y-%m-%dT%H:%M:%fZ','now'),'web-batch')",+ [(asset_id,) for asset_id in valid_ids],+ )+ else:+ connection.executemany(+ "INSERT INTO asset_preference(profile_id,asset_id,liked,reason,source,updated_at) "+ f"VALUES('{DEFAULT_PROFILE_ID}',?,1,'','web-batch',strftime('%Y-%m-%dT%H:%M:%fZ','now')) "+ "ON CONFLICT(profile_id,asset_id) DO UPDATE SET liked=1,source='web-batch',"+ "updated_at=excluded.updated_at",+ [(asset_id,) for asset_id in valid_ids],+ )+ except BaseException as error:+ if purge_outcome is not None:+ _restore_staged_media(purge_outcome["_staged"])+ handle.finish("cancelled" if isinstance(error, Cancelled) else "failed",+ error="" if isinstance(error, Cancelled) else f"{type(error).__name__}: {error}")+ raise+ if purge_outcome is not None:+ result = {"ok": True, "operation": operation, **_finish_purge(purge_outcome)}+ result.update(clean_resource_orphans(contract))+ handle.finish("succeeded", summary={"operation": operation,+ "changed": len(valid_ids)})+ return result+ handle.finish("succeeded", summary={"operation": operation,+ "changed": len(valid_ids)})+ return {"ok": True, "operation": operation, "changed": len(valid_ids), **state_receipt}+ except Cancelled:+ handle.finish('cancelled', summary={'cancelled_by_user': True})raise- if purge_outcome is not None:- result = {"ok": True, "operation": operation, **_finish_purge(purge_outcome)}- result.update(clean_resource_orphans(contract))- handle.finish("succeeded", summary={"operation": operation,- "changed": len(valid_ids)})- return result- handle.finish("succeeded", summary={"operation": operation,- "changed": len(valid_ids)})- return {"ok": True, "operation": operation, "changed": len(valid_ids), **state_receipt}def _add_large_short_copy_cluster(items: list[dict], clusters: list[list[dict]]):diff --git a/src/peach/web_jav_discovery.py b/src/peach/web_jav_discovery.pyindex f2d5765ff..040c30f1b 100644--- a/src/peach/web_jav_discovery.py+++ b/src/peach/web_jav_discovery.py@@ -140,7 +140,8 @@ def _metadata_response(contract, args, candidates, picked, limit, scope):def _metadata_message(job):- messages = {"running": "正在读取作品资料", "complete": "作品资料读取完成", "failed": "作品资料未取得"}+ messages = {"running": "正在读取作品资料", "complete": "作品资料读取完成", "failed": "作品资料未取得",+ 'cancelling': '正在取消作品资料读取', 'cancelled': '已取消作品资料读取'}reasons = {"request_budget": "本轮请求预算已用完", "byte_budget": "本轮流量预算已用完","time_budget": "本轮时间预算已用完", "source_cooldown": "来源暂时不可用,已停止读取","cancelled": "已停止读取作品资料"}diff --git a/src/peach/web_job_recovery.py b/src/peach/web_job_recovery.pyindex a2ad0c990..5c66ec913 100644--- a/src/peach/web_job_recovery.py+++ b/src/peach/web_job_recovery.py@@ -16,6 +16,8 @@ from apscheduler.schedulers.background import BackgroundSchedulerdef restore(contract):+ from .jav_discovery_metadata import discovery_metadata+ from .job_recovery import readreturn resume(contract.db_path, {"library-processing": lambda body: w_library_processing(contract, body, resume=True),"timeline-thumbnails": lambda body: w_thumbnail_jobs(contract, body),@@ -31,6 +33,9 @@ def restore(contract):"taste-refresh": lambda body: w_taste_refresh(contract, body),"media-repair": lambda body: w_media_repair(contract, body),"amane-bridge": lambda body: w_scraping_amane_rebuild(contract, body),+ 'jav-discovery-metadata': lambda body: discovery_metadata(contract).ensure(+ body['codes'], refresh=body.get('refresh', False),+ _resume=read(contract.db_path, 'jav-discovery-metadata').get('checkpoint')),"organize": lambda body: (w_organize_rollback(contract, body) if body.get('action') == 'rollback'else w_organize_apply(contract, body)),})diff --git a/src/peach/web_library_processing.py b/src/peach/web_library_processing.pyindex fbb898484..9ebfe1e12 100644--- a/src/peach/web_library_processing.py+++ b/src/peach/web_library_processing.py@@ -164,6 +164,9 @@ def _control_action(contract, config, body):if job_id:control.select_job(str(job_id))if action == 'cancel':+ if previous.get('run_id') is not None:+ from .task_control import request+ request(contract.task_runs, previous['run_id'], action)return _cancel_processing(contract, config, control, previous, str(job_id))if previous.get('status') == 'stopping':raise ValueError('正在等待任务停止,请稍后重试')@@ -172,6 +175,9 @@ def _control_action(contract, config, body):return q_library_processing(contract, {})if action == 'set_speed':return _set_processing_speed(contract, control, previous, body)+ if previous.get('run_id') is not None:+ from .task_control import request+ request(contract.task_runs, previous['run_id'], action)status = ('paused' if previous.get('status') == 'paused' else 'pausing') if action == 'pause' else 'running'_announce_control(contract.library_processing_job, str(job_id), status)control.request(action, str(job_id))diff --git a/src/peach/web_media_repair.py b/src/peach/web_media_repair.pyindex 555fd84ee..92361facb 100644--- a/src/peach/web_media_repair.py+++ b/src/peach/web_media_repair.py@@ -208,12 +208,14 @@ def _recover(contract, asset_id: int, raw: str, tools: tuple[Path, Path, Path])try:recovery = mp4recover.recover(source, references, untrunc=untrunc, ffmpeg=ffmpeg,ffprobe=ffprobe, work=work)- mp4recover.replace_original(source, recovery.path)+ from .task_control import committing+ with committing():+ mp4recover.replace_original(source, recovery.path)+ _record_replacement(contract, asset_id, source, ffprobe)except (RepairUnavailable, OSError, subprocess.SubprocessError):return Falsefinally:shutil.rmtree(work, ignore_errors=True)- _record_replacement(contract, asset_id, source, ffprobe)return True@@ -318,7 +320,7 @@ def w_media_repair(contract, body=None):job = contract.media_repair_jobif body.get("stop") is True:job.stop(resume=False)- return _public(None)+ return _public(job.snapshot())if body.get("status_only") is True:return _public(job.snapshot())if contract.header_repairs is None or contract.transcode_service is None:diff --git a/src/peach/web_resource_sync.py b/src/peach/web_resource_sync.pyindex df4b20e30..11a990d19 100644--- a/src/peach/web_resource_sync.py+++ b/src/peach/web_resource_sync.py@@ -21,6 +21,8 @@ import reimport shutilimport timefrom concurrent.futures import ThreadPoolExecutor+from contextvars import copy_context+from .task_control import controlledfrom pathlib import Path, PureWindowsPathfrom typing import Callable, Protocol, Sequence@@ -81,15 +83,19 @@ def configured_resource_locations() -> tuple[str, ...]:if location in SCANNABLE_LOCATIONS and roots)+@controlleddef _scan_resource_directory(item: tuple[Path, dict[str, list[int]]],) -> tuple[list[int], int]:+ from .task_control import checkpoint+ checkpoint()parent, expected = itempresent: set[str] = set()unreadable = 0try:with os.scandir(parent) as entries:for entry in entries:+ checkpoint()key = entry.name.casefold()if key not in expected:continue@@ -143,7 +149,9 @@ def _missing_resource_ids(max_workers=min(RESOURCE_SCAN_WORKERS, len(directory_items)),thread_name_prefix="PeachResourceScan",) as executor:- results = list(executor.map(_scan_resource_directory, directory_items))+ futures = [executor.submit(copy_context().run, _scan_resource_directory, item)+ for item in directory_items]+ results = [future.result() for future in futures]missing = [asset_id for ids, _unreadable in results for asset_id in ids]unreadable = sum(count for _ids, count in results)if unreadable_dirs is not None:@@ -193,7 +201,10 @@ def _confirm_vanished(rows: Sequence) -> list:if not rows:return []+ @controlleddef present(row) -> bool:+ from .task_control import checkpoint+ checkpoint()try:return translate_ledger_path(row["path"]).exists()except OSError:@@ -204,7 +215,8 @@ def _confirm_vanished(rows: Sequence) -> list:max_workers=min(RESOURCE_SCAN_WORKERS, len(rows)),thread_name_prefix="PeachVanishedCheck",) as executor:- verdicts = list(executor.map(present, rows))+ futures = [executor.submit(copy_context().run, present, row) for row in rows]+ verdicts = [future.result() for future in futures]return [row for row, here in zip(rows, verdicts) if not here]diff --git a/src/peach/web_state.py b/src/peach/web_state.pyindex 55058e055..dca058673 100644--- a/src/peach/web_state.py+++ b/src/peach/web_state.py@@ -368,6 +368,7 @@ class WebContract:self.organize_job.stop()self.media_repair_job.stop()self.amane_bridge_job.stop()+ self.face_models_job.stop()if hasattr(self, "jav_discovery_metadata"):self.jav_discovery_metadata.stop()self.followups.stop()diff --git a/src/peach/web_tasks.py b/src/peach/web_tasks.pyindex d1d75cddd..cc34ad282 100644--- a/src/peach/web_tasks.py+++ b/src/peach/web_tasks.py@@ -123,6 +123,10 @@ def _payload_reader(contract):def payload(row):result = row.payload()+ from .task_control import projection+ control = projection(contract.task_runs, row)+ if control is not None:+ result['control'] = controlif row.task_key not in RESULT_FIELDS or row.status not in ('succeeded', 'failed'):return resultif all(field in row.result_summary for field in RESULT_FIELDS[row.task_key]):diff --git a/tests/test_mp4repair.py b/tests/test_mp4repair.pyindex bd57265ec..40baecb86 100644--- a/tests/test_mp4repair.py+++ b/tests/test_mp4repair.py@@ -426,6 +426,39 @@ class HeaderRepairStoreTests(unittest.TestCase):self.assertEqual(seen, [Path("ffprobe")])+ def test_playback_header_repair_is_registered_before_it_reads_media(self):+ import threading+ from support.ledger import fresh_ledger+ from peach.task_runs import TaskRunStore+ from peach import task_control++ ledger = self.root / 'ledger'+ ledger.mkdir()+ store = TaskRunStore(fresh_ledger(ledger))+ repairs = HeaderRepairStore(self.root / 'managed-cache', _Resolver(), runs=store)+ entered, release = threading.Event(), threading.Event()+ def build(source, ffprobe):+ entered.set()+ release.wait(5)+ task_control.checkpoint()+ return self.header+ with patch.object(mp4repair, 'repaired_header', build):+ try:+ repairs.request(6297, self.source)+ self.assertTrue(entered.wait(5))+ run = store.query(task_key='mp4-header-repair')[0]+ self.assertEqual(run.status, 'running')+ task_control.request(store, run.id, 'cancel')+ release.set()+ worker = next(iter(repairs._jobs.values())).thread+ worker.join(5)+ self.assertFalse(worker.is_alive())+ self.assertEqual(store.get(run.id).status, 'cancelled')+ self.assertFalse(self.sidecar().exists())+ finally:+ release.set()+ repairs.stop()+def test_a_source_that_cannot_be_repaired_is_not_tried_again(self):"""修不了的片子每次播放都重解一遍,就是把一分多钟的整片读白扔一次。"""attempts: list[Path] = []diff --git a/tests/test_task_center_integration.py b/tests/test_task_center_integration.pyindex 1bac80784..bd9db358d 100644--- a/tests/test_task_center_integration.py+++ b/tests/test_task_center_integration.py@@ -16,7 +16,7 @@ from pathlib import Pathfrom peach import web_contract, web_tasksfrom peach.jobs import BackgroundJob, TaskRunConflict-from peach.routes_api import api_get, api_post, task_run_detail+from peach.routes_api import api_get, api_post, task_run_detail, task_run_controlfrom peach.repository import LedgerDatabasefrom peach.task_runs import TaskRunStorefrom support.ledger import fresh_ledger@@ -563,6 +563,30 @@ class ConflictStatusTests(unittest.TestCase):self.assertEqual(task_run_detail(self.request, run.id + 1000, {}).status_code, 404)+ def test_control_endpoint_exposes_pending_pause_and_resumes_the_same_row(self):+ parent = self.contract.task_runs.start('parent', trigger='manual')+ child = self.contract.task_runs.enqueue_followups(parent.id, [('leaf:1', 'leaf', '子任务')])['queued'][0]+ self.contract.task_runs.finish(parent.id, 'succeeded')+ with unittest.mock.patch.object(self.contract.followups, 'wake') as wake:+ paused = task_run_control(self.request, child, {'action': 'pause'}, {})+ self.assertEqual(paused['run']['control'], {'state': 'paused', 'actions': ['resume', 'cancel']})+ continued = task_run_control(self.request, child, {'action': 'resume'}, {})+ self.assertEqual(continued['run']['id'], child)+ self.assertEqual(continued['run']['control']['state'], 'running')+ self.assertEqual(wake.call_count, 2)++ def test_control_endpoint_rejects_unknown_finished_foreign_and_read_only_runs(self):+ run = self.contract.task_runs.start('control-test', trigger='manual')+ self.assertEqual(task_run_control(self.request, run.id + 1000, {'action': 'pause'}, {}).status_code, 404)+ self.assertEqual(task_run_control(self.request, run.id, {'action': 'delete'}, {}).status_code, 409)+ self.contract.task_runs.enabled = False+ self.assertEqual(task_run_control(self.request, run.id, {'action': 'pause'}, {}).status_code, 403)+ self.contract.task_runs.enabled = True+ foreign = TaskRunStore(self.db, host='other-host').start('elsewhere', trigger='manual')+ self.assertEqual(task_run_control(self.request, foreign.id, {'action': 'cancel'}, {}).status_code, 403)+ self.contract.task_runs.finish(run.id, 'succeeded')+ self.assertEqual(task_run_control(self.request, run.id, {'action': 'pause'}, {}).status_code, 409)+if __name__ == "__main__":unittest.main()diff --git a/tests/test_task_control.py b/tests/test_task_control.pynew file mode 100644index 000000000..d5b1409ef--- /dev/null+++ b/tests/test_task_control.py@@ -0,0 +1,442 @@+"""任务控制以临时账本、协作线程和本测试拥有的子进程验证。"""+from __future__ import annotations++from contextvars import copy_context+from pathlib import Path+import subprocess+import sys+import tempfile+import threading+import time+import unittest+from unittest.mock import patch++from peach import job_recovery, task_control, update_tasks+from peach.jobs import BackgroundJob+from peach.task_runs import TaskRunStore+from support.ledger import fresh_ledger+++HEARTBEAT_CHILD = """+from pathlib import Path+import sys+import time+path = Path(sys.argv[1])+print('child-output', flush=True)+print('child-error', file=sys.stderr, flush=True)+for _ in range(int(sys.argv[2])):+ with path.open('ab') as handle:+ handle.write(b'x')+ time.sleep(.02)+"""+++class TaskControlTests(unittest.TestCase):+ def setUp(self):+ temporary = tempfile.TemporaryDirectory()+ self.addCleanup(temporary.cleanup)+ self.root = Path(temporary.name).resolve()+ database = self.root / 'database'+ database.mkdir()+ self.db = fresh_ledger(database)+ self.store = TaskRunStore(self.db)+ self.jobs = []+ self.children = []+ self.releases = []+ self.addCleanup(self._finish_owned_work)++ def _finish_owned_work(self):+ for event in self.releases:+ event.set()+ for job in reversed(self.jobs):+ state = job.snapshot() or {}+ worker = job.thread+ if worker is not None and worker.is_alive():+ run_id = state.get('run_id')+ run = self.store.get(run_id) if run_id is not None else None+ if run is not None and run.active:+ task_control.request(self.store, run_id, 'cancel')+ worker.join(5)+ self.assertFalse(worker.is_alive(), '本测试的后台任务没有退出')+ for child in self.children:+ if child.poll() is None:+ child.kill()+ child.communicate(timeout=5)++ def event(self):+ event = threading.Event()+ self.releases.append(event)+ return event++ def wait_until(self, predicate, message='任务没有到达预期状态', timeout=5):+ deadline = time.monotonic() + timeout+ while not predicate():+ if time.monotonic() >= deadline:+ self.fail(message)+ time.sleep(.01)++ def state(self, run_id):+ return task_control.projection(self.store, self.store.get(run_id))++ def start(self, work, *, key='control-test', recovery=None):+ job = BackgroundJob('PeachControlTest', task_key=key, runs=self.store)+ self.jobs.append(job)+ original = job.start(lambda identity: work(job, identity), recovery=recovery,+ initial={'checked': 0, 'total': 10})+ return job, original++ def record_child(self):+ original = subprocess.Popen++ def create(*args, **kwargs):+ child = original(*args, **kwargs)+ self.children.append(child)+ return child++ return patch('peach.task_control.subprocess.Popen', side_effect=create)++ @staticmethod+ def child_command(path, count):+ return [sys.executable, '-u', '-c', HEARTBEAT_CHILD, str(path), str(count)]++ def test_pause_and_resume_keep_the_same_job_and_run_without_progress_while_paused(self):+ finish = self.event()+ progress = []++ def work(job, identity):+ while not finish.is_set():+ task_control.checkpoint()+ progress.append(identity)+ job.update(identity, checked=len(progress))+ time.sleep(.01)+ job.update(identity, status='complete')++ job, original = self.start(work)+ self.wait_until(lambda: len(progress) >= 2)+ run_id = original['run_id']+ task_control.request(self.store, run_id, 'pause')+ self.wait_until(lambda: self.state(run_id)['state'] == 'paused')+ paused_count = len(progress)+ time.sleep(.1)+ self.assertEqual(len(progress), paused_count)+ task_control.request(self.store, run_id, 'resume')+ self.wait_until(lambda: len(progress) > paused_count)+ self.assertEqual((job.snapshot()['job_id'], job.snapshot()['run_id']),+ (original['job_id'], run_id))+ self.assertEqual([row.id for row in self.store.query()], [run_id])+ finish.set()+ job.thread.join(5)+ self.assertFalse(job.thread.is_alive())+ self.assertEqual(self.store.get(run_id).status, 'succeeded')++ def test_cancel_stays_running_until_work_exits_and_rejects_a_stale_resume(self):+ entered, reach_checkpoint = self.event(), self.event()+ unwinding, allow_exit = self.event(), self.event()++ def work(_job, _identity):+ try:+ entered.set()+ reach_checkpoint.wait(5)+ task_control.checkpoint()+ finally:+ unwinding.set()+ allow_exit.wait(5)++ job, original = self.start(work)+ self.assertTrue(entered.wait(5))+ run_id = original['run_id']+ task_control.request(self.store, run_id, 'cancel')+ self.assertEqual(self.store.get(run_id).status, 'running')+ self.assertEqual(self.state(run_id), {'state': 'cancelling', 'actions': []})+ with self.assertRaises(ValueError):+ task_control.request(self.store, run_id, 'resume')+ reach_checkpoint.set()+ self.assertTrue(unwinding.wait(5))+ self.assertEqual(self.store.get(run_id).status, 'running')+ allow_exit.set()+ job.thread.join(5)+ self.assertFalse(job.thread.is_alive())+ self.assertEqual(self.store.get(run_id).status, 'cancelled')+ self.assertEqual(job.snapshot()['status'], 'cancelled')++ def test_a_finished_parent_controls_active_grandchildren_and_later_pending_work(self):+ parent = self.store.start('parent', trigger='manual')+ child_id = self.store.enqueue_followups(parent.id, [('child:1', 'child', '子任务')])['queued'][0]+ self.store.finish(child_id, 'succeeded')+ grandchild_id = self.store.enqueue_followups(child_id, [('leaf:1', 'leaf', '孙任务')])['queued'][0]+ self.store.finish(parent.id, 'succeeded')+ task_control.request(self.store, parent.id, 'pause')+ self.assertEqual(self.state(parent.id)['state'], 'paused')+ late_id = self.store.enqueue_followups(parent.id, [('leaf:2', 'leaf', '后来排入的任务')])['queued'][0]+ self.assertIsNone(self.store.claim_followup(['leaf']))+ self.assertEqual(self.state(late_id)['state'], 'paused')+ task_control.request(self.store, parent.id, 'resume')+ self.assertEqual(self.store.claim_followup(['leaf']).id, grandchild_id)+ self.store.finish(grandchild_id, 'succeeded')+ self.assertEqual(self.store.claim_followup(['leaf']).id, late_id)+ self.store.finish(late_id, 'succeeded')+ self.assertIsNone(self.state(parent.id))++ def test_cancelled_parent_does_not_run_followups_enqueued_after_the_request(self):+ parent = self.store.start('parent', trigger='manual')+ first = self.store.enqueue_followups(parent.id, [('leaf:1', 'leaf', '原任务')])['queued'][0]+ self.store.finish(parent.id, 'succeeded')+ task_control.request(self.store, parent.id, 'cancel')+ self.assertEqual(self.store.get(first).status, 'cancelled')+ late = self.store.enqueue_followups(parent.id, [('leaf:2', 'leaf', '后来排入的任务')])['queued'][0]+ self.assertIsNone(self.store.claim_followup(['leaf']))+ self.assertEqual(self.store.get(late).status, 'cancelled')++ def test_resuming_a_parent_cannot_undo_an_accepted_child_cancellation(self):+ parent = self.store.start('parent', trigger='manual')+ child_id = self.store.enqueue_followups(parent.id, [('leaf:1', 'leaf', '子任务')])['queued'][0]+ self.store.finish(parent.id, 'succeeded')+ child = self.store.claim_followup(['leaf'])+ task_control.request(self.store, child_id, 'cancel')+ task_control.request(self.store, parent.id, 'pause')+ task_control.request(self.store, parent.id, 'resume')+ self.assertEqual(task_control.requested(self.db, child.id, (parent.id,)), 'cancel')+ self.assertEqual(self.state(child.id)['state'], 'cancelling')+ self.store.finish(child.id, 'cancelled')++ def test_a_pending_database_commit_prevents_another_worker_from_confirming_pause(self):+ entered, commit, finish = self.event(), self.event(), self.event()+ errors = []+ def work(job, identity):+ def peer():+ try:+ entered.wait(5)+ while not finish.is_set():+ task_control.checkpoint()+ time.sleep(.01)+ except BaseException as error:+ errors.append(error)+ worker = threading.Thread(target=copy_context().run, args=(peer,))+ worker.start()+ try:+ with self.store.database.write_transaction() as connection:+ connection.execute("INSERT INTO asset(location,path,name,medium) VALUES('local','sample.mp4','sample','video')")+ entered.set()+ commit.wait(5)+ task_control.checkpoint()+ finish.set()+ finally:+ worker.join(5)+ if errors:+ raise errors[0]+ job.update(identity, status='complete')+ job, original = self.start(work)+ self.assertTrue(entered.wait(5))+ run_id = original['run_id']+ task_control.request(self.store, run_id, 'pause')+ self.wait_until(lambda: self.state(run_id)['state'] == 'pausing')+ self.assertEqual(self.state(run_id)['state'], 'pausing')+ commit.set()+ self.wait_until(lambda: self.state(run_id)['state'] == 'paused')+ task_control.request(self.store, run_id, 'resume')+ job.thread.join(5)+ self.assertFalse(job.thread.is_alive())+ self.assertEqual(self.store.get(run_id).status, 'succeeded')++ def test_parallel_operations_are_not_paused_until_every_inflight_step_parks(self):+ entered = [self.event(), self.event()]+ release = [self.event(), self.event()]+ after_step = []+ errors = []++ def operation(index):+ try:+ with task_control.operation():+ entered[index].set()+ release[index].wait(5)+ task_control.checkpoint()+ after_step.append(index)+ except BaseException as error:+ errors.append(error)++ def work(job, identity):+ workers = [threading.Thread(target=copy_context().run, args=(operation, index))+ for index in range(2)]+ for worker in workers:+ worker.start()+ for worker in workers:+ worker.join(5)+ if worker.is_alive():+ raise RuntimeError('并行操作未退出')+ if errors:+ raise errors[0]+ job.update(identity, status='complete')++ job, original = self.start(work)+ self.assertTrue(all(event.wait(5) for event in entered))+ run_id = original['run_id']+ task_control.request(self.store, run_id, 'pause')+ release[0].set()+ self.wait_until(lambda: self.state(run_id)['state'] == 'pausing')+ self.assertEqual(after_step, [])+ release[1].set()+ self.wait_until(lambda: self.state(run_id)['state'] == 'paused')+ self.assertEqual(after_step, [])+ task_control.request(self.store, run_id, 'resume')+ job.thread.join(5)+ self.assertFalse(job.thread.is_alive())+ self.assertEqual(sorted(after_step), [0, 1])+ self.assertEqual(self.store.get(run_id).status, 'succeeded')++ def test_pause_stops_both_owned_children_and_cancel_reaps_them_before_settlement(self):+ paths = [self.root / f'heartbeat-{index}' for index in range(2)]+ errors = []++ def child_work(path):+ try:+ task_control.run(self.child_command(path, 10000), capture_output=True, timeout=10,+ creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))+ except BaseException as error:+ errors.append(error)++ def work(_job, _identity):+ workers = [threading.Thread(target=copy_context().run, args=(child_work, path)) for path in paths]+ for worker in workers:+ worker.start()+ for worker in workers:+ worker.join(10)+ if worker.is_alive():+ raise RuntimeError('本测试的子进程管理线程未退出')+ if errors:+ raise errors[0]++ with self.record_child():+ job, original = self.start(work)+ self.wait_until(lambda: all(path.exists() and path.stat().st_size >= 2 for path in paths))+ run_id = original['run_id']+ task_control.request(self.store, run_id, 'pause')+ self.wait_until(lambda: self.state(run_id)['state'] == 'paused')+ paused_sizes = [path.stat().st_size for path in paths]+ time.sleep(.15)+ self.assertEqual([path.stat().st_size for path in paths], paused_sizes)+ task_control.request(self.store, run_id, 'resume')+ self.wait_until(lambda: all(path.stat().st_size > size for path, size in zip(paths, paused_sizes)))+ task_control.request(self.store, run_id, 'cancel')+ job.thread.join(5)+ self.assertFalse(job.thread.is_alive())+ self.assertEqual(self.store.get(run_id).status, 'cancelled')+ self.assertEqual(len(self.children), 2)+ self.assertTrue(all(child.poll() is not None for child in self.children))++ def test_child_output_is_preserved_and_user_pause_does_not_consume_its_timeout(self):+ path = self.root / 'heartbeat-finite'+ result = []++ def work(job, identity):+ result.append(task_control.run(self.child_command(path, 80), capture_output=True, timeout=3,+ creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0)))+ job.update(identity, status='complete')++ with self.record_child():+ job, original = self.start(work)+ self.wait_until(lambda: path.exists() and path.stat().st_size >= 2)+ task_control.request(self.store, original['run_id'], 'pause')+ self.wait_until(lambda: self.state(original['run_id'])['state'] == 'paused')+ time.sleep(3.2)+ task_control.request(self.store, original['run_id'], 'resume')+ job.thread.join(5)+ self.assertFalse(job.thread.is_alive())+ self.assertEqual(self.store.get(original['run_id']).status, 'succeeded')+ self.assertEqual(result[0].returncode, 0)+ self.assertIn(b'child-output', result[0].stdout)+ self.assertIn(b'child-error', result[0].stderr)+ self.assertIsNotNone(self.children[0].poll())++ def test_input_and_output_survive_repeated_communicate_timeouts(self):+ run = self.store.start('input-output', trigger='manual')+ command = [sys.executable, '-u', '-c',+ "import sys,time; data=sys.stdin.buffer.read(); time.sleep(.25); "+ "sys.stdout.buffer.write(data); sys.stderr.buffer.write(b'diagnostic')"]+ with self.record_child(), task_control.bind(self.store, run.id):+ result = task_control.run(command, input=b'payload\nsecond line', capture_output=True, timeout=5,+ creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))+ self.assertEqual(result.stdout, b'payload\nsecond line')+ self.assertEqual(result.stderr, b'diagnostic')+ self.assertEqual(result.returncode, 0)+ self.store.finish(run.id, 'succeeded')++ def test_timeout_keeps_partial_output_and_reaps_the_owned_child(self):+ run = self.store.start('timeout-output', trigger='manual')+ command = [sys.executable, '-u', '-c',+ "import sys,time; print('partial-output',flush=True); "+ "print('partial-error',file=sys.stderr,flush=True); time.sleep(10)"]+ with self.record_child(), task_control.bind(self.store, run.id):+ with self.assertRaises(subprocess.TimeoutExpired) as caught:+ task_control.run(command, capture_output=True, timeout=1,+ creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))+ self.assertIn(b'partial-output', caught.exception.output or b'')+ self.assertIn(b'partial-error', caught.exception.stderr or b'')+ self.assertIsNotNone(self.children[0].poll())+ self.store.finish(run.id, 'failed')++ def test_user_paused_recoverable_work_yields_to_installation_and_resumes_the_same_run(self):+ progressed = self.event()++ def work(job, identity):+ job.checkpoint(identity, checked=1, completed_items=[7])+ progressed.set()+ while True:+ task_control.checkpoint()+ time.sleep(.01)++ first, original = self.start(work, key='feed-check', recovery={'all': True})+ self.assertTrue(progressed.wait(5))+ run_id = original['run_id']+ task_control.request(self.store, run_id, 'pause')+ self.wait_until(lambda: self.state(run_id)['state'] == 'paused')+ token = update_tasks.reserve(self.db)+ try:+ first.thread.join(5)+ self.assertFalse(first.thread.is_alive())+ self.assertTrue(update_tasks.wait_quiescent(self.db, timeout=1))+ self.assertEqual(self.store.get(run_id).status, 'pending')+ finally:+ update_tasks.release(self.db, token)+ second = BackgroundJob('PeachControlTest', task_key='feed-check', runs=self.store)+ self.jobs.append(second)+ resumed = []++ def resume(identity):+ resumed.append(second.snapshot())+ second.update(identity, status='complete')++ job_recovery.resume(self.db, {'feed-check': lambda request: second.start(+ resume, restart=True, recovery=request)})+ self.wait_until(lambda: self.state(run_id)['state'] == 'paused')+ self.assertEqual(resumed, [])+ task_control.request(self.store, run_id, 'resume')+ self.wait_until(lambda: bool(resumed))+ second.thread.join(5)+ self.assertFalse(second.thread.is_alive())+ self.assertEqual((resumed[0]['job_id'], resumed[0]['run_id'], resumed[0]['completed_items']),+ (original['job_id'], run_id, [7]))+ self.assertEqual(self.store.get(run_id).status, 'succeeded')++ def test_shutdown_of_nonrecoverable_paused_work_does_not_leave_a_pending_resume_row(self):+ entered = self.event()++ def work(_job, _identity):+ entered.set()+ while True:+ task_control.checkpoint()+ time.sleep(.01)++ job, original = self.start(work)+ self.assertTrue(entered.wait(5))+ run_id = original['run_id']+ worker = job.thread+ task_control.request(self.store, run_id, 'pause')+ self.wait_until(lambda: self.state(run_id)['state'] == 'paused')+ token = update_tasks.reserve(self.db)+ try:+ job.stop(timeout=5)+ self.assertFalse(worker.is_alive())+ self.assertIn(self.store.get(run_id).status, ('cancelled', 'interrupted'))+ self.assertNotEqual(job_recovery.read(self.db, 'control-test').get('status'), 'active')+ finally:+ update_tasks.release(self.db, token)diff --git a/uv.lock b/uv.lockindex 08a1219e0..df2bff827 100644--- a/uv.lock+++ b/uv.lock@@ -1249,6 +1249,7 @@ dependencies = [{ name = "m3u8" },{ name = "pillow" },{ name = "protobuf" },+ { name = "psutil" },{ name = "pyahocorasick" },{ name = "pydantic" },{ name = "pystray" },@@ -1273,7 +1274,6 @@ build = [dev = [{ name = "filelock" },{ name = "httpx2" },- { name = "psutil" },{ name = "ruff" },{ name = "seiso" },]@@ -1314,7 +1314,7 @@ requires-dist = [{ name = "p115client", marker = "extra == 'maintenance-115'", specifier = "==0.0.9.7.2" },{ name = "pillow", specifier = "==13.0.0" },{ name = "protobuf", specifier = "==7.36.2" },- { name = "psutil", marker = "extra == 'dev'", specifier = "==7.2.2" },+ { name = "psutil", specifier = "==7.2.2" },{ name = "pyahocorasick", specifier = "==2.3.1" },{ name = "pydantic", specifier = "==2.14.2" },{ name = "pyinstaller", marker = "extra == 'build'", specifier = "==6.22.3" },