Skip to content

fix(plugins): report missing entry modules and update reload failures - #11072

Open
zzz27578 wants to merge 2 commits into
AstrBotDevs:masterfrom
zzz27578:fix/plugin-load-results
Open

zzz27578 wants to merge 2 commits into
AstrBotDevs:masterfrom
zzz27578:fix/plugin-load-results

Conversation

@zzz27578

@zzz27578 zzz27578 commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Plugin installation and failed-plugin reload can report success when the requested directory has no discoverable entry module. For example, an archive containing valid metadata.yaml and plugin.py, but neither main.py nor <directory_name>.py, is accepted even though no plugin is loaded. Plugin updates also discard a failed reload result, so single and batch updates can report success after import or initialization fails.

Modifications / 改动点

  • Make targeted loads fail with an error identifying the requested plugin when discovery finds no matching entry module. Installation then follows its existing failure handling, and failed-plugin reload retains the previous failure record.
  • Propagate reload failures from PluginManager.update_plugin() to the existing single and batch update error responses.
  • Remove the redundant reload in PluginService.update_plugin(), so a successful update reloads only once.
  • Rediscover the current entry module during reload, so switching between main.py and <directory_name>.py works without loading a same-named plugin from the other namespace. Migrate the persisted disabled entry path and remove the old registration when the entry changes.
  • Synchronize sandbox skills after attempted updates, including failed reloads and batches where every reload fails. Source-resolution failures that never attempt an update do not trigger synchronization.
  • Add 27 regression cases covering missing directories, incorrect entry filenames, real ZIP installation, preservation of failed-plugin state, supported entry changes for enabled/disabled user/built-in plugins, sandbox skill selection, and single/batch update outcomes.

Related: #10567 overlaps with the plugin update error propagation and redundant reload fix.

Scope considerations: update rollback and serialization of overlapping updates are existing limitations of the updater and require a separate change. Install-source refresh already returns early when failed loading removes the plugin from the registry; changing failed-plugin source persistence is also separate from this fix. The regression cases extend existing test files; no new test files are introduced.

  • This is NOT a breaking change. / 这不是一个破坏性变更。

Screenshots or Test Results / 运行截图或测试结果

Validated on Windows with Python 3.12.13 and Ruff 0.15.22.

Verification steps and results:

  1. Run the original 17 regression cases against the unchanged master production code: 11 failed, 6 passed. Failures confirm missing-target loads and installations reporting success, failed reloads deleting the failure record, update failures reporting success, and single updates reloading twice.
  2. Before the entry-switch and skill-sync fixes, run the 8 entry-switch cases and 6 update API cases: 10 failed, 4 passed. Failures confirm both supported entry-switch directions and missing skill synchronization after failed reloads.
  3. Apply the fixes and run both complete affected test files:
python -m pytest tests/test_plugin_manager.py tests/test_fastapi_v1_dashboard.py -q --tb=short
337 passed, 1 warning in 91.12s
  1. Run the repository's formatting and lint checks:
ruff format .
ruff format --check .
579 files already formatted

ruff check .
All checks passed!

ruff check tests/test_plugin_manager.py tests/test_fastapi_v1_dashboard.py
All checks passed!

git diff --check
Passed

The tests exercise real plugin discovery/import, ZIP extraction, and skill collection in temporary directories, and the update API through the ASGI test client. Network downloads and external services are mocked. The test warning is the existing Python 3.12 audioop deprecation warning. Local validation covers these two complete test files. The initial commit also passed the repository's Linux, Windows, and macOS test jobs; CI will rerun for this revision.

No WebUI navigation, page structure, labels, or API schemas change, so documentation screenshots and generated API clients do not need updates.


Checklist / 检查清单

  • 😊 If there are new features added in the PR, I have discussed it with the authors through issues/emails, etc.
    / 如果 PR 中有新加入的功能,已经通过 Issue / 邮件等方式和作者讨论过。
    Not applicable: this PR fixes existing plugin loading and update behavior.

  • 👀 My changes have been well-tested, and "Verification Steps" and "Screenshots" have been provided above.
    / 我的更改经过了良好的测试,并已在上方提供了“验证步骤”和“运行截图”。
    Automated test results are provided above; this is a backend change.

  • 📚 I checked the affected WebUI instructions and screenshots in docs/zh and docs/en against the changed navigation, page structure, and labels, and updated them in this PR (or explained why no documentation update is needed). For renamed, moved, or merged entry points, I included an old entry → new entry mapping in the documentation and changelog.
    / 我已对照变化后的 WebUI 入口、页面结构和术语,核对并在本 PR 中更新 docs/zh 和 docs/en 的相关操作说明与截图(或说明无需更新文档的原因)。入口改名、移动或合并时,已在文档和 changelog 中补充 旧入口 → 新入口 对照。

  • 🤓 I have ensured that no new dependencies are introduced, OR if new dependencies are introduced, they have been added to the appropriate locations in requirements.txt and pyproject.toml.
    / 我确保没有引入新依赖库,或者引入了新依赖库的同时将其添加到 requirements.txt 和 pyproject.toml 文件相应位置。

  • 😮 My changes do not introduce malicious code.
    / 我的更改没有引入恶意代码。

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 6 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="astrbot/core/star/star_manager.py" line_range="1935" />
<code_context>
             )
