Files
hermes-agent/pm/plugins_state.py
Teknium 0db846d3fe perf(pm): a worker serving many requests reads each unchanged input once
With one worker serving a whole default-plugins pass, every request still
re-read every home: each home's config.yaml (selection read and publication
snapshot), each enabled plugin's manifest and pyproject.toml, core's
pyproject.toml once per member, a walk of the bundled plugins dir per home
with a flat tree, and the marker environment of the target interpreter in a
child process. That kept the pass quadratic in the profile count.

- read_home_selection caches each local config.yaml's validated selection
  by the file's bytes (only when the bytes are unchanged across the parse;
  a remote config backend is never cached), returning copies.
- read_native_manifest and the module's pyproject reads parse each distinct
  file text once (stdlib only: PM's bootstrap reads these before the app's
  packages exist).
- selection_projection is memoized by the document bytes.
- enabled_selection judges every home's flat trees against one walk of the
  bundled dir (plugin_identity.one_bundled_walk).
- _target_environment asks each interpreter (by resolved path and stat) once.
2026-11-28 17:19:24 -08:00

279 lines
14 KiB
Python

"""Read every profile's enabled plugins in config order for the shared union.
Plugin admission owns writes; discovery never edits a profile's selection.
"""
from __future__ import annotations
import copy
from pathlib import Path
from typing import Any, Optional
import logging
LOG = logging.getLogger(__name__)
# plugins.<RECORD> maps each plugin an update disabled to {enabled, reason}: what to undo once it fits.
RECORD = "disabled_by_update"
def _profiles_root() -> Path:
# Plugin discovery and dependency publication must use the same home root.
from pm.environments import dependency_home_root
return dependency_home_root() / "profiles"
def _selection_readers(config_path: Path):
"""``(version(path), read(path), local)`` for a home's selection; *local*: it is read from the file at
*path*. PM's dependency runtime reads the LOCAL file it publishes to and compare-and-swaps
(``pm.publication``): it has neither the remote config backend's client nor the plane credential, so a
remote deployment never fails PM closed there. Every other process reads through the selected config
backend; a file deployment never asks whether this is PM's runtime (the selector is all it needs)."""
import os
from hermes_cli import config_backend
if os.environ.get(config_backend.BACKEND_ENV, "").strip().lower() in ("", "file"):
return config_backend.config_version, config_backend.read_config_doc, True
from pm.package import InstallError
from pm.runtime import is_runtime
try:
in_runtime = is_runtime()
except InstallError: # an application process whose packaged PM runtime is damaged: not PM's runtime
in_runtime = False
if not in_runtime:
return config_backend.config_version, config_backend.read_config_doc, False
backend, home = config_backend.local_file_layer(config_path)
return (lambda _path: backend.version(home)), (lambda _path: backend.read_user_doc(home)), True
def _bytes_or_none(path: Path) -> Optional[bytes]:
try:
return path.read_bytes()
except OSError:
return None
def read_home_selection(home: Path) -> Optional[dict[str, Any]]:
"""The plugin/memory selection a home's config.yaml declares (None: no config yet).
The public reader for anything that must agree with what PM installs for that home.
An unreadable selection raises rather than shrinking the next dependency generation;
empty YAML is an explicit empty configuration, as in the CLI loader.
"""
config_path = home / "config.yaml"
config_version, read_config_doc, local = _selection_readers(config_path)
# Stat before the YAML stack: a home without config needs none (PM's own runtime tree has none).
# Only a missing file means "no config"; a symlink loop or permission error still refuses.
try:
config_version(config_path)
except FileNotFoundError:
return None
except OSError as exc:
raise ValueError(f"could not read plugin selection: {config_path}") from exc
if not local: # a remote config backend: no file to key a parse on
return _parse_home_selection(config_path, read_config_doc)
seen = _bytes_or_none(config_path)
cached = _SELECTIONS.get(config_path)
if seen is not None and cached is not None and cached[0] == seen:
return copy.deepcopy(cached[1])
config = _parse_home_selection(config_path, read_config_doc)
if config is not None and seen is not None and _bytes_or_none(config_path) == seen: # the parse is of *seen*
if len(_SELECTIONS) >= _SELECTIONS_MAX:
_SELECTIONS.clear()
_SELECTIONS[config_path] = (seen, copy.deepcopy(config))
return config
# config.yaml path -> (the bytes parsed, validated selection). Every PM request reads every home's selection, and a
# worker serving a whole default-plugins pass (pm.client.one_worker) sends one or two requests per home: re-parsing
# each unchanged config.yaml per request made the pass quadratic in the profile count.
_SELECTIONS: dict[Path, tuple[bytes, dict[str, Any]]] = {}
_SELECTIONS_MAX = 1024
def _parse_home_selection(config_path: Path, read_config_doc) -> Optional[dict[str, Any]]:
""":func:`read_home_selection`'s parse and validation of *config_path* (None: it vanished)."""
# Missing YAML support is a broken runtime, not an empty plugin selection.
from ruamel.yaml.error import YAMLError
try:
config = read_config_doc(config_path)
except FileNotFoundError:
return None
except (OSError, UnicodeError) as exc:
raise ValueError(f"could not read plugin selection: {config_path}") from exc
except YAMLError as exc:
raise ValueError(f"could not parse plugin selection: {config_path}") from exc
if config is None:
return {}
if not isinstance(config, dict):
raise ValueError(f"configuration must be a mapping: {config_path}")
for section in ("plugins", "memory"):
if config.get(section) is not None and not isinstance(config[section], dict):
raise ValueError(f"{section} must be a mapping: {config_path}")
plugins = config.get("plugins") or {}
for key in ("enabled", "disabled"):
names = plugins.get(key)
if names is not None and (not isinstance(names, list)
or any(not isinstance(name, str) for name in names)):
raise ValueError(f"plugins.{key} must be a list of names: {config_path}")
provider = (config.get("memory") or {}).get("provider")
if provider is not None and not isinstance(provider, str):
raise ValueError(f"memory.provider must be a name: {config_path}")
return config
def _enabled_from_config(config: dict[str, Any], plugins_dir: Optional[Path] = None,
installing: Path | None = None) -> list[tuple[str, Optional[Path]]]:
"""``(entry, tree)`` for every plugin *config*'s ``plugins.enabled`` turns on in *plugins_dir*, in config
order. Each entry is resolved to the installed trees discovery loads for it and the dir it names by path in
*plugins_dir* (``plugin_identity.path_tree``: a manifest-less or staged tree, the home's own ``<entry>``
before a core-era key's catalog dir), and each tree is kept unless ``plugins.disabled`` names it: all by the
loader's own rule (``hermes_cli.plugin_identity``), so a fork, a nested copy or a core-era key gets the
verdict the loader gives it. ``tree`` is ``None`` for an entry nothing in *plugins_dir* answers to (a bundled
plugin): the caller resolves it (``pm.workspace.selected_plugin_dir``), judged by the identity its name gives."""
from hermes_cli.plugin_identity import installed_trees, path_tree, plugin_identity, plugin_listed
plugins_cfg = config.get("plugins")
if not isinstance(plugins_cfg, dict):
return []
enabled = plugins_cfg.get("enabled")
if not isinstance(enabled, list) or not any(isinstance(n, str) and n.strip() for n in enabled):
return [] # nothing selected: no folder needs reading
disabled = plugins_cfg.get("disabled", [])
trees = installed_trees(plugins_dir) if plugins_dir is not None else {}
if installing is not None and plugins_dir is not None and installing.parent.resolve() == plugins_dir.resolve() \
and not any(tree.resolve() == installing.resolve() for tree in trees):
trees[plugins_dir / installing.name] = plugin_identity(installing.name) # unpublished: keyed by its dir
out: list[tuple[str, Optional[Path]]] = []
for name in dict.fromkeys(n for n in enabled if isinstance(n, str) and n.strip()):
hits = [(tree, identity) for tree, identity in trees.items() if name in identity]
by_path = path_tree(plugins_dir, name, trees) if plugins_dir is not None else None
hits += [by_path] if by_path is not None else []
if not hits:
from hermes_cli.left_core_migration import legacy_plugin_alias
if not plugin_listed(plugin_identity(legacy_plugin_alias(name) or name, name), disabled):
out.append((name, None))
continue
out.extend((name, tree) for tree, identity in hits
if not plugin_listed(identity, disabled) and tree not in {t for _n, t in out})
return out
def _is_directory(path: Path) -> bool:
import stat
try:
return stat.S_ISDIR(path.stat().st_mode)
except FileNotFoundError:
return False
except OSError as exc:
raise ValueError(f"could not inspect plugin directory: {path}") from exc
def dependency_homes() -> list[Path]:
"""Every home whose selection feeds the shared venv: the default home plus each LIVE profile.
Enumerates the complete union or refuses; a partial scan cannot remove members.
Live means what ``hermes profile`` lists (hermes_constants): a valid id carrying an identity
marker and no tombstone. Staging dirs (``.work.staging-*``), deleted profiles and stray
marker-less dirs must not put plugins into the shared environment.
"""
from hermes_constants import PROFILE_ID_RE, named_profile_is_live
from pm.environments import dependency_home_root
homes = [dependency_home_root()]
root = _profiles_root()
try:
profiles = sorted(root.iterdir(), key=str)
except FileNotFoundError:
return homes
except OSError as exc:
raise ValueError(f"could not enumerate profiles: {root}") from exc
homes.extend(profile for profile in profiles
if _is_directory(profile) and profile.name != "default"
and PROFILE_ID_RE.match(profile.name) and named_profile_is_live(profile))
return homes
def enabled_plugins_ordered(*, proposed_home=None, enabled=None, disabled=None,
installing: Path | None = None,
skip_invalid_secondary: bool = False) -> dict[Path, list[str]]:
"""plugins_dir → ordered enabled list, per home: the entries of :func:`enabled_selection`."""
selection = enabled_selection(proposed_home=proposed_home, enabled=enabled, disabled=disabled,
installing=installing, skip_invalid_secondary=skip_invalid_secondary)
return {plugins_dir: list(dict.fromkeys(name for name, _tree in pairs)) for plugins_dir, pairs in selection.items()}
def enabled_selection(*, proposed_home=None, enabled=None, disabled=None, installing: Path | None = None,
skip_invalid_secondary: bool = False) -> dict[Path, list[tuple[str, Optional[Path]]]]:
"""plugins_dir → ordered ``(entry, tree)`` selection (:func:`_enabled_from_config`), per home. Keyed by the
PLUGINS DIR (where the member dirs live), not the home itself.
The ACTIVE MEMORY PROVIDER joins its home's list: providers install
via ``memory.provider`` (mnemosyne's documented path), not via
plugins.enabled — without this, a provider's dep plugin never joins
the union. Admission refuses a conflicting candidate without changing
the active environment or disabling an existing provider."""
from hermes_cli.plugin_identity import one_bundled_walk
out: dict[Path, list[tuple[str, Optional[Path]]]] = {}
homes = dependency_homes()
with one_bundled_walk(): # every home's flat trees are judged against one walk of the bundled dir
for home in homes:
# ONE parse per home feeds both queries (enabled + provider).
try:
config = read_home_selection(home)
except ValueError as exc:
if not skip_invalid_secondary or home == homes[0]:
raise
LOG.warning("Skipping broken secondary profile %s during dependency verification: %s", home, exc)
continue
config = config or {}
if proposed_home is not None and home.resolve() == Path(proposed_home).resolve():
config = {**config, "plugins": {"enabled": list(enabled or ()), "disabled": list(disabled or ())}}
selected = _enabled_from_config(config, home / "plugins", installing)
provider = _provider_from_config(home, config, installing=installing)
if provider and provider not in {name for name, _tree in selected}:
selected.append((provider, None))
if selected:
out[home / "plugins"] = selected
return out
def _provider_from_config(home: Path, config: dict[str, Any], *, installing: Path | None = None) -> Optional[str]:
"""The ``memory.provider`` key of an already-parsed config, when its
plugin dir exists (no dir = not a member) and plugins.disabled does not park it."""
provider = (config.get("memory") or {}).get("provider")
if not provider or not provider.strip():
return None
name = provider.strip()
plugin_dir = home / "plugins" / name
if installing is not None and plugin_dir.resolve() == installing.resolve():
return name
if not _is_directory(plugin_dir) or _parked(plugin_dir, config):
return None
return name
def _parked(plugin_dir: Path, config: dict[str, Any]) -> bool:
"""Whether plugins.disabled names this provider plugin. The provider loader honours the same
spellings (plugins.memory._explicitly_disabled), so a parked provider is never loaded and
installing its dependencies could only fail the generation for nothing."""
disabled = (config.get("plugins") or {}).get("disabled") or []
return bool(plugin_spellings(plugin_dir) & set(disabled))
def plugin_spellings(plugin_dir: Path, key: str | None = None) -> set[str]:
"""Every name a plugins list may use for this plugin: the selection key and its bare leaf, the
directory name and the manifest ``name:``. Read from the plugin itself, so it holds in any home."""
from pm.plugin_declarations import native_manifest_file, read_native_manifest
names = {plugin_dir.name} | ({key, key.rsplit("/", 1)[-1]} if key else set())
try:
manifest_file = native_manifest_file(plugin_dir)
if manifest_file is not None:
names.add(str(read_native_manifest(manifest_file).get("name") or ""))
except ValueError:
pass # no readable manifest: the other spellings still hold
names.discard("")
return names