Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
perf(plugins): read the entry-point catalogue once, not once per lookup
Ruben Lütkee53f64291fbc
diff --git a/jarvis/core/entry_points.py b/jarvis/core/entry_points.pynew file mode 100644index 0000000000..7921a810d9--- /dev/null+++ b/jarvis/core/entry_points.py@@ -0,0 +1,75 @@+"""One cached read of the installed entry-point catalogue, shared process-wide.++``importlib.metadata.entry_points()`` is not a lookup — it is a filesystem+sweep. Every call re-walks ``sys.path``, enumerates every installed+distribution and opens each one's ``entry_points.txt``. On a full Jarvis+install that is 535 distributions; measured here it costs ~30 ms once the OS+file cache is warm and **624 ms cold**, and a cold sweep under disk load has+been seen to take seconds.++That would be merely wasteful if it happened once. It does not: plugin+resolution asks per candidate, so a single cross-family fallback chain pays for+it once per provider it probes, and the callers sit on the asyncio event loop —+the same loop that serves every WebSocket, HTTP route and terminal pane. A+16.5 s loop stall was captured with exactly this call at the bottom of the+stack (``_dictation_session`` → ``build_stt_from_config`` →+``_load_provider_class`` → ``entry_points()`` → ``read_text`` → ``io.open``),+which is why this module exists.++Caching for the life of the process is correct rather than merely convenient:+the catalogue only changes when a distribution is installed or removed, and a+new entry-point does not take effect in an already-running interpreter anyway+(hence CLAUDE.md §10's ``pip install -e . --no-deps`` followed by a restart).+:func:`invalidate` is provided for the one case that does need it — a test, or+an in-process install that wants the next read to see new plugins.+"""++from __future__ import annotations++import threading+from importlib import metadata++__all__ = ["entry_points_for", "invalidate"]++# Guards the fill, not the read. Without it, the several subsystems that resolve+# plugins concurrently during boot would each pay the cold sweep in parallel —+# the one moment the sweep is at its most expensive.+_LOCK = threading.Lock()+_CACHE: dict[str, tuple[metadata.EntryPoint, ...]] = {}+++def entry_points_for(group: str) -> tuple[metadata.EntryPoint, ...]:+ """Every entry-point declared in ``group``, read from disk at most once.++ Args:+ group: An entry-point group name, e.g. ``"jarvis.stt"``.++ Returns:+ The group's entry-points as an immutable tuple. Empty when the group+ has no registered plugins — indistinguishable, deliberately, from a+ group nobody declared: both mean "nothing to load here".+ """+ cached = _CACHE.get(group)+ if cached is not None:+ return cached++ with _LOCK:+ # A second caller may have filled it while this one waited.+ cached = _CACHE.get(group)+ if cached is not None:+ return cached+ resolved = tuple(metadata.entry_points(group=group))+ _CACHE[group] = resolved+ return resolved+++def invalidate() -> None:+ """Drop the cache so the next read goes back to disk.++ For tests, and for the rare in-process install that adds plugins. Callers+ that merely want fresh *behaviour* from an existing plugin do not need+ this — the catalogue caches the entry-point declarations, never the loaded+ modules.+ """+ with _LOCK:+ _CACHE.clear()diff --git a/jarvis/core/registry.py b/jarvis/core/registry.pyindex 751b124c7b..0db1ff8122 100644--- a/jarvis/core/registry.py+++ b/jarvis/core/registry.py@@ -1,4 +1,4 @@-"""Plugin discovery via entry_points.+"""Plugin discovery via entry_points.All plugin slots are declared in pyproject.toml under[project.entry-points."jarvis.*"]. This module lists them at runtime, loads@@ -7,11 +7,12 @@ them lazily, and checks them against the matching Protocol.Important: `load()` only imports on actual invocation — this allows optionaldependencies (e.g. discord.py only loads when the Discord channel is enabled)."""+from __future__ import annotations-from importlib import metadatafrom typing import Any, Protocol+from .entry_points import entry_points_forfrom .protocols import PLUGIN_GROUPS@@ -35,7 +36,7 @@ def list_plugins(group: str) -> list[str]:"""if group not in PLUGIN_GROUPS:raise ValueError(f"Unknown plugin group: {group}. Allowed: {PLUGIN_GROUPS}")- eps = metadata.entry_points(group=group)+ eps = entry_points_for(group)return sorted(ep.name for ep in eps)@@ -62,13 +63,12 @@ def load(group: str, name: str, protocol: type[Protocol] | None = None) -> type[if group not in PLUGIN_GROUPS:raise ValueError(f"Unknown plugin group: {group}")- eps = metadata.entry_points(group=group)+ eps = entry_points_for(group)candidates = [ep for ep in eps if ep.name == name]if not candidates:available = sorted(ep.name for ep in eps)raise PluginNotFoundError(- f"Plugin '{name}' not found in group '{group}'. "- f"Available: {available}"+ f"Plugin '{name}' not found in group '{group}'. Available: {available}")ep = candidates[0]@@ -88,8 +88,7 @@ def load(group: str, name: str, protocol: type[Protocol] | None = None) -> type[plugin_cls = ep.load()except ImportError as exc:raise PluginLoadError(- f"Plugin '{name}' could not be imported. "- f"Missing a dependency? Original error: {exc}"+ f"Plugin '{name}' could not be imported. Missing a dependency? Original error: {exc}") from excexcept Exception as exc: # noqa: BLE001raise PluginLoadError(f"Plugin '{name}' load failed: {exc}") from exc@@ -98,9 +97,7 @@ def load(group: str, name: str, protocol: type[Protocol] | None = None) -> type[# signatures on the first isinstance call on an instance — not on the# class). Here we can at most ensure that it is a class.if not isinstance(plugin_cls, type):- raise PluginContractError(- f"Plugin '{name}' is not a class but {type(plugin_cls)}"- )+ raise PluginContractError(f"Plugin '{name}' is not a class but {type(plugin_cls)}")_ = protocol # Documentation-intent; verification happens at the instance levelreturn plugin_clsdiff --git a/jarvis/plugins/stt/__init__.py b/jarvis/plugins/stt/__init__.pyindex d3a752454d..9e738a0549 100644--- a/jarvis/plugins/stt/__init__.py+++ b/jarvis/plugins/stt/__init__.py@@ -291,13 +291,17 @@ def resolve_keyed_stt_fallback(def _load_provider_class(name: str) -> type | None:- """Resolve an STT provider class by its entry-point ``name`` (e.g. ``groq-api``)."""- eps = importlib_metadata.entry_points()- selected = (- eps.select(group=ENTRY_POINT_GROUP)- if hasattr(eps, "select")- else eps.get(ENTRY_POINT_GROUP, []) # type: ignore[attr-defined]- )+ """Resolve an STT provider class by its entry-point ``name`` (e.g. ``groq-api``).++ The catalogue read is cached process-wide (``jarvis.core.entry_points``)+ because this is a hot path on the event loop: the cross-family chain calls+ this once per candidate it probes, and an uncached read is a sweep over+ every installed distribution — the call at the bottom of a captured 16.5 s+ loop stall.+ """+ from jarvis.core.entry_points import entry_points_for++ selected = entry_points_for(ENTRY_POINT_GROUP)for ep in selected:if ep.name == name:try:diff --git a/tests/conftest.py b/tests/conftest.pyindex c23770981c..9f745c99ba 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -145,6 +145,24 @@ def _reset_config_caches():clear_config_cache()[email protected](autouse=True)+def _reset_entry_point_cache():+ """Start every test with a cold entry-point catalogue.++ Same reasoning as the config caches above: ``jarvis.core.entry_points``+ remembers the installed plugin catalogue for the life of the process, which+ is safe in production (a new entry-point needs a restart anyway) and unsafe+ across tests — a suite that monkeypatches ``importlib.metadata.entry_points``+ to fake a plugin set would otherwise be answered from whatever an earlier+ test happened to read from the real installation.+ """+ from jarvis.core.entry_points import invalidate++ invalidate()+ yield+ invalidate()++@pytest_asyncio.fixtureasync def fresh_bus():"""Fresh EventBus for each test."""diff --git a/tests/unit/core/test_entry_points_cache.py b/tests/unit/core/test_entry_points_cache.pynew file mode 100644index 0000000000..50a24c6e22--- /dev/null+++ b/tests/unit/core/test_entry_points_cache.py@@ -0,0 +1,132 @@+"""The entry-point catalogue is read from disk once, not once per lookup.++``importlib.metadata.entry_points()`` is a sweep over every installed+distribution, and plugin resolution asks per candidate from the asyncio event+loop — the combination produced a captured 16.5 s loop stall with+``entry_points()`` at the bottom of the stack. These tests pin the caching that+removed it, including the part that is easy to lose: that a *second* group does+not silently reuse the first group's answer.+"""++from __future__ import annotations++import threading+from importlib import metadata++import pytest++from jarvis.core import entry_points as ep_module+++class _CountingSweep:+ """Stands in for ``metadata.entry_points``, counting real reads per group."""++ def __init__(self, catalogue: dict[str, list[str]]) -> None:+ self._catalogue = catalogue+ self.calls: list[str] = []++ def __call__(self, *, group: str) -> list[metadata.EntryPoint]:+ self.calls.append(group)+ return [+ metadata.EntryPoint(name=name, value="mod:Cls", group=group)+ for name in self._catalogue.get(group, [])+ ]+++def sweep(monkeypatch: pytest.MonkeyPatch) -> _CountingSweep:+ counting = _CountingSweep(+ {"jarvis.stt": ["groq-api", "faster-whisper"], "jarvis.tts": ["piper"]}+ )+ monkeypatch.setattr(metadata, "entry_points", counting)+ ep_module.invalidate()+ return counting+++def test_repeated_lookups_hit_the_disk_once(sweep: _CountingSweep) -> None:+ """The whole point: N lookups, one sweep."""+ for _ in range(25):+ names = [ep.name for ep in ep_module.entry_points_for("jarvis.stt")]++ assert names == ["groq-api", "faster-whisper"]+ assert sweep.calls == ["jarvis.stt"]+++def test_each_group_is_cached_separately(sweep: _CountingSweep) -> None:+ """A per-group cache must not answer one group from another's entry."""+ stt = [ep.name for ep in ep_module.entry_points_for("jarvis.stt")]+ tts = [ep.name for ep in ep_module.entry_points_for("jarvis.tts")]++ assert stt == ["groq-api", "faster-whisper"]+ assert tts == ["piper"]+ assert sweep.calls == ["jarvis.stt", "jarvis.tts"]+++def test_unknown_group_is_empty_and_still_cached(sweep: _CountingSweep) -> None:+ """A group nobody declared must not re-sweep on every miss."""+ assert ep_module.entry_points_for("jarvis.nonexistent") == ()+ assert ep_module.entry_points_for("jarvis.nonexistent") == ()++ assert sweep.calls == ["jarvis.nonexistent"]+++def test_invalidate_goes_back_to_disk(sweep: _CountingSweep) -> None:+ """The escape hatch for tests and in-process installs actually works."""+ ep_module.entry_points_for("jarvis.stt")+ ep_module.invalidate()+ ep_module.entry_points_for("jarvis.stt")++ assert sweep.calls == ["jarvis.stt", "jarvis.stt"]+++def test_result_is_immutable(sweep: _CountingSweep) -> None:+ """Callers share one cached object, so it must not be a mutable list.++ ``list_plugins`` and the STT loader both iterate the result; if one of them+ could sort or pop in place, the next caller would get a mutated catalogue.+ """+ assert isinstance(ep_module.entry_points_for("jarvis.stt"), tuple)+++def test_concurrent_first_readers_sweep_once(sweep: _CountingSweep) -> None:+ """Boot resolves plugins from several threads at once.++ That is precisely when the sweep is at its most expensive (cold file cache),+ so the fill is locked. Without the lock each thread pays for its own.+ """+ barrier = threading.Barrier(8)+ results: list[tuple[str, ...]] = []+ lock = threading.Lock()++ def read() -> None:+ barrier.wait()+ names = tuple(ep.name for ep in ep_module.entry_points_for("jarvis.stt"))+ with lock:+ results.append(names)++ threads = [threading.Thread(target=read) for _ in range(8)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join()++ assert sweep.calls == ["jarvis.stt"]+ assert results == [("groq-api", "faster-whisper")] * 8+++def test_stt_loader_uses_the_cache(monkeypatch: pytest.MonkeyPatch) -> None:+ """The captured stall came from the STT loader — pin that it is on the cache.++ Guards against a future edit reinstating a direct ``entry_points()`` call in+ ``jarvis.plugins.stt``, which is what made a dictation start cost seconds.+ """+ from jarvis.plugins import stt as stt_module++ counting = _CountingSweep({"jarvis.stt": ["groq-api"]})+ monkeypatch.setattr(metadata, "entry_points", counting)+ ep_module.invalidate()++ for _ in range(10):+ stt_module._load_provider_class("no-such-provider")++ assert counting.calls == ["jarvis.stt"]