Skip to content

fix(provider): reload newly configured providers and explain lookup failures - #10895

Open
JosephTian876 wants to merge 1 commit into
AstrBotDevs:masterfrom
JosephTian876:fix/provider-reload-converges
Open

JosephTian876 wants to merge 1 commit into
AstrBotDevs:masterfrom
JosephTian876:fix/provider-reload-converges

Conversation

@JosephTian876

@JosephTian876 JosephTian876 commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #7425.

Problem

Provider IDs that are fully present in the configuration can be reported as
unavailable for the whole lifetime of the process:

Provider my-fallback was not found. Its provider or model ID may have been changed.

and requests that reference them (Agent Runner fallback chat providers, the
configured context-compression model) are silently skipped until the next
restart. The same message also appears for a provider that the user just
disabled, even though nothing about its ID changed.

Configuration and live instances drift apart

ProviderManager resolves explicit provider IDs only through inst_map, the
map of live provider instances. The configured provider list
(providers_config) and inst_map are two different things, and only startup
initialize() guarantees that every configured entry gets an instance.

ProviderManager.reload() re-syncs providers_config from the configuration
and terminates instances whose IDs disappeared, but it never instantiates
entries that appeared. So any provider entry that reaches the configuration
without going through create_provider() (editing cmd_config.json,
restoring a backup, a failed adapter import during startup) stays unloaded.
A later save of an unrelated provider runs reload() again and still does not
heal the drift, which is why only a restart helps.

A disabled provider is a second, deliberate case: load_provider() returns
before registration, so the provider correctly has no instance and
get_provider_by_id() correctly returns None.

Why the message points users in the wrong direction

Context.get_provider_by_id() treated "no live instance" as "unknown ID" and
always logged that the provider or model ID "may have been changed". That
claim is only true for IDs that are absent from the configuration. For a
disabled provider, or a configured provider that failed to load, it asks the
user to hunt for a typo in an ID that is exactly right, and it hides the real
state of the provider.

Changes

Two small, related changes.

  1. ProviderManager.reload() converges inst_map with the configuration.
    After the existing removal loop, each configured entry that is enabled, is
    not an agent_runner provider, and has no live instance is instantiated
    inside the manager's existing resource_lock. Each provider is loaded in its
    own try/except with the same error containment initialize() uses, so one
    broken provider is logged and cannot abort the reload or block the others.
    Eligibility is decided on the entry merged with its provider_source
    config - the same effective configuration load_provider() resolves - so a
    provider that inherits enable or provider_type from its source is loaded
    too rather than silently skipped. The entry passed to reload() itself is
    resolved the same way, so the provider-source upsert path no longer raises
    KeyError when a field is inherited.
    The method now reads self.acm.default_conf instead of the module-global
    astrbot_config, matching the configuration the manager was constructed
    from and the same object its create/update/delete methods operate on.
    create_provider() syncs that same list after saving. In production both
    refer to the default configuration, so this only removes an accidental
    source of divergence.

    The whole convergence pass runs under resource_lock, the same lock that
    create_provider(), update_provider() and delete_provider() take, so it
    cannot race a configuration mutation. This is a real race, not a theoretical
    one: the provider-source upsert path calls reload() without holding any
    manager lock, while delete_provider() takes only resource_lock. Without
    serialization, delete_provider("b") could complete while reload("a") was
    suspended inside load_provider("b"); the resumed convergence loop then
    registered b in inst_map after b had been removed from the
    configuration. The instance outlived the configuration entry.
    update_provider() already holds resource_lock when it reloads, so it now
    calls the private _reload_locked() body directly and every other caller
    enters through reload(). That keeps one lock for both configuration
    mutation and instance convergence: there is no lock-ordering cycle, and no
    path acquires resource_lock while already holding a manager lock. The
    former reload_lock is removed because, with every reload entered under
    resource_lock, it could no longer be contended.

  2. Context.get_provider_by_id() reports the real reason. On an
    inst_map miss it looks the ID up in the configured provider list. If the
    ID is unknown, the existing wording is preserved verbatim. If the ID is
    configured but disabled, the log says it is disabled and cannot be used. If
    it is configured but has no instance, the log says it was configured but
    not loaded and to check the logs. The method still returns None in every
    miss case, so a disabled provider is never silently used.

The diagnostic half matters as much as the loading half: users of #7425 were
told to look for a renamed provider or model, and the only actionable fact -
that their fallback/compression provider was disabled or had failed to load -
was never surfaced. Fixing convergence alone would still leave that misleading
message for genuinely disabled providers.

Verification

Diff scope: 2 production files (astrbot/core/provider/manager.py +102/-57, astrbot/core/star/context.py +22/-5; total +124/-62, no test files modified in this PR).

Eleven local verification scenarios (kept out of this PR diff to keep the change focused on the 2 production files; happy to include compact regression tests if preferred) were verified before/after this fix:

Reload convergence scenarios:

  • reload() instantiates a provider newly added to the configured list while
    inst_map is stale.
  • reload() skips disabled and agent_runner entries without creating
    instances, loading only the eligible provider, and without raising.
  • reload() instantiates a configured entry that inherits enable and
    provider_type only from its provider_source config.
  • Passing that inherited entry to reload() itself, as the provider-source
    upsert path does, loads it; it previously raised KeyError: 'enable'.
  • An entry whose provider_source config is disabled is still skipped.
  • A provider that fails to load during reload() is logged, does not raise
    out of reload(), and does not prevent the other new provider from loading.
  • A delete_provider() for a provider that reload() is in the middle of
    loading leaves that provider absent from the configuration,
    providers_config and inst_map. The load is suspended on an
    asyncio.Event, so the two coroutines deterministically interleave.
  • update_provider() completes and replaces the instance; it holds
    resource_lock while reloading, so the test times out if the reload path
    re-acquires that lock.

Lookup diagnostic scenarios:

  • get_provider_by_id() on a configured-but-disabled ID returns None, logs
    that it is disabled, and no longer emits the "may have been changed"
    wording.
  • get_provider_by_id() on a genuinely unknown ID keeps the existing wording
    exactly, while a configured-but-unloaded ID gets the truthful message.
  • End-to-end, _get_compress_provider() and _get_fallback_chat_providers()
    with a configured-but-disabled ID log the disabled reason for both paths
    instead of the "changed" wording.

Seven of the original eight tests fail on master; the eighth cannot complete
there. On master, reload() re-syncs from the module-global configuration and
terminates the instance that is not in it, so the update_provider() test also
fails there, with KeyError: 'existing_provider'. The interleaving test hangs on
master instead, because the gated convergence load it waits for never starts.

The two tests for an entry that inherits enable from its source fail on the
intermediate convergence state this branch had before the guard resolved the
merged config: the convergence test leaves the provider unloaded, and the
direct-reload test raises KeyError: 'enable'. The disabled-source test passes
in both states and guards against loading it after the fix.

The interleaving test targets the race introduced by the convergence pass
itself, so it fails on that intermediate state (convergence without the lock,
where inst_map keeps the deleted provider) and passes with the final change.
The update_provider() test fails with a TimeoutError if its reload path
re-acquires resource_lock.

Compatibility

  • No new configuration keys, no schema or API changes.
  • A healthy setup whose configured providers all have live instances is
    unaffected: reload() finds nothing missing, and lookups hit inst_map
    before any diagnostic runs.
  • Disabled providers stay unused; their behavior changes only in the message.

Suggested merge order

Independent from #10845 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

Keep configured provider instances synchronized during reloads and explain provider lookup failures accurately.

Bug Fixes:

  • Ensure configured providers added or restored without live instances are loaded during provider reloads, while retaining disabled and agent-runner providers as unavailable.
  • Provide accurate provider lookup diagnostics for unknown, disabled, and configured-but-unloaded providers instead of implying every failure is an ID change.

Enhancements:

  • Serialize provider configuration mutations and instance convergence under a single management lock, preventing reload and deletion races while preserving provider instance selection.

Tests:

  • Add coverage for provider convergence, inherited source configuration, load failures, concurrent deletion, update locking, and lookup diagnostics.

@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/provider/manager.py" line_range="933-938" />
<code_context>
+        # provider added to the config becomes usable without a restart.
+        for config_entry in self.providers_config:
+            provider_id = config_entry.get("id")
+            if not provider_id or provider_id in self.inst_map:
+                continue
+            # Judge eligibility on the same merged config load_provider() resolves,
+            # so fields inherited from the provider_source count here too.
+            effective_config = self.get_merged_provider_config(config_entry)
+            if not effective_config.get("enable", False):
+                continue
+            if effective_config.get("provider_type", "") == "agent_runner":
</code_context>
<issue_to_address>
**Disabled live provider remains usable**

When a configured provider with a live instance is changed to disabled outside a reload of that same provider, then another provider is reloaded, `_reload_locked()` skips an entry as soon as its ID is in `inst_map`, before checking whether it is now disabled, so the existing instance remains available and lookups continue returning it; callers can use a provider that the configuration disables.

During convergence, check effective enablement for existing instances too and terminate any instance whose effective configuration is disabled.
</issue_to_address>

Linked issues

#7425 [Bug]无论如何修改供应商ID,都会有“Fallback chat provider”或是“未找到指定的上下文压缩模型”,随即显示跳过阶段。 · 3 of 3 met

# Requirement Status Notes
1 Configured fallback chat providers should be resolved instead of skipped. ✅ Met The reload convergence pass loads eligible configured providers missing from inst_map, allowing fallback lookup to find them.
2 The configured context-compression model should be resolved instead of skipped. ✅ Met Context-compression lookup uses the same provider lookup path, and the added test exercises that path.
3 The warning should not imply a provider ID changed when the ID is configured. ✅ Met Lookup diagnostics distinguish unknown IDs from configured-but-disabled and configured-but-unloaded providers.

Sourcery assessment

Needs a human reviewer. 1 finding to address first, and a reload can now instantiate enabled providers from the saved configuration, making them available for requests and potentially auto-selecting one if no current provider exists. Prompts sent to a provider's configured endpoint cannot be recalled by reverting the change.

Blocking findings: astrbot/core/provider/manager.py:938


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

Comment thread astrbot/core/provider/manager.py Resolved
@JosephTian876

Copy link
Copy Markdown
Contributor Author

Rebased onto latest master (a084409) and trimmed newly added test files per .github/copilot-instructions.md to keep the diff focused on production changes.

Local Verification

  • Pre-trim regression tests: Verified production symbols cleanly against current master
  • Existing upstream test suite: 47 passed (test_star_context.py)
  • ruff check and ruff format --check: passed (0 issues)

@JosephTian876
JosephTian876 force-pushed the fix/provider-reload-converges branch from 80a1b7e to 8bc9fa7 Compare November 30, 2026 11:03
@JosephTian876

Copy link
Copy Markdown
Contributor Author

Updated in 8bc9fa7 to preserve the module-level astrbot_config re-export in astrbot/core/provider/manager.py for callers and tests that patch astrbot.core.provider.manager.astrbot_config (such as tests/test_openai_decision_provider.py::test_provider_manager_create_update_reload_and_connection_test), while keeping ProviderManager reading from self.acm.default_conf.

Verified locally: tests/test_openai_decision_provider.py (115 passed), tests/unit/test_star_context.py (47 passed), and ruff check / ruff format --check (0 issues).

@sourcery-ai

sourcery-ai Bot commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

Linked issues

Checked at commit 8bc9fa7

#7425 [Bug]无论如何修改供应商ID,都会有“Fallback chat provider”或是“未找到指定的上下文压缩模型”,随即显示跳过阶段。 · 1 of 1 met

# Requirement Status Notes
1 Configured fallback chat and context-compression providers should be found instead of skipped. ✅ Met Reload now loads configured, enabled providers that lack live instances, allowing ID lookups to resolve them; misses also distinguish disabled or unloaded providers from unknown IDs.

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

1 participant