ssapling 0.1.0__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.
- ssapling/__init__.py +12 -0
- ssapling/core/__init__.py +53 -0
- ssapling/core/_declarations.py +139 -0
- ssapling/core/_execution.py +155 -0
- ssapling/core/_plain.py +37 -0
- ssapling/core/_text.py +42 -0
- ssapling/core/errors.py +175 -0
- ssapling/core/loading.py +205 -0
- ssapling/core/registry.py +345 -0
- ssapling/core/settings.py +698 -0
- ssapling/core/spec.py +98 -0
- ssapling/data/__init__.py +89 -0
- ssapling/data/_matching.py +22 -0
- ssapling/data/batching.py +166 -0
- ssapling/data/collections.py +335 -0
- ssapling/data/encoding.py +107 -0
- ssapling/data/errors.py +104 -0
- ssapling/data/provenance.py +94 -0
- ssapling/data/records.py +546 -0
- ssapling/data/sampling.py +339 -0
- ssapling/data/storage.py +569 -0
- ssapling/environments/__init__.py +43 -0
- ssapling/environments/contracts.py +168 -0
- ssapling/environments/errors.py +53 -0
- ssapling/environments/runner.py +153 -0
- ssapling/environments/types.py +173 -0
- ssapling/evaluate/__init__.py +40 -0
- ssapling/evaluate/aggregation.py +173 -0
- ssapling/evaluate/assessment.py +429 -0
- ssapling/evaluate/measurement.py +165 -0
- ssapling/interaction/__init__.py +24 -0
- ssapling/interaction/episode.py +713 -0
- ssapling/interaction/errors.py +21 -0
- ssapling/interaction/hosting.py +287 -0
- ssapling/models/__init__.py +44 -0
- ssapling/models/buffering.py +189 -0
- ssapling/models/contracts.py +181 -0
- ssapling/models/errors.py +27 -0
- ssapling/models/types.py +75 -0
- ssapling/py.typed +0 -0
- ssapling/registries.py +37 -0
- ssapling/tasks/__init__.py +49 -0
- ssapling/tasks/contracts.py +137 -0
- ssapling/tasks/errors.py +37 -0
- ssapling/tasks/types.py +172 -0
- ssapling/teachers/__init__.py +34 -0
- ssapling/teachers/contracts.py +145 -0
- ssapling/teachers/errors.py +80 -0
- ssapling/teachers/runner.py +142 -0
- ssapling/teachers/types.py +178 -0
- ssapling/train/__init__.py +43 -0
- ssapling/train/components.py +194 -0
- ssapling/train/context.py +169 -0
- ssapling/train/errors.py +24 -0
- ssapling/train/procedure.py +316 -0
- ssapling/train/runner.py +398 -0
- ssapling/train/stages.py +463 -0
- ssapling-0.1.0.dist-info/METADATA +113 -0
- ssapling-0.1.0.dist-info/RECORD +61 -0
- ssapling-0.1.0.dist-info/WHEEL +4 -0
- ssapling-0.1.0.dist-info/licenses/LICENSE +201 -0
ssapling/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""SSAPling: infrastructure for System-Specification Alignment Problem projects.
|
|
2
|
+
|
|
3
|
+
SSAPling provides contracts, registries, and machinery. It contains no concrete
|
|
4
|
+
environments, tasks, teachers, models, or learning methods; those live in
|
|
5
|
+
downstream projects. Each package area is described in its own ``__init__``.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from .core.errors import SSAPlingError
|
|
9
|
+
|
|
10
|
+
__version__ = "0.1.0"
|
|
11
|
+
|
|
12
|
+
__all__ = ["SSAPlingError", "__version__"]
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""SSAPling core.
|
|
2
|
+
|
|
3
|
+
Responsibility: Component registration, configuration (including YAML files),
|
|
4
|
+
construction, and extension.
|
|
5
|
+
|
|
6
|
+
Not its responsibility: Subsystem contracts, seeds, run management, hashing.
|
|
7
|
+
|
|
8
|
+
May import: nothing. Enforced by tests/test_layering.py.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from ._execution import Execution
|
|
12
|
+
from .errors import (
|
|
13
|
+
ConfigError,
|
|
14
|
+
DuplicateRegistrationError,
|
|
15
|
+
MissingDependencyError,
|
|
16
|
+
Problem,
|
|
17
|
+
SettingsDeclarationError,
|
|
18
|
+
SSAPlingError,
|
|
19
|
+
UnknownComponentError,
|
|
20
|
+
)
|
|
21
|
+
from .loading import Config, load_config, load_named
|
|
22
|
+
from .registry import CatalogueEntry, Registration, Registry
|
|
23
|
+
from .settings import (
|
|
24
|
+
check_settings_class,
|
|
25
|
+
setting,
|
|
26
|
+
settings_schema,
|
|
27
|
+
settings_to_dict,
|
|
28
|
+
validate_settings,
|
|
29
|
+
)
|
|
30
|
+
from .spec import ComponentSpec
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
"CatalogueEntry",
|
|
34
|
+
"ComponentSpec",
|
|
35
|
+
"Config",
|
|
36
|
+
"ConfigError",
|
|
37
|
+
"DuplicateRegistrationError",
|
|
38
|
+
"Execution",
|
|
39
|
+
"MissingDependencyError",
|
|
40
|
+
"Problem",
|
|
41
|
+
"Registration",
|
|
42
|
+
"Registry",
|
|
43
|
+
"SSAPlingError",
|
|
44
|
+
"SettingsDeclarationError",
|
|
45
|
+
"UnknownComponentError",
|
|
46
|
+
"check_settings_class",
|
|
47
|
+
"load_config",
|
|
48
|
+
"load_named",
|
|
49
|
+
"setting",
|
|
50
|
+
"settings_schema",
|
|
51
|
+
"settings_to_dict",
|
|
52
|
+
"validate_settings",
|
|
53
|
+
]
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""Reading what a component declares about itself, the same way in every area.
|
|
2
|
+
|
|
3
|
+
Internal: the areas' contracts use these, and users never import them. A
|
|
4
|
+
component declares what it offers in a few standard ways: by having methods
|
|
5
|
+
(a task's features, an environment's capabilities), by listing names (a
|
|
6
|
+
teacher's operations, a model's learning operations and signals), and by the
|
|
7
|
+
parameters its methods take (a model's ``key``, an environment's ``seed``).
|
|
8
|
+
These helpers read such declarations and report mistakes in them alike.
|
|
9
|
+
|
|
10
|
+
The plain checks every area makes of its own values, that an id is a
|
|
11
|
+
non-empty string and a count an integer, are here too, so their messages
|
|
12
|
+
read alike as well.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import inspect
|
|
16
|
+
from collections.abc import Callable, Collection, Mapping
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def name_of(component: object) -> str:
|
|
21
|
+
"""The component's class name, for messages; ``component`` may be the class itself."""
|
|
22
|
+
return component.__name__ if isinstance(component, type) else type(component).__name__
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def names(
|
|
26
|
+
value: object, what: str, *, of: str = "names", example: str = "('a', 'b')"
|
|
27
|
+
) -> tuple[str, ...]:
|
|
28
|
+
"""``value`` as a tuple of names; it must be a collection of non-empty strings.
|
|
29
|
+
|
|
30
|
+
A single string is rejected, because ``"review" in "review_action"``
|
|
31
|
+
would be true.
|
|
32
|
+
|
|
33
|
+
Raises:
|
|
34
|
+
TypeError: ``value`` is a string or not a collection, or holds
|
|
35
|
+
something other than non-empty strings. The message names
|
|
36
|
+
``what``, such as ``"MyTeacher.operations"``.
|
|
37
|
+
"""
|
|
38
|
+
if isinstance(value, str | bytes) or not isinstance(value, Collection):
|
|
39
|
+
raise TypeError(f"{what} must be a collection of {of}, such as {example}, got {value!r}")
|
|
40
|
+
found = tuple(value)
|
|
41
|
+
if any(not isinstance(name, str) or not name for name in found):
|
|
42
|
+
raise TypeError(f"{what} must contain only non-empty strings, got {value!r}")
|
|
43
|
+
return found
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def keyed(value: object, what: str, keys: str) -> dict[str, Any]:
|
|
47
|
+
"""A copy of ``value``, which must be a mapping with string keys.
|
|
48
|
+
|
|
49
|
+
Raises:
|
|
50
|
+
TypeError: ``value`` is not a mapping, or a key is not a string. The
|
|
51
|
+
message names ``what`` and what the keys are, such as ``"agent ids"``.
|
|
52
|
+
"""
|
|
53
|
+
if not isinstance(value, Mapping):
|
|
54
|
+
raise TypeError(f"{what} must be a mapping keyed by {keys}, got {value!r}")
|
|
55
|
+
if any(not isinstance(key, str) for key in value):
|
|
56
|
+
raise TypeError(f"the keys of {what} must be strings ({keys})")
|
|
57
|
+
return dict(value)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def check_identifier(value: object, what: str) -> None:
|
|
61
|
+
"""Check that ``value`` is a non-empty string, as every id and name must be.
|
|
62
|
+
|
|
63
|
+
Raises:
|
|
64
|
+
ValueError: It is not. The message names ``what``, such as ``"a record id"``.
|
|
65
|
+
"""
|
|
66
|
+
if not isinstance(value, str) or not value:
|
|
67
|
+
raise ValueError(f"{what} must be a non-empty string, got {value!r}")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def check_int(value: object, what: str, *, minimum: int | None = None) -> None:
|
|
71
|
+
"""Check that ``value`` is an integer, and at least ``minimum`` if one is given.
|
|
72
|
+
|
|
73
|
+
A bool is not an integer here, as in Core's settings.
|
|
74
|
+
|
|
75
|
+
Raises:
|
|
76
|
+
TypeError: ``value`` is not an integer. The message names ``what``.
|
|
77
|
+
ValueError: ``value`` is less than ``minimum``.
|
|
78
|
+
"""
|
|
79
|
+
if isinstance(value, bool) or not isinstance(value, int):
|
|
80
|
+
raise TypeError(f"{what} must be an integer, got {value!r}")
|
|
81
|
+
if minimum is not None and value < minimum:
|
|
82
|
+
raise ValueError(f"{what} must be {minimum} or more, got {value!r}")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def takes(method: object, parameter: str) -> bool:
|
|
86
|
+
"""Whether ``method`` accepts ``parameter`` as a keyword argument (or any keyword)."""
|
|
87
|
+
if not callable(method):
|
|
88
|
+
return False
|
|
89
|
+
try:
|
|
90
|
+
parameters = inspect.signature(method).parameters.values()
|
|
91
|
+
except (TypeError, ValueError):
|
|
92
|
+
return False
|
|
93
|
+
return any(
|
|
94
|
+
p.kind is p.VAR_KEYWORD or (p.name == parameter and p.kind is not p.POSITIONAL_ONLY)
|
|
95
|
+
for p in parameters
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def has_feature(
|
|
100
|
+
component: object,
|
|
101
|
+
feature: str,
|
|
102
|
+
features: Mapping[str, tuple[str, ...]],
|
|
103
|
+
*,
|
|
104
|
+
word: str,
|
|
105
|
+
words: str,
|
|
106
|
+
requirement: Callable[[object], bool] | None = None,
|
|
107
|
+
) -> bool:
|
|
108
|
+
"""Whether ``component`` offers ``feature``, one of ``features``, declared by methods.
|
|
109
|
+
|
|
110
|
+
It offers a feature when it has every method the feature needs, meets
|
|
111
|
+
``requirement`` if there is one, and, if it defines a
|
|
112
|
+
``supports(feature)`` method of its own, that method agrees. That method
|
|
113
|
+
can only switch a feature off; it cannot claim one.
|
|
114
|
+
|
|
115
|
+
``word`` and ``words`` name the kind of feature in messages, such as
|
|
116
|
+
``"capability"`` and ``"capabilities"``.
|
|
117
|
+
|
|
118
|
+
Raises:
|
|
119
|
+
ValueError: ``feature`` is not one of ``features``: a mistake in the
|
|
120
|
+
calling code.
|
|
121
|
+
TypeError: The component has a ``supports`` attribute that is not a
|
|
122
|
+
method.
|
|
123
|
+
"""
|
|
124
|
+
try:
|
|
125
|
+
methods = features[feature]
|
|
126
|
+
except KeyError:
|
|
127
|
+
known = ", ".join(repr(name) for name in features)
|
|
128
|
+
raise ValueError(f"unknown {word} {feature!r}; the {words} are {known}") from None
|
|
129
|
+
declared = getattr(component, "supports", None)
|
|
130
|
+
if declared is not None and not callable(declared):
|
|
131
|
+
raise TypeError(
|
|
132
|
+
f"{name_of(component)}.supports must be a method that takes a {word} name, "
|
|
133
|
+
f"got {declared!r}"
|
|
134
|
+
)
|
|
135
|
+
if not all(callable(getattr(component, method, None)) for method in methods):
|
|
136
|
+
return False
|
|
137
|
+
if requirement is not None and not requirement(component):
|
|
138
|
+
return False
|
|
139
|
+
return declared is None or bool(declared(feature))
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""Calling a component's methods the same way whether they are synchronous or asynchronous.
|
|
2
|
+
|
|
3
|
+
Internal: the teacher runner, the environment runner, and the interaction loop
|
|
4
|
+
use this so that they are written once, with ``asyncio``, and still drive
|
|
5
|
+
synchronous components. Users choose a placement through those areas' public
|
|
6
|
+
settings, not by importing this module.
|
|
7
|
+
|
|
8
|
+
A synchronous call is not made non-blocking by being awaited. Run directly, it
|
|
9
|
+
blocks the event loop until it returns, and a timeout cannot interrupt it; run
|
|
10
|
+
in a thread, the loop keeps going while it works. Running a component in a
|
|
11
|
+
separate process needs a long-lived worker that keeps the component's state:
|
|
12
|
+
that is ``ssapling.interaction.in_process``, whose stand-in is called like
|
|
13
|
+
any other component.
|
|
14
|
+
|
|
15
|
+
Timeouts are handled here too, once, so every caller tells its own deadline
|
|
16
|
+
apart from a ``TimeoutError`` the component raises itself in the same way.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import asyncio
|
|
20
|
+
import contextvars
|
|
21
|
+
import functools
|
|
22
|
+
import inspect
|
|
23
|
+
import sys
|
|
24
|
+
from collections.abc import Awaitable, Callable
|
|
25
|
+
from concurrent.futures import Executor
|
|
26
|
+
from dataclasses import dataclass
|
|
27
|
+
from typing import Any, Literal, overload
|
|
28
|
+
|
|
29
|
+
Placement = Literal["direct", "thread"]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class DeadlineExpiredError(Exception):
|
|
33
|
+
"""The caller's timeout passed before the call returned.
|
|
34
|
+
|
|
35
|
+
Raised instead of ``TimeoutError``, so a ``TimeoutError`` the component
|
|
36
|
+
raises itself is not mistaken for it.
|
|
37
|
+
|
|
38
|
+
Attributes:
|
|
39
|
+
timeout: The timeout, in seconds.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
def __init__(self, timeout: float) -> None:
|
|
43
|
+
self.timeout = timeout
|
|
44
|
+
super().__init__(f"no response within {timeout} s")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True, slots=True)
|
|
48
|
+
class Execution:
|
|
49
|
+
"""Where a component's synchronous calls run.
|
|
50
|
+
|
|
51
|
+
Attributes:
|
|
52
|
+
placement: ``"direct"`` runs a synchronous call in the event loop's
|
|
53
|
+
thread. ``"thread"`` runs it in a worker thread, so the loop is
|
|
54
|
+
not blocked and a timeout can stop waiting for it.
|
|
55
|
+
executor: For ``"thread"``: the thread pool to use. ``None`` uses
|
|
56
|
+
``asyncio.to_thread``, which may run successive calls on different
|
|
57
|
+
threads. For components that must always be called from the same
|
|
58
|
+
thread, pass a ``ThreadPoolExecutor(max_workers=1)``.
|
|
59
|
+
|
|
60
|
+
Asynchronous calls always run in the event loop: there they already
|
|
61
|
+
yield while they wait, so a thread would add nothing.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
placement: Placement = "direct"
|
|
65
|
+
executor: Executor | None = None
|
|
66
|
+
|
|
67
|
+
def __post_init__(self) -> None:
|
|
68
|
+
if self.placement not in ("direct", "thread"):
|
|
69
|
+
raise ValueError(f"placement must be 'direct' or 'thread', not {self.placement!r}")
|
|
70
|
+
if self.executor is not None and self.placement != "thread":
|
|
71
|
+
raise ValueError("an executor applies only to placement='thread'")
|
|
72
|
+
if _is_process_pool(self.executor):
|
|
73
|
+
raise TypeError(
|
|
74
|
+
"a process pool would lose the component's state between calls; "
|
|
75
|
+
"to run a component in a process, use ssapling.interaction.in_process"
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
@overload
|
|
79
|
+
async def call[R](
|
|
80
|
+
self, function: Callable[..., Awaitable[R]], /, *args: Any, **kwargs: Any
|
|
81
|
+
) -> R: ...
|
|
82
|
+
|
|
83
|
+
@overload
|
|
84
|
+
async def call[R](self, function: Callable[..., R], /, *args: Any, **kwargs: Any) -> R: ...
|
|
85
|
+
|
|
86
|
+
async def call(self, function: Callable[..., Any], /, *args: Any, **kwargs: Any) -> Any:
|
|
87
|
+
"""Call ``function`` with the arguments and return its result.
|
|
88
|
+
|
|
89
|
+
An ``async def`` function is awaited in the event loop. A synchronous
|
|
90
|
+
function runs according to ``placement``. If a synchronous function
|
|
91
|
+
returns an awaitable (as a wrapper around an async function might),
|
|
92
|
+
that is awaited too.
|
|
93
|
+
"""
|
|
94
|
+
if inspect.iscoroutinefunction(function):
|
|
95
|
+
return await function(*args, **kwargs)
|
|
96
|
+
if self.placement == "direct":
|
|
97
|
+
result = function(*args, **kwargs)
|
|
98
|
+
elif self.executor is None:
|
|
99
|
+
result = await asyncio.to_thread(function, *args, **kwargs)
|
|
100
|
+
else:
|
|
101
|
+
# Like asyncio.to_thread, carry context variables into the thread.
|
|
102
|
+
context = contextvars.copy_context()
|
|
103
|
+
call = functools.partial(context.run, function, *args, **kwargs)
|
|
104
|
+
result = await asyncio.get_running_loop().run_in_executor(self.executor, call)
|
|
105
|
+
if inspect.isawaitable(result):
|
|
106
|
+
return await result
|
|
107
|
+
return result
|
|
108
|
+
|
|
109
|
+
def check_timeout(self, timeout: float, function: Callable[..., Any]) -> None:
|
|
110
|
+
"""Check that ``timeout`` is usable for calls to ``function``.
|
|
111
|
+
|
|
112
|
+
Call it before the call, so a mistake in the timeout is reported as
|
|
113
|
+
the caller's, not mistaken for a failure of the component.
|
|
114
|
+
|
|
115
|
+
Raises:
|
|
116
|
+
ValueError: ``timeout`` is not a positive number of seconds, or
|
|
117
|
+
``function`` is synchronous and runs directly, where no
|
|
118
|
+
timeout can interrupt it.
|
|
119
|
+
"""
|
|
120
|
+
if isinstance(timeout, bool) or not isinstance(timeout, int | float) or not timeout > 0:
|
|
121
|
+
raise ValueError(f"timeout must be a positive number of seconds, got {timeout!r}")
|
|
122
|
+
if self.placement == "direct" and not inspect.iscoroutinefunction(function):
|
|
123
|
+
name = getattr(function, "__qualname__", repr(function))
|
|
124
|
+
raise ValueError(
|
|
125
|
+
f"a timeout cannot interrupt {name}: it is synchronous and runs in the event "
|
|
126
|
+
"loop's thread, blocking the loop until it returns. Use placement='thread'."
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
async def call_with_timeout(
|
|
130
|
+
self, timeout: float | None, function: Callable[..., Any], /, *args: Any, **kwargs: Any
|
|
131
|
+
) -> Any:
|
|
132
|
+
"""``call``, giving up after ``timeout`` seconds; ``None`` waits as long as it takes.
|
|
133
|
+
|
|
134
|
+
Raises:
|
|
135
|
+
DeadlineExpiredError: ``timeout`` passed first. A ``TimeoutError`` the
|
|
136
|
+
function raises itself propagates unchanged.
|
|
137
|
+
ValueError: An unusable timeout (see ``check_timeout``).
|
|
138
|
+
"""
|
|
139
|
+
if timeout is not None:
|
|
140
|
+
self.check_timeout(timeout, function)
|
|
141
|
+
try:
|
|
142
|
+
async with asyncio.timeout(timeout) as deadline:
|
|
143
|
+
return await self.call(function, *args, **kwargs)
|
|
144
|
+
except TimeoutError:
|
|
145
|
+
if deadline.expired() and timeout is not None:
|
|
146
|
+
raise DeadlineExpiredError(timeout) from None
|
|
147
|
+
raise
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _is_process_pool(executor: Executor | None) -> bool:
|
|
151
|
+
# Importing ProcessPoolExecutor loads multiprocessing, which importing
|
|
152
|
+
# ssapling should not do. A process pool exists only if its module was
|
|
153
|
+
# imported, so look the class up there instead.
|
|
154
|
+
process = sys.modules.get("concurrent.futures.process")
|
|
155
|
+
return process is not None and isinstance(executor, process.ProcessPoolExecutor)
|
ssapling/core/_plain.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Plain values: what a JSON or YAML file holds, and reads back the same.
|
|
2
|
+
|
|
3
|
+
Internal: settings accept plain values only, so they never hold live objects;
|
|
4
|
+
provenance holds plain values only, so it can be stored whatever codec the
|
|
5
|
+
payloads use. Plain values are ``None``, booleans, numbers, strings, lists,
|
|
6
|
+
and mappings with string keys.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from collections.abc import Mapping
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from ._text import join_path, show
|
|
13
|
+
from .errors import Problem
|
|
14
|
+
|
|
15
|
+
PLAIN = "a plain value (None, bool, int, float, str, or a list or str-keyed dict of these)"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def plain_copy(value: Any, path: str, problems: list[Problem]) -> Any:
|
|
19
|
+
"""A copy of ``value`` made of plain values, with tuples as lists.
|
|
20
|
+
|
|
21
|
+
Appends a ``Problem`` for every part that is not plain, each with its
|
|
22
|
+
path, so all of them can be reported at once.
|
|
23
|
+
"""
|
|
24
|
+
if value is None or isinstance(value, bool | int | float | str):
|
|
25
|
+
return value
|
|
26
|
+
if isinstance(value, list | tuple):
|
|
27
|
+
return [plain_copy(item, f"{path}[{i}]", problems) for i, item in enumerate(value)]
|
|
28
|
+
if isinstance(value, Mapping):
|
|
29
|
+
copy = {}
|
|
30
|
+
for key, item in value.items():
|
|
31
|
+
if not isinstance(key, str):
|
|
32
|
+
problems.append(Problem(path, f"keys must be strings, got {show(key)}"))
|
|
33
|
+
continue
|
|
34
|
+
copy[key] = plain_copy(item, join_path(path, key), problems)
|
|
35
|
+
return copy
|
|
36
|
+
problems.append(Problem(path, f"expected {PLAIN}, got {show(value)}"))
|
|
37
|
+
return value
|
ssapling/core/_text.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Small text helpers shared by core's modules, for paths and error messages."""
|
|
2
|
+
|
|
3
|
+
import inspect
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def join_path(path: str, name: str) -> str:
|
|
8
|
+
"""Extend a dotted path: ``join_path("schedule", "warmup") == "schedule.warmup"``.
|
|
9
|
+
|
|
10
|
+
An empty ``name`` is the whole of ``path``, as for a problem with a whole
|
|
11
|
+
group of settings.
|
|
12
|
+
"""
|
|
13
|
+
return f"{path}.{name}" if path and name else path or name
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def show(value: Any) -> str:
|
|
17
|
+
"""Describe a value for an error message: its type and a shortened repr."""
|
|
18
|
+
if value is None:
|
|
19
|
+
return "None"
|
|
20
|
+
text = repr(value)
|
|
21
|
+
if len(text) > 60:
|
|
22
|
+
text = text[:57] + "..."
|
|
23
|
+
return f"{type(value).__name__} {text}"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def summary(obj: object) -> str | None:
|
|
27
|
+
"""The first paragraph of an object's own docstring, on one line, or None."""
|
|
28
|
+
doc = getattr(obj, "__doc__", None)
|
|
29
|
+
name = getattr(obj, "__name__", None)
|
|
30
|
+
# Without a docstring, dataclasses generates one like "Name(a: int = 1)".
|
|
31
|
+
if not isinstance(doc, str) or not doc.strip() or (name and doc.startswith(f"{name}(")):
|
|
32
|
+
return None
|
|
33
|
+
return " ".join(inspect.cleandoc(doc).split("\n\n")[0].split())
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def describe(obj: object) -> str:
|
|
37
|
+
"""Name a class or function by its module and qualified name, for error messages."""
|
|
38
|
+
module = getattr(obj, "__module__", None)
|
|
39
|
+
qualname = getattr(obj, "__qualname__", None)
|
|
40
|
+
if module and qualname:
|
|
41
|
+
return f"{module}.{qualname}"
|
|
42
|
+
return repr(obj)
|
ssapling/core/errors.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""Exceptions raised by SSAPling.
|
|
2
|
+
|
|
3
|
+
Every error SSAPling raises about components, settings, or compositions derives
|
|
4
|
+
from ``SSAPlingError``, so callers can catch them all at once. Each error also
|
|
5
|
+
derives from the closest built-in exception (``LookupError``, ``ValueError``),
|
|
6
|
+
so code that expects those keeps working.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import difflib
|
|
10
|
+
from collections.abc import Iterable
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from ._text import describe
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class SSAPlingError(Exception):
|
|
18
|
+
"""Base class for errors raised by SSAPling.
|
|
19
|
+
|
|
20
|
+
Every SSAPling error can be pickled, so it survives being sent from a
|
|
21
|
+
worker process to the caller with its message and attributes, whatever
|
|
22
|
+
arguments its ``__init__`` takes.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def __reduce__(self) -> tuple[Any, ...]:
|
|
26
|
+
# Pickle would call __init__ with the message alone, which most
|
|
27
|
+
# errors do not accept, so rebuild without calling __init__.
|
|
28
|
+
return (_rebuild, (type(self), self.args, self.__dict__))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _rebuild(cls: type[SSAPlingError], args: tuple[Any, ...], state: dict[str, Any]) -> Any:
|
|
32
|
+
error = cls.__new__(cls)
|
|
33
|
+
error.args = args
|
|
34
|
+
error.__dict__.update(state)
|
|
35
|
+
return error
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True, slots=True)
|
|
39
|
+
class Problem:
|
|
40
|
+
"""One problem found while checking settings.
|
|
41
|
+
|
|
42
|
+
Attributes:
|
|
43
|
+
path: Where the problem is, such as ``"schedule.weights[2]"``; empty
|
|
44
|
+
for a problem with the settings as a whole.
|
|
45
|
+
message: What is wrong.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
path: str
|
|
49
|
+
message: str
|
|
50
|
+
|
|
51
|
+
def __str__(self) -> str:
|
|
52
|
+
return f"{self.path}: {self.message}" if self.path else self.message
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class ConfigError(SSAPlingError, ValueError):
|
|
56
|
+
"""Settings values are invalid. Every problem found is listed, not just the first.
|
|
57
|
+
|
|
58
|
+
Attributes:
|
|
59
|
+
subject: What was being checked, such as ``"settings for StepwiseSettings"``.
|
|
60
|
+
problems: Every problem found.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
def __init__(self, subject: str, problems: Iterable[Problem]) -> None:
|
|
64
|
+
self.subject = subject
|
|
65
|
+
self.problems = tuple(problems)
|
|
66
|
+
super().__init__(_listing(f"Invalid {subject}:", self.problems))
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class SettingsDeclarationError(SSAPlingError, TypeError):
|
|
70
|
+
"""A settings class is declared in a way SSAPling cannot check.
|
|
71
|
+
|
|
72
|
+
Raised when the class is registered (or first used), so a downstream
|
|
73
|
+
author sees the mistake before any settings values are supplied.
|
|
74
|
+
|
|
75
|
+
Attributes:
|
|
76
|
+
settings_class: The name of the settings class.
|
|
77
|
+
problems: Every problem found.
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
def __init__(self, settings_class: str, problems: Iterable[Problem]) -> None:
|
|
81
|
+
self.settings_class = settings_class
|
|
82
|
+
self.problems = tuple(problems)
|
|
83
|
+
super().__init__(_listing(f"Invalid settings class {settings_class}:", self.problems))
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class UnknownComponentError(SSAPlingError, LookupError):
|
|
87
|
+
"""A name was looked up in a registry that has nothing registered under it.
|
|
88
|
+
|
|
89
|
+
Attributes:
|
|
90
|
+
kind: The registry's kind of component, such as ``"teacher"``.
|
|
91
|
+
name: The name that was looked up.
|
|
92
|
+
available: Every registered name, sorted.
|
|
93
|
+
suggestions: Registered names close to ``name``, best first.
|
|
94
|
+
location: Where the name was written, such as ``"run.yaml: teacher.name"``,
|
|
95
|
+
or ``None``.
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
def __init__(
|
|
99
|
+
self, kind: str, name: str, available: Iterable[str], *, location: str | None = None
|
|
100
|
+
) -> None:
|
|
101
|
+
self.kind = kind
|
|
102
|
+
self.name = name
|
|
103
|
+
self.available = tuple(sorted(available))
|
|
104
|
+
self.suggestions = tuple(difflib.get_close_matches(name, self.available, n=3, cutoff=0.6))
|
|
105
|
+
self.location = location
|
|
106
|
+
message = self._message()
|
|
107
|
+
super().__init__(f"{location}: {message}" if location else message)
|
|
108
|
+
|
|
109
|
+
def _message(self) -> str:
|
|
110
|
+
if not self.available:
|
|
111
|
+
return (
|
|
112
|
+
f"Unknown {self.kind} {self.name!r}: no {self.kind} has been registered. "
|
|
113
|
+
"Components from a downstream package are available only after that "
|
|
114
|
+
"package registers them, for example by calling its register_components()."
|
|
115
|
+
)
|
|
116
|
+
message = f"Unknown {self.kind} {self.name!r}."
|
|
117
|
+
if self.suggestions:
|
|
118
|
+
message += f" Did you mean {_quoted(self.suggestions, 'or')}?"
|
|
119
|
+
return message + f" Registered {self.kind} names: {_quoted(self.available, 'and')}."
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class DuplicateRegistrationError(SSAPlingError, ValueError):
|
|
123
|
+
"""A name was registered twice, with a different implementation or settings class.
|
|
124
|
+
|
|
125
|
+
Attributes:
|
|
126
|
+
kind: The registry's kind of component, such as ``"teacher"``.
|
|
127
|
+
name: The name registered twice.
|
|
128
|
+
existing: The implementation already registered under ``name``.
|
|
129
|
+
new: The implementation that was rejected.
|
|
130
|
+
"""
|
|
131
|
+
|
|
132
|
+
def __init__(
|
|
133
|
+
self,
|
|
134
|
+
kind: str,
|
|
135
|
+
name: str,
|
|
136
|
+
existing: object,
|
|
137
|
+
new: object,
|
|
138
|
+
*,
|
|
139
|
+
existing_settings: type | None = None,
|
|
140
|
+
new_settings: type | None = None,
|
|
141
|
+
) -> None:
|
|
142
|
+
self.kind = kind
|
|
143
|
+
self.name = name
|
|
144
|
+
self.existing = existing
|
|
145
|
+
self.new = new
|
|
146
|
+
super().__init__(
|
|
147
|
+
f"A {kind} named {name!r} is already registered "
|
|
148
|
+
f"({_registered(existing, existing_settings)}). Registering "
|
|
149
|
+
f"{_registered(new, new_settings)} under the same name would replace it; "
|
|
150
|
+
"pass replace=True if that is intended."
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class MissingDependencyError(SSAPlingError, ImportError):
|
|
155
|
+
"""An optional feature was used without the extra that provides it.
|
|
156
|
+
|
|
157
|
+
The message names the extra to install, such as ``ssapling[yaml]``.
|
|
158
|
+
"""
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _listing(title: str, problems: Iterable[Problem]) -> str:
|
|
162
|
+
return "\n - ".join([title, *(str(problem) for problem in problems)])
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _quoted(names: Iterable[str], conjunction: str) -> str:
|
|
166
|
+
quoted = [repr(name) for name in names]
|
|
167
|
+
if len(quoted) <= 2:
|
|
168
|
+
return f" {conjunction} ".join(quoted)
|
|
169
|
+
return f"{', '.join(quoted[:-1])}, {conjunction} {quoted[-1]}"
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _registered(implementation: object, settings: type | None) -> str:
|
|
173
|
+
if settings is None:
|
|
174
|
+
return describe(implementation)
|
|
175
|
+
return f"{describe(implementation)} with settings {describe(settings)}"
|