Skip to content

fix: 完善插件卸载时的清理逻辑,新增KV数据清理,更新了多语言文案以说明会清理数据库KV数据#8291

Open
leafliber wants to merge 5 commits into
AstrBotDevs:masterfrom
leafliber:master
Open

fix: 完善插件卸载时的清理逻辑,新增KV数据清理,更新了多语言文案以说明会清理数据库KV数据#8291
leafliber wants to merge 5 commits into
AstrBotDevs:masterfrom
leafliber:master

Conversation

@leafliber
Copy link
Copy Markdown

@leafliber leafliber commented May 22, 2026

Modifications / 改动点

  • 完善插件卸载时的清理逻辑,新增插件KV数据清理
  • 更新了多语言文案以说明会清理数据库KV数据
  • 新增了相关的单元测试

Fixes #8290

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

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

============================= test session starts =============================
platform win32 -- Python 3.12.13, pytest-9.0.3, pluggy-1.6.0 -- C:\Users\leaf\code\AstrBot.venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: C:\Users\leaf\code\AstrBot
configfile: pyproject.toml
plugins: anyio-4.13.0, asyncio-1.3.0, cov-7.1.0
asyncio: mode=Mode.STRICT, debug=False, asyncio_default_fixture_loop_scope=None, asyncio_default_test_loop_scope=function
collecting ... collected 40 items / 36 deselected / 4 selected

tests/test_plugin_manager.py::test_cleanup_plugin_optional_artifacts_clears_kv_when_plugin_id_present PASSED [ 25%]
tests/test_plugin_manager.py::test_cleanup_plugin_optional_artifacts_skips_kv_when_plugin_id_none PASSED [ 50%]
tests/test_plugin_manager.py::test_uninstall_plugin_reads_plugin_id_from_star_cls PASSED [ 75%]
tests/test_plugin_manager.py::test_uninstall_failed_plugin_passes_none_plugin_id PASSED [100%]

====================== 4 passed, 36 deselected in 5.83s =======================


Checklist / 检查清单

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

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

  • 🤓 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.txtpyproject.toml 文件相应位置。

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

Summary by Sourcery

Ensure plugin uninstallation also clears associated KV data and reflects this behavior in UI text and tests.

Bug Fixes:

  • Fix plugin uninstallation leaving behind plugin-scoped KV data in the database.

Enhancements:

  • Propagate plugin_id through uninstall flows so KV cleanup can be performed safely when available.
  • Handle missing plugin metadata gracefully during uninstall without breaking the cleanup process.

Documentation:

  • Update multilingual extension management copy to explicitly state that database KV data will be cleared on plugin uninstall.

Tests:

  • Add unit tests covering KV cleanup behavior during plugin optional artifact cleanup and various uninstall paths.

@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. feature:plugin The bug / feature is about AstrBot plugin system. labels May 22, 2026
Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey - I've found 1 issue, and left some high level feedback:

  • Since _cleanup_plugin_optional_artifacts is now async, consider renaming it (e.g., _cleanup_plugin_optional_artifacts_async) or adding a short docstring to make it clear it must be awaited, which helps prevent future callers from accidentally using it synchronously.
  • In the KV cleanup warning log (清除插件 KV 数据失败), consider including the plugin_id as well as plugin_label to make troubleshooting failed cleanup cases easier.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Since `_cleanup_plugin_optional_artifacts` is now async, consider renaming it (e.g., `_cleanup_plugin_optional_artifacts_async`) or adding a short docstring to make it clear it must be awaited, which helps prevent future callers from accidentally using it synchronously.
- In the KV cleanup warning log (`清除插件 KV 数据失败`), consider including the `plugin_id` as well as `plugin_label` to make troubleshooting failed cleanup cases easier.

## Individual Comments

### Comment 1
<location path="tests/test_plugin_manager.py" line_range="1344-1356" />
<code_context>
+        lambda p: None,
+    )
+
+    async def mock_cleanup(*, root_dir_name, plugin_label, plugin_id, delete_config, delete_data):
+        cleanup_calls.append(
+            {"root_dir_name": root_dir_name, "plugin_label": plugin_label, "plugin_id": plugin_id}
+        )
+
+    monkeypatch.setattr(plugin_manager_pm, "_cleanup_plugin_optional_artifacts", mock_cleanup)
+
+    await plugin_manager_pm.uninstall_plugin(
+        TEST_PLUGIN_NAME, delete_config=False, delete_data=True
+    )
+
+    assert len(cleanup_calls) == 1
+    assert cleanup_calls[0]["plugin_id"] == "mock_author/mock_name"
+
+
</code_context>
<issue_to_address>
**suggestion (testing):** Assert that `delete_config`/`delete_data` flags are correctly forwarded to `_cleanup_plugin_optional_artifacts`.

