Peach: Local-first video metadata scraper and media manager.
fix(tasks): 校正跨平台任务资源计量并补齐容器边界
longmeidaocce17ebeb3a5
diff --git a/README.md b/README.mdindex b81167ba9..317359f8b 100644--- a/README.md+++ b/README.md@@ -49,6 +49,7 @@ Movie demo data; see [asset credits and licenses](https://peach.video/en/credits- **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; permanently delete videos by performer while keeping profiles and photos. Metadata and watch history are stored locally.- **Task center**: pause, resume or cancel local background tasks and view their CPU, GPU and download activity where available.+- **Guided tours**: learn the interface and settings as needed; tutorial progress is shared across devices connected to the same instance.## Download and usediff --git a/README.zh-CN.md b/README.zh-CN.mdindex 0bc51d6c9..3152d5468 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -49,6 +49,7 @@- **云下载**:按影片编号查找或提交磁力,下载完成后整理入库。- **馆藏管理**:管理标签、重复文件、多版本与分卷;按女优批量永久删除影片,保留人物档案和照片。资料和观看记录保存在本机。- **任务中心**:暂停、继续或取消本机后台任务,查看可取得的各任务 CPU、GPU 与下载活动。+- **新手教程**:按需了解界面和设置,连接同一实例的设备共用教程进度。## 下载与使用diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.mdindex 1b5d7bcb3..5857f8a9d 100644--- a/docs/OPERATIONS.md+++ b/docs/OPERATIONS.md@@ -214,7 +214,9 @@ Windows 测试包默认使用 `%LOCALAPPDATA%\Peach\peach-data`。首次设置播放触发的文件头修复、发现页资料读取和诊断导出同样登记在任务中心。媒体子进程可暂停、继续和取消,暂停时长不计入处理超时。支持断点恢复的任务在重启后保留暂停意图;没有恢复入口的即时任务在服务关闭后结算,不留下无法继续的排队任务。-活动任务显示蓝色 CPU、紫色 GPU 与青色网络标签。CPU 百分比以本机总计算容量为 100%,计入已登记的工作线程与所属子进程;共享原生线程无法准确归属时不计入。逐任务 GPU 计量目前支持 Windows,显示所属子进程最忙引擎的使用率;macOS/Linux、计数器不可用或共享服务进程的 GPU 活动无法准确归属时显示「未取得」。网络显示已观测的下载速度,挂载与 SMB 的缓存、预读以及未计量的外部请求显示「未取得」,不以零值代替。首次读取显示「采样中」。CPU 或 GPU 达到 50%、下载达到 10 MiB/s 时,同色标签加深,仅作显示提示。已取消的任务显示红色标签。+活动任务显示蓝色 CPU、紫色 GPU 与青色网络标签。CPU 百分比以执行端可用计算容量为 100%,计入已登记的工作线程与所属子进程;共享原生线程无法准确归属时不计入。macOS 按原生线程 ID 读取时间,Linux 与 Docker 同时考虑 CPU 亲和性和当前命名空间可见的 cgroup v1/v2 配额。无法读取容量时显示「未取得」。++逐任务 GPU 显示所属子进程最忙引擎的使用率。Windows 使用系统引擎计数器;Linux 使用驱动提供的 DRM fdinfo 引擎时间,Docker 需要映射 GPU 设备并允许读取任务进程信息。macOS、未提供 DRM 引擎时间的驱动、设备未映射、权限不足,以及共享 GPU 活动无法准确归属的情况显示「未取得」并说明原因。网络显示已观测的下载速度,挂载与 SMB 的缓存、预读以及未计量的外部请求显示「未取得」,不以零值代替。首次读取显示「采样中」。CPU 或 GPU 达到 50%、下载达到 10 MiB/s 时,同色标签加深,仅作显示提示。已取消的任务显示红色标签。后台任务把任务标识、处理范围、完成集合和计数保存在本机。服务重启时接回同一条任务记录,继续未完成的部分。用户暂停的任务保持暂停;明确停止会取消恢复。失败、限流或未取得的结果保留原有重试与冷却规则,不作为成功项目跳过。diff --git a/docs/REUSE.md b/docs/REUSE.mdindex bd8e790ce..924455fc9 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -1,5 +1,11 @@# 复用清单+## 跨平台任务资源计量++继续使用 psutil 7.2.2 读取进程 CPU 时间和身份。该版本的 macOS 线程列表使用序号,不能与 Python 原生线程 ID 对应;因此使用系统 `libproc` 的 `PROC_PIDTHREADID64INFO` 取得指定线程的纳秒时间,接口与单位见 [XNU 实现](https://github.com/apple-oss-distributions/xnu/blob/main/osfmk/kern/bsd_kern.c)。Linux 的可用 CPU 容量复用亲和性、控制组成员和挂载信息,按可见 cgroup v1/v2 配额归一化。++Linux GPU 读取 [DRM fdinfo 标准](https://docs.kernel.org/gpu/drm-usage-stats.html)的客户端、设备和引擎忙碌时间;重复描述符去重,计数回退保持高水位,进程重用重新采样。容器沿用当前设备与 PID 命名空间,不要求宿主 PID 权限。macOS 和未提供该计数的 Linux 驱动明确显示未取得,不使用整机 GPU 占用替代任务。实现只调用系统接口,无新增依赖;测试覆盖平台接口、配额、权限、重复客户端和原生线程时间增长。+## 数据管理层级数据管理首页按待处理事项看板、扫描与采集、整理与维护、清理与删除排列。日常扫描直接操作,其余工具在独立二级页展开表单和清单;首页只读摘要。工具名称、顺序和地址由 `frontend/src/cleanup-tools.ts` 供首页、路由、面包屑与加载态共用。已分享的工具锚点转到对应二级页,保留查询参数。diff --git a/scripts/ci_scope.py b/scripts/ci_scope.pyindex ec18a95b0..579020801 100644--- a/scripts/ci_scope.py+++ b/scripts/ci_scope.py@@ -26,6 +26,7 @@ sys.path.insert(0, str(ROOT / "src"))_SHARED = ("test_platform", "test_fsutil", "test_folder_picker", "test_certs", "test_auth", "test_onboarding","test_media", "test_media_probe", "test_frame_capture",+ "test_data_storage", "test_task_resources", "test_resource_platform","frontend/e2e/setup.test.ts", "frontend/e2e/playback-resume.test.ts","frontend/e2e/player-v10.test.ts", "frontend/e2e/http-configuration.test.ts",)@@ -35,7 +36,7 @@ PLATFORM_TESTS: dict[str, tuple[str, ...]] = {"test_tray", "test_tray_detached", "test_tray_diagnostics", "test_tray_lifecycle","test_restart_windows_tray", "test_process_job", "test_windows_update","test_desktop_settings", "test_desktop_installer", "test_standalone_update",- "test_data_storage", "test_interaction", "test_jobs", "test_scan", "test_media_tool_import",+ "test_interaction", "test_jobs", "test_scan", "test_media_tool_import","frontend/e2e/external-playback.test.ts"),"macos": (*_SHARED,"test_tray", "test_mount", "test_netwatch", "test_mdns", "test_macos_standalone", "test_macos_media",diff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex 716030b0f..5af73e669 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_task_control.py", "test_task_resources.py", "test_face_models.py",+ "test_task_runs.py", "test_followups.py", "test_task_center_integration.py", "test_task_control.py", "test_task_resources.py", "test_resource_platform.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_task_control.py", "test_task_resources.py", "test_reference_updates.py",+ "test_task_center_integration.py", "test_task_control.py", "test_task_resources.py", "test_resource_platform.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",@@ -209,6 +209,9 @@ AUTO_SCOPE_FILES: dict[str, tuple[str, ...]] = {'src/peach/task_control.py': ('catalog', 'media', 'metadata', 'follow', 'sync', 'tooling', 'web'),'tests/test_task_control.py': ('media', 'tooling'),'tests/test_task_resources.py': ('media', 'tooling'),+ 'tests/test_resource_platform.py': ('media', 'tooling'),+ 'src/peach/resource_platform.py': ('media', 'tooling', 'web'),+ 'src/peach/gpu_linux.py': ('media', 'tooling', 'web'),'src/peach/task_resources.py': ('catalog', 'media', 'metadata', 'follow', 'sync', 'tooling', 'web'),'src/peach/gpu_usage.py': ('media', 'tooling', 'web'),# 托盘重启的实现由 `test_restart_windows_tray.py` 验,模块名推不出来。diff --git a/src/peach/gpu_linux.py b/src/peach/gpu_linux.pynew file mode 100644index 000000000..3154e0986--- /dev/null+++ b/src/peach/gpu_linux.py@@ -0,0 +1,100 @@+"""Linux DRM fdinfo 的逐进程引擎时间;容器仅读取已映射设备及当前 PID 空间。"""+from __future__ import annotations++from pathlib import Path+import re+import time+++class LinuxGpuCounters:+ def __init__(self, *, proc=Path('/proc'), devices=Path('/dev/dri'), clock=time.monotonic):+ self.proc, self.devices, self.clock = proc, devices, clock+ self.previous = {}+ self.cache = {}+ self.now = None++ def sample(self):+ self.now = self.clock()+ self.cache = {}+ self.previous = {key: value for key, value in self.previous.items() if self.now - value[0] < 60}+ return None, 'sampling', '等待读取任务的 GPU 进程'++ def _read(self, pid):+ clients = {}+ for path in (self.proc / str(pid) / 'fdinfo').iterdir():+ try:+ text = path.read_text()+ except FileNotFoundError:+ continue+ fields = dict(line.split(':', 1) for line in text.splitlines() if ':' in line)+ fields = {key: value.strip() for key, value in fields.items()}+ if 'drm-driver' not in fields:+ continue+ client = fields.get('drm-client-id')+ if client is None or not client.isdigit():+ raise ValueError('GPU 驱动未提供可去重的 DRM 客户端编号')+ device = fields.get('drm-pdev', fields['drm-driver'])+ engines = {}+ for key, value in fields.items():+ if not key.startswith('drm-engine-') or key.startswith('drm-engine-capacity-'):+ continue+ name = key.removeprefix('drm-engine-')+ match = re.fullmatch(r'(\d+)\s+ns', value)+ capacity = fields.get(f'drm-engine-capacity-{name}', '1')+ if match is None or not capacity.isdigit() or int(capacity) <= 0:+ raise ValueError('GPU 引擎时间或容量格式无效')+ engines[f'{device}:{name}'] = (int(match[1]), int(capacity))+ if not engines:+ raise ValueError('GPU 驱动未提供 DRM 引擎忙碌时间')+ clients[(device, client)] = engines+ return clients++ def _process(self, pid, created):+ identity = (pid, created)+ if identity in self.cache:+ return self.cache[identity]+ clients = self._read(pid)+ values, sampling = {}, False+ for client, engines in clients.items():+ for engine, (busy, capacity) in engines.items():+ key = (pid, created, client, engine)+ old = self.previous.get(key)+ if old is None:+ sampling = True+ self.previous[key] = (self.now, busy)+ continue+ elapsed = self.now - old[0]+ if elapsed <= 0:+ sampling = True+ continue+ # DRM 允许短暂回退;保留高水位,避免恢复时重复累计。+ if busy >= old[1]:+ values[engine] = values.get(engine, 0) + 100 * (busy - old[1]) / 1e9 / elapsed / capacity+ self.previous[key] = (self.now, busy)+ else:+ values.setdefault(engine, 0.0)+ result = (values, sampling, set(clients))+ self.cache[identity] = result+ return result++ def sample_processes(self, processes):+ if not self.devices.exists():+ return None, 'unavailable', '未发现可读取的 DRM GPU 设备;容器需映射设备,驱动需支持逐进程计数'+ result, clients, sampling = {}, set(), False+ try:+ for pid, created in processes.items():+ values, pending, owned = self._process(pid, created)+ if clients & owned:+ return None, 'unavailable', '多个进程共享 GPU 客户端,使用量无法准确归属'+ clients.update(owned)+ sampling |= pending+ result[pid] = values+ except (OSError, ValueError) as error:+ return None, 'unavailable', f'任务 GPU 计数器未取得:{error}'+ if sampling:+ return None, 'sampling', '等待下一次 GPU 采样'+ return result, 'ready', ''++ def close(self):+ self.previous.clear()+ self.cache.clear()diff --git a/src/peach/gpu_usage.py b/src/peach/gpu_usage.pyindex 7eef63896..fc4bc59a4 100644--- a/src/peach/gpu_usage.py+++ b/src/peach/gpu_usage.py@@ -5,6 +5,7 @@ import ctypesimport mathimport osimport re+import sysfrom ctypes import wintypes@@ -15,6 +16,8 @@ class GpuCounters:self.counter = ctypes.c_void_p()self.collected = Falseself.error = '当前平台未提供逐进程 GPU 计数器'+ if sys.platform == 'darwin':+ self.error = 'macOS 未提供本功能可用的逐进程 GPU 引擎计数;系统整体 GPU 占用不能归属到任务'if os.name != 'nt':returntry:diff --git a/src/peach/resource_platform.py b/src/peach/resource_platform.pynew file mode 100644index 000000000..878f99a49--- /dev/null+++ b/src/peach/resource_platform.py@@ -0,0 +1,106 @@+"""按原生线程身份读取 CPU 时间,按执行进程可用容量归一化。"""+from __future__ import annotations++import ctypes+import errno+import re+import sys+from functools import lru_cache+from pathlib import Path, PurePosixPath++import psutil+++class ThreadInfo(ctypes.Structure):+ _fields_ = [('user', ctypes.c_uint64), ('system', ctypes.c_uint64),+ ('scheduling', ctypes.c_int32 * 8), ('name', ctypes.c_char * 64)]+++@lru_cache(maxsize=1)+def _libproc():+ library = ctypes.CDLL('/usr/lib/libproc.dylib', use_errno=True)+ library.proc_pidinfo.argtypes = (ctypes.c_int, ctypes.c_int, ctypes.c_uint64,+ ctypes.c_void_p, ctypes.c_int)+ library.proc_pidinfo.restype = ctypes.c_int+ return library+++def thread_times(process, identities):+ if sys.platform != 'darwin':+ return {thread.id: thread.user_time + thread.system_time+ for thread in process.threads() if thread.id in identities}+ result = {}+ library = _libproc()+ for identity in identities:+ info = ThreadInfo()+ ctypes.set_errno(0)+ size = library.proc_pidinfo(process.pid, 15, identity, ctypes.byref(info), ctypes.sizeof(info))+ if size != ctypes.sizeof(info):+ code = ctypes.get_errno()+ if code == errno.ESRCH:+ continue # 采样前线程已退出。+ raise OSError(code, 'macOS 原生线程 CPU 时间未取得')+ result[identity] = (info.user + info.system) / 1_000_000_000+ return result+++def _unescape(value):+ return re.sub(r'\\([0-7]{3})', lambda match: chr(int(match[1], 8)), value)+++def cgroup_capacity(proc_root, pid):+ """读取当前挂载命名空间中可见的 v1/v2 CPU 配额,包括可见父组。"""+ memberships = {}+ for line in (proc_root / str(pid) / 'cgroup').read_text().splitlines():+ _hierarchy, controllers, group = line.split(':', 2)+ for controller in controllers.split(','):+ memberships[controller] = PurePosixPath(group)+ capacities = []+ for line in (proc_root / str(pid) / 'mountinfo').read_text().splitlines():+ before, after = line.split(' - ', 1)+ fields, filesystem = before.split(), after.split()+ unified = filesystem[0] == 'cgroup2'+ if not unified and not (filesystem[0] == 'cgroup' and 'cpu' in filesystem[2].split(',')):+ continue+ group = memberships.get('' if unified else 'cpu')+ root = PurePosixPath(_unescape(fields[3]))+ if group is None or not group.is_relative_to(root):+ continue+ mount = Path(_unescape(fields[4]))+ current = mount.joinpath(*group.relative_to(root).parts)+ if '..' in group.parts:+ raise ValueError('CPU 控制组路径不可访问')+ while True:+ try:+ if unified:+ quota, period = (current / 'cpu.max').read_text().split()+ else:+ quota = (current / 'cpu.cfs_quota_us').read_text().strip()+ period = (current / 'cpu.cfs_period_us').read_text().strip()+ if int(period) <= 0:+ raise ValueError('CPU 控制组周期无效')+ if quota not in ('max', '-1'):+ if int(quota) <= 0:+ raise ValueError('CPU 控制组配额无效')+ capacities.append(int(quota) / int(period))+ except FileNotFoundError:+ pass # 根组或未启用 CPU 控制器的组没有配额文件。+ if current == mount:+ break+ current = current.parent+ return min(capacities) if capacities else None+++def cpu_capacity(process):+ capacity = psutil.cpu_count()+ if not capacity:+ raise ValueError('CPU 总容量未取得')+ if sys.platform.startswith('linux'):+ allowed = process.cpu_affinity()+ if not allowed:+ raise ValueError('执行进程的 CPU 可用范围未取得')+ capacity = min(capacity, len(allowed))+ quota = cgroup_capacity(Path('/proc'), process.pid)+ if quota is not None:+ capacity = min(capacity, quota)+ return capacitydiff --git a/src/peach/task_resources.py b/src/peach/task_resources.pyindex 24185a749..93e7e8a2f 100644--- a/src/peach/task_resources.py+++ b/src/peach/task_resources.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport jsonimport mathimport os+import sysimport threadingimport timefrom datetime import datetime, timezone@@ -12,6 +13,7 @@ import psutilfrom .fsutil import atomic_write_textfrom .gpu_usage import GpuCounters+from .resource_platform import cpu_capacity, thread_timesfrom .update_tasks import state_for_LIVE = {}@@ -180,8 +182,8 @@ class Monitor:if root.create_time() != owners['created']:return emptywanted = set(owners['threads'])- cpu = {f't:{root.pid}:{thread.id}': thread.user_time + thread.system_time- for thread in root.threads() if thread.id in wanted}+ cpu = {f't:{root.pid}:{identity}': value+ for identity, value in thread_times(root, wanted).items()}children = {}for pid, created in owners['processes'].items():try:@@ -209,9 +211,10 @@ class Monitor:network_metric = _metric('sampling', 'bytes_per_second')else:elapsed = max(.001, now - previous[0])- capacity = psutil.cpu_count()- if capacity is None:- cpu_metric = _metric('unavailable', 'percent', reason='本机 CPU 总容量未取得')+ try:+ capacity = cpu_capacity(root)+ except (psutil.Error, OSError, ValueError) as error:+ cpu_metric = _metric('unavailable', 'percent', reason=f'执行端 CPU 可用容量未取得:{error}')else:parts = {key: 100 * max(0, value - previous[1].get(key, value)) / elapsed / capacityfor key, value in cpu.items()}@@ -220,6 +223,12 @@ class Monitor:network_metric = _metric('ready', 'bytes_per_second', round(rate), threshold=NETWORK_HIGH)if owners.get('network_error'):network_metric = _metric('unavailable', 'bytes_per_second', reason=owners['network_error'])+ if hasattr(self.gpu, 'sample_processes'):+ try:+ identities = {root.pid: root.create_time(), **{pid: child.create_time() for pid, child in children.items()}}+ gpu, gpu_state, gpu_error = self.gpu.sample_processes(identities)+ except psutil.Error as error:+ gpu, gpu_state, gpu_error = None, 'unavailable', f'GPU 进程身份未取得:{type(error).__name__}'gpu_metric = _metric(gpu_state, 'percent', reason=gpu_error)engines = {}gpu_parts = {}@@ -247,11 +256,15 @@ class Monitor:self.rows, self.previous, self.sampled_at = {}, {}, nowreturn self.rowsif self.gpu is None:- self.gpu = GpuCounters()+ if sys.platform.startswith('linux'):+ from .gpu_linux import LinuxGpuCounters+ self.gpu = LinuxGpuCounters()+ else:+ self.gpu = GpuCounters()gpu, state, reason = self.gpu.sample()stamp = datetime.now(timezone.utc).isoformat()self.rows = {run.id: {**self._sample(run, now, gpu, state, reason), 'sampled_at': stamp,- 'detail': 'CPU 按已登记工作线程及子进程计量,占本机总容量;GPU 为所属子进程最忙引擎;网络为已观测下载速率。'}+ 'detail': 'CPU 按已登记工作线程及子进程计量,占执行端可用容量(容器按可见 CPU 配额);GPU 为所属子进程最忙引擎;网络为已观测下载速率。'}for run in runs}active = {run.id for run in runs}self.previous = {key: value for key, value in self.previous.items() if key in active}@@ -280,7 +293,7 @@ class Monitor:'network': _metric('unavailable', 'bytes_per_second', reason='执行端的传输读数未取得')}samples = [waiting if row['status'] == 'pending' else rows.get(row['id'], unknown) for row in family]result = {'sampled_at': datetime.now(timezone.utc).isoformat(),- 'detail': 'CPU 为已登记工作线程及所属子进程占本机总容量,未包含无法归属的共享原生线程;GPU 为所属子进程最忙引擎;网络为已观测下载速率,未取得时不报告零值。颜色加深阈值:CPU/GPU 50%,网络 10 MiB/s,仅作显示提示。'}+ 'detail': 'CPU 为已登记工作线程及所属子进程占执行端可用容量(容器按可见 CPU 配额),未包含无法归属的共享原生线程;GPU 为所属子进程最忙引擎;网络为已观测下载速率,未取得时不报告零值。颜色加深阈值:CPU/GPU 50%,网络 10 MiB/s,仅作显示提示。'}for name, field, threshold in (('cpu', 'percent', CPU_HIGH), ('gpu', 'percent', GPU_HIGH),('network', 'bytes_per_second', NETWORK_HIGH)):values = [sample[name] for sample in samples]diff --git a/tests/test_resource_platform.py b/tests/test_resource_platform.pynew file mode 100644index 000000000..f674162bf--- /dev/null+++ b/tests/test_resource_platform.py@@ -0,0 +1,205 @@+"""原生线程读取和 Linux 控制组容量的行为验证。"""+from __future__ import annotations++import ctypes+import errno+import os+from pathlib import Path+import sys+import tempfile+import threading+import time+from types import SimpleNamespace+import unittest+from unittest.mock import Mock, patch++import psutil++from peach.resource_platform import ThreadInfo, cgroup_capacity, cpu_capacity, thread_times+from peach.gpu_linux import LinuxGpuCounters+from peach.gpu_usage import GpuCounters+++class PlatformCpuTests(unittest.TestCase):+ def setUp(self):+ temporary = tempfile.TemporaryDirectory()+ self.addCleanup(temporary.cleanup)+ self.root = Path(temporary.name).resolve()+ self.proc = self.root / 'proc'+ (self.proc / '10').mkdir(parents=True)+ self.mount = self.root / 'groups'+ (self.mount / 'service' / 'worker').mkdir(parents=True)++ def groups(self, *, version=2, mount_root='/', group='/service/worker'):+ unified = version == 2+ (self.proc / '10/cgroup').write_text(f"{'0::' if unified else '2:cpu,cpuacct:'}{group}\n")+ path = str(self.mount).replace(' ', r'\040')+ filesystem = 'cgroup2 cgroup rw' if unified else 'cgroup cgroup rw,cpu,cpuacct'+ (self.proc / '10/mountinfo').write_text(f'20 1 0:30 {mount_root} {path} rw - {filesystem}\n')++ def test_v2_uses_visible_parent_quota_and_container_namespace_root(self):+ self.groups()+ (self.mount / 'cpu.max').write_text('max 100000')+ (self.mount / 'service/cpu.max').write_text('150000 100000')+ (self.mount / 'service/worker/cpu.max').write_text('200000 100000')+ self.assertEqual(cgroup_capacity(self.proc, 10), 1.5)+ self.groups(group='/')+ (self.mount / 'cpu.max').write_text('50000 100000')+ self.assertEqual(cgroup_capacity(self.proc, 10), .5)++ def test_v1_uses_cpu_mount_root_and_does_not_treat_unlimited_as_zero(self):+ self.groups(version=1, mount_root='/docker/unit', group='/docker/unit/service')+ (self.mount / 'cpu.cfs_quota_us').write_text('-1')+ (self.mount / 'cpu.cfs_period_us').write_text('100000')+ (self.mount / 'service/cpu.cfs_quota_us').write_text('75000')+ (self.mount / 'service/cpu.cfs_period_us').write_text('100000')+ self.assertEqual(cgroup_capacity(self.proc, 10), .75)+ (self.mount / 'service/cpu.cfs_quota_us').write_text('-1')+ self.assertIsNone(cgroup_capacity(self.proc, 10))++ def test_invalid_quota_and_unreadable_membership_are_not_host_capacity(self):+ self.groups()+ for value in ('0 100000', '200000 0', 'broken', 'max zero'):+ with self.subTest(value=value):+ (self.mount / 'service/worker/cpu.max').write_text(value)+ with self.assertRaises(ValueError):+ cgroup_capacity(self.proc, 10)+ with patch.object(Path, 'read_text', side_effect=PermissionError('denied')):+ with self.assertRaises(PermissionError):+ cgroup_capacity(self.proc, 10)++ def test_capacity_intersects_host_affinity_and_fractional_quota(self):+ process = Mock(pid=10)+ process.cpu_affinity.return_value = [2, 3]+ with patch('peach.resource_platform.sys.platform', 'linux'), \+ patch('peach.resource_platform.psutil.cpu_count', return_value=32), \+ patch('peach.resource_platform.cgroup_capacity', return_value=.5) as quota:+ self.assertEqual(cpu_capacity(process), .5)+ quota.return_value = None+ self.assertEqual(cpu_capacity(process), 2)++ def test_macos_requests_native_thread_ids_and_converts_nanoseconds(self):+ def read(pid, flavor, identity, buffer, size):+ self.assertEqual((pid, flavor, size), (10, 15, ctypes.sizeof(ThreadInfo)))+ self.assertIn(identity, (123456789, 987654321))+ buffer._obj.user, buffer._obj.system = 1_000_000_000, 250_000_000+ return size+ library = SimpleNamespace(proc_pidinfo=Mock(side_effect=read))+ with patch('peach.resource_platform.sys.platform', 'darwin'), \+ patch('peach.resource_platform._libproc', return_value=library):+ self.assertEqual(thread_times(SimpleNamespace(pid=10), {123456789, 987654321}),+ {123456789: 1.25, 987654321: 1.25})++ def test_macos_permission_error_is_distinct_from_an_exited_thread(self):+ def denied(*_args):+ ctypes.set_errno(errno.EPERM)+ return 0+ library = SimpleNamespace(proc_pidinfo=Mock(side_effect=denied))+ with patch('peach.resource_platform.sys.platform', 'darwin'), \+ patch('peach.resource_platform._libproc', return_value=library):+ with self.assertRaises(PermissionError):+ thread_times(SimpleNamespace(pid=10), {20})+ def exited(*_args):+ ctypes.set_errno(errno.ESRCH)+ return 0+ library.proc_pidinfo.side_effect = exited+ self.assertEqual(thread_times(SimpleNamespace(pid=10), {20}), {})++ def test_native_running_thread_has_increasing_cpu_time(self):+ process = psutil.Process(os.getpid())+ identity = threading.get_native_id()+ before = thread_times(process, {identity})+ deadline = time.thread_time() + .04+ while time.thread_time() < deadline:+ pass+ after = thread_times(process, {identity})+ self.assertGreater(after[identity], before[identity])+ self.assertGreater(cpu_capacity(process), 0)++ @unittest.skipUnless(sys.platform == 'darwin', 'macOS 原生 GPU 能力边界')+ def test_macos_gpu_unavailable_does_not_return_zero(self):+ counter = GpuCounters()+ self.addCleanup(counter.close)+ values, state, reason = counter.sample()+ self.assertIsNone(values)+ self.assertEqual(state, 'unavailable')+ self.assertIn('macOS', reason)+++class LinuxGpuTests(unittest.TestCase):+ def setUp(self):+ temporary = tempfile.TemporaryDirectory()+ self.addCleanup(temporary.cleanup)+ self.root = Path(temporary.name).resolve()+ self.devices = self.root / 'dri'+ self.devices.mkdir()+ self.now = 100.0+ self.counter = LinuxGpuCounters(proc=self.root / 'proc', devices=self.devices, clock=lambda: self.now)+ self.addCleanup(self.counter.close)++ def fd(self, pid, descriptor, busy, *, client=1, capacity=1, device='0000:01:00.0'):+ folder = self.root / 'proc' / str(pid) / 'fdinfo'+ folder.mkdir(parents=True, exist_ok=True)+ path = folder / str(descriptor)+ path.write_text(f'drm-driver: i915\ndrm-pdev: {device}\ndrm-client-id: {client}\n'+ f'drm-engine-render: {busy} ns\ndrm-engine-capacity-render: {capacity}\n')+ return path++ def sample(self, processes=None):+ self.counter.sample()+ return self.counter.sample_processes(processes or {10: 1.0})++ def test_drm_duplicates_are_counted_once_and_capacity_normalizes_busy_time(self):+ for descriptor in (4, 5):+ self.fd(10, descriptor, 1_000_000_000, capacity=2)+ self.assertEqual(self.sample()[1], 'sampling')+ self.now += 2+ for descriptor in (4, 5):+ self.fd(10, descriptor, 3_000_000_000, capacity=2)+ values, state, reason = self.sample()+ self.assertEqual((state, reason), ('ready', ''))+ self.assertEqual(values[10], {'0000:01:00.0:render': 50.0})++ def test_counter_regression_keeps_high_water_mark_and_pid_reuse_starts_sampling(self):+ self.fd(10, 4, 2_000_000_000)+ self.sample()+ self.now += 1+ self.fd(10, 4, 1_000_000_000)+ self.assertEqual(self.sample()[0][10]['0000:01:00.0:render'], 0.0)+ self.now += 1+ self.fd(10, 4, 3_000_000_000)+ self.assertEqual(self.sample()[0][10]['0000:01:00.0:render'], 50.0)+ self.now += 1+ self.assertEqual(self.sample({10: 2.0})[1], 'sampling')++ def test_shared_clients_are_not_attributed_twice_to_owned_processes(self):+ self.fd(10, 4, 0)+ self.fd(20, 6, 0)+ values, state, reason = self.sample({10: 1.0, 20: 2.0})+ self.assertIsNone(values)+ self.assertEqual(state, 'unavailable')+ self.assertIn('共享', reason)++ def test_missing_container_device_or_process_permissions_are_unavailable(self):+ self.devices.rmdir()+ self.assertEqual(self.sample()[1], 'unavailable')+ self.devices.mkdir()+ with patch.object(Path, 'iterdir', side_effect=PermissionError('fdinfo denied')):+ values, state, reason = self.sample()+ self.assertIsNone(values)+ self.assertEqual(state, 'unavailable')+ self.assertIn('denied', reason)++ def test_driver_without_engine_counters_is_not_idle_zero(self):+ path = self.fd(10, 4, 0)+ path.write_text('drm-driver: nvidia\ndrm-client-id: 1\n')+ values, state, reason = self.sample()+ self.assertIsNone(values)+ self.assertEqual(state, 'unavailable')+ self.assertIn('未提供', reason)++ def test_readable_process_with_no_gpu_descriptors_is_idle(self):+ folder = self.root / 'proc/10/fdinfo'+ folder.mkdir(parents=True)+ (folder / '0').write_text('pos: 0\nflags: 0100000\n')+ self.assertEqual(self.sample(), ({10: {}}, 'ready', ''))diff --git a/tests/test_task_resources.py b/tests/test_task_resources.pyindex 10ef3b7c7..a952b0769 100644--- a/tests/test_task_resources.py+++ b/tests/test_task_resources.py@@ -53,6 +53,9 @@ class Process:def children(self, *, recursive=False):return self.members+ def cpu_affinity(self):+ return list(range(4))+class GpuReader:def __init__(self, values=None, *, state='ready', reason=''):@@ -87,6 +90,14 @@ class TaskResourceTests(unittest.TestCase):capacity_patch = patch('peach.task_resources.psutil.cpu_count', return_value=4)self.capacity = capacity_patch.start()self.addCleanup(capacity_patch.stop)+ threads_patch = patch('peach.task_resources.thread_times',+ side_effect=lambda process, wanted: {t.id: t.user_time + t.system_time+ for t in process.threads() if t.id in wanted})+ threads_patch.start()+ self.addCleanup(threads_patch.stop)+ quota_patch = patch('peach.resource_platform.cgroup_capacity', return_value=None)+ quota_patch.start()+ self.addCleanup(quota_patch.stop)def process(self, pid=None):identity = self.root_process.pid if pid is None else int(pid)