Repository navigation
fix(plugins): report missing entry modules and update reload failures #11072
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 |
|---|---|---|
|
|
@@ -1036,6 +1036,8 @@ async def reload(self, specified_plugin_name=None): | |
| specified_module_path = smd.module_path | ||
| break | ||
|
|
||
| load_module_path = specified_module_path | ||
|
|
||
| # 终止插件 | ||
| if not specified_module_path: | ||
| # 重载所有插件 | ||
|
|
@@ -1058,6 +1060,17 @@ async def reload(self, specified_plugin_name=None): | |
| # 只重载指定插件 | ||
| smd = star_map.get(specified_module_path) | ||
| if smd: | ||
| # Updates may change the entry filename within this plugin. | ||
| for plugin_module in self._get_plugin_modules(): | ||
| if ( | ||
| plugin_module["pname"] == smd.root_dir_name | ||
| and plugin_module.get("reserved", False) == smd.reserved | ||
| ): | ||
| module_prefix = specified_module_path.rsplit(".", 1)[0] | ||
| load_module_path = ( | ||
| f"{module_prefix}.{plugin_module['module']}" | ||
| ) | ||
| break | ||
| try: | ||
| await self._terminate_plugin(smd) | ||
| except Exception as e: | ||
|
|
@@ -1066,10 +1079,27 @@ async def reload(self, specified_plugin_name=None): | |
| f"Plugin {smd.name} did not terminate cleanly: {e!s}. " | ||
| "The plugin may not work correctly.", | ||
| ) | ||
| if smd.name and smd.activated: | ||
| if smd.name and ( | ||
| smd.activated or load_module_path != specified_module_path | ||
| ): | ||
| await self._unbind_plugin(smd.name, specified_module_path) | ||
| if load_module_path != specified_module_path: | ||
| # Disabled state is persisted under the entry module path. | ||
| inactivated_plugins = await sp.global_get( | ||
| "inactivated_plugins", [] | ||
| ) | ||
| if specified_module_path in inactivated_plugins: | ||
| await sp.global_put( | ||
| "inactivated_plugins", | ||
| [ | ||
| load_module_path | ||
| if path == specified_module_path | ||
| else path | ||
| for path in inactivated_plugins | ||
| ], | ||
| ) | ||
|
|
||
| result = await self.load(specified_module_path) | ||
| result = await self.load(load_module_path) | ||
|
|
||
| return result | ||
|
|
||
|
|
@@ -1101,6 +1131,7 @@ async def load( | |
| return False, "未找到任何插件模块" | ||
|
|
||
| has_load_error = False | ||
| found_plugin = False | ||
|
|
||
| # 导入插件模块,并尝试实例化插件类 | ||
| for plugin_module in plugin_modules: | ||
|
|
@@ -1129,6 +1160,8 @@ async def load( | |
| if specified_dir_name and root_dir_name != specified_dir_name: | ||
| continue | ||
|
|
||
| found_plugin = True | ||
|
|
||
| # Use the directory name until plugin metadata is available. | ||
| plugin_logger = logging.LoggerAdapter( | ||
| logger, {"plugin_name": root_dir_name} | ||
|
|
@@ -1504,6 +1537,9 @@ async def load( | |
| self._rebuild_failed_plugin_info() | ||
| if has_load_error: | ||
| return False, self.failed_plugin_info | ||
| if (specified_module_path or specified_dir_name) and not found_plugin: | ||
| target = specified_dir_name or specified_module_path | ||
| return False, f"No entry module found for plugin {target}." | ||
| return True, None | ||
|
|
||
| async def _cleanup_failed_plugin_install( | ||
|
|
@@ -1925,7 +1961,11 @@ async def update_plugin( | |
| plugin_dir_path, | ||
| plugin_name, | ||
| ) | ||
| await self.reload(plugin_name) | ||
| success, error = await self.reload(plugin_name) | ||
|
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. 🟠 High · Concurrent updates corrupt plugin state When two update requests target the same plugin at overlapping times, including duplicate names in one batch, Serialize the complete update-and-reload operation per plugin, and deduplicate plugin names in batch requests. Prompt for AI agentsIn `astrbot/core/star/star_manager.py` at line 1934:
**Concurrent updates corrupt plugin state**
When two update requests target the same plugin at overlapping times, including duplicate names in one batch, `_updater.update` replaces the plugin directory before `reload` acquires `_pm_lock`, so concurrent requests for the same plugin can reload another request's intermediate or different-version files and report an outcome for the wrong update.
Serialize the complete update-and-reload operation per plugin, and deduplicate plugin names in batch requests. |
||
| if not success: | ||
|
sourcery-ai[bot] marked this conversation as resolved.
Resolved
|
||
| raise Exception( | ||
| error or f"Failed to reload plugin {plugin_name} after update." | ||
|
Comment on lines
+1965
to
+1967
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 source details stay stale When an update replaces the plugin files and changes the source fields, but the updated plugin fails to reload, Refresh the install-source record after file replacement even when the reload fails. Prompt for AI agentsIn `astrbot/core/star/star_manager.py` at lines 1935-1937:
**Plugin source details stay stale**
When an update replaces the plugin files and changes the source fields, but the updated plugin fails to reload, `PluginManager.update_plugin` raises before `PluginService.update_plugin` reaches `refresh_plugin_install_source_after_update`, so the replaced files retain the old persisted repository, download URL, or market ID and later source display or update resolution uses stale data.
Refresh the install-source record after file replacement even when the reload fails.
sourcery-ai[bot] marked this conversation as resolved.
Resolved
|
||
| ) | ||
|
|
||
| async def turn_off_plugin(self, plugin_name: str) -> None: | ||
| """禁用一个插件。 | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -23,6 +23,7 @@ | |
| import astrbot.dashboard.services.config_service as config_service | ||
| import astrbot.dashboard.services.stat_service as stat_service | ||
| from astrbot.core import file_token_service | ||
| from astrbot.core.star.star_manager import PluginManager | ||
| from astrbot.core.utils import llm_metadata | ||
| from astrbot.dashboard.api.app import create_dashboard_asgi_app | ||
| from astrbot.dashboard.api.backups import download_backup as download_backup_route | ||
|
|
@@ -3358,6 +3359,152 @@ async def fake_get_plugin_install_sources(): | |
| assert update_info["record"]["install_method"] == "repository" | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| @pytest.mark.parametrize("batch", [False, True]) | ||
| @pytest.mark.parametrize("reload_success", [False, True]) | ||
| async def test_v1_plugin_update_reports_reload_result( | ||
| asgi_app: FastAPI, | ||
| asgi_client: httpx.AsyncClient, | ||
| monkeypatch: pytest.MonkeyPatch, | ||
| tmp_path: Path, | ||
| batch: bool, | ||
| reload_success: bool, | ||
| ): | ||
| """Report the manager's reload outcome without reloading a second time.""" | ||
| from astrbot.core.astr_agent_runtime.computer import computer_client | ||
| from astrbot.core.skills.skill_manager import SkillManager | ||
| from astrbot.core.star import star as star_module | ||
|
|
||
| plugin_name = "astrbot_plugin_demo" | ||
| plugin = SimpleNamespace( | ||
| name=plugin_name, root_dir_name=plugin_name, reserved=False, activated=True | ||
| ) | ||
| loaded_plugins = [plugin] | ||
| plugin_store = tmp_path / "plugins" | ||
| skill_dir = plugin_store / plugin_name / "skills" / "demo-skill" | ||
| skill_dir.mkdir(parents=True) | ||
| (skill_dir / "SKILL.md").write_text("# Demo skill\n", encoding="utf-8") | ||
| skill_manager = SkillManager( | ||
| skills_root=str(tmp_path / "skills"), plugins_root=str(plugin_store) | ||
| ) | ||
| skill_manager.config_path = str(tmp_path / "skills.json") | ||
| skill_manager.sandbox_skills_cache_path = str(tmp_path / "sandbox-skills.json") | ||
| monkeypatch.setattr(star_module, "star_registry", loaded_plugins) | ||
| monkeypatch.setattr(computer_client, "SkillManager", lambda **kwargs: skill_manager) | ||
| assert computer_client._collect_sync_skill_dirs() == [("demo-skill", skill_dir)] | ||
|
|
||
| reload_error = "Plugin initialization failed" | ||
|
|
||
| async def reload_plugin(name): | ||
| assert name == plugin_name | ||
| if not reload_success: | ||
| loaded_plugins.clear() | ||
| return reload_success, None if reload_success else reload_error | ||
|
|
||
| manager = SimpleNamespace( | ||
| context=SimpleNamespace( | ||
| get_registered_star=Mock( | ||
| side_effect=lambda name: plugin if plugin in loaded_plugins else None | ||
| ) | ||
| ), | ||
| plugin_store_path=str(plugin_store), | ||
| _updater=SimpleNamespace(update=AsyncMock()), | ||
| _ensure_plugin_requirements=AsyncMock(), | ||
| reload=AsyncMock(side_effect=reload_plugin), | ||
| ) | ||
|
|
||
| async def update_plugin(*args, **kwargs): | ||
| await PluginManager.update_plugin(manager, *args, **kwargs) | ||
|
|
||
| manager.update_plugin = update_plugin | ||
| service = asgi_app.state.services.plugins | ||
| update_info = {"repo": "https://github.com/example/plugin", "download_url": ""} | ||
| refresh_source = AsyncMock() | ||
| synced_skills = [] | ||
| sync_skills = AsyncMock( | ||
| side_effect=lambda: synced_skills.append( | ||
| computer_client._collect_sync_skill_dirs() | ||
| ) | ||
| ) | ||
| monkeypatch.setattr(service, "plugin_manager", manager) | ||
| monkeypatch.setattr( | ||
| service, "resolve_market_update_info", AsyncMock(return_value=update_info) | ||
| ) | ||
| monkeypatch.setattr( | ||
| service, "refresh_plugin_install_source_after_update", refresh_source | ||
| ) | ||
| monkeypatch.setattr(service, "sync_skills_after_plugin_change", sync_skills) | ||
|
|
||
| response = await asgi_client.post( | ||
| "/api/v1/plugins/update", | ||
| json={"plugin_ids": [plugin_name]} if batch else {"plugin_id": plugin_name}, | ||
| headers=_jwt_headers(), | ||
| ) | ||
|
|
||
| assert response.status_code == 200 | ||
| data = response.json() | ||
| if batch: | ||
| assert data["status"] == "ok" | ||
| result = data["data"]["results"][0] | ||
| assert result["name"] == plugin_name | ||
| else: | ||
| result = data | ||
| assert result["status"] == ("ok" if reload_success else "error") | ||
| manager.reload.assert_awaited_once_with(plugin_name) | ||
| manager._updater.update.assert_awaited_once_with( | ||
| plugin, proxy="", download_url="", repo_url=update_info["repo"] | ||
| ) | ||
| sync_skills.assert_awaited_once_with() | ||
| assert synced_skills == [[("demo-skill", skill_dir)] if reload_success else []] | ||
| if reload_success: | ||
| refresh_source.assert_awaited_once_with(plugin_name, update_info) | ||
| else: | ||
| assert reload_error not in result["message"] | ||
| refresh_source.assert_not_awaited() | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| @pytest.mark.parametrize("batch", [False, True]) | ||
| async def test_v1_plugin_update_source_failure_skips_skill_sync( | ||
| asgi_app: FastAPI, | ||
| asgi_client: httpx.AsyncClient, | ||
| monkeypatch: pytest.MonkeyPatch, | ||
| batch: bool, | ||
| ): | ||
| """Avoid syncing unchanged plugins when update source resolution fails.""" | ||
| plugin_name = "astrbot_plugin_demo" | ||
| service = asgi_app.state.services.plugins | ||
| update_plugin = AsyncMock() | ||
| sync_skills = AsyncMock() | ||
| monkeypatch.setattr( | ||
| service.plugin_manager, "update_plugin", update_plugin, raising=False | ||
| ) | ||
| monkeypatch.setattr( | ||
| service, | ||
| "resolve_market_update_info", | ||
| AsyncMock(side_effect=PluginServiceError("Update source is unavailable")), | ||
| ) | ||
| monkeypatch.setattr(service, "sync_skills_after_plugin_change", sync_skills) | ||
|
|
||
| response = await asgi_client.post( | ||
| "/api/v1/plugins/update", | ||
| json={"plugin_ids": [plugin_name]} if batch else {"plugin_id": plugin_name}, | ||
| headers=_jwt_headers(), | ||
| ) | ||
|
|
||
| assert response.status_code == 200 | ||
| data = response.json() | ||
| if batch: | ||
| assert data["status"] == "ok" | ||
| result = data["data"]["results"][0] | ||
| else: | ||
| result = data | ||
| assert result["status"] == "error" | ||
| assert result["message"] == "Update source is unavailable" | ||
| update_plugin.assert_not_awaited() | ||
| sync_skills.assert_not_awaited() | ||
|
|
||
|
Comment on lines
+3362
to
+3506
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. ⚪ Low · Regression tests are added When the PR adds the regression cases, Remove the added regression tests and their test-only fixture, or obtain an update to the repository guidance permitting tests. Also at Prompt for AI agentsIn `tests/test_fastapi_v1_dashboard.py` at lines 3362-3427:
**Regression tests are added**
When the PR adds the regression cases, `test_v1_plugin_update_reports_reload_result` and the new plugin-manager tests add regression-test code despite the explicit prohibition, so the PR introduces test code forbidden by repository guidance.
Remove the added regression tests and their test-only fixture, or obtain an update to the repository guidance permitting tests.
Also at `tests/test_plugin_manager.py:1501-2192`.From Do not generate test files for now. |
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_v1_plugin_update_all_hides_internal_exceptions( | ||
| asgi_client: httpx.AsyncClient, | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.