Since `mock_cleanup` already receives `delete_config` and `delete_data`, please also assert that these flags are forwarded with the expected values (e.g. `False` and `True`) to better validate the wiring between `uninstall_plugin` and `_cleanup_plugin_optional_artifacts`.

```suggestion
    async def mock_cleanup(*, root_dir_name, plugin_label, plugin_id, delete_config, delete_data):
        cleanup_calls.append(
            {
                "root_dir_name": root_dir_name,
                "plugin_label": plugin_label,
                "plugin_id": plugin_id,
                "delete_config": delete_config,
                "delete_data": delete_data,
            }
        )

    monkeypatch.setattr(plugin_manager_pm, "_cleanup_plugin_optional_artifacts", mock_cleanup)

    await plugin_manager_pm.uninstall_plugin(
        TEST_PLUGIN_NAME, delete_config=False, delete_data=True
    )

    assert len(cleanup_calls) == 1
    assert cleanup_calls[0]["plugin_id"] == "mock_author/mock_name"
    assert cleanup_calls[0]["delete_config"] is False
    assert cleanup_calls[0]["delete_data"] is True
```
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread tests/test_plugin_manager.py Outdated
Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request implements the deletion of plugin-specific KV preference data from the database during the uninstallation process. Key changes include updating _cleanup_plugin_optional_artifacts to be asynchronous, integrating database cleanup logic, and updating the dashboard's localization files to inform users of this new behavior. Comprehensive unit tests were also added to verify the cleanup logic. Feedback from the reviewer suggests improving the robustness of plugin ID retrieval by using plugin.star_cls_type as a fallback when a plugin is disabled and refactoring this extraction logic into a shared helper function to reduce duplication across different uninstallation scenarios.

Comment thread astrbot/core/star/star_manager.py Outdated
Comment thread astrbot/core/star/star_manager.py Outdated
Comment thread tests/test_plugin_manager.py Outdated
Copy link
Copy Markdown
Member

@Dt8333 Dt8333 left a comment

Choose a reason for hiding this comment

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

也许将plugin_id的生成提取为一个工具函数会更好?

将插件ID生成逻辑抽离到StarMetadata类中,移除重复的代码实现,
同时在__post_init__中自动补全plugin_id字段。
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:S This PR changes 10-29 lines, ignoring generated files. labels May 28, 2026
@leafliber
Copy link
Copy Markdown
Author

也许将plugin_id的生成提取为一个工具函数会更好?

已修改

@Soulter Soulter force-pushed the master branch 3 times, most recently from a4c4a7d to 9bd38ca Compare May 28, 2026 16:55
@leafliber leafliber requested a review from Dt8333 May 31, 2026 17:22
Copy link
Copy Markdown
Member

@Dt8333 Dt8333 left a comment

Choose a reason for hiding this comment

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

[09:07:07.325] [Core] [INFO] [star.star_manager:927]: Loading plugin builtin_commands ...
[09:07:07.361] [Core] [INFO] [star.star_manager:1015]: Plugin builtin_commands (0.0.1) by Soulter: AstrBot's internal plugin, providing all built-in commands such as /reset.
[09:07:07.361] [Core] [ERRO] [v4.25.1] [star.star_manager:1214]: ----- 插件 builtin_commands 载入失败 -----
[09:07:07.361] [Core] [ERRO] [v4.25.1] [star.star_manager:1217]: | Traceback (most recent call last):
[09:07:07.361] [Core] [ERRO] [v4.25.1] [star.star_manager:1217]: |   File "AstrBot\astrbot\core\star\star_manager.py", line 1021, in load
[09:07:07.361] [Core] [ERRO] [v4.25.1] [star.star_manager:1217]: |     p_author, p_name = plugin_id.split("/")
[09:07:07.363] [Core] [ERRO] [v4.25.1] [star.star_manager:1217]: |                        ^^^^^^^^^^^^^^^
[09:07:07.363] [Core] [ERRO] [v4.25.1] [star.star_manager:1217]: | AttributeError: 'NoneType' object has no attribute 'split'
[09:07:07.363] [Core] [ERRO] [v4.25.1] [star.star_manager:1217]: | 
[09:07:07.363] [Core] [ERRO] [v4.25.1] [star.star_manager:1218]: ----------------------------------
[09:07:07.363] [Core] [INFO] [star.star_manager:1231]: 失败插件依旧在插件列表中,正在清理...

看起来在实例化Star类前就有对plugin_id的使用。这时候postInit还未被调用。

