Repository navigation
fix(plugins): serialize updates and keep install sources current #11353
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -12,11 +12,12 @@ | |
| import sys | ||
| import tempfile | ||
| import traceback | ||
| from collections.abc import Iterable | ||
| from collections.abc import Awaitable, Callable, Iterable | ||
| from dataclasses import dataclass | ||
| from enum import Enum, auto | ||
| from pathlib import Path | ||
| from types import ModuleType | ||
| from weakref import WeakValueDictionary | ||
|
|
||
| import yaml | ||
| from packaging.specifiers import InvalidSpecifier, SpecifierSet | ||
|
|
@@ -214,6 +215,9 @@ def __init__(self, context: Context, config: AstrBotConfig) -> None: | |
| """插件配置 Schema 文件名""" | ||
| self._pm_lock = asyncio.Lock() | ||
| """StarManager操作互斥锁""" | ||
| self._update_locks: WeakValueDictionary[Path, asyncio.Lock] = ( | ||
| WeakValueDictionary() | ||
| ) | ||
|
|
||
| self.failed_plugin_dict = {} | ||
| """加载失败插件的信息,用于后续可能的热重载""" | ||
|
|
@@ -1924,6 +1928,8 @@ async def update_plugin( | |
| proxy="", | ||
| download_url: str = "", | ||
| repo_url: str = "", | ||
| *, | ||
| on_files_replaced: Callable[[str], Awaitable[None]] | None = None, | ||
| ) -> None: | ||
| """Update and reload an installed plugin. | ||
|
|
@@ -1932,6 +1938,8 @@ async def update_plugin( | |
| proxy: Optional URL-prefix mirror for archive downloads. | ||
| download_url: Optional direct plugin archive URL. | ||
| repo_url: Repository locator selected by the update source. | ||
| on_files_replaced: Optional callback receiving the root directory name | ||
| after the updater replaces the files, even if loading later fails. | ||
| Returns: | ||
| None. | ||
|
|
@@ -1943,22 +1951,35 @@ async def update_plugin( | |
| plugin = self.context.get_registered_star(plugin_name) | ||
| if not plugin: | ||
| raise Exception("插件不存在。") | ||
| if plugin.reserved: | ||
| raise Exception("该插件是 AstrBot 保留插件,无法更新。") | ||
|
|
||
| await self._updater.update( | ||
| plugin, | ||
| proxy=proxy, | ||
| download_url=download_url, | ||
| repo_url=repo_url, | ||
| ) | ||
| if plugin.root_dir_name: | ||
| plugin_dir_path = os.path.join(self.plugin_store_path, plugin.root_dir_name) | ||
| await self._ensure_plugin_requirements( | ||
| plugin_dir_path, | ||
| plugin_name, | ||
| root_dir_name = plugin.root_dir_name | ||
| if not root_dir_name: | ||
| raise ValueError(f"Plugin {plugin_name} has no root directory name.") | ||
|
|
||
| plugin_path = Path(self.plugin_store_path) / root_dir_name | ||
| update_lock = self._update_locks.setdefault(plugin_path, asyncio.Lock()) | ||
| async with update_lock: | ||
| plugin = self.context.get_registered_star(plugin_name) | ||
| if not plugin or plugin.root_dir_name != root_dir_name: | ||
| raise Exception("插件不存在。") | ||
| if plugin.reserved: | ||
| raise Exception("该插件是 AstrBot 保留插件,无法更新。") | ||
|
|
||
| await self._updater.update( | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Medium · Uninstall can be undone by update When an uninstall removes a plugin while its update is downloading, Coordinate uninstall with the same installation-directory lock, and recheck that the plugin is still installed before committing or reloading an update. Prompt for AI agentsIn `astrbot/core/star/star_manager.py` at line 1967:
**Uninstall can be undone by update**
When an uninstall removes a plugin while its update is downloading, `uninstall_plugin` does not acquire this per-directory update lock. If it removes the plugin while `_updater.update` is downloading, the updater can then recreate the directory; the subsequent reload can load that plugin again, so the uninstall caller sees success but the plugin is installed again.
Coordinate uninstall with the same installation-directory lock, and recheck that the plugin is still installed before committing or reloading an update. |
||
| plugin, | ||
| proxy=proxy, | ||
| download_url=download_url, | ||
| repo_url=repo_url, | ||
| ) | ||
| await self.reload(plugin_name) | ||
| try: | ||
| if on_files_replaced is not None: | ||
| await on_files_replaced(root_dir_name) | ||
| finally: | ||
| await self._ensure_plugin_requirements(str(plugin_path), plugin_name) | ||
| success, error = await self.reload(plugin_name) | ||
| if not success: | ||
| raise RuntimeError( | ||
| error or f"Failed to reload plugin {plugin_name} after update." | ||
| ) | ||
|
|
||
| async def turn_off_plugin(self, plugin_name: str) -> None: | ||
| """禁用一个插件。 | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -8,6 +8,7 @@ | |
| from collections.abc import Awaitable, Callable | ||
| from dataclasses import dataclass | ||
| from datetime import datetime, timezone | ||
| from functools import partial | ||
| from pathlib import Path | ||
| from typing import Any | ||
|
|
||
|
|
@@ -109,6 +110,7 @@ def __init__( | |
| EventType.OnPluginErrorEvent: "插件报错时", | ||
| } | ||
| self._logo_cache: dict[str, str] = {} | ||
| self._install_source_lock = asyncio.Lock() | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Medium · Plugin sources revert after concurrent writes When an install, source binding, or removal overlaps an update’s source refresh, Use Also at Prompt for AI agentsIn `astrbot/dashboard/services/plugin_service.py` at line 113:
**Plugin sources revert after concurrent writes**
When an install, source binding, or removal overlaps an update’s source refresh, `refresh_plugin_install_source_after_update`, `persist_plugin_install_source`, `bind_plugin_market_source`, and `remove_plugin_install_source` read and write the same records mapping without all using the shared lock, so a stale save overwrites another plugin’s record or a newer binding or removal.
Use `_install_source_lock` for every read-modify-write operation on the install-source records.
Also at `astrbot/dashboard/services/plugin_service.py:1557-1583`. |
||
|
|
||
| @staticmethod | ||
| def _payload(data: object) -> dict[str, Any]: | ||
|
|
@@ -1543,43 +1545,41 @@ async def bind_plugin_market_source(self, data: object) -> tuple[dict, str]: | |
|
|
||
| async def refresh_plugin_install_source_after_update( | ||
| self, | ||
| plugin_name: str, | ||
| root_dir_name: str, | ||
| update_info: dict[str, Any], | ||
| ) -> None: | ||
| """Refresh stored source fields after a successful plugin update. | ||
| """Refresh the source for the installed files independently of reload. | ||
| Args: | ||
| plugin_name: Installed plugin metadata name. | ||
| root_dir_name: Stable key for the installed plugin directory. | ||
| update_info: Marketplace update information. | ||
| """ | ||
| plugin = self.find_plugin_by_name(plugin_name) | ||
| if not plugin or not plugin.root_dir_name: | ||
| return | ||
| records = await self.get_plugin_install_sources() | ||
| record = records.get(plugin.root_dir_name) | ||
| if not isinstance(record, dict): | ||
| update_record = update_info.get("record") | ||
| if not isinstance(update_record, dict): | ||
| return | ||
| record = dict(update_record) | ||
| market_plugin = update_info.get("market_plugin") | ||
| if isinstance(market_plugin, dict): | ||
| market_plugin_id = self.get_market_plugin_id(market_plugin) | ||
| if market_plugin_id: | ||
| record["market_plugin_id"] = market_plugin_id | ||
| record["repo"] = str( | ||
| market_plugin.get("repo") or record.get("repo") or "" | ||
| ).strip() | ||
| record["download_url"] = str( | ||
| market_plugin.get("download_url") | ||
| or update_info.get("download_url") | ||
| or record.get("download_url") | ||
| or "" | ||
| ).strip() | ||
| record["root_dir_name"] = plugin.root_dir_name | ||
| record["updated_at"] = datetime.now(timezone.utc).isoformat() | ||
| records[plugin.root_dir_name] = record | ||
| await self.save_plugin_install_sources(records) | ||
| async with self._install_source_lock: | ||
| records = await self.get_plugin_install_sources() | ||
| record = records.get(root_dir_name) | ||
| if not isinstance(record, dict): | ||
| update_record = update_info.get("record") | ||
| if not isinstance(update_record, dict): | ||
| return | ||
| record = dict(update_record) | ||
| market_plugin = update_info.get("market_plugin") | ||
| if isinstance(market_plugin, dict): | ||
| market_plugin_id = self.get_market_plugin_id(market_plugin) | ||
| if market_plugin_id: | ||
| record["market_plugin_id"] = market_plugin_id | ||
| record["repo"] = str( | ||
| market_plugin.get("repo") or record.get("repo") or "" | ||
| ).strip() | ||
| record["download_url"] = str( | ||
| market_plugin.get("download_url") | ||
| or update_info.get("download_url") | ||
| or record.get("download_url") | ||
| or "" | ||
| ).strip() | ||
| record["root_dir_name"] = root_dir_name | ||
| record["updated_at"] = datetime.now(timezone.utc).isoformat() | ||
| records[root_dir_name] = record | ||
| await self.save_plugin_install_sources(records) | ||
|
|
||
| async def install_plugin(self, data: object) -> tuple[dict, str]: | ||
| self._ensure_not_demo() | ||
|
|
@@ -1802,15 +1802,19 @@ async def update_plugin(self, data: object) -> tuple[None, str]: | |
| download_url = str(update_info.get("download_url") or "").strip() | ||
| repo_url = str(update_info.get("repo") or "").strip() | ||
| logger.info(f"Updating plugin {plugin_name}") | ||
| await self.plugin_manager.update_plugin( | ||
| plugin_name, | ||
| proxy or "", | ||
| download_url=download_url, | ||
| repo_url=repo_url, | ||
| ) | ||
| await self.refresh_plugin_install_source_after_update(plugin_name, update_info) | ||
| await self.plugin_manager.reload(plugin_name) | ||
| await self.sync_skills_after_plugin_change() | ||
| try: | ||
| await self.plugin_manager.update_plugin( | ||
| plugin_name, | ||
| proxy or "", | ||
| download_url=download_url, | ||
| repo_url=repo_url, | ||
| on_files_replaced=partial( | ||
| self.refresh_plugin_install_source_after_update, | ||
| update_info=update_info, | ||
| ), | ||
| ) | ||
| finally: | ||
| await self.sync_skills_after_plugin_change() | ||
| logger.info(f"Updated plugin {plugin_name} successfully.") | ||
| return None, "更新成功。" | ||
|
|
||
|
|
@@ -1822,26 +1826,32 @@ async def update_all_plugins(self, data: object) -> tuple[dict, str]: | |
|
|
||
| if not isinstance(plugin_names, list) or not plugin_names: | ||
| raise PluginServiceError("插件列表不能为空") | ||
| if any(not isinstance(name, str) for name in plugin_names): | ||
| raise PluginServiceError("插件名称必须是字符串") | ||
| plugin_names = list(dict.fromkeys(plugin_names)) | ||
|
|
||
| results = [] | ||
| sem = asyncio.Semaphore(PLUGIN_UPDATE_CONCURRENCY) | ||
| attempted_update = False | ||
|
|
||
| async def _update_one(name: str): | ||
| nonlocal attempted_update | ||
| async with sem: | ||
| try: | ||
| logger.info(f"Updating plugin {name} as part of a batch update.") | ||
| update_info = await self.resolve_market_update_info(name) | ||
| download_url = str(update_info.get("download_url") or "").strip() | ||
| repo_url = str(update_info.get("repo") or "").strip() | ||
| attempted_update = True | ||
| await self.plugin_manager.update_plugin( | ||
| name, | ||
| proxy, | ||
| download_url=download_url, | ||
| repo_url=repo_url, | ||
| ) | ||
| await self.refresh_plugin_install_source_after_update( | ||
| name, | ||
| update_info, | ||
| on_files_replaced=partial( | ||
| self.refresh_plugin_install_source_after_update, | ||
| update_info=update_info, | ||
| ), | ||
| ) | ||
| return {"name": name, "status": "ok", "message": "更新成功"} | ||
| except PluginServiceError as exc: | ||
|
|
@@ -1887,7 +1897,7 @@ async def _update_one(name: str): | |
| results.append(result) | ||
|
|
||
| failed = [result for result in results if result["status"] == "error"] | ||
| if len(failed) < len(results): | ||
| if attempted_update: | ||
| await self.sync_skills_after_plugin_change() | ||
| message = ( | ||
| "批量更新完成,全部成功。" | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -20,6 +20,7 @@ | |
| from astrbot.core.utils.astrbot_path import get_astrbot_system_tmp_path | ||
| from astrbot.core.utils.pip_installer import PipInstallError | ||
| from astrbot.core.utils.requirements_utils import MissingRequirementsPlan | ||
| from astrbot.dashboard.services.plugin_service import PluginService | ||
|
|
||
| # --- Test Data & Helpers --- | ||
|
|
||
|
|
@@ -2089,6 +2090,128 @@ async def mock_update(plugin, proxy="", download_url="", repo_url=""): | |
| assert ("reload", TEST_PLUGIN_DIR) in events | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_update_plugin_serializes_only_overlapping_plugin_updates( | ||
| plugin_manager_pm: PluginManager, monkeypatch | ||
| ): | ||
| other_plugin = MockStar() | ||
| other_plugin.name = other_plugin.root_dir_name = "other_plugin" | ||
| cast(Any, plugin_manager_pm.context).stars.extend([MockStar(), other_plugin]) | ||
| first_reload_started = asyncio.Event() | ||
| allow_first_reload = asyncio.Event() | ||
| other_update_started = asyncio.Event() | ||
| versions = {} | ||
| loaded = [] | ||
|
|
||
| async def update(plugin, *, proxy, download_url, repo_url): | ||
| versions[plugin.root_dir_name] = download_url | ||
| if plugin is other_plugin: | ||
| other_update_started.set() | ||
|
|
||
| async def reload(name): | ||
| if name == TEST_PLUGIN_NAME and not first_reload_started.is_set(): | ||
| first_reload_started.set() | ||
| await allow_first_reload.wait() | ||
| loaded.append((name, versions[name])) | ||
| return True, None | ||
|
|
||
| monkeypatch.setattr(plugin_manager_pm._updater, "update", update) | ||
| monkeypatch.setattr(plugin_manager_pm, "reload", reload) | ||
|
|
||
| async with asyncio.timeout(5), asyncio.TaskGroup() as tasks: | ||
| tasks.create_task( | ||
| plugin_manager_pm.update_plugin(TEST_PLUGIN_NAME, download_url="first") | ||
| ) | ||
| await first_reload_started.wait() | ||
| tasks.create_task( | ||
| plugin_manager_pm.update_plugin(TEST_PLUGIN_NAME, download_url="second") | ||
| ) | ||
| tasks.create_task( | ||
| plugin_manager_pm.update_plugin(other_plugin.name, download_url="other") | ||
| ) | ||
| await other_update_started.wait() | ||
| allow_first_reload.set() | ||
|
|
||
| assert loaded == [ | ||
| (other_plugin.name, "other"), | ||
| (TEST_PLUGIN_NAME, "first"), | ||
| (TEST_PLUGIN_NAME, "second"), | ||
| ] | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| @pytest.mark.parametrize("batch", [False, True]) | ||
| @pytest.mark.parametrize("download_fails", [False, True]) | ||
| async def test_update_plugin_persists_source_only_after_replacing_files( | ||
| plugin_manager_pm: PluginManager, monkeypatch, batch, download_fails | ||
| ): | ||
| plugin_name = "demo_plugin" | ||
| plugin = MockStar() | ||
| plugin.name = plugin_name | ||
| stars = cast(Any, plugin_manager_pm.context).stars | ||
| stars.append(plugin) | ||
| service = PluginService(None, plugin_manager_pm) | ||
| old_source = { | ||
| "install_method": "market", | ||
| "market_plugin_id": "owner/old-plugin", | ||
| "repo": "https://github.com/owner/old-plugin", | ||
| "download_url": "https://example.com/old.zip", | ||
| "installed_at": "2026-01-01T00:00:00+00:00", | ||
| } | ||
| new_source = { | ||
| "market_plugin_id": "owner/new-plugin", | ||
| "repo": "https://github.com/owner/new-plugin", | ||
| "download_url": "https://example.com/new.zip", | ||
| } | ||
| write_sources = AsyncMock() | ||
| download = AsyncMock( | ||
| side_effect=RuntimeError("Download failed") if download_fails else None | ||
| ) | ||
|
|
||
| async def reload(_name): | ||
| stars.clear() | ||
| return False, "Plugin initialization failed" | ||
|
|
||
| reload_plugin = AsyncMock(side_effect=reload) | ||
| monkeypatch.setattr(plugin_manager_pm._updater, "update", download) | ||
| monkeypatch.setattr(plugin_manager_pm, "reload", reload_plugin) | ||
| monkeypatch.setattr(service, "sync_skills_after_plugin_change", AsyncMock()) | ||
| monkeypatch.setattr( | ||
| service, | ||
| "get_plugin_install_sources", | ||
| AsyncMock(return_value={TEST_PLUGIN_DIR: dict(old_source)}), | ||
| ) | ||
| monkeypatch.setattr(service, "save_plugin_install_sources", write_sources) | ||
| monkeypatch.setattr( | ||
| service, | ||
| "resolve_market_update_info", | ||
| AsyncMock(return_value={**new_source, "market_plugin": new_source}), | ||
| ) | ||
|
|
||
| if batch: | ||
| data, _message = await service.update_all_plugins({"names": [plugin_name] * 2}) | ||
| assert [result["status"] for result in data["results"]] == ["error"] | ||
| else: | ||
| error = "Download failed" if download_fails else "Plugin initialization failed" | ||
| with pytest.raises(RuntimeError, match=error): | ||
| await service.update_plugin({"name": plugin_name}) | ||
|
|
||
| download.assert_awaited_once() | ||
| if download_fails: | ||
| write_sources.assert_not_awaited() | ||
| reload_plugin.assert_not_awaited() | ||
| else: | ||
| reload_plugin.assert_awaited_once_with(plugin_name) | ||
| write_sources.assert_awaited_once() | ||
| record = write_sources.await_args.args[0][TEST_PLUGIN_DIR] | ||
| assert record == { | ||
| **old_source, | ||
| **new_source, | ||
| "root_dir_name": TEST_PLUGIN_DIR, | ||
| "updated_at": record["updated_at"], | ||
| } | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Medium · Stale source timestamp passes When the source refresh writes a stale or malformed Assert that Prompt for AI agentsIn `tests/test_plugin_manager.py` at line 2212:
**Stale source timestamp passes**
When the source refresh writes a stale or malformed `updated_at` value, `test_update_plugin_persists_source_only_after_replacing_files` copies `record["updated_at"]` into its own expected value on line 2211, so a stale or malformed timestamp still passes the equality assertion.
Assert that `updated_at` parses as a timestamp and is newer than a fixed old timestamp in the source record. |
||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_install_plugin_skips_dependency_install_when_no_requirements_missing( | ||
| plugin_manager_pm: PluginManager, monkeypatch | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟡 Medium · Queued update cannot recover failed reload
When two updates for the same plugin overlap and the first replacement fails to reload, the first update can replace the files and then fail to reload, causing
loadto remove the plugin from the runtime registry. A second request already waiting on the same directory lock then fails this registry check and never applies its update, leaving the installed files unrepaired even when its source contains a fix.Allow the queued update to proceed using the captured installation directory and a safe reload path even if the preceding reload removed the plugin from the runtime registry.
Prompt for AI agents