-        await self.reload(plugin_name)
+        success, error = await self.reload(plugin_name)
+        if not success:
+            raise Exception(
+                error or f"Failed to reload plugin {plugin_name} after update."
</code_context>
<issue_to_address>
**Failed updates discard working plugin**

When the updated plugin fails to import or initialize during reload, `_updater.update` has already replaced the installed directory when `reload` reports failure, and `update_plugin` raises without restoring the previous files. The caller receives an update error while the previously working plugin is left unavailable and only the failed version remains installed.

Keep a backup of the installed directory and restore it, then reload it, if the updated plugin cannot be reloaded.
</issue_to_address>

### Comment 2
<location path="astrbot/core/star/star_manager.py" line_range="1934" />
<code_context>
                 plugin_name,
             )
-        await self.reload(plugin_name)
+        success, error = await self.reload(plugin_name)
+        if not success:
+            raise Exception(
</code_context>
<issue_to_address>
**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.
</issue_to_address>

### Comment 3
<location path="astrbot/core/star/star_manager.py" line_range="1512" />
<code_context>
             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

</code_context>
<issue_to_address>
**Updated plugin stays unloaded**

When an update changes the plugin between the supported `main.py` and `<directory_name>.py` entry filenames, `reload` passes the old registered module path to `load`, whose exact-path filter skips the supported new entry module; the no-match check returns failure after the old plugin is unbound, so the update errors and leaves it unloaded.

Reload by the plugin directory or otherwise discover the new supported entry path instead of filtering by the old module path.

Also at `astrbot/dashboard/services/plugin_service.py:1812`, `astrbot/core/star/star_manager.py:1935-1937`.
</issue_to_address>

### Comment 4
<location path="astrbot/core/star/star_manager.py" line_range="1935-1937" />
<code_context>
             )
-        await self.reload(plugin_name)
+        success, error = await self.reload(plugin_name)
+        if not success:
+            raise Exception(
+                error or f"Failed to reload plugin {plugin_name} after update."
+            )

</code_context>
<issue_to_address>
**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.
</issue_to_address>

### Comment 5
<location path="astrbot/core/star/star_manager.py" line_range="1935-1937" />
<code_context>
             )
-        await self.reload(plugin_name)
+        success, error = await self.reload(plugin_name)
+        if not success:
+            raise Exception(
+                error or f"Failed to reload plugin {plugin_name} after update."
+            )

</code_context>
<issue_to_address>
**Sandboxes expose stale plugin skills**

When an updated plugin that provides skills fails to reload while a sandbox session is active, `PluginManager.update_plugin` raises before `PluginService.update_plugin` reaches `sync_skills_after_plugin_change`, so active sandboxes retain stale skill files and metadata for a plugin that is no longer active.

Synchronize plugin skills after the update even when the reload fails.
</issue_to_address>

### Comment 6
<location path="tests/test_fastapi_v1_dashboard.py" line_range="3362-3427" />
<code_context>
+        sync_skills.assert_not_awaited()
+
+
 @pytest.mark.asyncio
 async def test_v1_plugin_update_all_hides_internal_exceptions(
     asgi_client: httpx.AsyncClient,
diff --git a/tests/test_plugin_manager.py b/tests/test_plugin_manager.py
index 77e1fb70cc..0f6b08bb2d 100644
--- a/tests/test_plugin_manager.py
+++ b/tests/test_plugin_manager.py
@@ -422,6 +422,30 @@ def local_updater(plugin_manager_pm):
     return path


+@pytest.fixture
+def isolated_plugin_loader(plugin_manager_pm, tmp_path, monkeypatch):
+    """Keep real plugin discovery and loading isolated from persistent state."""
+    _clear_star_runtime_state()
+    monkeypatch.setattr(
+        plugin_manager_pm, "reserved_plugin_path", str(tmp_path / "reserved")
+    )
+    monkeypatch.setattr(
+        plugin_manager_pm, "plugin_config_path", str(tmp_path / "config")
+    )
+    monkeypatch.setattr(
+        plugin_manager_pm.context, "stars", star_manager_module.star_registry
+    )
</code_context>
<issue_to_address>
**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`.
</issue_to_address>

Sourcery assessment

Approval pending. 5 findings to address first.

Blocking findings: astrbot/core/star/star_manager.py:1935, astrbot/core/star/star_manager.py:1934, astrbot/core/star/star_manager.py:1512, astrbot/core/star/star_manager.py:1937, astrbot/core/star/star_manager.py:1937


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread astrbot/core/star/star_manager.py Resolved
plugin_name,
)
await self.reload(plugin_name)
success, error = await self.reload(plugin_name)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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, _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.

Prompt for AI agents
In `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.

Comment thread astrbot/core/star/star_manager.py Resolved
Comment on lines +1935 to +1937
if not success:
raise Exception(
error or f"Failed to reload plugin {plugin_name} after update."

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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, 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.

Prompt for AI agents
In `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.

Comment thread astrbot/core/star/star_manager.py Resolved
Comment on lines +3362 to +3427
@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,
batch: bool,
reload_success: bool,
):
"""Report the manager's reload outcome without reloading a second time."""
plugin_name = "astrbot_plugin_demo"
plugin = SimpleNamespace(name=plugin_name, root_dir_name=None, reserved=False)
reload_error = "Plugin initialization failed"
manager = SimpleNamespace(
context=SimpleNamespace(get_registered_star=Mock(return_value=plugin)),
_updater=SimpleNamespace(update=AsyncMock()),
reload=AsyncMock(
return_value=(reload_success, None if reload_success else reload_error)
),
)

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()
sync_skills = AsyncMock()
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"]
)
if reload_success:
refresh_source.assert_awaited_once_with(plugin_name, update_info)
sync_skills.assert_awaited_once_with()
else:
assert reload_error not in result["message"]
refresh_source.assert_not_awaited()
sync_skills.assert_not_awaited()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚪ Low · 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.

Prompt for AI agents
In `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 .github/copilot-instructions.md L27:

Do not generate test files for now.

@codecov-commenter

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants