refactor: one place loads plugin entry points

#908 and #911 landed two plugin groups — deeptutor.plugins for registry
capabilities, deeptutor.loop_capabilities for chat-loop ones — each with its own
copy of the same plumbing: read the group, import each target, warn and skip
whatever fails. Only the coercer actually differed.

Move the plumbing into core/entry_points.py, which both layers already depend
on, so the containment guarantee (one bad plugin cannot stop the others) is
stated and tested once instead of twice. Both suites now stub the single seam
rather than a module-local alias.

Drops #908's Python <3.10 entry_points() fallback along the way: the project
requires >=3.11, so the keyword form is the only API in play.
This commit is contained in:
Bingxi Zhao (Frank)
2026-08-20 00:34:08 +08:00
parent f46e188cdd
commit 802a19779f
6 changed files with 176 additions and 57 deletions

View File

@@ -3,7 +3,6 @@
from __future__ import annotations
from functools import cache
from importlib.metadata import entry_points
import inspect
import logging
from typing import Any
@@ -18,6 +17,7 @@ from deeptutor.capabilities.setup import SetupCapability
from deeptutor.capabilities.solve import SolveLoopCapability
from deeptutor.capabilities.subagent import SubagentCapability
from deeptutor.core.context import UnifiedContext
from deeptutor.core.entry_points import load_entry_point_group
logger = logging.getLogger(__name__)
@@ -95,35 +95,26 @@ def discover_external_loop_capabilities() -> tuple[LoopCapability, ...]:
server; tests reset the cache with ``discover_external_loop_capabilities
.cache_clear()``.
"""
found: list[LoopCapability] = []
seen = {cap.name for cap in LOOP_CAPABILITIES}
try:
discovered = entry_points(group=LOOP_CAPABILITIES_GROUP)
except Exception as exc:
logger.warning("Failed to read %s entry points: %s", LOOP_CAPABILITIES_GROUP, exc)
return ()
for ep in discovered:
try:
cap = _coerce_loop_capability(ep.load())
except Exception as exc:
logger.warning("Failed to load loop capability plugin '%s': %s", ep.name, exc)
continue
def _accept(ep_name: str, loaded: object) -> LoopCapability | None:
cap = _coerce_loop_capability(loaded)
if cap is None:
logger.warning(
"Ignoring loop capability plugin '%s': not a LoopCapability class or factory",
ep.name,
ep_name,
)
continue
return None
if cap.name in seen:
logger.warning(
"Loop capability plugin '%s' shadowed by built-in or earlier plugin (ignored)",
cap.name,
)
continue
return None
seen.add(cap.name)
found.append(cap)
return tuple(found)
return cap
return tuple(load_entry_point_group(LOOP_CAPABILITIES_GROUP, _accept, log=logger))
def all_loop_capabilities() -> tuple[LoopCapability, ...]:

View File

@@ -0,0 +1,60 @@
"""Load an entry-point group without letting one bad plugin take the app down.
DeepTutor exposes two plugin groups — ``deeptutor.plugins`` for capabilities the
registry can run, ``deeptutor.loop_capabilities`` for chat-loop capabilities —
and both need the same plumbing: read the group, import each target, hand it to
a group-specific coercer, and skip whatever fails with a warning naming the
entry point. Only the coercer differs, so only the coercer lives at the call
site.
Third-party code runs at import time here, which is what an entry point is; the
guarantee this module makes is narrower and worth stating plainly: a plugin that
raises cannot stop the others from loading.
"""
from __future__ import annotations
from collections.abc import Callable
from importlib.metadata import entry_points
import logging
from typing import Any, TypeVar
logger = logging.getLogger(__name__)
T = TypeVar("T")
def load_entry_point_group(
group: str,
coerce: Callable[[str, Any], T | None],
*,
log: logging.Logger | None = None,
) -> list[T]:
"""Return every ``group`` entry point that imports and coerces cleanly.
``coerce`` receives ``(entry_point_name, loaded_object)`` and returns the
value to keep, or ``None`` to reject it — a rejection is the coercer's own
judgement, so it is expected to say why. Anything raised while importing or
coercing is logged against that entry point's name and skipped.
"""
out: list[T] = []
emit = log or logger
try:
discovered = list(entry_points(group=group))
except Exception:
emit.warning("Failed to read %s entry points; no plugins loaded.", group, exc_info=True)
return out
for ep in discovered:
name = getattr(ep, "name", str(ep))
try:
value = coerce(name, ep.load())
except Exception:
emit.warning("Failed to load %s entry point %r; skipping.", group, name, exc_info=True)
continue
if value is not None:
out.append(value)
return out
__all__ = ["load_entry_point_group"]

View File

@@ -14,12 +14,12 @@ from __future__ import annotations
from dataclasses import dataclass, field
import importlib
from importlib.metadata import entry_points
import inspect
import logging
from typing import Any
from deeptutor.core.capability_protocol import BaseCapability
from deeptutor.core.entry_points import load_entry_point_group
logger = logging.getLogger(__name__)
@@ -41,30 +41,7 @@ class PluginManifest:
def discover_plugins() -> list[PluginManifest]:
"""Discover plugins registered via ``deeptutor.plugins`` entry points."""
manifests: list[PluginManifest] = []
try:
eps = entry_points(group=ENTRY_POINT_GROUP)
except TypeError:
# Python <3.10 style Selection / dict API
all_eps = entry_points()
if isinstance(all_eps, dict):
eps = all_eps.get(ENTRY_POINT_GROUP, [])
else:
eps = all_eps.select(group=ENTRY_POINT_GROUP)
for ep in eps:
try:
loaded = ep.load()
manifest = _coerce_manifest(ep.name, loaded)
if manifest is not None:
manifests.append(manifest)
except Exception:
logger.warning(
"Failed to load plugin entry point %r; skipping.",
getattr(ep, "name", ep),
exc_info=True,
)
return manifests
return load_entry_point_group(ENTRY_POINT_GROUP, _coerce_manifest, log=logger)
def load_plugin_capability(manifest: PluginManifest) -> BaseCapability | None:

View File

@@ -8,6 +8,7 @@ import pytest
from deeptutor.capabilities.registry import LOOP_CAPABILITIES, discover_external_loop_capabilities
from deeptutor.core.context import UnifiedContext
import deeptutor.core.entry_points as ep_module
@pytest.fixture(autouse=True)
@@ -97,7 +98,7 @@ def test_loop_capabilities_tuple_is_builtins_only() -> None:
def test_all_loop_capabilities_equals_builtins_without_plugins(monkeypatch) -> None:
from deeptutor.capabilities import registry
monkeypatch.setattr(registry, "entry_points", _no_plugins)
monkeypatch.setattr(ep_module, "entry_points", _no_plugins)
merged = registry.all_loop_capabilities()
assert merged == LOOP_CAPABILITIES
@@ -110,7 +111,7 @@ def test_external_class_is_appended(monkeypatch) -> None:
assert group == "deeptutor.loop_capabilities"
return [_ep("demo_loop", lambda: _DemoLoop)]
monkeypatch.setattr(registry, "entry_points", fake_entry_points)
monkeypatch.setattr(ep_module, "entry_points", fake_entry_points)
merged = registry.all_loop_capabilities()
assert merged[: len(LOOP_CAPABILITIES)] == LOOP_CAPABILITIES
@@ -125,7 +126,7 @@ def test_factory_callable_returning_instance(monkeypatch) -> None:
assert group == "deeptutor.loop_capabilities"
return [_ep("demo_loop", lambda: lambda: _DemoLoop())]
monkeypatch.setattr(registry, "entry_points", fake_entry_points)
monkeypatch.setattr(ep_module, "entry_points", fake_entry_points)
merged = registry.all_loop_capabilities()
assert merged[-1].name == "demo_loop"
@@ -137,7 +138,7 @@ def test_builtin_name_wins_and_warns(monkeypatch) -> None:
def fake_entry_points(*, group: str):
return [_ep("mastery", lambda: _ShadowMastery)]
monkeypatch.setattr(registry, "entry_points", fake_entry_points)
monkeypatch.setattr(ep_module, "entry_points", fake_entry_points)
warnings = _capture_warnings(monkeypatch, registry)
merged = registry.all_loop_capabilities()
@@ -157,7 +158,7 @@ def test_broken_entry_point_is_skipped(monkeypatch) -> None:
def fake_entry_points(*, group: str):
return [_ep("broken", boom), _ep("demo_loop", lambda: _DemoLoop)]
monkeypatch.setattr(registry, "entry_points", fake_entry_points)
monkeypatch.setattr(ep_module, "entry_points", fake_entry_points)
warnings = _capture_warnings(monkeypatch, registry)
merged = registry.all_loop_capabilities()
@@ -172,7 +173,7 @@ def test_invalid_object_is_skipped(monkeypatch) -> None:
def fake_entry_points(*, group: str):
return [_ep("not_a_cap", lambda: object)]
monkeypatch.setattr(registry, "entry_points", fake_entry_points)
monkeypatch.setattr(ep_module, "entry_points", fake_entry_points)
warnings = _capture_warnings(monkeypatch, registry)
merged = registry.all_loop_capabilities()
@@ -205,7 +206,7 @@ def test_duplicate_external_name_first_wins(monkeypatch) -> None:
_ep("demo_loop_dup", lambda: _Other),
]
monkeypatch.setattr(registry, "entry_points", fake_entry_points)
monkeypatch.setattr(ep_module, "entry_points", fake_entry_points)
merged = registry.all_loop_capabilities()
demo = [cap for cap in merged if cap.name == "demo_loop"]
@@ -219,7 +220,7 @@ def test_active_loop_capabilities_includes_external(monkeypatch) -> None:
def fake_entry_points(*, group: str):
return [_ep("demo_loop", lambda: _DemoLoop)]
monkeypatch.setattr(registry, "entry_points", fake_entry_points)
monkeypatch.setattr(ep_module, "entry_points", fake_entry_points)
idle = registry.active_loop_capabilities(UnifiedContext())
assert all(cap.name != "demo_loop" for cap in idle)
@@ -234,7 +235,7 @@ def test_capability_tool_owners_includes_external(monkeypatch) -> None:
def fake_entry_points(*, group: str):
return [_ep("demo_loop", lambda: _DemoLoop)]
monkeypatch.setattr(registry, "entry_points", fake_entry_points)
monkeypatch.setattr(ep_module, "entry_points", fake_entry_points)
owners = registry.capability_tool_owners()
assert owners["demo_tool"] == "demo_loop"

View File

@@ -0,0 +1,89 @@
"""``load_entry_point_group`` is the one place third-party plugin code is imported.
Its whole job is containment: a plugin that raises on import, or that the
coercer rejects, must not stop the rest of the group from loading.
"""
from __future__ import annotations
from types import SimpleNamespace
import pytest
import deeptutor.core.entry_points as ep_module
from deeptutor.core.entry_points import load_entry_point_group
def _ep(name: str, load):
return SimpleNamespace(name=name, load=load)
def _keep(_name: str, loaded: object) -> object | None:
return loaded
def _stub(monkeypatch: pytest.MonkeyPatch, entries: list[object]) -> None:
def _entry_points(*, group: str):
assert group == "demo.group"
return entries
monkeypatch.setattr(ep_module, "entry_points", _entry_points)
def test_loads_every_healthy_entry_point(monkeypatch: pytest.MonkeyPatch) -> None:
_stub(monkeypatch, [_ep("a", lambda: "one"), _ep("b", lambda: "two")])
assert load_entry_point_group("demo.group", _keep) == ["one", "two"]
def test_a_raising_entry_point_does_not_stop_the_others(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
def _boom():
raise RuntimeError("import blew up")
_stub(monkeypatch, [_ep("broken", _boom), _ep("healthy", lambda: "kept")])
with caplog.at_level("WARNING"):
assert load_entry_point_group("demo.group", _keep) == ["kept"]
assert "broken" in caplog.text
def test_a_raising_coercer_is_contained_too(monkeypatch: pytest.MonkeyPatch) -> None:
def _picky(name: str, loaded: object) -> object | None:
if name == "bad":
raise ValueError("cannot use this")
return loaded
_stub(monkeypatch, [_ep("bad", lambda: "x"), _ep("good", lambda: "y")])
assert load_entry_point_group("demo.group", _picky) == ["y"]
def test_a_rejected_entry_point_is_dropped_silently_here(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A ``None`` is the coercer's own verdict, so it owns the explanation."""
_stub(monkeypatch, [_ep("a", lambda: "one"), _ep("b", lambda: "two")])
kept = load_entry_point_group(
"demo.group", lambda name, loaded: None if name == "a" else loaded
)
assert kept == ["two"]
def test_an_unreadable_group_yields_nothing(
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
def _explode(*, group: str):
raise OSError("metadata unreadable")
monkeypatch.setattr(ep_module, "entry_points", _explode)
with caplog.at_level("WARNING"):
assert load_entry_point_group("demo.group", _keep) == []
assert "demo.group" in caplog.text
def test_no_entry_points_is_not_an_error(monkeypatch: pytest.MonkeyPatch) -> None:
_stub(monkeypatch, [])
assert load_entry_point_group("demo.group", _keep) == []

View File

@@ -8,6 +8,7 @@ import pytest
from deeptutor.core.capability_protocol import BaseCapability, CapabilityManifest
from deeptutor.core.context import UnifiedContext
import deeptutor.core.entry_points as ep_module
from deeptutor.core.stream_bus import StreamBus
@@ -33,7 +34,7 @@ def test_discover_plugins_from_capability_class(monkeypatch):
assert group == "deeptutor.plugins"
return [_ep("demo_cap", lambda: _DemoCapability)]
monkeypatch.setattr(loader, "entry_points", fake_entry_points)
monkeypatch.setattr(ep_module, "entry_points", fake_entry_points)
manifests = loader.discover_plugins()
assert len(manifests) == 1
@@ -57,7 +58,7 @@ def test_discover_skips_broken_entry_points(monkeypatch):
_ep("demo_cap", lambda: _DemoCapability),
]
monkeypatch.setattr(loader, "entry_points", fake_entry_points)
monkeypatch.setattr(ep_module, "entry_points", fake_entry_points)
manifests = loader.discover_plugins()
assert [m.name for m in manifests] == ["demo_cap"]
@@ -66,7 +67,7 @@ def test_load_plugin_capability_instantiates(monkeypatch):
from deeptutor.plugins import loader
monkeypatch.setattr(
loader,
ep_module,
"entry_points",
lambda *, group: [_ep("demo_cap", lambda: _DemoCapability)],
)
@@ -102,7 +103,7 @@ def test_discover_from_manifest_factory(monkeypatch):
)
monkeypatch.setattr(
loader,
ep_module,
"entry_points",
lambda *, group: [_ep("from_factory", factory)],
)
@@ -117,7 +118,7 @@ def test_capability_registry_loads_plugins(monkeypatch):
from deeptutor.runtime.registry import capability_registry as cr
monkeypatch.setattr(
loader,
ep_module,
"entry_points",
lambda *, group: [_ep("demo_cap", lambda: _DemoCapability)],
)