个人觉得这个工具函数放到StarManager下改动会比较小。

如果有其他方案也可直接进行修复。

@leafliber
Copy link
Copy Markdown
Author

[09:07:07.325] [Core] [INFO] [star.star_manager:927]: Loading plugin builtin_commands ...
[09:07:07.361] [Core] [INFO] [star.star_manager:1015]: Plugin builtin_commands (0.0.1) by Soulter: AstrBot's internal plugin, providing all built-in commands such as /reset.
[09:07:07.361] [Core] [ERRO] [v4.25.1] [star.star_manager:1214]: ----- 插件 builtin_commands 载入失败 -----
[09:07:07.361] [Core] [ERRO] [v4.25.1] [star.star_manager:1217]: | Traceback (most recent call last):
[09:07:07.361] [Core] [ERRO] [v4.25.1] [star.star_manager:1217]: |   File "AstrBot\astrbot\core\star\star_manager.py", line 1021, in load
[09:07:07.361] [Core] [ERRO] [v4.25.1] [star.star_manager:1217]: |     p_author, p_name = plugin_id.split("/")
[09:07:07.363] [Core] [ERRO] [v4.25.1] [star.star_manager:1217]: |                        ^^^^^^^^^^^^^^^
[09:07:07.363] [Core] [ERRO] [v4.25.1] [star.star_manager:1217]: | AttributeError: 'NoneType' object has no attribute 'split'
[09:07:07.363] [Core] [ERRO] [v4.25.1] [star.star_manager:1217]: | 
[09:07:07.363] [Core] [ERRO] [v4.25.1] [star.star_manager:1218]: ----------------------------------
[09:07:07.363] [Core] [INFO] [star.star_manager:1231]: 失败插件依旧在插件列表中,正在清理...

看起来在实例化Star类前就有对plugin_id的使用。这时候postInit还未被调用。

个人觉得这个工具函数放到StarManager下改动会比较小。

如果有其他方案也可直接进行修复。

确实存在问题,上次修复采用Mock的方式测试,没有加载正确的环境
排查问题后发现:在插件正常加载时,init后并没有传入author和star信息,而是通过代码注入的,所以__post_init__调用生成函数会获得None结果

这次的修复根据改动小的原则,把plugin_id改为@Property,动态计算,这样能够提供最大的兼容性
关于建议的改动,我认为plugin_id作为插件的基本信息,应当放入metadata类,和author、name放在一起
感谢review

本次修改我在本地docker环境下做了测试,没有出现加载问题:
[16:04:20.558] [Core] [INFO] [star.star_manager:927]: Loading plugin astrbot ...
[16:04:20.560] [Core] [INFO] [star.star_manager:1015]: Plugin astrbot (4.1.0) by AstrBot Team: AstrBot's internal plugin, providing some basic capabilities.
[16:04:20.560] [Core] [INFO] [star.star_manager:927]: Loading plugin builtin_commands ...
[16:04:20.563] [Core] [INFO] [star.star_manager:1015]: Plugin builtin_commands (0.0.1) by Soulter: AstrBot's internal plugin, providing all built-in commands such as /reset.

@leafliber leafliber requested a review from Dt8333 June 2, 2026 16:28
@Dt8333
Copy link
Copy Markdown
Member

Dt8333 commented Jun 2, 2026

个人感觉每次计算pluginId可能性能开销相对来说有点大?
或许可以加一个私有属性,仅在第一次调用时计算并存入,后续都读取这个计算好的?

以上为个人意见,仅供参考。

@leafliber
Copy link
Copy Markdown
Author

个人感觉每次计算pluginId可能性能开销相对来说有点大? 或许可以加一个私有属性,仅在第一次调用时计算并存入,后续都读取这个计算好的?

以上为个人意见,仅供参考。

理解你的顾虑,一方面该plugin_id的计算量并不大,而且调用也不频繁,只在插件加载、卸载、日志打印时使用
另一方面,一开始是采用了私有函数通过__post_init__进行计算存入,但是该类在init时,并没有存入author和name值,导致错误,计算id的时机需要在插件正确加载和插件没有正确加载的两个合适时机进行计算,否则会导致错误,这对于后面的修改是有些许隐患的
使用动态计算能提供最大的兼容性,且对性能影响很小的

其实个人感觉,更好的解决方案是将plugin_id固定到插件的metadata文件,这样的plugin_id可以在插件市场确保唯一,避免数据存储混乱,但修改内容过多,且对现有插件不兼容

@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Jun 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature:plugin The bug / feature is about AstrBot plugin system. lgtm This PR has been approved by a maintainer size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] Plugin卸载时添加清除KV存储的选项

2 participants