Skip to content

fix: initialize providers across plugin startup phases - #10845

Open
JosephTian876 wants to merge 2 commits into
AstrBotDevs:masterfrom
JosephTian876:fix/init-providers-before-plugins
Open

JosephTian876 wants to merge 2 commits into
AstrBotDevs:masterfrom
JosephTian876:fix/init-providers-before-plugins

Conversation

@JosephTian876

@JosephTian876 JosephTian876 commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Modifications / 改动点

AstrBotCoreLifecycle.initialize() activates every plugin before any Provider exists, so a plugin that resolves its configured Provider during startup sees an empty inst_map:

# astrbot/core/core_lifecycle.py (master, abf683071)
self.plugin_manager = PluginManager(self.star_context, self.astrbot_config)
await self.plugin_manager.reload()          # 260 — plugins activated here
self._default_chat_provider_warning_emitted = False
await self.provider_manager.initialize()    # 264 — providers constructed only now

Plugins register Provider adapters in two different places — at module import, and inside Star.initialize() — so simply moving provider_manager.initialize() earlier is not compatible with both. This PR introduces explicit startup phases instead:

  • discover/import plugin modules (PluginManager.initialize_plugins) before the first Provider pass, so import-time adapters are registered;
  • initialize configured Providers before plugin instances are constructed and activated;
  • after activation, load only enabled, configured Provider IDs whose adapter appeared during activation and whose instance does not exist yet (ProviderManager.initialize_pending_registered_providers), without reinitialising anything that already exists;
  • isolate a failing late Provider so the remaining pending Providers still load;
  • restore the persisted chat / STT / TTS / decision selection once a late Provider exists, without re-running MCP initialisation;
  • terminate Provider instances whose adapter registration was rolled back, and restore the current-selection fallbacks;
  • keep the unset-default warning after the final activation state is known.

Rebased onto abf683071. One conflict in star_manager.py was resolved in favour of this PR's extracted _apply_plugin_metadata_yaml / _ensure_supported_plugin_version helpers (master still has that body inline, and three other call sites in this commit use the helpers); the helper's field list now copies views, which upstream renamed from pages after this branch was first written. ProviderType.DECISION, added upstream since, is handled in the pending pass and in the rolled-back-adapter cleanup.

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

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

Diff scope: 5 files (+622/-91): astrbot/core/core_lifecycle.py, astrbot/core/provider/manager.py, astrbot/core/provider/register.py, astrbot/core/star/star_manager.py, plus the required mock updates in existing tests/unit/test_core_lifecycle.py (+24/-5 for initialize_plugins / initialize_pending_registered_providers).

Existing tests/test_plugin_manager.py, tests/unit/test_core_lifecycle.py, and tests/unit/test_command_plugin_activation.py pass in CI (ruff format --check and ruff check clean). In addition, 8 local behavioral regression scenarios (covering import-time and activation-time plugin provider loading, incompatible-plugin isolation, disabled-plugin adapter retention, failed-activation reconciliation, inactive tools before activation, and partial-import rollback) were verified locally before/after the fix and omitted from tests/test_plugin_manager.py in this PR diff to keep test changes minimal (happy to restore compact tests if preferred).

This branch includes the rollback-safety prerequisite from #9900 until #9900 merges, as originally described.

Checklist / 检查清单
  • 😊 No new feature, so nothing to discuss with the authors — this is a lifecycle bug fix.
  • 👀 Changes are tested, and the evidence is above (before/after on the same commit).
  • 📚 No WebUI navigation, page structure or label changes, so docs/zh / docs/en need no update.
  • 🤓 No new dependencies.
  • 😮 No malicious code.

Supersedes #9513

#9513 was closed on 2026-10-12 by the staleness sweep with an invitation to rebase and reopen, not on its merits. GitHub refuses to reopen it: gh pr reopen 9513 returns GraphQL: Could not open the pull request (reopenPullRequest), and PATCH /pulls/9513 {"state": "open"} returns HTTP 422 state cannot be changed. This PR is the same change rebased onto current master, so it supersedes #9513; the original description and discussion stay there.

Suggested merge order

Independent from #10895 and #10846, though all three touch astrbot/core/provider/manager.py. Suggested order: #10845 → #10895 → #10846 (any order works with a minor rebase if needed).

Summary by Sourcery

Initialize plugin-provided Providers across discovery and activation phases while safely reconciling failures and preserving configured selections.

Bug Fixes:

  • Fix plugin startup so Providers registered during module discovery or plugin activation are available when plugins initialize.
  • Prevent failed or rolled-back plugin Provider registrations from leaving stale runtime instances or blocking other pending Providers.
  • Restore persisted Provider selections and safe fallbacks after late Provider loading or cleanup.

Enhancements:

  • Split plugin startup into discovery, Provider initialization, and plugin activation phases while keeping plugin tools inactive until activation.
  • Improve plugin import recovery and cleanup for partial registrations, including Provider adapters and nested plugin tools.
  • Move the unset-default Provider warning until the final startup state is established.

Tests:

  • Update lifecycle tests to verify the phased plugin and Provider initialization callbacks.

@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 1 issue

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="823-840" />
<code_context>
         )

+    @staticmethod
+    def _plugin_root_module_path(plugin_module_path: str) -> str:
+        """Return the import prefix shared by every module in one plugin.
+
+        Args:
+            plugin_module_path: Plugin main or child module path.
</code_context>
<issue_to_address>
**Unneeded helper adds indirection**

The plugin-root calculation is extracted into a helper used at only one call site; inlining it in the short caller would stay below the documented length threshold, so this adds indirection contrary to the repository guidance.

Inline the plugin-root calculation in `_claim_llm_tools_for_plugin` unless it gains repeated use or makes that function too long.
</issue_to_address>

Sourcery assessment

Approved.


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

Comment thread astrbot/core/star/star_manager.py Resolved
@JosephTian876

Copy link
Copy Markdown
Contributor Author

Startup now loads configured Providers before plugin activation and runs a second Provider pass after it, so a plugin Star can query its Provider during initialize() and adapters registered by plugins during activation are loaded. The changes since the last review:

  • The post-activation pass only considers adapter types that were absent when the startup pass finished (_startup_provider_types), so a Provider that failed at startup is not constructed a second time; it also resolves provider-source entries through the merged configuration before deciding.
  • The single-call-site plugin-root prefix helper is inlined into _claim_llm_tools_for_plugin.

Tests: 10 new tests in tests/test_plugin_manager.py covering the startup phase order, late adapter registration, the failed-provider skip, provider-source merging, tool claiming and import rollback, plus the two-phase wiring assertions in tests/unit/test_core_lifecycle.py. test_pending_provider_pass_skips_provider_that_failed_at_startup asserts creation_attempts == 1 for the failing adapter while the late adapter is created and initialised once.

Known limitation: the pending pass runs once per startup, so an adapter registered by a plugin loaded later at runtime is not picked up by it.

Note on the base: the first commit on this branch, fix: make plugin imports rollback-safe, is the change from #9900, kept here because the startup-phase work builds on the rollback-safe import path (dropping it and rebasing onto master conflicts in star_manager.py). It is patch-identical to #9900's current head, so reviewing and merging #9900 first would leave only the five commits above; if #9900 changes shape before it lands, I will rebase this branch on top of the new version.

@Soulter Soulter moved this to In Progress in AstrBot Roadmap Nov 2, 2026
@JosephTian876
JosephTian876 force-pushed the fix/init-providers-before-plugins branch from 473fb89 to 49f1b7a Compare November 5, 2026 22:20
@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

❌ Patch coverage is 92.07921% with 16 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
astrbot/core/star/star_manager.py 92.10% 9 Missing ⚠️
astrbot/core/provider/manager.py 90.66% 7 Missing ⚠️

📢 Thoughts on this report? Let us know!

@JosephTian876

Copy link
Copy Markdown
Contributor Author

Rebased onto the updated #9900 branch (a084409 base), resolved star_manager.py conflicts (is_plugin_disabled), and trimmed newly added tests per .github/copilot-instructions.md (retaining only the minimal existing lifecycle mock contract update in tests/unit/test_core_lifecycle.py).

Local Verification

  • Pre-trim regression tests: 172 passed (test_core_lifecycle.py, test_plugin_manager.py)
  • Existing upstream test suite: 162 passed (test_core_lifecycle.py, test_plugin_manager.py)
  • ruff check and ruff format --check: passed (0 issues)

建议合并顺序

  1. #10897(插件卸载/导入失败时注销模型提供商适配器)
  2. #9900(插件导入失败事务性回滚清理)
  3. #10845(跨插件发现与激活两阶段初始化 Provider,基于 #9900 堆叠)

@JosephTian876
JosephTian876 force-pushed the fix/init-providers-before-plugins branch from 91781d5 to 0d56858 Compare November 30, 2026 11:02
@JosephTian876

Copy link
Copy Markdown
Contributor Author

Rebased onto the updated #9900 head (69c4286, new head 0d56858), fixing the CI failure in tests/unit/test_astr_agent_tool_exec.py::test_legacy_agent_registration_executes_nested_tool by preserving PluginManager._iter_concrete_llm_tools while using _iter_registered_llm_tools for internal ownership and rollback traversal.

Local Verification

  • pytest tests/unit/test_astr_agent_tool_exec.py tests/test_plugin_manager.py tests/unit/test_core_lifecycle.py tests/unit/test_command_plugin_activation.py tests/unit/test_star_base.py tests/unit/test_star_context.py tests/test_decision_provider.py tests/unit/test_provider_stats.py -> 321 passed
  • ruff check and ruff format --check on changed files -> passed (0 issues)

@JosephTian876
JosephTian876 force-pushed the fix/init-providers-before-plugins branch from 0d56858 to 8a9aacd Compare December 1, 2026 20:28

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

Status: In Progress

Development

Successfully merging this pull request may close these issues.

2 participants