diff --git a/app/adapters/system/plugin/package.py b/app/adapters/system/plugin/package.py index 502c2631a..4f98e7be0 100644 --- a/app/adapters/system/plugin/package.py +++ b/app/adapters/system/plugin/package.py @@ -36,6 +36,9 @@ from app.runtime.dependencies.native import ( capture_loaded_native_dependencies, detect_changed_native_dependencies, ) +from app.runtime.execution import ( + plugin_package_lock, +) from app.runtime.execution import ( run_in_threadpool_to_completion as _await_thread_operation, ) @@ -472,6 +475,23 @@ class PluginPackageManager: label: str, ) -> None: """用同级 staging 替换目录,并兼容 overlayfs 的跨设备替换。""" + with plugin_package_lock(target.name): + PluginPackageManager.__restore_tree_locked( + target=target, + snapshot=snapshot, + existed=existed, + label=label, + ) + + @staticmethod + def __restore_tree_locked( + *, + target: Path, + snapshot: Path, + existed: bool, + label: str, + ) -> None: + """在持有插件包锁时用同级 staging 替换目录。""" if existed and not snapshot.is_dir(): raise FileNotFoundError(f"{label}补偿快照不存在:{snapshot}") @@ -1488,11 +1508,11 @@ class PluginPackageManager: 要么是新内容,唯一的中间态是"运行目录短暂缺失、旧内容完整躺在 previous 目录里",仍可人工恢复,不会出现任何一份内容被删到无处可取的时点。 - 两个改名都可能因跨文件系统失败:overlayfs 会拒绝把镜像层的插件目录直接改 - 名到可写层,暂存目录又常落在独立的临时分区。两处都退化为复制,代价是复制 - 期间可能中途失败留下半份目录,因此复制失败一律先删掉半成品再把旧目录换 - 回;换回本身也失败时只记录旧目录的保留位置,原始失败原样挂在异常链上不被 - 吞掉,避免出现"看起来只是安装失败"实则运行目录已空的假象。 + 暂存目录常落在独立的临时分区,不能直接改名到运行目录。此时先把新内容完整 + 复制到运行目录同级的隐藏暂存目录,再用一次原子改名发布;插件加载器不会看见 + 逐文件复制中的半成品。改名旧目录也可能被 overlayfs 拒绝,退化为复制旧内容 + 留档后再清理运行目录。复制失败时先删掉半成品再把旧目录换回;换回本身也失败 + 时只记录旧目录的保留位置,原始失败原样挂在异常链上不被吞掉。 旧目录退化为复制后还得逐个删掉原目录,这一步同样可能删到一半才失败。删除 一旦开始运行目录就不再完整,因此把"可回滚"状态提前到删除之前置位:只要运 @@ -1503,12 +1523,32 @@ class PluginPackageManager: :param final_dir: 插件运行目录,可能已存在旧内容 :raise PluginContentSwapError: 换入失败,异常携带运行目录的实际恢复结论 """ + with plugin_package_lock(final_dir.name): + PluginPackageManager.__swap_staged_plugin_content_locked( + staging_dir=staging_dir, + final_dir=final_dir, + ) + + @staticmethod + def __swap_staged_plugin_content_locked( + *, + staging_dir: Path, + final_dir: Path, + ) -> None: + """在持有插件包锁时发布暂存内容并保留失败回滚能力。""" final_dir.parent.mkdir(parents=True, exist_ok=True) previous = final_dir.parent / f".{final_dir.name}.previous-{uuid.uuid4().hex}" + publish_staging: Optional[Path] = None previous_available = False runtime_dirty = False published = False try: + publish_source, publish_staging = ( + PluginPackageManager.__prepare_publish_source( + staging_dir=staging_dir, + final_dir=final_dir, + ) + ) if final_dir.exists(): try: final_dir.replace(previous) @@ -1525,14 +1565,22 @@ class PluginPackageManager: # 旧内容已挪开或本来就不存在,此后才允许重建运行目录 runtime_dirty = True try: - staging_dir.replace(final_dir) + publish_source.replace(final_dir) except OSError as error: if error.errno != errno.EXDEV: raise + if publish_source != staging_dir: + raise logger.debug( - f"插件安装内容跨文件系统无法改名换入,退化为复制:{staging_dir}" + f"插件安装内容跨文件系统无法改名换入,先复制到运行目录同级暂存:" + f"{staging_dir}" ) - shutil.copytree(staging_dir, final_dir, symlinks=True) + publish_staging = ( + final_dir.parent + / f".{final_dir.name}.staging-{uuid.uuid4().hex}" + ) + shutil.copytree(staging_dir, publish_staging, symlinks=True) + publish_staging.replace(final_dir) published = True except Exception as error: # 运行目录从未被触碰时无需回滚,它本身就还是换入前那一份 @@ -1553,9 +1601,30 @@ class PluginPackageManager: error, runtime_intact=runtime_intact ) from error finally: + if publish_staging and publish_staging.exists(): + shutil.rmtree(publish_staging, ignore_errors=True) if previous.exists() and (published or not previous_available): shutil.rmtree(previous, ignore_errors=True) + @staticmethod + def __prepare_publish_source( + *, + staging_dir: Path, + final_dir: Path, + ) -> tuple[Path, Optional[Path]]: + """将跨文件系统的安装载荷复制到运行目录同级,供后续原子改名发布。""" + if ( + not staging_dir.exists() + or staging_dir.stat().st_dev == final_dir.parent.stat().st_dev + ): + return staging_dir, None + + publish_staging = ( + final_dir.parent / f".{final_dir.name}.staging-{uuid.uuid4().hex}" + ) + shutil.copytree(staging_dir, publish_staging, symlinks=True) + return publish_staging, publish_staging + async def __async_swap_staged_plugin_content( self, staging_dir: Path, final_dir: Path ) -> None: diff --git a/app/runtime/execution.py b/app/runtime/execution.py index 2b5fc4ffe..af20f91f5 100644 --- a/app/runtime/execution.py +++ b/app/runtime/execution.py @@ -2,7 +2,9 @@ import asyncio import inspect import threading import time +from collections.abc import Iterator from concurrent.futures import Executor, Future, ThreadPoolExecutor, wait +from contextlib import contextmanager from contextvars import Context, copy_context from functools import partial, wraps from typing import Any, Callable, TypeVar, cast @@ -15,6 +17,23 @@ from app.schemas.exception import ImmediateException TaskResult = TypeVar("TaskResult") ExecutorResult = TypeVar("ExecutorResult") +# 包目录替换在线程池中执行,导入在同步生命周期线程中执行;两者须共享进程锁。 +_plugin_package_locks: dict[str, Any] = {} +_plugin_package_locks_guard = threading.Lock() + + +@contextmanager +def plugin_package_lock(plugin_id: str) -> Iterator[None]: + """串行化单个插件的代码导入、包替换和目录恢复。""" + normalized_id = plugin_id.casefold() + with _plugin_package_locks_guard: + lock = _plugin_package_locks.setdefault( + normalized_id, + threading.RLock(), + ) + with lock: + yield + def submit_with_context( executor: Executor, diff --git a/app/runtime/extensions/plugin/lifecycle.py b/app/runtime/extensions/plugin/lifecycle.py index 46382e257..af2d81d06 100644 --- a/app/runtime/extensions/plugin/lifecycle.py +++ b/app/runtime/extensions/plugin/lifecycle.py @@ -197,6 +197,11 @@ class PluginLifecycle: if self._runtime_compatible(plugin_id) else PluginRuntimeStatus.INCOMPATIBLE_RUNTIME ) + if status is PluginRuntimeStatus.LOAD_FAILED: + self._logger.error( + f"插件 {plugin_id} 加载失败:加载器未返回匹配的插件类," + "请检查插件目录内容及模块导入日志" + ) self._runtime_status_writer(plugin_id, status) results[plugin_id] = status self._clear_tools() diff --git a/app/runtime/extensions/plugin/loader.py b/app/runtime/extensions/plugin/loader.py index c3642dabb..845810e04 100644 --- a/app/runtime/extensions/plugin/loader.py +++ b/app/runtime/extensions/plugin/loader.py @@ -14,6 +14,7 @@ from typing import Any, Optional from app.domain.plugin import check_plugin_runtime_compatibility from app.foundation.environment import is_free_threaded_runtime +from app.runtime.execution import plugin_package_lock from app.runtime.extensions.plugin.gil import ( GilFallbackRecorder, attribute_gil_fallback, @@ -165,8 +166,8 @@ class PluginLoader: self._logger.debug("没有需要加载的插件") return [] - plugins = [] - loaded_classes = set() + plugins: list[Any] = [] + loaded_classes: set[str] = set() for plugin_dir in self._plugins_root.iterdir(): if not plugin_dir.is_dir() or plugin_dir.name.startswith("_"): continue @@ -175,60 +176,89 @@ class PluginLoader: f"跳过插件目录:{plugin_dir.name}(不在加载列表中)" ) continue - if not (plugin_dir / "__init__.py").exists(): - self._logger.debug( - f"跳过插件目录:{plugin_dir.name}(缺少__init__.py)" - ) - continue - if not self._is_runtime_compatible(plugin_dir.name): - self._logger.warning( - f"跳过插件 {plugin_dir.name}:声明与当前运行时不兼容" - ) - self._mark_incompatible_runtime( - installed_ids.get(plugin_dir.name, plugin_dir.name) - ) - continue - - try: - module_name = f"app.plugins.{plugin_dir.name}" - self._logger.debug(f"正在导入插件模块:{module_name}") - self._import_preparer( - plugin_id=plugin_dir.name, + with plugin_package_lock(plugin_dir.name): + self._load_plugin_directory( plugin_dir=plugin_dir, - ) - self._import_scanner( - plugin_id=plugin_dir.name, - plugin_dir=plugin_dir, - ) - # 插件模块顶层导入原生扩展最常见,GIL 回退多发生在这一步; - # 全量启动时逐个模块观察,才能把回退归因到具体插件 - with attribute_gil_fallback( - installed_ids.get(plugin_dir.name, plugin_dir.name), - self._gil_fallback_recorder, - ): - module = importlib.import_module(module_name) - for name, candidate in module.__dict__.items(): - if name.startswith("_") or not isinstance(candidate, type): - continue - if name in loaded_classes or not validator(candidate): - continue - loaded_classes.add(name) - plugins.append(candidate) - self._logger.debug(f"找到符合条件的插件类:{name}") - break - except Exception as err: - self._logger.error( - f"加载插件 {plugin_dir.name} 失败:{str(err)} - " - f"{traceback.format_exc()}" + plugin_id=installed_ids.get( + plugin_dir.name, + plugin_dir.name, + ), + validator=validator, + loaded_classes=loaded_classes, + plugins=plugins, ) return plugins + def _load_plugin_directory( + self, + *, + plugin_dir: Path, + plugin_id: str, + validator: PluginValidator, + loaded_classes: set[str], + plugins: list[Any], + ) -> None: + """在持有包锁期间验证并导入一个完整的插件目录。""" + if not (plugin_dir / "__init__.py").exists(): + self._logger.debug( + f"跳过插件目录:{plugin_dir.name}(缺少__init__.py)" + ) + return + if not self._is_runtime_compatible(plugin_dir.name): + self._logger.warning( + f"跳过插件 {plugin_dir.name}:声明与当前运行时不兼容" + ) + self._mark_incompatible_runtime(plugin_id) + return + + try: + module_name = f"app.plugins.{plugin_dir.name}" + self._logger.debug(f"正在导入插件模块:{module_name}") + self._import_preparer( + plugin_id=plugin_dir.name, + plugin_dir=plugin_dir, + ) + self._import_scanner( + plugin_id=plugin_dir.name, + plugin_dir=plugin_dir, + ) + # 插件模块顶层导入原生扩展最常见,GIL 回退多发生在这一步; + # 全量启动时逐个模块观察,才能把回退归因到具体插件 + with attribute_gil_fallback( + plugin_id, + self._gil_fallback_recorder, + ): + module = importlib.import_module(module_name) + for name, candidate in module.__dict__.items(): + if name.startswith("_") or not isinstance(candidate, type): + continue + if name in loaded_classes or not validator(candidate): + continue + loaded_classes.add(name) + plugins.append(candidate) + self._logger.debug(f"找到符合条件的插件类:{name}") + break + except Exception as error: + self._logger.error( + f"加载插件 {plugin_dir.name} 失败:{str(error)} - " + f"{traceback.format_exc()}" + ) + def load_instance( self, instance: PluginInstance, validator: PluginValidator, ) -> list[Any]: """在实例专属模块命名空间中重新执行源插件代码并返回适配类。""" + with plugin_package_lock(instance.source_plugin_id): + return self._load_instance_locked(instance, validator) + + def _load_instance_locked( + self, + instance: PluginInstance, + validator: PluginValidator, + ) -> list[Any]: + """在持有源插件包锁时从磁盘加载虚拟插件实例模块。""" source_dir = self._plugins_root / instance.source_plugin_id.lower() source_file = source_dir / "__init__.py" if not source_file.exists(): diff --git a/app/runtime/extensions/plugin/sync.py b/app/runtime/extensions/plugin/sync.py index 5f9f0e8c1..b7b539876 100644 --- a/app/runtime/extensions/plugin/sync.py +++ b/app/runtime/extensions/plugin/sync.py @@ -43,7 +43,7 @@ class PluginSyncService: *, online_restore_plugins: set[str] | None = None, ) -> list[str]: - """并发安装本地缺失、需要更新或应恢复在线载荷的插件。""" + """并发安装缺失或需恢复的插件,单个失败只记状态并继续启动编排。""" if self._frozen(): return [] @@ -177,6 +177,7 @@ class PluginSyncService: except Exception as error: # noqa: BLE001 if plugin.id.lower() in recovery_ids: failed_recovery.append(plugin.id) + failed.append(plugin.id) if self._runtime_status_writer: self._runtime_status_writer( plugin.id, @@ -190,8 +191,8 @@ class PluginSyncService: f"第三方插件安装完成,成功:{len(synced)} 个,失败:{len(failed)} 个" ) if failed_recovery: - raise RuntimeError( - "插件同步未完成:" + self._logger.warning( + "以下插件恢复同步失败,继续处理其它可用插件:" f"{', '.join(sorted(set(failed_recovery)))}" ) return synced diff --git a/app/startup/initializers/plugins.py b/app/startup/initializers/plugins.py index 257d24f8a..af95a596c 100644 --- a/app/startup/initializers/plugins.py +++ b/app/startup/initializers/plugins.py @@ -921,6 +921,12 @@ async def _sync_plugins_admitted( return False if not changed_ids: + if any( + status is PluginRuntimeStatus.SYNC_FAILED + for status in previous_statuses.values() + ): + logger.warning("插件同步存在失败项,已继续初始化其余服务") + return True logger.debug("没有新的插件进入可运行状态") return False @@ -954,7 +960,12 @@ def _activate_ready_plugins( previous_statuses.get(plugin_id) is PluginRuntimeStatus.DEPENDENCY_PENDING ) - if plugin_id in running_ids and (source_id in synced or dependency_recovered): + sync_failed = ( + previous_statuses.get(plugin_id) is PluginRuntimeStatus.SYNC_FAILED + ) + if plugin_id in running_ids and ( + source_id in synced or dependency_recovered or sync_failed + ): plugin_manager.reload_plugin(plugin_id) changed_ids.append(plugin_id) continue diff --git a/docs/architecture-overview.md b/docs/architecture-overview.md index b9db4a4e2..1fb16c68f 100644 --- a/docs/architecture-overview.md +++ b/docs/architecture-overview.md @@ -763,7 +763,7 @@ flowchart LR | 指标 | 当前值 | |---|---:| | Python 模块 | 1114 | -| 内部导入边 | 9,421 | +| 内部导入边 | 9,422 | | 非平凡 SCC | 1(精确 containment 的 TMDB 移植包环) | | Application / Chain 具体 Adapter 直连 | 0 / 0 | | Direct egress | 49(债务已清零,49 条精确 containment) | @@ -773,7 +773,7 @@ flowchart LR | Model/Oper 自动事务与自建 Session | 0 | | 组合根外 `SystemConfigOper()` | 0 | -整理失败反馈由 `app.application.transfer.feedback` 集中投影;已整理下载的站点字幕复用 `app.chain.transfer` 自动整理队列;网络连通性检测按 `app.application.nettest` 归档,并覆盖 HTTP 与 WebSocket 探测。未启用智能助手的消息音乐交互由 `app.chain.music_interaction` 包中的解析展示与订阅协调模块处理;音乐标签准入与批次共识由 `app.chain.transfer.music` 负责,预览证据由 `app.application.transfer.projection` 只读投影;宿主依赖边现为 9,421;工作流添加下载动作由 `app.workflow.actions.add_download` 转换工作流 Schema 为下载链领域上下文,新增 5 条模块导入边。音乐来源链与识别缓存复用领域身份核验,音乐交互包未新增 SCC,插件一次性任务 owner `app.scheduler.oncejob` 带来 1 个模块和 9 条依赖边。Agent 持久回执新增 Application 端口及 DB Model/Oper/Adapter 四个冷导入模块。缓存组合根只在启动时选用 Redis 缓存才导入 Redis 适配器,依赖 langchain_core 的对话记忆模型归属 `app.agent.memory`,文件缓存且未启用智能体的实例不再加载 redis 与 langchain_core。Telegram 渠道改用模块内 `app.modules.telegram.botapi` 精简 Bot API 客户端,经 `RequestUtils` 出站,宿主不再导入 pyTelegramBotAPI,启用 Telegram 的实例也不会因该 SDK 加载 redis;该依赖暂时保留给插件使用。Web Push 协议(aes128gcm 加密、VAPID 签名与经 `RequestUtils` 投递)由网络适配器 `app.adapters.network.webpush` 直接基于 http-ece 与 py-vapid 实现,消息端点与 `WebPushModule` 共用,宿主不再导入 pywebpush 及其连带的 aiohttp;该依赖同样暂时保留给插件使用。飞书渠道改用模块内 `app.modules.feishu.openapi` OpenAPI 客户端(经 `RequestUtils` 出站)与网络适配器 `app.adapters.network.feishu` 事件长连接(websocket-client 同步收发 pbbp2 帧),宿主不再导入 lark-oapi 及其上万个生成模块,长连接也不再依赖 SDK 的模块级事件循环;插件经 `app.sdk.feishu` 复用同一长连接,lark-oapi 暂时保留给尚未迁移的插件使用。API 文档路由由 `app.adapters.web.docs` 按 `API_DOCS_ENABLE` 逐请求开放,默认关闭,未开放时不生成文档。当前 `app.startup.lifecycle` 为 582、`app.factory` 为 595、`app.main` 为 597。音乐调用观察 `app.application.music.observation` 新增一个轻量模块,记录来源结果及请求预算;AcoustID及路径识别复用此上下文传递有界指纹候选,保留旧单ID模块合同。站点图片域名快照新增 `app.application.security.image`,各启动入口增加一个模块;性能基线只同步模块数量,原有耗时预算、历史采样和生命周期资源约束保持有效。 +整理失败反馈由 `app.application.transfer.feedback` 集中投影;已整理下载的站点字幕复用 `app.chain.transfer` 自动整理队列;网络连通性检测按 `app.application.nettest` 归档,并覆盖 HTTP 与 WebSocket 探测。未启用智能助手的消息音乐交互由 `app.chain.music_interaction` 包中的解析展示与订阅协调模块处理;音乐标签准入与批次共识由 `app.chain.transfer.music` 负责,预览证据由 `app.application.transfer.projection` 只读投影;宿主依赖边现为 9,422;工作流添加下载动作由 `app.workflow.actions.add_download` 转换工作流 Schema 为下载链领域上下文,新增 5 条模块导入边。音乐来源链与识别缓存复用领域身份核验,音乐交互包未新增 SCC,插件一次性任务 owner `app.scheduler.oncejob` 带来 1 个模块和 9 条依赖边。Agent 持久回执新增 Application 端口及 DB Model/Oper/Adapter 四个冷导入模块。缓存组合根只在启动时选用 Redis 缓存才导入 Redis 适配器,依赖 langchain_core 的对话记忆模型归属 `app.agent.memory`,文件缓存且未启用智能体的实例不再加载 redis 与 langchain_core。Telegram 渠道改用模块内 `app.modules.telegram.botapi` 精简 Bot API 客户端,经 `RequestUtils` 出站,宿主不再导入 pyTelegramBotAPI,启用 Telegram 的实例也不会因该 SDK 加载 redis;该依赖暂时保留给插件使用。Web Push 协议(aes128gcm 加密、VAPID 签名与经 `RequestUtils` 投递)由网络适配器 `app.adapters.network.webpush` 直接基于 http-ece 与 py-vapid 实现,消息端点与 `WebPushModule` 共用,宿主不再导入 pywebpush 及其连带的 aiohttp;该依赖同样暂时保留给插件使用。飞书渠道改用模块内 `app.modules.feishu.openapi` OpenAPI 客户端(经 `RequestUtils` 出站)与网络适配器 `app.adapters.network.feishu` 事件长连接(websocket-client 同步收发 pbbp2 帧),宿主不再导入 lark-oapi 及其上万个生成模块,长连接也不再依赖 SDK 的模块级事件循环;插件经 `app.sdk.feishu` 复用同一长连接,lark-oapi 暂时保留给尚未迁移的插件使用。API 文档路由由 `app.adapters.web.docs` 按 `API_DOCS_ENABLE` 逐请求开放,默认关闭,未开放时不生成文档。当前 `app.startup.lifecycle` 为 582、`app.factory` 为 595、`app.main` 为 597。音乐调用观察 `app.application.music.observation` 新增一个轻量模块,记录来源结果及请求预算;AcoustID及路径识别复用此上下文传递有界指纹候选,保留旧单ID模块合同。站点图片域名快照新增 `app.application.security.image`,各启动入口增加一个模块;性能基线只同步模块数量,原有耗时预算、历史采样和生命周期资源约束保持有效。 架构专项验证分为两个 CI 投影:`Check event semantic policy` 先运行依赖、Adapter、出口和 Event 语义门禁,`Check host architecture snapshot` 再执行快照测试及一次 diff --git a/docs/refactor/optimization-checklist.md b/docs/refactor/optimization-checklist.md index 6b4caeb4f..a8356bd08 100644 --- a/docs/refactor/optimization-checklist.md +++ b/docs/refactor/optimization-checklist.md @@ -98,7 +98,7 @@ ARCH-201 至 ARCH-204 均达到实现、验证、提交、推送和远端门禁 | 指标 | 当前值 | 解释 | |---|---:|---| -| 宿主 Python 模块 / 内部依赖边 | 1114 / 9,421 | `dependency-baseline.json` 当前快照;系统设置合同按 `app.application.settings` 包组织,系统设置 API 端点独立按 `app.api.endpoints.settings` 归档;消息音乐交互由 `app.chain.music_interaction` 包中的音乐解析/展示与订阅协调模块处理;已整理下载的站点字幕经 `app.chain.transfer` 自动整理队列完成命名与归档;网络连通性检测按 `app.application.nettest` 归档;工作流添加下载动作由 `app.workflow.actions.add_download` 转换工作流 Schema 为下载链领域上下文,新增 5 条合法模块导入边;LLM 独占连接关闭复用宿主线程池;歌词字形转换复用 `app.foundation.text`;订阅创建使用 `app.domain.context.MediaInfo` 和运行时配置端口,将非 TMDB 影视身份投影为 TMDB 身份 | +| 宿主 Python 模块 / 内部依赖边 | 1114 / 9,422 | `dependency-baseline.json` 当前快照;系统设置合同按 `app.application.settings` 包组织,系统设置 API 端点独立按 `app.api.endpoints.settings` 归档;消息音乐交互由 `app.chain.music_interaction` 包中的音乐解析/展示与订阅协调模块处理;已整理下载的站点字幕经 `app.chain.transfer` 自动整理队列完成命名与归档;网络连通性检测按 `app.application.nettest` 归档;工作流添加下载动作由 `app.workflow.actions.add_download` 转换工作流 Schema 为下载链领域上下文,新增 5 条合法模块导入边;LLM 独占连接关闭复用宿主线程池;歌词字形转换复用 `app.foundation.text`;订阅创建使用 `app.domain.context.MediaInfo` 和运行时配置端口,将非 TMDB 影视身份投影为 TMDB 身份 | | 非平凡 SCC | 1 | 仅保留精确 containment 的 29 模块 TMDB 移植包环 | | 跨层 DB 边界债务 | 0 | Application、Chain、API、Agent、Runtime、Workflow 到 DB 的受控债务均为零 | | Model/Oper 事务债务 | 0 | 自建 Session、自动事务装饰器、直接 commit/rollback 等基线均为零 | diff --git a/tests/fixtures/architecture/dependency-baseline.json b/tests/fixtures/architecture/dependency-baseline.json index 1e786d202..aaac0ca4c 100644 --- a/tests/fixtures/architecture/dependency-baseline.json +++ b/tests/fixtures/architecture/dependency-baseline.json @@ -941,8 +941,8 @@ "runtime_only": true } }, - "edge_count": 9421, - "edge_sha256": "605aad14dd551c25ca9d9bb87680f4ca05c68d00b613ce552abb19f0449c8669", + "edge_count": 9422, + "edge_sha256": "db087968510ab776ed59d5c8a06b673795620b5d15e00752731f1c96af59947d", "edges": [ "app -> app.foundation", "app -> app.foundation.environment", @@ -8861,6 +8861,7 @@ "app.runtime.extensions.plugin.loader -> app.foundation", "app.runtime.extensions.plugin.loader -> app.foundation.environment", "app.runtime.extensions.plugin.loader -> app.runtime", + "app.runtime.extensions.plugin.loader -> app.runtime.execution", "app.runtime.extensions.plugin.loader -> app.runtime.extensions", "app.runtime.extensions.plugin.loader -> app.runtime.extensions.plugin", "app.runtime.extensions.plugin.loader -> app.runtime.extensions.plugin.gil", diff --git a/tests/test_plugin_install_atomic_swap.py b/tests/test_plugin_install_atomic_swap.py index 89591a9c9..e0b873f3c 100644 --- a/tests/test_plugin_install_atomic_swap.py +++ b/tests/test_plugin_install_atomic_swap.py @@ -2,6 +2,8 @@ import errno import shutil +import threading +from contextlib import contextmanager from pathlib import Path from types import SimpleNamespace from unittest.mock import Mock @@ -12,6 +14,7 @@ from app.adapters.system.plugin.package import ( PluginContentSwapError, PluginPackageManager, ) +from app.runtime.extensions.plugin.loader import PluginLoader PLUGIN_ID = "DemoPlugin" REPO_URL = "https://github.com/demo/MoviePilot-Plugins" @@ -89,6 +92,7 @@ def _assert_no_staging_residue(tmp_path: Path) -> None: def _assert_no_swap_residue(plugin_dir: Path) -> None: """换入结束后不得在插件根目录残留换入用的回滚材料。""" assert not list(plugin_dir.parent.glob(f".{plugin_dir.name}.previous-*")) + assert not list(plugin_dir.parent.glob(f".{plugin_dir.name}.staging-*")) @pytest.mark.parametrize("force_install", [True, False]) @@ -302,7 +306,7 @@ def test_swap_publishes_new_content_and_drops_old_content(tmp_path: Path) -> Non def test_swap_falls_back_to_copy_when_staging_crosses_filesystems( monkeypatch, tmp_path: Path ) -> None: - """暂存目录与插件根目录跨文件系统时退化为复制,结果与改名一致。""" + """暂存目录跨文件系统时先完整复制到同级再原子发布。""" staging_dir, final_dir = _staged_pair(tmp_path) _break_replace(monkeypatch, source=staging_dir, code=errno.EXDEV) @@ -313,6 +317,49 @@ def test_swap_falls_back_to_copy_when_staging_crosses_filesystems( _assert_no_swap_residue(final_dir) +def test_swap_prepares_cross_device_content_before_touching_runtime_directory( + monkeypatch, tmp_path: Path +) -> None: + """跨文件系统载荷须先在运行目录旁完整就位,避免加载器读到半份内容。""" + staging_dir, final_dir = _staged_pair(tmp_path) + original_stat = Path.stat + original_copytree = shutil.copytree + copied_destinations: list[Path] = [] + + def cross_device_stat(path: Path, *, follow_symlinks: bool = True): + """只把外置安装暂存目录报告为另一个文件系统。""" + result = original_stat(path, follow_symlinks=follow_symlinks) + if path == staging_dir: + return SimpleNamespace(st_dev=result.st_dev + 1, st_mode=result.st_mode) + return result + + def observe_copy(src, dst, *args, **kwargs): + """确认新载荷复制时旧运行目录仍保持完整。""" + if Path(src) == staging_dir: + destination = Path(dst) + copied_destinations.append(destination) + assert destination.parent == final_dir.parent + assert destination != final_dir + assert (final_dir / "__init__.py").read_text(encoding="utf-8") == ( + INSTALLED_MARK + ) + assert (final_dir / "stale.py").exists() + return original_copytree(src, dst, *args, **kwargs) + + monkeypatch.setattr(Path, "stat", cross_device_stat) + monkeypatch.setattr( + "app.adapters.system.plugin.package.shutil.copytree", observe_copy + ) + + _swap(staging_dir, final_dir) + + assert len(copied_destinations) == 1 + assert copied_destinations[0].name.startswith(f".{final_dir.name}.staging-") + assert (final_dir / "__init__.py").read_text(encoding="utf-8") == "upgraded" + assert not (final_dir / "stale.py").exists() + _assert_no_swap_residue(final_dir) + + def test_swap_falls_back_to_copy_when_old_directory_cannot_be_renamed( monkeypatch, tmp_path: Path ) -> None: @@ -327,6 +374,117 @@ def test_swap_falls_back_to_copy_when_old_directory_cannot_be_renamed( _assert_no_swap_residue(final_dir) +@pytest.mark.parametrize("restore", [False, True], ids=["install", "rollback"]) +def test_plugin_loader_waits_for_overlayfs_package_replacement( + monkeypatch, tmp_path: Path, restore: bool +) -> None: + """安装换入和事务回滚都须在包锁内完成逐文件删除与目录替换。""" + import app.adapters.system.plugin.package as package_module + import app.runtime.extensions.plugin.loader as loader_module + + plugin_root = tmp_path / "plugins" + plugin_dir = plugin_root / "demo" + plugin_dir.mkdir(parents=True) + (plugin_dir / "__init__.py").write_text("old", encoding="utf-8") + (plugin_dir / "version.py").write_text("old", encoding="utf-8") + staging_dir = tmp_path / "staging" / "demo" + staging_dir.mkdir(parents=True) + (staging_dir / "__init__.py").write_text("new", encoding="utf-8") + (staging_dir / "version.py").write_text("new", encoding="utf-8") + + original_replace = Path.replace + real_rmtree = shutil.rmtree + removal_started = threading.Event() + allow_removal = threading.Event() + loader_waiting = threading.Event() + loader_lock_acquired = threading.Event() + import_completed = threading.Event() + imported_versions: list[str] = [] + + def cross_device_old_directory(source: Path, destination: Path) -> Path: + """模拟 overlayfs 拒绝将旧 lower-layer 目录改名到 previous。""" + if source == plugin_dir and ".previous-" in destination.name: + raise OSError(errno.EXDEV, "cross-device link") + return original_replace(source, destination) + + def block_old_directory_removal(path: Path, *args, **kwargs) -> None: + """在旧文件删除窗口暂停,模拟评论中观察到的逐文件替换时间线。""" + if path == plugin_dir: + (plugin_dir / "version.py").unlink(missing_ok=True) + removal_started.set() + if not allow_removal.wait(timeout=3): + raise TimeoutError("test did not release simulated package removal") + real_rmtree(path, *args, **kwargs) + + @contextmanager + def observe_loader_lock(plugin_id: str): + """记录加载器已到达包锁,再委托真实锁完成并发协调。""" + loader_waiting.set() + with package_module.plugin_package_lock(plugin_id): + loader_lock_acquired.set() + yield + + def import_plugin(_module_name: str) -> SimpleNamespace: + """读取模块导入依赖的文件并记录实际可见版本。""" + imported_versions.append( + (plugin_dir / "version.py").read_text(encoding="utf-8") + ) + import_completed.set() + return SimpleNamespace(__dict__={}) + + monkeypatch.setattr(Path, "replace", cross_device_old_directory) + monkeypatch.setattr(package_module.shutil, "rmtree", block_old_directory_removal) + monkeypatch.setattr(loader_module, "plugin_package_lock", observe_loader_lock) + monkeypatch.setattr(loader_module, "get_runtime_setting", lambda _key: None) + monkeypatch.setattr( + loader_module, + "importlib", + SimpleNamespace(import_module=import_plugin), + ) + loader = PluginLoader( + plugins_root=plugin_root, + import_preparer=Mock(), + import_scanner=Mock(), + log=Mock(), + runtime_declaration=lambda _plugin_id: {}, + ) + + def replace_package() -> None: + """执行安装换入或事务恢复。""" + if restore: + PluginPackageManager._PluginPackageManager__restore_tree( # type: ignore[attr-defined] + target=plugin_dir, + snapshot=staging_dir, + existed=True, + label="插件 demo", + ) + else: + _swap(staging_dir, plugin_dir) + + swap_thread = threading.Thread(target=replace_package, daemon=True) + swap_thread.start() + try: + assert removal_started.wait(timeout=3) + loader_thread = threading.Thread( + target=loader.load, + args=("demo", ["demo"], lambda _candidate: True), + daemon=True, + ) + loader_thread.start() + assert loader_waiting.wait(timeout=3) + assert not loader_lock_acquired.wait(timeout=0.1) + assert not import_completed.is_set() + finally: + allow_removal.set() + swap_thread.join(timeout=3) + if "loader_thread" in locals(): + loader_thread.join(timeout=3) + + assert not swap_thread.is_alive() + assert "loader_thread" in locals() and not loader_thread.is_alive() + assert imported_versions == ["new"] + + def test_swap_keeps_old_content_when_staging_is_missing(tmp_path: Path) -> None: """待换入内容不存在时运行目录必须原样退回,而不是被清空。""" staging_dir, final_dir = _staged_pair(tmp_path) diff --git a/tests/test_plugin_lifecycle_status.py b/tests/test_plugin_lifecycle_status.py index c8fae74bd..9ab1a55e0 100644 --- a/tests/test_plugin_lifecycle_status.py +++ b/tests/test_plugin_lifecycle_status.py @@ -117,14 +117,17 @@ def test_lifecycle_records_load_failure_for_init_exception(): def test_lifecycle_records_load_failure_when_loader_returns_no_class(): - """目标源码无法产生合法插件类时进入 load_failed。""" - lifecycle, _classes, running, statuses = _lifecycle(plugins=[]) + """目标源码没有可加载类时进入 load_failed 并记录插件及诊断阶段。""" + log = MagicMock() + lifecycle, _classes, running, statuses = _lifecycle(plugins=[], log=log) result = lifecycle.start("DemoPlugin") assert result == {"DemoPlugin": PluginRuntimeStatus.LOAD_FAILED} assert running == {} assert statuses["DemoPlugin"] is PluginRuntimeStatus.LOAD_FAILED + assert "DemoPlugin" in log.error.call_args.args[0] + assert "加载器未返回匹配的插件类" in log.error.call_args.args[0] def test_lifecycle_reports_incompatible_runtime_instead_of_load_failure(): diff --git a/tests/test_plugin_monitor_lifecycle.py b/tests/test_plugin_monitor_lifecycle.py index d154ea13f..59a291be5 100644 --- a/tests/test_plugin_monitor_lifecycle.py +++ b/tests/test_plugin_monitor_lifecycle.py @@ -407,6 +407,66 @@ async def test_sync_plugins_reloads_only_updated_running_plugins(monkeypatch) -> register.assert_called_once_with("UpdatedPlugin") +@pytest.mark.asyncio +async def test_sync_plugins_reloads_running_plugin_after_sync_failure( + monkeypatch, +) -> None: + """回滚后仍运行的插件需重新确认运行态,并继续激活其他就绪插件。""" + manager = MagicMock() + manager.sync.return_value = [] + manager.async_install_plugin_missing_dependencies_with_status.return_value = ( + PluginDependencyInstallResult(missing=[], success=True) + ) + manager.classify_plugins.return_value = PluginDependencyClassification( + ready=("RecoveredPlugin", "OtherPlugin"), + missing_dependencies=(), + missing_source=(), + ) + manager.running_plugins = {"RecoveredPlugin": object()} + register = _patch_sync_plugins(monkeypatch, manager) + manager.get_plugin_runtime_statuses.return_value = { + "RecoveredPlugin": PluginRuntimeStatus.SYNC_FAILED, + } + + assert await plugins_initializer.sync_plugins() is True + + manager.reload_plugin.assert_called_once_with("RecoveredPlugin") + manager.start.assert_called_once_with("OtherPlugin") + assert [call.args[0] for call in register.call_args_list] == [ + "RecoveredPlugin", + "OtherPlugin", + ] + + +@pytest.mark.asyncio +async def test_sync_plugins_continues_startup_when_failed_plugin_is_not_ready( + monkeypatch, +) -> None: + """不可恢复的单插件失败仍让启动继续完成依赖与服务初始化。""" + manager = MagicMock() + manager.sync.return_value = [] + manager.async_install_plugin_missing_dependencies_with_status.return_value = ( + PluginDependencyInstallResult(missing=[], success=True) + ) + manager.classify_plugins.return_value = PluginDependencyClassification( + ready=(), + missing_dependencies=(), + missing_source=("FailedPlugin",), + ) + manager.running_plugins = {} + register = _patch_sync_plugins(monkeypatch, manager) + manager.get_plugin_runtime_statuses.return_value = { + "FailedPlugin": PluginRuntimeStatus.SYNC_FAILED, + } + + assert await plugins_initializer.sync_plugins() is True + + manager.async_install_plugin_missing_dependencies_with_status.assert_awaited_once() + manager.start.assert_not_called() + manager.reload_plugin.assert_not_called() + register.assert_not_called() + + @pytest.mark.asyncio async def test_sync_plugins_reloads_running_plugin_after_dependency_recovery( monkeypatch, diff --git a/tests/test_plugin_sync_service.py b/tests/test_plugin_sync_service.py index 14fab2753..b0c32942c 100644 --- a/tests/test_plugin_sync_service.py +++ b/tests/test_plugin_sync_service.py @@ -265,8 +265,8 @@ def test_market_sync_defers_source_selection_to_gateway() -> None: install.assert_called_once_with(local.id, local.repo_url, False, None) -def test_market_sync_reports_local_install_failure() -> None: - """本地载荷安装失败必须阻止启动编排继续激活旧代码。""" +def test_market_sync_isolates_local_install_failure() -> None: + """本地载荷恢复失败保留该插件状态,但不阻止其余启动编排。""" local = SimpleNamespace( id="DemoPlugin", repo_url="local://DemoPlugin?path=/private/plugins&version=v3", @@ -275,6 +275,7 @@ def test_market_sync_reports_local_install_failure() -> None: system_version_compatible=True, runtime_compatible=True, ) + statuses: list[tuple[str, PluginRuntimeStatus]] = [] service = PluginSyncService( frozen=lambda: False, installed_plugins=lambda: [local.id], @@ -283,11 +284,60 @@ def test_market_sync_reports_local_install_failure() -> None: merge_plugins=lambda items, *_args: items, plugin_exists=lambda *_args: False, install=Mock(return_value=(False, "copy failed")), + runtime_status_writer=lambda plugin_id, status: statuses.append( + (plugin_id, status) + ), log=Mock(), ) - with pytest.raises(RuntimeError, match="插件同步未完成:DemoPlugin"): - service.sync() + assert service.sync() == [] + assert statuses == [("DemoPlugin", PluginRuntimeStatus.SYNC_FAILED)] + + +def test_market_sync_continues_after_one_plugin_install_failure() -> None: + """一个恢复目标失败时仍完成其它插件的安装并返回其成功清单。""" + failed = SimpleNamespace( + id="FailedPlugin", + repo_url="local://FailedPlugin?version=v3", + plugin_name="Failed", + plugin_version="1.0.0", + system_version_compatible=True, + runtime_compatible=True, + ) + succeeded = SimpleNamespace( + id="GoodPlugin", + repo_url="local://GoodPlugin?version=v3", + plugin_name="Good", + plugin_version="1.0.0", + system_version_compatible=True, + runtime_compatible=True, + ) + install = Mock( + side_effect=lambda plugin_id, *_args: ( + (False, "copy failed") if plugin_id == failed.id else (True, "") + ) + ) + statuses: list[tuple[str, PluginRuntimeStatus]] = [] + service = PluginSyncService( + frozen=lambda: False, + installed_plugins=lambda: [failed.id, succeeded.id], + online_plugins=lambda: [], + local_plugins=lambda: [failed, succeeded], + merge_plugins=lambda items, *_args: items, + plugin_exists=lambda *_args: False, + install=install, + runtime_status_writer=lambda plugin_id, status: statuses.append( + (plugin_id, status) + ), + log=Mock(), + ) + + assert set(service.sync()) == {succeeded.id} + assert {call.args[0] for call in install.call_args_list} == { + failed.id, + succeeded.id, + } + assert statuses == [(failed.id, PluginRuntimeStatus.SYNC_FAILED)] def test_market_sync_stops_without_online_fallback_when_local_scan_fails() -> None: @@ -599,12 +649,12 @@ async def test_market_sync_blocks_activation_when_gateway_selected_local_fails( ) async with plugin_lifecycle.hold_startup() as startup_token: - with pytest.raises(RuntimeError, match="插件同步未完成:DemoPlugin"): - await asyncio.wait_for( - asyncio.to_thread(service.sync, startup_token), - timeout=2, - ) + result = await asyncio.wait_for( + asyncio.to_thread(service.sync, startup_token), + timeout=2, + ) + assert result == [] executor.execute.assert_awaited_once() assert executor.execute.await_args.kwargs["local_sync"] is True admission = executor.execute.await_args.kwargs["admission"]