ovperf-remote 0.1.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,159 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """pytest plugin that makes one job run exactly the tests it was assigned.
5
+
6
+ A job runs pytest with the run's own arguments, so it collects the run's whole
7
+ suite. This plugin keeps the node IDs assigned to the job and stops the session
8
+ before any test runs when an assigned ID is missing here, or when this session
9
+ collected an ID the controller did not.
10
+
11
+ ``ovperf.remote`` also uploads this file to remote workers as
12
+ ``ovperf_remote_assignment.py`` and loads it there with ``-p``, next to the
13
+ assignment file named by ``OVPERF_REMOTE_ASSIGNMENT_FILE``. It therefore imports
14
+ only the standard library and pytest, has no relative import and keeps to
15
+ Python 3.10 syntax.
16
+
17
+ A plugin that replaces pytest's run loop is not supported.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import json
23
+ import os
24
+ import sys
25
+ from collections import Counter
26
+ from typing import Any, Iterable, Sequence
27
+
28
+ import pytest
29
+
30
+ ASSIGNMENT_FILE_ENV = "OVPERF_REMOTE_ASSIGNMENT_FILE"
31
+ ASSIGNMENT_FILE_NAME = "assignment.json"
32
+ MISMATCH_MARKER = "OVPERF_REMOTE_ASSIGNMENT_MISMATCH="
33
+ PLUGIN_MODULE = "ovperf_remote_assignment"
34
+ # pytest names under which the selection can be switched off with `-p no:<name>`.
35
+ SELECTION_PLUGIN_NAME = PLUGIN_MODULE + "_selection"
36
+ PLUGIN_NAMES = (PLUGIN_MODULE, SELECTION_PLUGIN_NAME)
37
+ SCHEMA_VERSION = 1
38
+ MISMATCH_NAME_LIMIT = 50
39
+
40
+
41
+ class AssignmentPlugin:
42
+ """Keep the assigned node IDs and refuse a collection that differs from the controller's."""
43
+
44
+ def __init__(self, assigned: Iterable[str], collected: Iterable[str]) -> None:
45
+ self.assigned = Counter(assigned)
46
+ self.collected = Counter(collected)
47
+ # This session's own collection, before the selection below.
48
+ self.seen: Counter[str] = Counter()
49
+ self.missing: list[str] = []
50
+ self.extra: list[str] = []
51
+
52
+ def _split(self, items: Sequence[Any]) -> tuple[list[Any], list[Any]]:
53
+ """The items of ``items`` to run (in order, as many per ID as assigned) and the rest."""
54
+ wanted = Counter(self.assigned)
55
+ keep, drop = [], []
56
+ for item in items:
57
+ if wanted[item.nodeid] > 0:
58
+ wanted[item.nodeid] -= 1
59
+ keep.append(item)
60
+ else:
61
+ drop.append(item)
62
+ return keep, drop
63
+
64
+ @pytest.hookimpl(wrapper=True, tryfirst=True)
65
+ def pytest_collection_modifyitems(self, config, items):
66
+ result = yield
67
+ # Other plugins and conftest files have changed the list by now. Record
68
+ # it before selecting: the run loop needs it to name worker-only tests.
69
+ # The selection here shapes what later hooks and the summary see; the
70
+ # run loop below is what guarantees it.
71
+ self.seen = Counter(item.nodeid for item in items)
72
+ keep, drop = self._split(items)
73
+ if drop:
74
+ config.hook.pytest_deselected(items=drop)
75
+ items[:] = keep
76
+ return result
77
+
78
+ @pytest.hookimpl(tryfirst=True)
79
+ def pytest_runtestloop(self, session):
80
+ have = Counter(item.nodeid for item in session.items)
81
+ self.missing = sorted((self.assigned - have).elements())
82
+ self.extra = sorted(((self.seen | have) - self.collected).elements())
83
+ if self.missing or self.extra:
84
+ print(MISMATCH_MARKER + json.dumps(mismatch_payload(self.missing, self.extra), sort_keys=True),
85
+ file=sys.stderr, flush=True)
86
+ raise pytest.UsageError(
87
+ "the tests collected here differ from the controller's "
88
+ f"({len(self.missing)} assigned test(s) missing, {len(self.extra)} test(s) the controller "
89
+ "did not collect); nothing was run"
90
+ )
91
+ # Exactly the assigned items, whatever another plugin did since the selection.
92
+ session.items[:] = self._split(session.items)[0]
93
+
94
+ @pytest.hookimpl(tryfirst=True)
95
+ def pytest_runtest_protocol(self, item):
96
+ # Cannot happen after the run loop's check; it stops a session whose run loop was replaced.
97
+ if item.nodeid not in self.assigned:
98
+ pytest.exit("unassigned test reached execution: " + item.nodeid, returncode=4)
99
+
100
+
101
+ def mismatch_payload(missing: Sequence[str], extra: Sequence[str]) -> dict[str, Any]:
102
+ """What the marker line carries: the first names of each kind and both counts."""
103
+ return {
104
+ "missing": list(missing[:MISMATCH_NAME_LIMIT]),
105
+ "missing_count": len(missing),
106
+ "extra": list(extra[:MISMATCH_NAME_LIMIT]),
107
+ "extra_count": len(extra),
108
+ }
109
+
110
+
111
+ def mismatch_from_output(text: str) -> dict[str, Any] | None:
112
+ """The payload of the last marker line in a job's output, if it printed one."""
113
+ for line in reversed(text.splitlines()):
114
+ _, marker, payload = line.partition(MISMATCH_MARKER)
115
+ if not marker:
116
+ continue
117
+ try:
118
+ data = json.loads(payload)
119
+ except ValueError:
120
+ continue
121
+ if isinstance(data, dict):
122
+ return data
123
+ return None
124
+
125
+
126
+ def assignment_text(assigned: Iterable[str], collected: Iterable[str]) -> str:
127
+ """The assignment file's content: the job's node IDs and the controller's whole collection."""
128
+ return json.dumps({"schema_version": SCHEMA_VERSION, "assigned": list(assigned), "collected": list(collected)})
129
+
130
+
131
+ def read_assignment(path: str) -> tuple[list[str], list[str]]:
132
+ """The assigned and collected node IDs of an assignment file."""
133
+ with open(path, encoding="utf-8") as stream:
134
+ data = json.load(stream)
135
+ if not isinstance(data, dict) or data.get("schema_version") != SCHEMA_VERSION:
136
+ raise ValueError("not an assignment file of schema version %d" % SCHEMA_VERSION)
137
+ lists = (data.get("assigned"), data.get("collected"))
138
+ if any(not isinstance(names, list) or any(not isinstance(name, str) for name in names) for names in lists):
139
+ raise ValueError("assigned and collected must be lists of node IDs")
140
+ return lists[0], lists[1]
141
+
142
+
143
+ def plugin_source() -> str:
144
+ """This file's text, as uploaded to workers."""
145
+ with open(__file__, encoding="utf-8") as stream:
146
+ return stream.read()
147
+
148
+
149
+ def pytest_configure(config) -> None:
150
+ """Loaded with ``-p``: read the job's assignment file and register the selection."""
151
+ path = os.environ.get(ASSIGNMENT_FILE_ENV, "")
152
+ try:
153
+ assigned, collected = read_assignment(path)
154
+ except (OSError, ValueError) as exc:
155
+ raise pytest.UsageError(f"ovperf assignment file {path!r} cannot be used: {exc}") from exc
156
+ plugin = AssignmentPlugin(assigned, collected)
157
+ config.pluginmanager.register(plugin, SELECTION_PLUGIN_NAME)
158
+ if not config.pluginmanager.is_registered(plugin):
159
+ raise pytest.UsageError("the ovperf assignment selection is switched off; this job cannot select its tests")
@@ -0,0 +1,167 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Display-only rendering of remote command lines for run logs.
5
+
6
+ The SSH/GTL backends build very long remote shell scripts (inlined env exports,
7
+ embedded Python credential-fetch programs, heredocs) and echo them into the
8
+ run's ``stdout.log`` as ``== ovperf SSH ... command line: ... ==``. Printed
9
+ verbatim, a single echo can span ~180 lines. ``display_command`` renders a
10
+ trimmed version for humans: the command that is actually executed is never
11
+ touched, only the text that is logged.
12
+
13
+ The trimming steps, all configured in this module:
14
+
15
+ * ``OMITTED_CODE_BLOBS``: known embedded programs (matched by regex) are
16
+ collapsed to a one-line ``<omitted: ...>`` placeholder.
17
+ * Nested shell-quote escape runs (``'"'"'"'"'...``) are flattened to ``'``.
18
+ * ``OMITTED_ENV_VARS`` / ``SECRET_ENV_VAR_PATTERN``: the value of a ``NAME=value``
19
+ assignment for a listed variable is replaced with a placeholder. Variables
20
+ whose name looks secret-bearing are always replaced with ``<redacted>`` (no
21
+ length leaked), as defence in depth: today the GTL secrets are fetched on the
22
+ worker and never appear in the command, and this keeps it that way in logs
23
+ if someone later inlines one.
24
+
25
+ To trim another variable, add its name to ``OMITTED_ENV_VARS``. To collapse
26
+ another embedded program, add a ``(label, pattern)`` entry to
27
+ ``OMITTED_CODE_BLOBS``; the pattern should be anchored on text unique to that
28
+ program and tolerate runs of quote characters around it, since the blob is
29
+ rendered through several levels of shell quoting.
30
+
31
+ Because of the omissions the logged text is not runnable; the exact argv is
32
+ still recorded in the host's ``remote-command.json`` and the run result.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import re
38
+ import shlex
39
+ from typing import Sequence
40
+
41
+ # Env vars whose *value* is noise in a logged command line. Keep short,
42
+ # diagnostic values (machine, run name, versions, commit) visible; list here
43
+ # only long or redundant ones. Matching is on the exact variable name.
44
+ OMITTED_ENV_VARS: frozenset[str] = frozenset(
45
+ {
46
+ # Per-run scratch dirs: same long path as TMPDIR, repeated 3 more times.
47
+ "TEMP",
48
+ "TMP",
49
+ "UV_CACHE_DIR",
50
+ }
51
+ )
52
+
53
+ # Names that look secret-bearing are always rendered as ``<redacted>``.
54
+ SECRET_ENV_VAR_PATTERN = re.compile(
55
+ r"(?:PASSWORD|PASSWD|SECRET|TOKEN|API_KEY|ACCESS_KEY|PRIVATE_KEY|CREDENTIAL)",
56
+ re.IGNORECASE,
57
+ )
58
+
59
+ # The GTL backend's credential fetch script (shell or JSON output mode).
60
+ _GTL_FETCH_SCRIPT = (
61
+ r"import errno, json, os, shlex, socket, sys, time, urllib\.error, "
62
+ r"urllib\.parse, urllib\.request\r?\n"
63
+ # Match the end of either the legacy top-level fetch or the callable's CLI adapter.
64
+ r".*?\r?\n(?:_additional = _c\(\"GetCredentialAdditionalSecureInfo\"\)"
65
+ r"| raise SystemExit\(_error\.exit_code\) from None)\r?\n"
66
+ r"(?:print\([^\n]*\)\r?\n?)*"
67
+ )
68
+
69
+ # Embedded programs collapsed to a placeholder, tried in order. Each pattern is
70
+ # matched with DOTALL against the already shell-quoted command text, so allow
71
+ # for arbitrary runs of quote characters around the program body.
72
+ OMITTED_CODE_BLOBS: tuple[tuple[str, re.Pattern[str]], ...] = (
73
+ (
74
+ # ovperf_gtl_backend._credentials_prelude: the whole
75
+ # OVPERF_GTL_CREDS="$("$PYTHON_ENTRYPOINT" -c '<script>')" && eval ...
76
+ # step, emitted once per GTL credential per command (~90 lines each).
77
+ "GTL credential fetch (OVPERF_GTL_CREDS)",
78
+ re.compile(
79
+ r"OVPERF_GTL_CREDS=\"\$\(\"\$PYTHON_ENTRYPOINT\" -c ['\"]*"
80
+ + _GTL_FETCH_SCRIPT
81
+ + r"['\"]*\)\" && eval \"\$OVPERF_GTL_CREDS\"",
82
+ re.DOTALL,
83
+ ),
84
+ ),
85
+ (
86
+ # The same fetch script embedded any other way (e.g. JSON output mode).
87
+ "GTL credential fetch script",
88
+ re.compile(_GTL_FETCH_SCRIPT, re.DOTALL),
89
+ ),
90
+ (
91
+ # ovperf.remote._remote_directory_guard_command: the Python program that
92
+ # checks and creates each remote folder (~70 lines, in most commands).
93
+ "remote directory guard",
94
+ re.compile(
95
+ r"import os, stat, sys\r?\nfrom collections import deque\r?\nsystem_uid = .*?"
96
+ r"for path in sys\.argv\[1:\]:\r?\n prepare\(path\)\r?\n?",
97
+ re.DOTALL,
98
+ ),
99
+ ),
100
+ (
101
+ # Inline base64 payloads (e.g. the Windows credential script passed to
102
+ # [Convert]::FromBase64String). Paths never form runs this long.
103
+ "base64 payload",
104
+ re.compile(r"[A-Za-z0-9+/]{200,}={0,2}"),
105
+ ),
106
+ )
107
+
108
+ # Runs of nested shell-quote escaping such as '"'"'"'"'"'"'"'"' (each extra
109
+ # level of `sh -c` doubles it). In the log these are flattened to a single ';
110
+ # the exact executed argv is kept in remote-command.json / the run result.
111
+ _QUOTE_ESCAPE_RUN = re.compile(r"[\'\"]{5,}")
112
+
113
+ _EXPORTED_NAME = re.compile(r'print\("export ([A-Za-z_]\w*)=', re.ASCII)
114
+
115
+ # A shell word as it appears after ``NAME=``: a double/single-quoted string or a
116
+ # bare run of non-separator characters. Conservative on purpose; anything it
117
+ # does not match is left as-is.
118
+ _VALUE = r"(?:\"[^\"\n]*\"|'[^'\n]*'|[^\s;&|'\"()]+)"
119
+ _ASSIGNMENT = re.compile(
120
+ r"(?<![A-Za-z0-9_$])([A-Za-z_][A-Za-z0-9_]*)=(" + _VALUE + r")"
121
+ )
122
+
123
+
124
+ def _collapse_blob(label: str, match: re.Match[str]) -> str:
125
+ text = match.group(0)
126
+ exported = _EXPORTED_NAME.findall(text)
127
+ detail = f" -> exports {', '.join(exported)}" if exported else ""
128
+ return f"<omitted: {label}, {len(text)} chars{detail}>"
129
+
130
+
131
+ def _trim_assignment(match: re.Match[str]) -> str:
132
+ name, value = match.group(1), match.group(2)
133
+ if SECRET_ENV_VAR_PATTERN.search(name):
134
+ # Shell references such as "$UV_AUTH_LOGIN_PASSWORD" are not secrets.
135
+ if value.strip("\"'").startswith("$"):
136
+ return match.group(0)
137
+ return f"{name}=<redacted>"
138
+ if name in OMITTED_ENV_VARS:
139
+ return f"{name}=<omitted: {len(value)} chars>"
140
+ return match.group(0)
141
+
142
+
143
+ def _flatten_quote_run(match: re.Match[str]) -> str:
144
+ run = match.group(0)
145
+ # The escape idiom '"'"' always starts and ends with a single quote; any
146
+ # double quotes outside that span belong to the surrounding script (e.g.
147
+ # the closing quote of "$d/status"), so keep them.
148
+ first, last = run.find("'"), run.rfind("'")
149
+ if first < 0:
150
+ return run
151
+ core = run[first : last + 1]
152
+ if '"' not in core:
153
+ return run
154
+ return run[:first] + "'" + run[last + 1 :]
155
+
156
+
157
+ def trim_command_text(text: str) -> str:
158
+ """Return ``text`` (a rendered command line) with noisy parts trimmed."""
159
+ for label, pattern in OMITTED_CODE_BLOBS:
160
+ text = pattern.sub(lambda m, label=label: _collapse_blob(label, m), text)
161
+ text = _QUOTE_ESCAPE_RUN.sub(_flatten_quote_run, text)
162
+ return _ASSIGNMENT.sub(_trim_assignment, text)
163
+
164
+
165
+ def display_command(argv: Sequence[str]) -> str:
166
+ """Render ``argv`` for a log line. Display only; never execute the result."""
167
+ return trim_command_text(shlex.join(argv))
ovperf/executors.py ADDED
@@ -0,0 +1,260 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Pluggable executor interface and registry.
5
+
6
+ An executor executes the jobs of a run. It acquires execution targets, declares
7
+ which shared steps it runs against them, executes a job, and releases targets
8
+ when done. ovperf core selects one executor per run by name and drives it without
9
+ knowing whether it is SSH, a dummy executor, or a third-party executor.
10
+
11
+ This module deliberately avoids importing :mod:`ovperf.remote` at runtime so the
12
+ two can reference each other without a circular import: the concrete built-in
13
+ executors live in ``remote.py`` and register themselves here.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import enum
19
+ import importlib
20
+ import importlib.metadata
21
+ import os
22
+ import sys
23
+ from typing import TYPE_CHECKING, Any, Mapping, Protocol, Sequence, runtime_checkable
24
+
25
+ ENTRY_POINT_GROUP = "ovperf.executors"
26
+ EXECUTORS_ENV = "OVPERF_EXECUTORS"
27
+
28
+ if TYPE_CHECKING: # pragma: no cover - typing only
29
+ from pathlib import Path
30
+
31
+ from .remote import RemoteRunConfig, WorkerJob, WorkerRun
32
+
33
+
34
+ PHASE_MARKER_PREFIX = "== ovperf phase: "
35
+ PHASE_MARKER_SUFFIX = " =="
36
+
37
+
38
+ def emit_phase(phase: str) -> None:
39
+ """Announce the run's current phase as a structured stdout marker.
40
+
41
+ The service tails the run's ``stdout.log`` and shows the latest marker
42
+ under the ``running`` state on the dashboard, so ``phase`` is a stable
43
+ snake_case id (for example ``waiting_for_machine``), never free text.
44
+ Observation only: a failure to print must never affect the run.
45
+ """
46
+ try:
47
+ print(f"{PHASE_MARKER_PREFIX}{phase}{PHASE_MARKER_SUFFIX}", file=sys.stdout, flush=True)
48
+ except Exception: # noqa: BLE001
49
+ pass
50
+
51
+
52
+ class StepName(enum.Enum):
53
+ """Named steps an executor may run against an acquired target.
54
+
55
+ Executors assemble their own ordered list of steps rather than toggling a
56
+ fixed menu, so an executor can run only the steps it needs (for example a
57
+ render-only executor omits :data:`PROVISION`).
58
+ """
59
+
60
+ PROVISION = "provision" # agent-tool install + agent-login upload (agentic jobs)
61
+ SYNC = "sync" # workspace sync to the target
62
+ RUN = "run" # run the measured workload with live output streaming
63
+ COLLECT = "collect" # collect the report from the target
64
+
65
+
66
+ @runtime_checkable
67
+ class Executor(Protocol):
68
+ """A pluggable executor.
69
+
70
+ ``name`` is the identifier used with ``--executor-type``; an installed
71
+ plugin's ``ovperf.executors`` entry-point name must equal it, because the
72
+ plugin is found by that name without importing it. ``steps`` lists the
73
+ steps the executor uses; an executor built on the shared SSH transport
74
+ passes it to ``ovperf.remote`` so that :data:`StepName.PROVISION` (agent
75
+ tools and agent logins) is skipped when absent. The transport always syncs,
76
+ runs and collects in that order. ``run_job`` executes a single job and
77
+ returns the executor result mapping the orchestrator aggregates.
78
+
79
+ Workers returned by ``acquire`` use transport ``"ssh"`` or ``"local"``.
80
+
81
+ ``job.pytest_args`` are the run's own pytest arguments, the same for every
82
+ job; they do not select the job's tests. ``ovperf.remote``'s transport and
83
+ local worker run exactly ``job.assigned_nodeids``. An executor that runs
84
+ the arguments with its own transport must do the same: a passed job whose
85
+ report lists any other set of tests is failed by the orchestrator.
86
+
87
+ Optional attribute: ``gpu_preflight_reboot_default = True`` says the
88
+ executor books each worker for the run alone, so ``ovperf.remote`` may
89
+ reboot a worker whose GPU check fails. It is the value of
90
+ ``RemoteRunConfig.gpu_preflight_reboot`` when the user set neither the
91
+ option nor the setting; without the attribute that default is off.
92
+
93
+ Optional methods the orchestrator calls when present: ``detach(workers,
94
+ config=...)`` to keep acquired targets for a later run instead of releasing
95
+ them, ``handoff_supported(workers, config=...)`` and
96
+ ``checkpoint_handoff(workers, config=...)`` for service handoff, and
97
+ ``finalize_profiles(workers, config=..., results=..., payload=...)`` after
98
+ the aggregate report is written.
99
+ """
100
+
101
+ name: str
102
+ steps: tuple[StepName, ...]
103
+
104
+ def acquire(self, config: "RemoteRunConfig") -> "Sequence[WorkerRun]":
105
+ """Acquire the worker targets this executor will run jobs on."""
106
+ ...
107
+
108
+ def release(
109
+ self, workers: "Sequence[WorkerRun]", *, config: "RemoteRunConfig"
110
+ ) -> None:
111
+ """Release any targets acquired for the run (no-op for static executors)."""
112
+ ...
113
+
114
+ def run_job(
115
+ self,
116
+ job: "WorkerJob",
117
+ *,
118
+ config: "RemoteRunConfig",
119
+ report_dir: "Path",
120
+ run_id: str,
121
+ ) -> dict[str, Any]: ...
122
+
123
+
124
+ class UnknownExecutorError(LookupError):
125
+ """Raised when a named executor is not registered."""
126
+
127
+ def __init__(self, name: str, available: Sequence[str]) -> None:
128
+ self.name = name
129
+ self.available = tuple(available)
130
+ super().__init__(
131
+ f"unknown executor {name!r}; available executors: "
132
+ + (", ".join(available) or "(none)")
133
+ )
134
+
135
+
136
+ _REGISTRY: dict[str, Executor] = {}
137
+
138
+
139
+ def register_executor(executor: Executor) -> None:
140
+ """Register an executor instance under its ``name``."""
141
+ _REGISTRY[executor.name] = executor
142
+
143
+
144
+ def get_executor(name: str) -> Executor:
145
+ """Return executor ``name``, loading its installed plugin on first use.
146
+
147
+ Raises ``UnknownExecutorError`` for a name nothing provides and
148
+ ``ExecutorLoadError`` when the plugin that provides it cannot load.
149
+ """
150
+ try:
151
+ return _REGISTRY[name]
152
+ except KeyError:
153
+ pass
154
+ executor = _load_entry_point_executor(name)
155
+ if executor is None:
156
+ raise UnknownExecutorError(name, available_executor_names())
157
+ return executor
158
+
159
+
160
+ def registered_executor_names() -> tuple[str, ...]:
161
+ """Return the sorted names of all registered (already loaded) executors."""
162
+ return tuple(sorted(_REGISTRY))
163
+
164
+
165
+ def available_executor_names() -> tuple[str, ...]:
166
+ """Registered executors plus installed plugins, without importing any plugin."""
167
+ names = set(_REGISTRY)
168
+ try:
169
+ names.update(entry_point.name for entry_point in importlib.metadata.entry_points(group=ENTRY_POINT_GROUP))
170
+ except Exception: # noqa: BLE001 - broken metadata must not hide the built-ins
171
+ pass
172
+ return tuple(sorted(names))
173
+
174
+
175
+ def _load_named_entry_point(entry_point: Any) -> Executor:
176
+ spec = f"{ENTRY_POINT_GROUP} entry point {entry_point.name!r}"
177
+ try:
178
+ executor = _coerce_executor(entry_point.load(), spec)
179
+ except ExecutorLoadError:
180
+ raise
181
+ except Exception as exc: # noqa: BLE001 - re-raised with the offending spec
182
+ raise ExecutorLoadError(spec, exc) from exc
183
+ if executor.name != entry_point.name:
184
+ # Plugins are selected by entry-point name before they are imported.
185
+ raise ExecutorLoadError(spec, ValueError(
186
+ f"it provides executor {executor.name!r}; the entry-point name must equal the executor's name"))
187
+ return executor
188
+
189
+
190
+ def _load_entry_point_executor(name: str) -> Executor | None:
191
+ for entry_point in importlib.metadata.entry_points(group=ENTRY_POINT_GROUP):
192
+ if entry_point.name != name:
193
+ continue
194
+ executor = _load_named_entry_point(entry_point)
195
+ register_executor(executor)
196
+ return executor
197
+ return None
198
+
199
+
200
+ class ExecutorLoadError(RuntimeError):
201
+ """Raised when a discovered executor cannot be imported or does not conform."""
202
+
203
+ def __init__(self, spec: str, cause: Exception) -> None:
204
+ self.spec = spec
205
+ super().__init__(f"could not load executor {spec!r}: {cause}")
206
+
207
+
208
+ def _coerce_executor(obj: Any, spec: str) -> Executor:
209
+ executor = obj() if isinstance(obj, type) else obj
210
+ if not isinstance(executor, Executor):
211
+ raise ExecutorLoadError(
212
+ spec, TypeError("object does not implement the Executor protocol")
213
+ )
214
+ return executor
215
+
216
+
217
+ def load_entry_point_executors() -> None:
218
+ """Register executors declared by installed packages via entry points."""
219
+ entry_points = importlib.metadata.entry_points(group=ENTRY_POINT_GROUP)
220
+ for entry_point in entry_points:
221
+ register_executor(_load_named_entry_point(entry_point))
222
+
223
+
224
+ def load_env_executors(env: Mapping[str, str] | None = None) -> None:
225
+ """Register executors named by ``OVPERF_EXECUTORS=module:Class,...``."""
226
+ environ = os.environ if env is None else env
227
+ raw = environ.get(EXECUTORS_ENV, "")
228
+ for spec in (part.strip() for part in raw.split(",")):
229
+ if not spec:
230
+ continue
231
+ module_name, separator, attribute = spec.partition(":")
232
+ if not separator or not module_name or not attribute:
233
+ raise ExecutorLoadError(
234
+ spec, ValueError("expected 'module:Class' form")
235
+ )
236
+ try:
237
+ module = importlib.import_module(module_name)
238
+ obj = getattr(module, attribute)
239
+ except ExecutorLoadError:
240
+ raise
241
+ except Exception as exc: # noqa: BLE001 - re-raised with the offending spec
242
+ raise ExecutorLoadError(spec, exc) from exc
243
+ register_executor(_coerce_executor(obj, spec))
244
+
245
+
246
+ _DISCOVERY_DONE = False
247
+
248
+
249
+ def ensure_executors_loaded() -> None:
250
+ """Load the executors named in ``OVPERF_EXECUTORS`` once per process.
251
+
252
+ Installed ``ovperf.executors`` plugins are not imported here: get_executor
253
+ loads one when it is selected, so a broken plugin the run does not use
254
+ cannot stop it (call load_entry_point_executors to import them all).
255
+ """
256
+ global _DISCOVERY_DONE
257
+ if _DISCOVERY_DONE:
258
+ return
259
+ load_env_executors()
260
+ _DISCOVERY_DONE = True