openpickleball-engine 1.0.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.
- open_engine/__init__.py +95 -0
- open_engine/_config.py +1379 -0
- open_engine/_connectivity.py +167 -0
- open_engine/_engine.py +1582 -0
- open_engine/_errors.py +90 -0
- open_engine/_evaluation.py +705 -0
- open_engine/_ledger.py +277 -0
- open_engine/_math.py +290 -0
- open_engine/_model.py +614 -0
- open_engine/_replay.py +255 -0
- open_engine/_seeds.py +327 -0
- open_engine/_snapshot.py +1511 -0
- open_engine/_types.py +254 -0
- open_engine/_validation.py +220 -0
- open_engine/_version.py +9 -0
- open_engine/engine.py +99 -0
- open_engine/params/v1.json +108 -0
- open_engine/py.typed +0 -0
- open_engine/winprob.py +196 -0
- openpickleball_engine-1.0.0.dist-info/METADATA +248 -0
- openpickleball_engine-1.0.0.dist-info/RECORD +23 -0
- openpickleball_engine-1.0.0.dist-info/WHEEL +4 -0
- openpickleball_engine-1.0.0.dist-info/licenses/LICENSE +662 -0
open_engine/_config.py
ADDED
|
@@ -0,0 +1,1379 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Config, its tables and limits, and the helpers that check and rebuild it.
|
|
3
|
+
|
|
4
|
+
Reference implementation: outputs are not OPEN ratings, and ratings are
|
|
5
|
+
provisional (see "Status" in docs/behavior.md).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import importlib.resources
|
|
12
|
+
import json
|
|
13
|
+
import math
|
|
14
|
+
import re
|
|
15
|
+
import sys
|
|
16
|
+
from collections.abc import Callable, Iterator, Mapping
|
|
17
|
+
from dataclasses import dataclass, field, fields
|
|
18
|
+
from enum import Enum
|
|
19
|
+
from types import MemberDescriptorType
|
|
20
|
+
from typing import TypeVar, cast
|
|
21
|
+
|
|
22
|
+
from ._errors import ConfigError
|
|
23
|
+
from ._types import ALL_GAME_FORMATS, MatchType, ScoringType, _is_member
|
|
24
|
+
from ._validation import (
|
|
25
|
+
_MAX_DAYS,
|
|
26
|
+
_as_float,
|
|
27
|
+
_is_config_number,
|
|
28
|
+
_is_config_whole,
|
|
29
|
+
_plain_number,
|
|
30
|
+
_type_is,
|
|
31
|
+
_type_name,
|
|
32
|
+
)
|
|
33
|
+
from ._version import __version__
|
|
34
|
+
|
|
35
|
+
# ---------------------------------------------------------------------------
|
|
36
|
+
# Configuration
|
|
37
|
+
# ---------------------------------------------------------------------------
|
|
38
|
+
|
|
39
|
+
_K = TypeVar("_K")
|
|
40
|
+
_V = TypeVar("_V")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class _FrozenMapping(Mapping[_K, _V]):
|
|
44
|
+
"""A read-only copy of a mapping. Hashable, picklable, and deep-copyable."""
|
|
45
|
+
|
|
46
|
+
__slots__ = ("_data",)
|
|
47
|
+
|
|
48
|
+
_data: dict[_K, _V]
|
|
49
|
+
|
|
50
|
+
def __init__(self, data: Mapping[_K, _V]) -> None:
|
|
51
|
+
self._data = dict(data)
|
|
52
|
+
|
|
53
|
+
def __getitem__(self, key: _K) -> _V:
|
|
54
|
+
return self._data[key]
|
|
55
|
+
|
|
56
|
+
def __iter__(self) -> Iterator[_K]:
|
|
57
|
+
return iter(self._data)
|
|
58
|
+
|
|
59
|
+
def __len__(self) -> int:
|
|
60
|
+
return len(self._data)
|
|
61
|
+
|
|
62
|
+
def __hash__(self) -> int:
|
|
63
|
+
return hash(frozenset(self._data.items()))
|
|
64
|
+
|
|
65
|
+
def __repr__(self) -> str:
|
|
66
|
+
return repr(self._data)
|
|
67
|
+
|
|
68
|
+
def __reduce__(self) -> tuple[type[_FrozenMapping[_K, _V]], tuple[dict[_K, _V]]]:
|
|
69
|
+
return (type(self), (self._data,))
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
_SCORING_VALUES = frozenset(ScoringType)
|
|
73
|
+
_FORMAT_PAIRS = "allowed_game_formats entries must be (scoring type, whole number) pairs"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _format_scoring(value: object) -> ScoringType | None:
|
|
77
|
+
"""An allowed_game_formats scoring item as a member: a member, or exactly a str naming one."""
|
|
78
|
+
if _is_member(value, ScoringType):
|
|
79
|
+
return cast(ScoringType, value)
|
|
80
|
+
if type(value) is str and value in _SCORING_VALUES:
|
|
81
|
+
return ScoringType(value)
|
|
82
|
+
return None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _format_points(value: object) -> int | None:
|
|
86
|
+
"""An allowed_game_formats points item as a plain int, judged by its real type alone."""
|
|
87
|
+
real = type(value)
|
|
88
|
+
if real is bool or not issubclass(real, int):
|
|
89
|
+
return None
|
|
90
|
+
points = int.__int__(cast(int, value))
|
|
91
|
+
return points if _is_config_whole(points) else None
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# Config fields that hold a mapping. __post_init__ stores each as a read-only copy.
|
|
95
|
+
_CONFIG_MAPPING_FIELDS = (
|
|
96
|
+
"scale_by_scoring",
|
|
97
|
+
"win_calibration_by_scoring",
|
|
98
|
+
"match_weights",
|
|
99
|
+
"game_length_weights",
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
# The largest rating bound, RD bound, or daily RD growth a Config accepts.
|
|
103
|
+
# Squaring a value this size is finite, and so are team sums, rating gaps,
|
|
104
|
+
# and imbalance across the whole rating range.
|
|
105
|
+
_RATING_LIMIT = 2.0**511
|
|
106
|
+
_RATING_LIMIT_TEXT = "2**511"
|
|
107
|
+
|
|
108
|
+
# Int-only bounds. Exact int arithmetic raises OverflowError where float
|
|
109
|
+
# arithmetic goes to inf, so these two fields have a lower bound as ints.
|
|
110
|
+
_INT_GROWTH_LIMIT = 2**500
|
|
111
|
+
_INT_GROWTH_LIMIT_TEXT = "2**500"
|
|
112
|
+
_INT_BONUS_LIMIT = 2**511
|
|
113
|
+
_INT_BONUS_LIMIT_TEXT = "2**511"
|
|
114
|
+
# The most games the multiplier check allows: len() returns at most sys.maxsize.
|
|
115
|
+
_MAX_GAME_COUNT = sys.maxsize
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
# Config scalar fields by kind, checked for type and finiteness first.
|
|
119
|
+
_CONFIG_NUMBER_FIELDS = (
|
|
120
|
+
"min_rating",
|
|
121
|
+
"max_rating",
|
|
122
|
+
"default_rating",
|
|
123
|
+
"k_min",
|
|
124
|
+
"k_max",
|
|
125
|
+
"rd_min",
|
|
126
|
+
"rd_max",
|
|
127
|
+
"new_player_rd",
|
|
128
|
+
"external_seed_rd",
|
|
129
|
+
"category_seed_rd",
|
|
130
|
+
"rd_shrink_per_match",
|
|
131
|
+
"rd_growth_per_day",
|
|
132
|
+
"win_weight",
|
|
133
|
+
"game_count_bonus",
|
|
134
|
+
"max_information_multiplier",
|
|
135
|
+
"self_reported_repeat_factor",
|
|
136
|
+
"established_reliability_threshold",
|
|
137
|
+
)
|
|
138
|
+
_CONFIG_WHOLE_FIELDS = (
|
|
139
|
+
"replay_interval_days",
|
|
140
|
+
"diversity_window_days",
|
|
141
|
+
"diversity_target",
|
|
142
|
+
"self_reported_repeat_window_days",
|
|
143
|
+
"self_reported_max_repeats",
|
|
144
|
+
"import_reliability_carry_matches",
|
|
145
|
+
"import_reliability_max_age_days",
|
|
146
|
+
"established_min_verified_matches",
|
|
147
|
+
"connectivity_min_shared_contacts",
|
|
148
|
+
"connectivity_min_contact_days",
|
|
149
|
+
"connectivity_min_outside_players",
|
|
150
|
+
)
|
|
151
|
+
_CONFIG_OPTIONAL_NUMBER_FIELDS = (
|
|
152
|
+
"connectivity_reliability_cap",
|
|
153
|
+
"max_singles_rating_gap",
|
|
154
|
+
"max_doubles_partner_gap",
|
|
155
|
+
)
|
|
156
|
+
_CONFIG_BOOL_FIELDS = (
|
|
157
|
+
"self_reported_requires_both_teams",
|
|
158
|
+
"reject_content_duplicates",
|
|
159
|
+
"category_feeds_parent",
|
|
160
|
+
)
|
|
161
|
+
_CONFIG_DAY_FIELDS = (
|
|
162
|
+
"replay_interval_days",
|
|
163
|
+
"diversity_window_days",
|
|
164
|
+
"self_reported_repeat_window_days",
|
|
165
|
+
"import_reliability_max_age_days",
|
|
166
|
+
)
|
|
167
|
+
# The form of Config.params_version: v, then a positive whole number in
|
|
168
|
+
# ASCII digits with no leading zero. fullmatch, so no trailing newline passes.
|
|
169
|
+
_PARAMS_VERSION = re.compile(r"v[1-9][0-9]*")
|
|
170
|
+
_PARAMS_VERSION_FORM = (
|
|
171
|
+
"params_version must be None or v<N>, with N a positive whole number "
|
|
172
|
+
"and no leading zero, such as v1"
|
|
173
|
+
)
|
|
174
|
+
# The two version labels, which change no rating: parameter_fingerprint()
|
|
175
|
+
# leaves them out.
|
|
176
|
+
_CONFIG_LABEL_FIELDS = ("version", "params_version")
|
|
177
|
+
# Type failures that keep the message an earlier release already raised.
|
|
178
|
+
_CONFIG_TYPE_MESSAGES = {
|
|
179
|
+
"established_reliability_threshold": (
|
|
180
|
+
"established_reliability_threshold must be between 0 and 100"
|
|
181
|
+
),
|
|
182
|
+
"established_min_verified_matches": (
|
|
183
|
+
"established_min_verified_matches must be a nonnegative int"
|
|
184
|
+
),
|
|
185
|
+
"connectivity_reliability_cap": (
|
|
186
|
+
"connectivity_reliability_cap must be None or a number from 0 to 100"
|
|
187
|
+
),
|
|
188
|
+
"connectivity_min_shared_contacts": "connectivity_min_shared_contacts must be a positive int",
|
|
189
|
+
"connectivity_min_contact_days": "connectivity_min_contact_days must be a positive int",
|
|
190
|
+
"connectivity_min_outside_players": "connectivity_min_outside_players must be a positive int",
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
@dataclass(frozen=True, eq=False)
|
|
195
|
+
class Config:
|
|
196
|
+
"""
|
|
197
|
+
Every rating parameter. Frozen, so a config cannot change during a replay.
|
|
198
|
+
|
|
199
|
+
Each default is an uncalibrated placeholder, a declared choice, or a label
|
|
200
|
+
that changes no rating, as the parameter table in docs/model.md marks it.
|
|
201
|
+
fingerprint() identifies the exact config behind published ratings, both
|
|
202
|
+
version labels included. parameter_fingerprint() identifies the parameter
|
|
203
|
+
values alone: it leaves out version and params_version, so it survives a
|
|
204
|
+
release that changes no parameter value, though not one that adds,
|
|
205
|
+
removes, or renames a field or changes how a value is written in the
|
|
206
|
+
payload. to_dict() and from_dict() store and load a config.
|
|
207
|
+
|
|
208
|
+
Every field is checked when the config is built, and any failure
|
|
209
|
+
raises ConfigError. Mapping fields are stored as read-only copies, and
|
|
210
|
+
allowed_game_formats as a frozenset of (scoring type, whole number)
|
|
211
|
+
pairs. Two configs are equal exactly when their fingerprint payloads are
|
|
212
|
+
equal, so equal configs share a fingerprint and a hash.
|
|
213
|
+
|
|
214
|
+
An entry point that takes a config accepts only an exact Config with
|
|
215
|
+
nothing in its instance __dict__ but its fields (or None, where it
|
|
216
|
+
allows one), and uses a fresh copy built from the given one's stored
|
|
217
|
+
field values. Compare configs with == or fingerprint(), not is.
|
|
218
|
+
|
|
219
|
+
Raises:
|
|
220
|
+
ConfigError: a field breaks its rule.
|
|
221
|
+
|
|
222
|
+
See docs/behavior.md, "Config validation", for every rule, and docs/model.md,
|
|
223
|
+
"Parameters", for what each field means.
|
|
224
|
+
"""
|
|
225
|
+
|
|
226
|
+
version: str = __version__
|
|
227
|
+
|
|
228
|
+
# The published parameter set's label, "v<N>" with N a positive whole
|
|
229
|
+
# number and no leading zero, so it names a file such as
|
|
230
|
+
# src/open_engine/params/v1.json.
|
|
231
|
+
# None, the default, means the config is not a published parameter set.
|
|
232
|
+
# A label only: it changes no rating. parameter_fingerprint() leaves it
|
|
233
|
+
# out, and fingerprint() includes it.
|
|
234
|
+
params_version: str | None = None
|
|
235
|
+
|
|
236
|
+
# Rating scale
|
|
237
|
+
min_rating: float = 2.0
|
|
238
|
+
max_rating: float = 8.0
|
|
239
|
+
default_rating: float = 3.5
|
|
240
|
+
|
|
241
|
+
# Logistic expectation curve, one scale per scoring type, because side-out
|
|
242
|
+
# and rally scoring produce different point shares for the same skill gap.
|
|
243
|
+
# A rating gap equal to the scale gives 10:1 expected point-share odds.
|
|
244
|
+
# Both values are UNCALIBRATED placeholders. Fit them with fit_scale().
|
|
245
|
+
scale_by_scoring: Mapping[ScoringType, float] = field(
|
|
246
|
+
default_factory=lambda: {
|
|
247
|
+
ScoringType.SIDE_OUT: 2.9,
|
|
248
|
+
ScoringType.RALLY: 2.9,
|
|
249
|
+
}
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
# Win-probability calibration, one exponent per scoring type: the match win
|
|
253
|
+
# probability p becomes sigmoid(a * logit(p)). 1.0 leaves it unchanged.
|
|
254
|
+
win_calibration_by_scoring: Mapping[ScoringType, float] = field(
|
|
255
|
+
default_factory=lambda: {
|
|
256
|
+
ScoringType.SIDE_OUT: 1.0,
|
|
257
|
+
ScoringType.RALLY: 1.0,
|
|
258
|
+
}
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
# Per-player responsiveness. K is derived from RD, and each player moves
|
|
262
|
+
# by their own K, so team-average movement is not always zero-sum.
|
|
263
|
+
# MatchResult.imbalance reports the net.
|
|
264
|
+
k_min: float = 0.12
|
|
265
|
+
k_max: float = 0.60
|
|
266
|
+
|
|
267
|
+
# Rating deviation (RD) is OPEN's internal uncertainty measure.
|
|
268
|
+
rd_min: float = 0.10
|
|
269
|
+
rd_max: float = 0.80
|
|
270
|
+
new_player_rd: float = 0.80
|
|
271
|
+
external_seed_rd: float = 0.42
|
|
272
|
+
category_seed_rd: float = 0.50
|
|
273
|
+
rd_shrink_per_match: float = 0.08
|
|
274
|
+
rd_growth_per_day: float = 0.012
|
|
275
|
+
|
|
276
|
+
# Match performance: actual = (1 - win_weight) * pooled point share
|
|
277
|
+
# + win_weight * (1 if team A won else 0). The default 0.0 is pure
|
|
278
|
+
# point share, so a team can win and still lose rating when it wins by
|
|
279
|
+
# less than expected or wins a best of 3 (or 5) with fewer total
|
|
280
|
+
# points. 1.0 scores the result only, so a winner never loses rating.
|
|
281
|
+
# There is no floor on a winner's change, other than the rating range.
|
|
282
|
+
# The default changes only when out-of-sample evaluation supports
|
|
283
|
+
# another value (issue #20). See "Match performance" in
|
|
284
|
+
# docs/behavior.md for the full policy.
|
|
285
|
+
win_weight: float = 0.0
|
|
286
|
+
|
|
287
|
+
# Evidence quality. These are OPEN policy choices.
|
|
288
|
+
match_weights: Mapping[MatchType, float] = field(
|
|
289
|
+
default_factory=lambda: {
|
|
290
|
+
MatchType.TOURNAMENT: 1.00,
|
|
291
|
+
MatchType.LEAGUE: 0.90,
|
|
292
|
+
MatchType.REC_VERIFIED: 0.75,
|
|
293
|
+
MatchType.SELF_REPORTED: 0.40,
|
|
294
|
+
}
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
# Game formats accepted for rating, as (scoring type, points to).
|
|
298
|
+
allowed_game_formats: frozenset[tuple[ScoringType, int]] = ALL_GAME_FORMATS
|
|
299
|
+
|
|
300
|
+
# Information multiplier: longer games and more games carry more evidence.
|
|
301
|
+
# multiplier = min(max, length_weight[points_to] * (1 + bonus * (games - 1)))
|
|
302
|
+
game_length_weights: Mapping[int, float] = field(
|
|
303
|
+
default_factory=lambda: {
|
|
304
|
+
11: 1.00,
|
|
305
|
+
15: 1.10,
|
|
306
|
+
21: 1.20,
|
|
307
|
+
}
|
|
308
|
+
)
|
|
309
|
+
game_count_bonus: float = 0.12
|
|
310
|
+
max_information_multiplier: float = 1.30
|
|
311
|
+
|
|
312
|
+
# Published recalculation schedule. Informational: the platform runs
|
|
313
|
+
# replay() on this interval and labels ratings between runs as live.
|
|
314
|
+
replay_interval_days: int = 7
|
|
315
|
+
|
|
316
|
+
# Diversity uses a rolling window.
|
|
317
|
+
diversity_window_days: int = 365
|
|
318
|
+
diversity_target: int = 12
|
|
319
|
+
|
|
320
|
+
# Self-reported match safeguards.
|
|
321
|
+
self_reported_requires_both_teams: bool = True
|
|
322
|
+
self_reported_repeat_window_days: int = 90
|
|
323
|
+
self_reported_repeat_factor: float = 0.5
|
|
324
|
+
self_reported_max_repeats: int = 4
|
|
325
|
+
|
|
326
|
+
# Likely duplicates: a match with the same played_on, the same two teams
|
|
327
|
+
# (either side may be team A), and the same game scores as an earlier
|
|
328
|
+
# counted match, under another match_id. False does not reject it for
|
|
329
|
+
# this, and a counted one has MatchResult.possible_duplicate_of set.
|
|
330
|
+
# True does not count it (RejectionReason.POSSIBLE_DUPLICATE). A real
|
|
331
|
+
# same-day rematch with the same scores is caught too, so the default
|
|
332
|
+
# only flags. Under True the first report to count in processing order
|
|
333
|
+
# survives, whatever its match type or format, so a weaker or
|
|
334
|
+
# relabeled copy can win. Use True only when the backend trusts who
|
|
335
|
+
# files reports. See "Likely duplicates" in docs/behavior.md.
|
|
336
|
+
reject_content_duplicates: bool = False
|
|
337
|
+
|
|
338
|
+
# Imported reliability display.
|
|
339
|
+
import_reliability_carry_matches: int = 10
|
|
340
|
+
import_reliability_max_age_days: int = 365
|
|
341
|
+
|
|
342
|
+
# Reliability label. PlayerSummary.established is True when OPEN-earned
|
|
343
|
+
# reliability, as displayed, is at least the threshold (0-100) and the
|
|
344
|
+
# state has at least established_min_verified_matches counted
|
|
345
|
+
# tournament, league, or recreational verified matches. Self-reported
|
|
346
|
+
# matches never count toward the minimum. A label only: it changes no
|
|
347
|
+
# rating, prediction, or evaluation. A minimum of 0 leaves the
|
|
348
|
+
# reliability rule alone.
|
|
349
|
+
established_reliability_threshold: float = 60.0
|
|
350
|
+
established_min_verified_matches: int = 3
|
|
351
|
+
|
|
352
|
+
# Network connectivity, a reliability label (issue #58). Measured per
|
|
353
|
+
# rating format over the diversity window at the summary's reference
|
|
354
|
+
# date. Two players in contact are tied when they share at least
|
|
355
|
+
# connectivity_min_shared_contacts partners or opponents and each of
|
|
356
|
+
# them reached those players on at least connectivity_min_contact_days
|
|
357
|
+
# distinct dates; a pool is a set of players linked by ties. A player
|
|
358
|
+
# is connected when their group of players linked by contact has at
|
|
359
|
+
# least half as many players as the largest group and either the pool
|
|
360
|
+
# with its fringe (drop-ins who met only the pool) holds more than half
|
|
361
|
+
# the group or the pool has at least connectivity_min_outside_players
|
|
362
|
+
# other outside players on at least connectivity_min_contact_days
|
|
363
|
+
# dates. PlayerSummary.reliability of a player who is not connected is
|
|
364
|
+
# at most connectivity_reliability_cap; None, the default, turns the
|
|
365
|
+
# cap off. The rule can be gamed through group sizes and can cap
|
|
366
|
+
# players in a real but smaller network, so the cap stays off until
|
|
367
|
+
# out-of-sample review of real ledgers supports a default (issue #58). A label only: it
|
|
368
|
+
# changes no rating, prediction, or evaluation. The defaults are
|
|
369
|
+
# declared choices, not calibrated ones.
|
|
370
|
+
connectivity_reliability_cap: float | None = None
|
|
371
|
+
connectivity_min_shared_contacts: int = 4
|
|
372
|
+
connectivity_min_contact_days: int = 3
|
|
373
|
+
connectivity_min_outside_players: int = 8
|
|
374
|
+
|
|
375
|
+
# Category doubles matches also update overall doubles.
|
|
376
|
+
category_feeds_parent: bool = True
|
|
377
|
+
|
|
378
|
+
# Optional eligibility filters. Disabled by default.
|
|
379
|
+
max_singles_rating_gap: float | None = None
|
|
380
|
+
max_doubles_partner_gap: float | None = None
|
|
381
|
+
|
|
382
|
+
def __post_init__(self) -> None:
|
|
383
|
+
"""
|
|
384
|
+
Check every field and store plain values and read-only copies, in this order.
|
|
385
|
+
|
|
386
|
+
First the type and finiteness of every scalar field, so no comparison
|
|
387
|
+
in a later step can raise TypeError. Then the mapping and format
|
|
388
|
+
fields, then ranges and cross-field rules. The first failing check
|
|
389
|
+
raises ConfigError.
|
|
390
|
+
"""
|
|
391
|
+
self._check_scalar_fields()
|
|
392
|
+
pairs = self._read_mapping_pairs()
|
|
393
|
+
self._store_game_lengths(pairs)
|
|
394
|
+
self._store_game_formats()
|
|
395
|
+
self._store_enum_mappings(pairs)
|
|
396
|
+
self._check_mapping_values()
|
|
397
|
+
self._check_rating_range()
|
|
398
|
+
self._check_k_and_rd()
|
|
399
|
+
self._check_step_size()
|
|
400
|
+
self._check_windows_and_counts()
|
|
401
|
+
self._check_labels_and_filters()
|
|
402
|
+
|
|
403
|
+
def _check_scalar_fields(self) -> None:
|
|
404
|
+
"""
|
|
405
|
+
Check each scalar field's type, storing every number as its plain value.
|
|
406
|
+
|
|
407
|
+
In order: version is exactly a str; params_version is None or exactly
|
|
408
|
+
a str, then of the form v<N>; every number field is stored as
|
|
409
|
+
its plain int or float; then the number, whole number, optional
|
|
410
|
+
number, and bool fields, each group in its listed order.
|
|
411
|
+
"""
|
|
412
|
+
|
|
413
|
+
def must_be(name: str, kind: str) -> str:
|
|
414
|
+
return _CONFIG_TYPE_MESSAGES.get(name, f"{name} must be {kind}")
|
|
415
|
+
|
|
416
|
+
# Exactly str: the snapshot loader accepts only a plain str, so a
|
|
417
|
+
# subclass would give a snapshot that does not load.
|
|
418
|
+
if type(self.version) is not str:
|
|
419
|
+
raise ConfigError(must_be("version", "a str"))
|
|
420
|
+
# Exactly str before the pattern runs, so no subclass code runs.
|
|
421
|
+
params = self.params_version
|
|
422
|
+
if params is not None:
|
|
423
|
+
if type(params) is not str:
|
|
424
|
+
raise ConfigError(must_be("params_version", "None or a str"))
|
|
425
|
+
if _PARAMS_VERSION.fullmatch(params) is None:
|
|
426
|
+
raise ConfigError(_PARAMS_VERSION_FORM)
|
|
427
|
+
# Store every number as the plain int or float of its own value, so
|
|
428
|
+
# every later check, fingerprint(), and rating code read the same
|
|
429
|
+
# value (issue #107). A bool or a non-number is kept, and a spoofed
|
|
430
|
+
# number replaced, for the type checks below to reject.
|
|
431
|
+
for name in _CONFIG_NUMBER_FIELDS + _CONFIG_WHOLE_FIELDS + _CONFIG_OPTIONAL_NUMBER_FIELDS:
|
|
432
|
+
object.__setattr__(self, name, _plain_number(getattr(self, name)))
|
|
433
|
+
for name in _CONFIG_NUMBER_FIELDS:
|
|
434
|
+
if not _is_config_number(getattr(self, name)):
|
|
435
|
+
raise ConfigError(must_be(name, "a finite number"))
|
|
436
|
+
for name in _CONFIG_WHOLE_FIELDS:
|
|
437
|
+
if not _is_config_whole(getattr(self, name)):
|
|
438
|
+
raise ConfigError(must_be(name, "a whole number"))
|
|
439
|
+
for name in _CONFIG_OPTIONAL_NUMBER_FIELDS:
|
|
440
|
+
value = getattr(self, name)
|
|
441
|
+
if value is not None and not _is_config_number(value):
|
|
442
|
+
raise ConfigError(must_be(name, "None or a finite number"))
|
|
443
|
+
for name in _CONFIG_BOOL_FIELDS:
|
|
444
|
+
# Exactly bool: an object whose __class__ claims bool passes isinstance.
|
|
445
|
+
if type(getattr(self, name)) is not bool:
|
|
446
|
+
raise ConfigError(must_be(name, "a bool"))
|
|
447
|
+
|
|
448
|
+
def _read_mapping_pairs(self) -> dict[str, list[tuple[object, object]]]:
|
|
449
|
+
"""
|
|
450
|
+
Read each mapping field once, as (key, plain value) pairs.
|
|
451
|
+
|
|
452
|
+
For each field in _CONFIG_MAPPING_FIELDS, in order: it must be a
|
|
453
|
+
mapping, then every value a finite number.
|
|
454
|
+
"""
|
|
455
|
+
# The mapping and format helpers check types and keys and store
|
|
456
|
+
# read-only copies. Keys and format entries are stored as their own
|
|
457
|
+
# types (an enum member, a plain int), so the fingerprint never
|
|
458
|
+
# depends on how an equal key prints or whether JSON can hold it.
|
|
459
|
+
# One read of each caller's mapping, as (key, plain value) pairs;
|
|
460
|
+
# every later mapping check reads these pairs or the copies built
|
|
461
|
+
# from them, never the caller's mapping, and no game length key is
|
|
462
|
+
# hashed before it is converted.
|
|
463
|
+
pairs: dict[str, list[tuple[object, object]]] = {}
|
|
464
|
+
for name in _CONFIG_MAPPING_FIELDS:
|
|
465
|
+
value = getattr(self, name)
|
|
466
|
+
if not isinstance(value, Mapping):
|
|
467
|
+
raise ConfigError(f"{name} must be a mapping")
|
|
468
|
+
pairs[name] = [(key, _plain_number(item)) for key, item in value.items()]
|
|
469
|
+
if not all(_is_config_number(item) for _, item in pairs[name]):
|
|
470
|
+
raise ConfigError(f"{name} values must be finite numbers")
|
|
471
|
+
return pairs
|
|
472
|
+
|
|
473
|
+
def _store_game_lengths(self, pairs: dict[str, list[tuple[object, object]]]) -> None:
|
|
474
|
+
"""
|
|
475
|
+
Store game_length_weights from its read pairs, as a read-only copy with int keys.
|
|
476
|
+
|
|
477
|
+
In order: every key is a whole number, no game length repeats, then
|
|
478
|
+
every key is at least 1 and every value positive.
|
|
479
|
+
"""
|
|
480
|
+
# Each game length key as its plain int, from its own value.
|
|
481
|
+
length_pairs = [(_plain_number(key), item) for key, item in pairs["game_length_weights"]]
|
|
482
|
+
if not all(_is_config_whole(key) for key, _ in length_pairs):
|
|
483
|
+
raise ConfigError("game_length_weights keys must be whole numbers")
|
|
484
|
+
lengths: dict[int, float] = {}
|
|
485
|
+
for key, item in length_pairs:
|
|
486
|
+
points = cast(int, key)
|
|
487
|
+
if points in lengths:
|
|
488
|
+
raise ConfigError(f"game_length_weights repeats the game length {points}")
|
|
489
|
+
lengths[points] = cast(float, item)
|
|
490
|
+
object.__setattr__(self, "game_length_weights", _FrozenMapping(lengths))
|
|
491
|
+
if any(key < 1 for key in self.game_length_weights):
|
|
492
|
+
raise ConfigError("game_length_weights keys must be at least 1")
|
|
493
|
+
if any(value <= 0 for value in self.game_length_weights.values()):
|
|
494
|
+
raise ConfigError("game_length_weights values must be positive")
|
|
495
|
+
|
|
496
|
+
def _store_game_formats(self) -> None:
|
|
497
|
+
"""
|
|
498
|
+
Store allowed_game_formats as a frozenset of (ScoringType, int) pairs.
|
|
499
|
+
|
|
500
|
+
In order: it is a set or frozenset, then every entry is a tuple of
|
|
501
|
+
two items, then no entry's first item is a ScoringType that is not a
|
|
502
|
+
member, then every entry is a scoring type (a member, or exactly a
|
|
503
|
+
str naming one) and a whole number (a real int, not a bool, finite
|
|
504
|
+
as a float), then every whole number is at least 1. Each step checks
|
|
505
|
+
every entry before the next starts, so the message does not depend
|
|
506
|
+
on set order, which can change with the hash seed (issue #145).
|
|
507
|
+
The container is judged by its real type, so a __class__ property
|
|
508
|
+
never runs, and is read once (a set or frozenset subclass's own
|
|
509
|
+
__iter__ can run). Every entry and item is judged by type() alone,
|
|
510
|
+
so no other caller code runs.
|
|
511
|
+
"""
|
|
512
|
+
if not issubclass(type(self.allowed_game_formats), (set, frozenset)):
|
|
513
|
+
raise ConfigError("allowed_game_formats must be a set or frozenset")
|
|
514
|
+
# Each entry is read once, through tuple's own methods, so a tuple
|
|
515
|
+
# subclass cannot show the check one pair and the stored set another.
|
|
516
|
+
entries: list[tuple[object, object]] = []
|
|
517
|
+
for entry in self.allowed_game_formats:
|
|
518
|
+
if not (issubclass(type(entry), tuple) and tuple.__len__(entry) == 2):
|
|
519
|
+
raise ConfigError(_FORMAT_PAIRS)
|
|
520
|
+
entries.append((tuple.__getitem__(entry, 0), tuple.__getitem__(entry, 1)))
|
|
521
|
+
for entry_scoring, _ in entries:
|
|
522
|
+
if type(entry_scoring) is ScoringType and not _is_member(entry_scoring, ScoringType):
|
|
523
|
+
raise ConfigError("allowed_game_formats has a ScoringType that is not a member")
|
|
524
|
+
formats: list[tuple[ScoringType, int]] = []
|
|
525
|
+
for entry_scoring, entry_points in entries:
|
|
526
|
+
scoring = _format_scoring(entry_scoring)
|
|
527
|
+
points = _format_points(entry_points)
|
|
528
|
+
if scoring is None or points is None:
|
|
529
|
+
raise ConfigError(_FORMAT_PAIRS)
|
|
530
|
+
formats.append((scoring, points))
|
|
531
|
+
if any(points < 1 for _, points in formats):
|
|
532
|
+
raise ConfigError("allowed_game_formats points must be at least 1")
|
|
533
|
+
object.__setattr__(self, "allowed_game_formats", frozenset(formats))
|
|
534
|
+
|
|
535
|
+
def _store_enum_mappings(self, pairs: dict[str, list[tuple[object, object]]]) -> None:
|
|
536
|
+
"""
|
|
537
|
+
Store the enum-keyed mappings as read-only copies keyed by members.
|
|
538
|
+
|
|
539
|
+
In order scale_by_scoring, win_calibration_by_scoring, then
|
|
540
|
+
match_weights: each needs exactly one value for every member.
|
|
541
|
+
"""
|
|
542
|
+
for name, kind, label in (
|
|
543
|
+
("scale_by_scoring", ScoringType, "scoring type"),
|
|
544
|
+
("win_calibration_by_scoring", ScoringType, "scoring type"),
|
|
545
|
+
("match_weights", MatchType, "match type"),
|
|
546
|
+
):
|
|
547
|
+
# Each key is converted exactly once, and every check reads the
|
|
548
|
+
# converted list: a key hashed twice could hash as one member
|
|
549
|
+
# for a check and as another for the stored mapping.
|
|
550
|
+
converted = [(_config_enum_key(key, kind, name), item) for key, item in pairs[name]]
|
|
551
|
+
members = [member for member, _ in converted if member is not None]
|
|
552
|
+
if len(members) != len(converted) or len(members) != len(set(members)):
|
|
553
|
+
raise ConfigError(f"{name} needs a value for every {label}")
|
|
554
|
+
if set(members) != set(kind):
|
|
555
|
+
raise ConfigError(f"{name} needs a value for every {label}")
|
|
556
|
+
keyed = {cast(Enum, member): item for member, item in converted}
|
|
557
|
+
object.__setattr__(self, name, _FrozenMapping(keyed))
|
|
558
|
+
|
|
559
|
+
def _check_mapping_values(self) -> None:
|
|
560
|
+
"""
|
|
561
|
+
Check the stored mapping values.
|
|
562
|
+
|
|
563
|
+
In order: scales, win calibration values, and match weights are
|
|
564
|
+
positive, then every allowed game format has a game length weight,
|
|
565
|
+
naming the shortest game length that has none.
|
|
566
|
+
"""
|
|
567
|
+
if any(value <= 0 for value in self.scale_by_scoring.values()):
|
|
568
|
+
raise ConfigError("scales must be positive")
|
|
569
|
+
if any(value <= 0 for value in self.win_calibration_by_scoring.values()):
|
|
570
|
+
raise ConfigError("win calibration values must be positive")
|
|
571
|
+
if any(value <= 0 for value in self.match_weights.values()):
|
|
572
|
+
raise ConfigError("match_weights values must be positive")
|
|
573
|
+
# Stored points are plain ints, so sorting runs no caller code, and
|
|
574
|
+
# the shortest missing length is named whatever the set order.
|
|
575
|
+
for points in sorted({points for _, points in self.allowed_game_formats}):
|
|
576
|
+
if points not in self.game_length_weights:
|
|
577
|
+
raise ConfigError(f"No game_length_weight for games to {points}")
|
|
578
|
+
|
|
579
|
+
def _check_rating_range(self) -> None:
|
|
580
|
+
"""
|
|
581
|
+
Check the rating range.
|
|
582
|
+
|
|
583
|
+
In order: each of min_rating, max_rating, and default_rating is within
|
|
584
|
+
the rating limit, min_rating is below max_rating, then default_rating
|
|
585
|
+
is within them.
|
|
586
|
+
"""
|
|
587
|
+
limit = _RATING_LIMIT_TEXT
|
|
588
|
+
for name in ("min_rating", "max_rating", "default_rating"):
|
|
589
|
+
if not -_RATING_LIMIT <= getattr(self, name) <= _RATING_LIMIT:
|
|
590
|
+
raise ConfigError(f"{name} must be between -{limit} and {limit}")
|
|
591
|
+
if not self.min_rating < self.max_rating:
|
|
592
|
+
raise ConfigError("min_rating must be less than max_rating")
|
|
593
|
+
if not self.min_rating <= self.default_rating <= self.max_rating:
|
|
594
|
+
raise ConfigError("default_rating must be within rating bounds")
|
|
595
|
+
|
|
596
|
+
def _check_k_and_rd(self) -> None:
|
|
597
|
+
"""
|
|
598
|
+
Check the K and RD parameters.
|
|
599
|
+
|
|
600
|
+
In order: the K bounds, the RD bounds, rd_max against the rating
|
|
601
|
+
limit, the three starting RDs within the RD bounds,
|
|
602
|
+
rd_shrink_per_match, then rd_growth_per_day and its int limit.
|
|
603
|
+
"""
|
|
604
|
+
limit = _RATING_LIMIT_TEXT
|
|
605
|
+
if not 0 <= self.k_min <= self.k_max:
|
|
606
|
+
raise ConfigError("K-factor bounds are invalid")
|
|
607
|
+
# player_k and reliability divide by rd_max - rd_min as computed here,
|
|
608
|
+
# so an int and a float that differ only before conversion are equal.
|
|
609
|
+
if not (0 < self.rd_min < self.rd_max and self.rd_max - self.rd_min > 0):
|
|
610
|
+
raise ConfigError("RD bounds are invalid")
|
|
611
|
+
if self.rd_max > _RATING_LIMIT:
|
|
612
|
+
raise ConfigError(f"rd_max must be at most {limit}")
|
|
613
|
+
for name in ("new_player_rd", "external_seed_rd", "category_seed_rd"):
|
|
614
|
+
if not self.rd_min <= getattr(self, name) <= self.rd_max:
|
|
615
|
+
raise ConfigError(f"{name} must be within RD bounds")
|
|
616
|
+
if self.rd_shrink_per_match < 0:
|
|
617
|
+
raise ConfigError("rd_shrink_per_match must be at least 0")
|
|
618
|
+
if not 0 <= self.rd_growth_per_day <= _RATING_LIMIT:
|
|
619
|
+
raise ConfigError(f"rd_growth_per_day must be between 0 and {limit}")
|
|
620
|
+
# Exact int arithmetic raises where float arithmetic goes to inf, so an
|
|
621
|
+
# int gets a lower bound: rd_max**2 + growth**2 * _MAX_DAYS stays a float.
|
|
622
|
+
if isinstance(self.rd_growth_per_day, int) and self.rd_growth_per_day > _INT_GROWTH_LIMIT:
|
|
623
|
+
raise ConfigError(
|
|
624
|
+
f"rd_growth_per_day must be at most {_INT_GROWTH_LIMIT_TEXT} when it is an int"
|
|
625
|
+
)
|
|
626
|
+
|
|
627
|
+
def _check_step_size(self) -> None:
|
|
628
|
+
"""
|
|
629
|
+
Check the match performance and evidence weight parameters, and the largest step.
|
|
630
|
+
|
|
631
|
+
In order: win_weight, game_count_bonus and its int limit,
|
|
632
|
+
max_information_multiplier, then the largest step size as computed
|
|
633
|
+
in floats, then, for int weights, the exact int products the engine
|
|
634
|
+
forms (issue #93).
|
|
635
|
+
"""
|
|
636
|
+
if not 0.0 <= self.win_weight <= 1.0:
|
|
637
|
+
raise ConfigError("win_weight must be between 0 and 1")
|
|
638
|
+
if self.game_count_bonus < 0:
|
|
639
|
+
raise ConfigError("game_count_bonus must be at least 0")
|
|
640
|
+
# The same for an int bonus times a game count below 2**63.
|
|
641
|
+
if isinstance(self.game_count_bonus, int) and self.game_count_bonus > _INT_BONUS_LIMIT:
|
|
642
|
+
raise ConfigError(
|
|
643
|
+
f"game_count_bonus must be at most {_INT_BONUS_LIMIT_TEXT} when it is an int"
|
|
644
|
+
)
|
|
645
|
+
if self.max_information_multiplier < 1.0:
|
|
646
|
+
raise ConfigError("max_information_multiplier must be at least 1")
|
|
647
|
+
# The largest step size a match can reach. When it overflows to inf,
|
|
648
|
+
# a surprise of exactly 0 gives a NaN change. The largest K is what
|
|
649
|
+
# player_k returns at fraction 1.0, which can round above k_max. The
|
|
650
|
+
# first check bounds the step as computed in floats.
|
|
651
|
+
largest_k = _as_float(self.k_min + (self.k_max - self.k_min) * 1.0)
|
|
652
|
+
largest_weight = _as_float(max(self.match_weights.values())) * _as_float(
|
|
653
|
+
self.max_information_multiplier
|
|
654
|
+
)
|
|
655
|
+
k_message = (
|
|
656
|
+
"k_max times the largest match weight and max_information_multiplier must be finite"
|
|
657
|
+
)
|
|
658
|
+
if not math.isfinite(largest_k * largest_weight):
|
|
659
|
+
raise ConfigError(k_message)
|
|
660
|
+
# On a self-reported match the step weight is weight * factor**prior
|
|
661
|
+
# * information_multiplier. With an int weight, an int factor
|
|
662
|
+
# (factor**prior is then the int 1), and an int multiplier that
|
|
663
|
+
# information_multiplier returns, that product is an exact int.
|
|
664
|
+
# Converting it can raise OverflowError, or land above the float
|
|
665
|
+
# product checked above, and an int rd_shrink_per_match times
|
|
666
|
+
# it is another exact int. So form those products as the engine does
|
|
667
|
+
# (issue #93).
|
|
668
|
+
weight = self.match_weights[MatchType.SELF_REPORTED]
|
|
669
|
+
multiplier = self.max_information_multiplier
|
|
670
|
+
if (
|
|
671
|
+
isinstance(weight, int)
|
|
672
|
+
and isinstance(multiplier, int)
|
|
673
|
+
and isinstance(self.self_reported_repeat_factor, int)
|
|
674
|
+
and self._multiplier_reachable()
|
|
675
|
+
):
|
|
676
|
+
exact_weight = int.__int__(weight) * int.__int__(multiplier)
|
|
677
|
+
try:
|
|
678
|
+
step_weight = _as_float(exact_weight)
|
|
679
|
+
except OverflowError:
|
|
680
|
+
raise ConfigError(k_message) from None
|
|
681
|
+
if not math.isfinite(largest_k * step_weight):
|
|
682
|
+
raise ConfigError(k_message)
|
|
683
|
+
if isinstance(self.rd_shrink_per_match, int):
|
|
684
|
+
try:
|
|
685
|
+
_as_float(int.__int__(self.rd_shrink_per_match) * exact_weight)
|
|
686
|
+
except OverflowError:
|
|
687
|
+
raise ConfigError(
|
|
688
|
+
"rd_shrink_per_match times the largest match weight and "
|
|
689
|
+
"max_information_multiplier must be finite"
|
|
690
|
+
) from None
|
|
691
|
+
|
|
692
|
+
def _check_windows_and_counts(self) -> None:
|
|
693
|
+
"""
|
|
694
|
+
Check the day windows and match counts.
|
|
695
|
+
|
|
696
|
+
In order: replay_interval_days, the diversity settings, the
|
|
697
|
+
self-reported repeat factor and limits, the import reliability
|
|
698
|
+
limits, then every day field against the largest day count.
|
|
699
|
+
"""
|
|
700
|
+
if self.replay_interval_days <= 0:
|
|
701
|
+
raise ConfigError("replay_interval_days must be positive")
|
|
702
|
+
if self.diversity_window_days <= 0 or self.diversity_target <= 0:
|
|
703
|
+
raise ConfigError("diversity settings must be positive")
|
|
704
|
+
if not 0.0 < self.self_reported_repeat_factor <= 1.0:
|
|
705
|
+
raise ConfigError("self_reported_repeat_factor must be in (0, 1]")
|
|
706
|
+
if self.self_reported_max_repeats < 1 or self.self_reported_repeat_window_days <= 0:
|
|
707
|
+
raise ConfigError("self-reported repeat limits must be positive")
|
|
708
|
+
if self.import_reliability_carry_matches < 0 or self.import_reliability_max_age_days < 0:
|
|
709
|
+
raise ConfigError("import reliability limits must be nonnegative")
|
|
710
|
+
for name in _CONFIG_DAY_FIELDS:
|
|
711
|
+
if getattr(self, name) > _MAX_DAYS:
|
|
712
|
+
raise ConfigError(f"{name} must be at most {_MAX_DAYS}")
|
|
713
|
+
|
|
714
|
+
def _check_labels_and_filters(self) -> None:
|
|
715
|
+
"""
|
|
716
|
+
Check the reliability label and eligibility filter parameters.
|
|
717
|
+
|
|
718
|
+
In order: the established threshold and minimum, the connectivity
|
|
719
|
+
cap, the three connectivity minimums, then the two gap filters.
|
|
720
|
+
"""
|
|
721
|
+
if not 0.0 <= self.established_reliability_threshold <= 100.0:
|
|
722
|
+
raise ConfigError("established_reliability_threshold must be between 0 and 100")
|
|
723
|
+
if self.established_min_verified_matches < 0:
|
|
724
|
+
raise ConfigError("established_min_verified_matches must be a nonnegative int")
|
|
725
|
+
cap = self.connectivity_reliability_cap
|
|
726
|
+
if cap is not None and not 0.0 <= cap <= 100.0:
|
|
727
|
+
raise ConfigError("connectivity_reliability_cap must be None or a number from 0 to 100")
|
|
728
|
+
for name in (
|
|
729
|
+
"connectivity_min_shared_contacts",
|
|
730
|
+
"connectivity_min_contact_days",
|
|
731
|
+
"connectivity_min_outside_players",
|
|
732
|
+
):
|
|
733
|
+
if getattr(self, name) < 1:
|
|
734
|
+
raise ConfigError(f"{name} must be a positive int")
|
|
735
|
+
for name in ("max_singles_rating_gap", "max_doubles_partner_gap"):
|
|
736
|
+
gap = getattr(self, name)
|
|
737
|
+
if gap is not None and gap < 0:
|
|
738
|
+
raise ConfigError(f"{name} must be None or at least 0")
|
|
739
|
+
|
|
740
|
+
def _multiplier_reachable(self) -> bool:
|
|
741
|
+
"""
|
|
742
|
+
True when information_multiplier can return max_information_multiplier.
|
|
743
|
+
|
|
744
|
+
It returns the multiplier when length * count is not below it (min
|
|
745
|
+
keeps its first argument on a tie), for the length weight of an
|
|
746
|
+
allowed format (record rejects any other format first) and some game
|
|
747
|
+
count. count = 1.0 + game_count_bonus * (games - 1) never falls as
|
|
748
|
+
games grows, since the bonus is at least 0 and float rounding keeps
|
|
749
|
+
that order, so the largest game count decides. It converts: an int
|
|
750
|
+
bonus is at most 2**511. Computed on the plain values.
|
|
751
|
+
"""
|
|
752
|
+
|
|
753
|
+
def plain(value: float) -> float:
|
|
754
|
+
return int.__int__(value) if isinstance(value, int) else float.__float__(value)
|
|
755
|
+
|
|
756
|
+
multiplier = plain(self.max_information_multiplier)
|
|
757
|
+
count = 1.0 + plain(self.game_count_bonus) * (_MAX_GAME_COUNT - 1)
|
|
758
|
+
return any(
|
|
759
|
+
not plain(self.game_length_weights[points]) * count < multiplier
|
|
760
|
+
for _, points in sorted(self.allowed_game_formats)
|
|
761
|
+
)
|
|
762
|
+
|
|
763
|
+
def _payload(self) -> dict[str, object]:
|
|
764
|
+
"""Every parameter as fresh JSON-safe data: the input to fingerprint()."""
|
|
765
|
+
|
|
766
|
+
def norm(value: object) -> object:
|
|
767
|
+
if isinstance(value, Enum):
|
|
768
|
+
return value.value
|
|
769
|
+
if isinstance(value, Mapping):
|
|
770
|
+
return {str(norm(k)): norm(v) for k, v in value.items()}
|
|
771
|
+
if isinstance(value, (set, frozenset)):
|
|
772
|
+
return sorted((norm(v) for v in value), key=str)
|
|
773
|
+
if isinstance(value, tuple):
|
|
774
|
+
return [norm(v) for v in value]
|
|
775
|
+
return value
|
|
776
|
+
|
|
777
|
+
# The fields of Config itself: an instance __dataclass_fields__ or a
|
|
778
|
+
# subclass's extra fields never change the fingerprint (issue #107).
|
|
779
|
+
return {f.name: norm(getattr(self, f.name)) for f in fields(Config)}
|
|
780
|
+
|
|
781
|
+
def _canonical(self) -> str:
|
|
782
|
+
return json.dumps(self._payload(), sort_keys=True)
|
|
783
|
+
|
|
784
|
+
def fingerprint(self) -> str:
|
|
785
|
+
"""Stable hash of every field, both version labels included, stored with each replay."""
|
|
786
|
+
return hashlib.sha256(self._canonical().encode()).hexdigest()[:16]
|
|
787
|
+
|
|
788
|
+
def parameter_fingerprint(self) -> str:
|
|
789
|
+
"""
|
|
790
|
+
Stable hash of the parameter values alone, stored with each replay.
|
|
791
|
+
|
|
792
|
+
The same walk over every field as fingerprint(), without the two
|
|
793
|
+
version labels, version and params_version. So the same values under
|
|
794
|
+
another package version or params_version give the same parameter
|
|
795
|
+
fingerprint, and a change to any other field changes it. Adding,
|
|
796
|
+
removing, or renaming a field, or changing how a value is written
|
|
797
|
+
in the payload, changes it for every config. 16 lowercase hex
|
|
798
|
+
characters, like fingerprint().
|
|
799
|
+
"""
|
|
800
|
+
payload = self._payload()
|
|
801
|
+
for name in _CONFIG_LABEL_FIELDS:
|
|
802
|
+
del payload[name]
|
|
803
|
+
text = json.dumps(payload, sort_keys=True)
|
|
804
|
+
return hashlib.sha256(text.encode()).hexdigest()[:16]
|
|
805
|
+
|
|
806
|
+
def __eq__(self, other: object) -> bool:
|
|
807
|
+
if not isinstance(other, Config):
|
|
808
|
+
return NotImplemented
|
|
809
|
+
return self._canonical() == other._canonical()
|
|
810
|
+
|
|
811
|
+
def __hash__(self) -> int:
|
|
812
|
+
return hash(self._canonical())
|
|
813
|
+
|
|
814
|
+
def to_dict(self) -> dict[str, object]:
|
|
815
|
+
"""
|
|
816
|
+
Every parameter as a new dict of JSON data, for storage.
|
|
817
|
+
|
|
818
|
+
Enum keys and values become their string values, game length keys
|
|
819
|
+
become strings, and allowed_game_formats becomes a sorted list of
|
|
820
|
+
[scoring, points] pairs. Other values are passed through, so the
|
|
821
|
+
dict is plain JSON when every field has its documented type.
|
|
822
|
+
from_dict() turns it back into an equal Config with the same
|
|
823
|
+
fingerprint. A store that rewrites 8.0 as 8 changes the config: an
|
|
824
|
+
int and a float are different values to the fingerprint.
|
|
825
|
+
"""
|
|
826
|
+
return self._payload()
|
|
827
|
+
|
|
828
|
+
@classmethod
|
|
829
|
+
def from_dict(cls, data: Mapping[str, object]) -> Config:
|
|
830
|
+
"""
|
|
831
|
+
Build a Config from to_dict() output, also after a round trip through Python's json module.
|
|
832
|
+
|
|
833
|
+
Args:
|
|
834
|
+
data: Exactly a dict (json.loads gives one; another mapping type
|
|
835
|
+
raises) with exactly the keys to_dict() gives, so a stored config
|
|
836
|
+
names every parameter.
|
|
837
|
+
|
|
838
|
+
Returns:
|
|
839
|
+
The Config.
|
|
840
|
+
|
|
841
|
+
Raises:
|
|
842
|
+
ConfigError: data of another type, a missing or unknown key, a value
|
|
843
|
+
that cannot be converted, or a value Config rejects.
|
|
844
|
+
"""
|
|
845
|
+
# Exactly dict: a mapping type runs its own code on every read, so
|
|
846
|
+
# the checks below and Config could read different values.
|
|
847
|
+
if type(data) is not dict:
|
|
848
|
+
raise ConfigError(
|
|
849
|
+
f"Config data must be a mapping, exactly a dict, not {_type_name(data)}"
|
|
850
|
+
)
|
|
851
|
+
# Exactly str keys, checked before any set operation or lookup: a
|
|
852
|
+
# key type's own __hash__ and __eq__ would run in both.
|
|
853
|
+
odd = sorted({_type_name(key) for key in data if type(key) is not str})
|
|
854
|
+
if odd:
|
|
855
|
+
raise ConfigError(f"Config data has unknown keys: keys of type {', '.join(odd)}")
|
|
856
|
+
# The fields of Config itself, as to_dict() gives them.
|
|
857
|
+
names = [f.name for f in fields(Config)]
|
|
858
|
+
missing = sorted(set(names) - set(data))
|
|
859
|
+
if missing:
|
|
860
|
+
raise ConfigError(f"Config data has missing keys: {', '.join(missing)}")
|
|
861
|
+
unknown = sorted(_shown(key, str) for key in set(data) - set(names))
|
|
862
|
+
if unknown:
|
|
863
|
+
raise ConfigError(f"Config data has unknown keys: {', '.join(unknown)}")
|
|
864
|
+
values = {name: data[name] for name in names}
|
|
865
|
+
values["scale_by_scoring"] = _enum_keyed(
|
|
866
|
+
values["scale_by_scoring"], ScoringType, "scale_by_scoring"
|
|
867
|
+
)
|
|
868
|
+
values["win_calibration_by_scoring"] = _enum_keyed(
|
|
869
|
+
values["win_calibration_by_scoring"], ScoringType, "win_calibration_by_scoring"
|
|
870
|
+
)
|
|
871
|
+
values["match_weights"] = _enum_keyed(values["match_weights"], MatchType, "match_weights")
|
|
872
|
+
values["game_length_weights"] = _int_keyed(values["game_length_weights"])
|
|
873
|
+
values["allowed_game_formats"] = _game_formats(values["allowed_game_formats"])
|
|
874
|
+
try:
|
|
875
|
+
return cls(**values)
|
|
876
|
+
except TypeError as exc:
|
|
877
|
+
raise ConfigError(f"Config data has a value of the wrong type: {exc}") from exc
|
|
878
|
+
|
|
879
|
+
@classmethod
|
|
880
|
+
def from_parameter_set(cls, data: Mapping[str, object]) -> Config:
|
|
881
|
+
"""
|
|
882
|
+
Load a published parameter set from the parsed JSON of its file.
|
|
883
|
+
|
|
884
|
+
The files are src/open_engine/params/v<N>.json, shipped in the
|
|
885
|
+
package; published() reads one and calls this. The label must name
|
|
886
|
+
a set this release publishes, the recorded fingerprint must be the
|
|
887
|
+
one published for it, and the values must hash to it, so a file
|
|
888
|
+
cannot pass other values off as a published set or relabel one. A
|
|
889
|
+
new set needs an engine release that adds it. This method reads no
|
|
890
|
+
file: pass json.loads output. Other keys are allowed and not read.
|
|
891
|
+
|
|
892
|
+
Args:
|
|
893
|
+
data: Exactly a dict with exactly str keys, holding
|
|
894
|
+
params_version (v<N>), parameter_fingerprint, and parameters
|
|
895
|
+
(to_dict() output without version and params_version).
|
|
896
|
+
|
|
897
|
+
Returns:
|
|
898
|
+
The Config, with version the running package version and
|
|
899
|
+
params_version the file's label.
|
|
900
|
+
|
|
901
|
+
Raises:
|
|
902
|
+
ConfigError: in this order, data not exactly a dict; a key not
|
|
903
|
+
exactly a str; a missing required key; a params_version, then
|
|
904
|
+
parameter_fingerprint, not exactly a str; parameters not
|
|
905
|
+
exactly a dict, with a key not exactly a str, or holding a
|
|
906
|
+
label; a fingerprint not 16 lowercase hex characters; a label
|
|
907
|
+
not v<N>; a label this release does not publish; a fingerprint
|
|
908
|
+
not the published one; a from_dict() failure; and values that
|
|
909
|
+
do not hash to the fingerprint. See docs/behavior.md, "Config
|
|
910
|
+
validation".
|
|
911
|
+
"""
|
|
912
|
+
# Exactly dict and exactly str keys, as in from_dict(), checked
|
|
913
|
+
# before any lookup so no caller code runs.
|
|
914
|
+
if type(data) is not dict:
|
|
915
|
+
raise ConfigError(
|
|
916
|
+
f"Parameter set must be a mapping, exactly a dict, not {_type_name(data)}"
|
|
917
|
+
)
|
|
918
|
+
odd = sorted({_type_name(key) for key in data if type(key) is not str})
|
|
919
|
+
if odd:
|
|
920
|
+
raise ConfigError(f"Parameter set has unknown keys: keys of type {', '.join(odd)}")
|
|
921
|
+
missing = sorted(set(_PARAMETER_SET_KEYS) - set(data))
|
|
922
|
+
if missing:
|
|
923
|
+
raise ConfigError(f"Parameter set has missing keys: {', '.join(missing)}")
|
|
924
|
+
label = data["params_version"]
|
|
925
|
+
recorded = data["parameter_fingerprint"]
|
|
926
|
+
params = data["parameters"]
|
|
927
|
+
# A None label would load as an unlabelled config, so the label
|
|
928
|
+
# must be a str here, not only None or a str as Config allows.
|
|
929
|
+
for name, value in (("params_version", label), ("parameter_fingerprint", recorded)):
|
|
930
|
+
if type(value) is not str:
|
|
931
|
+
raise ConfigError(
|
|
932
|
+
f"Parameter set {name} must be exactly a str, not {_type_name(value)}"
|
|
933
|
+
)
|
|
934
|
+
if type(params) is not dict:
|
|
935
|
+
raise ConfigError(
|
|
936
|
+
f"Parameter set parameters must be exactly a dict, not {_type_name(params)}"
|
|
937
|
+
)
|
|
938
|
+
odd = sorted({_type_name(key) for key in params if type(key) is not str})
|
|
939
|
+
if odd:
|
|
940
|
+
raise ConfigError(
|
|
941
|
+
f"Parameter set parameters has unknown keys: keys of type {', '.join(odd)}"
|
|
942
|
+
)
|
|
943
|
+
# The labels come from the file's own params_version and the running
|
|
944
|
+
# package, never from the values.
|
|
945
|
+
smuggled = sorted(name for name in _CONFIG_LABEL_FIELDS if name in params)
|
|
946
|
+
if smuggled:
|
|
947
|
+
raise ConfigError(
|
|
948
|
+
f"Parameter set parameters must not hold {', '.join(smuggled)}:"
|
|
949
|
+
" the labels come from params_version and the running package"
|
|
950
|
+
)
|
|
951
|
+
# Both passed the exact str check above.
|
|
952
|
+
label = cast(str, label)
|
|
953
|
+
recorded = cast(str, recorded)
|
|
954
|
+
# Neither str is echoed until it has passed its form check, so a
|
|
955
|
+
# message never grows with the caller's input.
|
|
956
|
+
if _FINGERPRINT_FORM.fullmatch(recorded) is None:
|
|
957
|
+
raise ConfigError(
|
|
958
|
+
"Parameter set parameter_fingerprint must be exactly 16 lowercase hex characters"
|
|
959
|
+
)
|
|
960
|
+
if _PARAMS_VERSION.fullmatch(label) is None:
|
|
961
|
+
raise ConfigError(
|
|
962
|
+
"Parameter set params_version must be v<N>, with N a positive whole"
|
|
963
|
+
" number and no leading zero, such as v1"
|
|
964
|
+
)
|
|
965
|
+
published = dict(_PUBLISHED_PARAMETER_SETS).get(label)
|
|
966
|
+
if published is None:
|
|
967
|
+
raise ConfigError(
|
|
968
|
+
"Parameter set params_version is not a parameter set this release publishes"
|
|
969
|
+
f" (it publishes {', '.join(name for name, _ in _PUBLISHED_PARAMETER_SETS)})"
|
|
970
|
+
)
|
|
971
|
+
if recorded != published:
|
|
972
|
+
raise ConfigError(
|
|
973
|
+
f"Parameter set {label} parameter_fingerprint {recorded!r} differs from"
|
|
974
|
+
f" the published {published!r}"
|
|
975
|
+
)
|
|
976
|
+
cfg = cls.from_dict({**params, "version": __version__, "params_version": label})
|
|
977
|
+
computed = cfg.parameter_fingerprint()
|
|
978
|
+
if computed != recorded:
|
|
979
|
+
raise ConfigError(
|
|
980
|
+
f"Parameter set {label} parameter_fingerprint {recorded!r} does not match"
|
|
981
|
+
f" its values, which hash to {computed!r}"
|
|
982
|
+
)
|
|
983
|
+
return cfg
|
|
984
|
+
|
|
985
|
+
@classmethod
|
|
986
|
+
def published(cls, label: str) -> Config:
|
|
987
|
+
"""
|
|
988
|
+
Load a parameter set this release publishes, from the package.
|
|
989
|
+
|
|
990
|
+
Reads open_engine/params/<label>.json, which the wheel ships, and
|
|
991
|
+
passes its parsed JSON to from_parameter_set(), so the packaged file
|
|
992
|
+
gets the same label and fingerprint checks. published_sets() lists
|
|
993
|
+
the labels.
|
|
994
|
+
|
|
995
|
+
Args:
|
|
996
|
+
label: Exactly a str, a label in published_sets(), such as "v1".
|
|
997
|
+
|
|
998
|
+
Returns:
|
|
999
|
+
The Config, as from_parameter_set() returns it: version the
|
|
1000
|
+
running package version and params_version the label.
|
|
1001
|
+
|
|
1002
|
+
Raises:
|
|
1003
|
+
ConfigError: in this order, label not exactly a str; a label
|
|
1004
|
+
this release does not publish (the message names the ones it
|
|
1005
|
+
does and not the label); a packaged file that is missing,
|
|
1006
|
+
unreadable, or not JSON; and any from_parameter_set() failure.
|
|
1007
|
+
"""
|
|
1008
|
+
if type(label) is not str:
|
|
1009
|
+
raise ConfigError(f"Parameter set label must be exactly a str, not {_type_name(label)}")
|
|
1010
|
+
# Only a label from the table names a file, so no caller string
|
|
1011
|
+
# reaches a path, and the message never grows with the input.
|
|
1012
|
+
if label not in dict(_PUBLISHED_PARAMETER_SETS):
|
|
1013
|
+
raise ConfigError(
|
|
1014
|
+
"Parameter set label is not a parameter set this release publishes"
|
|
1015
|
+
f" (it publishes {', '.join(cls.published_sets())})"
|
|
1016
|
+
)
|
|
1017
|
+
try:
|
|
1018
|
+
data = json.loads(_packaged_parameter_set_text(label))
|
|
1019
|
+
except (OSError, ValueError, RecursionError) as exc:
|
|
1020
|
+
raise ConfigError(
|
|
1021
|
+
f"Parameter set {label} could not be read from the installed package: {exc}"
|
|
1022
|
+
) from exc
|
|
1023
|
+
return cls.from_parameter_set(data)
|
|
1024
|
+
|
|
1025
|
+
@classmethod
|
|
1026
|
+
def published_sets(cls) -> tuple[str, ...]:
|
|
1027
|
+
"""
|
|
1028
|
+
The labels of the parameter sets this release publishes, in label order.
|
|
1029
|
+
|
|
1030
|
+
Each one loads with published(). The tuple is the same on every call
|
|
1031
|
+
within a release.
|
|
1032
|
+
"""
|
|
1033
|
+
return tuple(label for label, _ in _PUBLISHED_PARAMETER_SETS)
|
|
1034
|
+
|
|
1035
|
+
|
|
1036
|
+
def _packaged_parameter_set_text(label: str) -> str:
|
|
1037
|
+
"""The text of the packaged file for a published label, read as UTF-8."""
|
|
1038
|
+
resource = importlib.resources.files(_PACKAGE) / _PARAMS_DIRECTORY / f"{label}.json"
|
|
1039
|
+
return resource.read_text(encoding="utf-8")
|
|
1040
|
+
|
|
1041
|
+
|
|
1042
|
+
# The package that ships the parameter set files, and their directory in it.
|
|
1043
|
+
_PACKAGE = "open_engine"
|
|
1044
|
+
_PARAMS_DIRECTORY = "params"
|
|
1045
|
+
# The keys from_parameter_set() reads from a parameter set.
|
|
1046
|
+
_PARAMETER_SET_KEYS = ("params_version", "parameter_fingerprint", "parameters")
|
|
1047
|
+
# The form of a parameter_fingerprint(): 16 lowercase hex characters.
|
|
1048
|
+
_FINGERPRINT_FORM = re.compile(r"[0-9a-f]{16}")
|
|
1049
|
+
# The parameter sets this release publishes, as (params_version,
|
|
1050
|
+
# parameter_fingerprint) pairs in label order. A new set is published by
|
|
1051
|
+
# adding its file under src/open_engine/params/, its PARAMETERS.md entry,
|
|
1052
|
+
# its path in PACKAGE_FILES in scripts/check_wheel.py, and its pair here,
|
|
1053
|
+
# in one release. tests/test_parameter_set_binding.py checks that this
|
|
1054
|
+
# table and the packaged files match.
|
|
1055
|
+
_PUBLISHED_PARAMETER_SETS: tuple[tuple[str, str], ...] = (("v1", "f9149f3c38a01efc"),)
|
|
1056
|
+
|
|
1057
|
+
_CONFIG_FIELD_NAMES = frozenset(f.name for f in fields(Config))
|
|
1058
|
+
|
|
1059
|
+
|
|
1060
|
+
def _config_enum_key(key: object, kind: type[Enum], name: str) -> Enum | None:
|
|
1061
|
+
"""
|
|
1062
|
+
A Config enum mapping key as its member, read once; None for an unknown plain str.
|
|
1063
|
+
|
|
1064
|
+
A member stays as it is, and an exact str converts by value. A str
|
|
1065
|
+
subclass, or an object of kind's type that is not a member, raises
|
|
1066
|
+
ConfigError before anything hashes it: its own __hash__ and __eq__
|
|
1067
|
+
could answer differently on each call. Any other key gives None, which
|
|
1068
|
+
the caller reports as a missing member.
|
|
1069
|
+
"""
|
|
1070
|
+
if _is_member(key, kind):
|
|
1071
|
+
return cast(Enum, key)
|
|
1072
|
+
if type(key) is kind:
|
|
1073
|
+
raise ConfigError(f"{name} has a {kind.__name__} key that is not a member")
|
|
1074
|
+
if type(key) is str:
|
|
1075
|
+
values = {member.value: member for member in kind}
|
|
1076
|
+
return values.get(key)
|
|
1077
|
+
if isinstance(key, str):
|
|
1078
|
+
raise ConfigError(f"{name} has an unknown key")
|
|
1079
|
+
return None
|
|
1080
|
+
|
|
1081
|
+
|
|
1082
|
+
def _require_config(cfg: object) -> Config:
|
|
1083
|
+
"""
|
|
1084
|
+
A rebuilt copy of cfg when it is exactly a Config with only its fields.
|
|
1085
|
+
|
|
1086
|
+
Raises ConfigError otherwise, or when the rebuild does (see
|
|
1087
|
+
_rebuilt_config). An entry point that drains a caller iterable calls it
|
|
1088
|
+
only after it has read matches and seed_players (issue #122), with
|
|
1089
|
+
_config_shape as its early check.
|
|
1090
|
+
"""
|
|
1091
|
+
return _rebuilt_config(_config_shape_checked(cfg))
|
|
1092
|
+
|
|
1093
|
+
|
|
1094
|
+
def _config_shape(cfg: object) -> Config | None:
|
|
1095
|
+
"""None for None, else cfg after the type and field checks, not rebuilt."""
|
|
1096
|
+
return None if cfg is None else _config_shape_checked(cfg)
|
|
1097
|
+
|
|
1098
|
+
|
|
1099
|
+
def _config_shape_checked(cfg: object) -> Config:
|
|
1100
|
+
"""
|
|
1101
|
+
cfg when it is exactly a Config with only its fields; ConfigError otherwise.
|
|
1102
|
+
|
|
1103
|
+
A subclass can run its own methods: store a value after __post_init__
|
|
1104
|
+
made every number plain, or override fingerprint, _payload, or __eq__
|
|
1105
|
+
(issue #118). An exact Config must also hold nothing in its instance
|
|
1106
|
+
__dict__ but its own fields: another entry there could hide
|
|
1107
|
+
fingerprint, _payload, or the field list (__dataclass_fields__).
|
|
1108
|
+
"""
|
|
1109
|
+
if type(cfg) is not Config:
|
|
1110
|
+
raise ConfigError(f"cfg must be exactly a Config, not {_type_name(cfg)}")
|
|
1111
|
+
held = vars(cfg)
|
|
1112
|
+
# An exact dict, so __len__ and __iter__ cannot hide an entry.
|
|
1113
|
+
if (
|
|
1114
|
+
type(held) is not dict
|
|
1115
|
+
or len(held) != len(_CONFIG_FIELD_NAMES)
|
|
1116
|
+
or not all(type(name) is str and name in _CONFIG_FIELD_NAMES for name in held)
|
|
1117
|
+
):
|
|
1118
|
+
raise ConfigError("cfg has attributes that are not Config fields")
|
|
1119
|
+
return cfg
|
|
1120
|
+
|
|
1121
|
+
|
|
1122
|
+
# The _data slot of _FrozenMapping, read without calling any method of the
|
|
1123
|
+
# object that holds it (issue #122).
|
|
1124
|
+
_FROZEN_DATA = cast(MemberDescriptorType, vars(_FrozenMapping)["_data"])
|
|
1125
|
+
|
|
1126
|
+
|
|
1127
|
+
# The enum each enum-keyed Config mapping field is keyed by.
|
|
1128
|
+
_CONFIG_ENUM_KEYS: dict[str, type[Enum]] = {
|
|
1129
|
+
"scale_by_scoring": ScoringType,
|
|
1130
|
+
"win_calibration_by_scoring": ScoringType,
|
|
1131
|
+
"match_weights": MatchType,
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1134
|
+
|
|
1135
|
+
def _leaf_value(name: str, value: object) -> object:
|
|
1136
|
+
"""
|
|
1137
|
+
One stored Config leaf as a plain value, judged by its real type alone.
|
|
1138
|
+
|
|
1139
|
+
An exact bool, an exact str, and None are kept; a real int or float
|
|
1140
|
+
subclass becomes the plain int or float of its own value. Anything else
|
|
1141
|
+
raises ConfigError. Only type(), issubclass(), and int's and float's own
|
|
1142
|
+
methods run, so no caller code does (issue #122). Config(...) then
|
|
1143
|
+
checks the plain value as it checks a constructor argument.
|
|
1144
|
+
"""
|
|
1145
|
+
real = type(value)
|
|
1146
|
+
if real is bool or real is str or value is None:
|
|
1147
|
+
return value
|
|
1148
|
+
if issubclass(real, int):
|
|
1149
|
+
return int.__int__(cast(int, value))
|
|
1150
|
+
if issubclass(real, float):
|
|
1151
|
+
return float.__float__(cast(float, value))
|
|
1152
|
+
raise ConfigError(f"cfg.{name} must hold a plain value, not {_type_name(value)}")
|
|
1153
|
+
|
|
1154
|
+
|
|
1155
|
+
def _leaf_member(name: str, value: object, kind: type[Enum]) -> object:
|
|
1156
|
+
"""
|
|
1157
|
+
A stored enum key or scoring entry: a member by identity, or an exact str.
|
|
1158
|
+
|
|
1159
|
+
An exact str naming a member becomes that member; any other exact str
|
|
1160
|
+
is kept for Config(...) to reject. Anything else raises ConfigError
|
|
1161
|
+
without running its code.
|
|
1162
|
+
"""
|
|
1163
|
+
if _is_member(value, kind):
|
|
1164
|
+
return value
|
|
1165
|
+
if type(value) is str:
|
|
1166
|
+
return {member.value: member for member in kind}.get(value, value)
|
|
1167
|
+
raise ConfigError(f"cfg.{name} has a key or entry of type {_type_name(value)}")
|
|
1168
|
+
|
|
1169
|
+
|
|
1170
|
+
def _leaf_whole(name: str, value: object) -> int:
|
|
1171
|
+
"""A stored game length key or format points: a real int, not a bool, as a plain int."""
|
|
1172
|
+
real = type(value)
|
|
1173
|
+
if real is bool or not issubclass(real, int):
|
|
1174
|
+
raise ConfigError(f"cfg.{name} must hold whole numbers, not {_type_name(value)}")
|
|
1175
|
+
return int.__int__(cast(int, value))
|
|
1176
|
+
|
|
1177
|
+
|
|
1178
|
+
def _rebuilt_config(cfg: Config) -> Config:
|
|
1179
|
+
"""
|
|
1180
|
+
A fresh Config built from cfg's stored field values (issue #122).
|
|
1181
|
+
|
|
1182
|
+
cfg passed _require_config, so its instance __dict__ is an exact dict
|
|
1183
|
+
holding exactly its fields. object.__setattr__ can still rewrite a
|
|
1184
|
+
field after __post_init__ checked it, so every field value goes through
|
|
1185
|
+
Config(...) again: every check and the plain-value conversion (#107)
|
|
1186
|
+
run on it. First every leaf becomes a plain value by its real type
|
|
1187
|
+
alone (_leaf_value, _leaf_member, _leaf_whole), so no caller code runs
|
|
1188
|
+
here or in Config(...). A mapping field must hold exactly a dict, or
|
|
1189
|
+
exactly a _FrozenMapping whose _data slot holds exactly a dict, read
|
|
1190
|
+
through the slot descriptor; its keys are enum members or exact strs
|
|
1191
|
+
(game length keys real ints), and two keys that become one raise.
|
|
1192
|
+
allowed_game_formats must be exactly a frozenset or set of real tuple
|
|
1193
|
+
entries, read through tuple's own methods. Anything else raises
|
|
1194
|
+
ConfigError. The result shares nothing with cfg.
|
|
1195
|
+
"""
|
|
1196
|
+
held = vars(cfg)
|
|
1197
|
+
values: dict[str, object] = {}
|
|
1198
|
+
for f in fields(Config):
|
|
1199
|
+
name = f.name
|
|
1200
|
+
value = held[name]
|
|
1201
|
+
if name in _CONFIG_MAPPING_FIELDS:
|
|
1202
|
+
values[name] = _rebuilt_mapping(name, value)
|
|
1203
|
+
elif name == "allowed_game_formats":
|
|
1204
|
+
values[name] = _rebuilt_formats(value)
|
|
1205
|
+
else:
|
|
1206
|
+
values[name] = _leaf_value(name, value)
|
|
1207
|
+
try:
|
|
1208
|
+
return Config(**values) # type: ignore[arg-type]
|
|
1209
|
+
except TypeError as exc:
|
|
1210
|
+
raise ConfigError(f"cfg has a value of the wrong type: {exc}") from exc
|
|
1211
|
+
|
|
1212
|
+
|
|
1213
|
+
def _rebuilt_mapping(name: str, value: object) -> dict[object, object]:
|
|
1214
|
+
"""A stored Config mapping field as a new dict of plain keys and values."""
|
|
1215
|
+
if type(value) is _FrozenMapping:
|
|
1216
|
+
try:
|
|
1217
|
+
value = _FROZEN_DATA.__get__(value, _FrozenMapping)
|
|
1218
|
+
except AttributeError:
|
|
1219
|
+
raise ConfigError(f"cfg.{name} has no stored mapping") from None
|
|
1220
|
+
if type(value) is not dict:
|
|
1221
|
+
raise ConfigError(f"cfg.{name} must hold exactly a dict, not {_type_name(value)}")
|
|
1222
|
+
kind = _CONFIG_ENUM_KEYS.get(name)
|
|
1223
|
+
rebuilt: dict[object, object] = {}
|
|
1224
|
+
# dict.items of an exact dict reads no key or value method.
|
|
1225
|
+
for key, item in dict.items(cast("dict[object, object]", value)):
|
|
1226
|
+
plain = _leaf_whole(name, key) if kind is None else _leaf_member(name, key, kind)
|
|
1227
|
+
if plain in rebuilt:
|
|
1228
|
+
raise ConfigError(f"cfg.{name} repeats a key")
|
|
1229
|
+
rebuilt[plain] = _leaf_value(name, item)
|
|
1230
|
+
return rebuilt
|
|
1231
|
+
|
|
1232
|
+
|
|
1233
|
+
def _rebuilt_formats(value: object) -> frozenset[tuple[object, int]]:
|
|
1234
|
+
"""The stored allowed_game_formats as a new frozenset of plain pairs."""
|
|
1235
|
+
name = "allowed_game_formats"
|
|
1236
|
+
if type(value) is not frozenset and type(value) is not set:
|
|
1237
|
+
raise ConfigError(f"cfg.{name} must be exactly a frozenset or set, not {_type_name(value)}")
|
|
1238
|
+
rebuilt: set[tuple[object, int]] = set()
|
|
1239
|
+
problems: list[str] = []
|
|
1240
|
+
# Iterating an exact set or frozenset calls no method of its entries.
|
|
1241
|
+
# Every entry is checked, and the first problem in sorted order is
|
|
1242
|
+
# raised, so the message does not depend on set order (issue #145).
|
|
1243
|
+
for entry in cast("set[object]", value):
|
|
1244
|
+
try:
|
|
1245
|
+
rebuilt.add(_rebuilt_format(entry))
|
|
1246
|
+
except ConfigError as exc:
|
|
1247
|
+
problems.append(str(exc))
|
|
1248
|
+
if problems:
|
|
1249
|
+
raise ConfigError(min(problems))
|
|
1250
|
+
return frozenset(rebuilt)
|
|
1251
|
+
|
|
1252
|
+
|
|
1253
|
+
def _rebuilt_format(entry: object) -> tuple[object, int]:
|
|
1254
|
+
"""One stored allowed_game_formats entry as a plain pair, by its real types alone."""
|
|
1255
|
+
name = "allowed_game_formats"
|
|
1256
|
+
if not (issubclass(type(entry), tuple) and tuple.__len__(cast(tuple[object], entry)) == 2):
|
|
1257
|
+
raise ConfigError(f"cfg.{name} entries must be pairs, not {_type_name(entry)}")
|
|
1258
|
+
pair = cast(tuple[object, object], entry)
|
|
1259
|
+
scoring = _leaf_member(name, tuple.__getitem__(pair, 0), ScoringType)
|
|
1260
|
+
points = _leaf_whole(name, tuple.__getitem__(pair, 1))
|
|
1261
|
+
if type(scoring) is str:
|
|
1262
|
+
raise ConfigError(f"cfg.{name} has an unknown scoring type")
|
|
1263
|
+
return (scoring, points)
|
|
1264
|
+
|
|
1265
|
+
|
|
1266
|
+
def _config_or_default(cfg: object) -> Config:
|
|
1267
|
+
"""Config() for None, else cfg checked by _require_config."""
|
|
1268
|
+
return Config() if cfg is None else _require_config(cfg)
|
|
1269
|
+
|
|
1270
|
+
|
|
1271
|
+
_E = TypeVar("_E", bound=Enum)
|
|
1272
|
+
|
|
1273
|
+
|
|
1274
|
+
def _enum_keyed(value: object, kind: type[_E], name: str) -> dict[_E, object]:
|
|
1275
|
+
"""
|
|
1276
|
+
A from_dict enum mapping with member keys.
|
|
1277
|
+
|
|
1278
|
+
The mapping must be exactly a dict whose keys are members or exact
|
|
1279
|
+
strs, checked before anything hashes a key or calls its methods.
|
|
1280
|
+
"""
|
|
1281
|
+
if type(value) is not dict:
|
|
1282
|
+
raise ConfigError(f"{name} must be a mapping")
|
|
1283
|
+
out: dict[_E, object] = {}
|
|
1284
|
+
for key, item in value.items():
|
|
1285
|
+
if _is_member(key, kind):
|
|
1286
|
+
out[cast(_E, key)] = item
|
|
1287
|
+
continue
|
|
1288
|
+
if type(key) is not str:
|
|
1289
|
+
raise ConfigError(f"{name} has an unknown key: {_shown(key)}")
|
|
1290
|
+
try:
|
|
1291
|
+
out[kind(key)] = item
|
|
1292
|
+
except ValueError as exc:
|
|
1293
|
+
raise ConfigError(f"{name} has an unknown key: {_shown(key)}") from exc
|
|
1294
|
+
return out
|
|
1295
|
+
|
|
1296
|
+
|
|
1297
|
+
def _shown(value: object, show: Callable[[object], str] = repr) -> str:
|
|
1298
|
+
"""
|
|
1299
|
+
value for an error message, without running caller code.
|
|
1300
|
+
|
|
1301
|
+
An exact str, int, float, bool, or None is shown with show (repr by
|
|
1302
|
+
default), and an exact list or tuple of those by repr; anything else by
|
|
1303
|
+
its type name. An int over the int-to-str limit cannot print.
|
|
1304
|
+
"""
|
|
1305
|
+
plain = (str, int, float, bool, type(None))
|
|
1306
|
+
if _type_is(value, list, tuple) and all(_type_is(item, *plain) for item in value): # type: ignore[attr-defined]
|
|
1307
|
+
show = repr
|
|
1308
|
+
elif not _type_is(value, *plain):
|
|
1309
|
+
return _type_name(value)
|
|
1310
|
+
try:
|
|
1311
|
+
return show(value)
|
|
1312
|
+
except ValueError:
|
|
1313
|
+
return "a value too large to show"
|
|
1314
|
+
|
|
1315
|
+
|
|
1316
|
+
def _int_keyed(value: object) -> dict[int, object]:
|
|
1317
|
+
"""
|
|
1318
|
+
game_length_weights from from_dict, with int keys.
|
|
1319
|
+
|
|
1320
|
+
The mapping must be exactly a dict, and each key exactly an int (not a
|
|
1321
|
+
bool) or exactly a str of ASCII digits, checked before anything hashes
|
|
1322
|
+
a key or calls its methods.
|
|
1323
|
+
"""
|
|
1324
|
+
if type(value) is not dict:
|
|
1325
|
+
raise ConfigError("game_length_weights must be a mapping")
|
|
1326
|
+
out: dict[int, object] = {}
|
|
1327
|
+
for key, item in value.items():
|
|
1328
|
+
if type(key) is int:
|
|
1329
|
+
points = key
|
|
1330
|
+
elif type(key) is str and key.isascii() and key.isdigit():
|
|
1331
|
+
try:
|
|
1332
|
+
points = int(key)
|
|
1333
|
+
except ValueError as exc: # more digits than int() converts
|
|
1334
|
+
raise ConfigError(
|
|
1335
|
+
f"game_length_weights has a key that is not a whole number: {_shown(key)}"
|
|
1336
|
+
) from exc
|
|
1337
|
+
else:
|
|
1338
|
+
raise ConfigError(
|
|
1339
|
+
f"game_length_weights has a key that is not a whole number: {_shown(key)}"
|
|
1340
|
+
)
|
|
1341
|
+
if points in out:
|
|
1342
|
+
raise ConfigError(f"game_length_weights repeats the game length {points}")
|
|
1343
|
+
out[points] = item
|
|
1344
|
+
return out
|
|
1345
|
+
|
|
1346
|
+
|
|
1347
|
+
def _game_formats(value: object) -> frozenset[tuple[ScoringType, int]]:
|
|
1348
|
+
"""
|
|
1349
|
+
allowed_game_formats from from_dict.
|
|
1350
|
+
|
|
1351
|
+
It must be exactly a list or tuple of entries that are each exactly a
|
|
1352
|
+
list or tuple of two: a ScoringType member or an exact str, and exactly
|
|
1353
|
+
an int (not a bool).
|
|
1354
|
+
"""
|
|
1355
|
+
if type(value) is not list and type(value) is not tuple:
|
|
1356
|
+
raise ConfigError("allowed_game_formats must be a list of [scoring, points] pairs")
|
|
1357
|
+
out: set[tuple[ScoringType, int]] = set()
|
|
1358
|
+
for item in value:
|
|
1359
|
+
if (type(item) is not list and type(item) is not tuple) or len(item) != 2:
|
|
1360
|
+
raise ConfigError(
|
|
1361
|
+
f"allowed_game_formats has an entry that is not a pair: {_shown(item)}"
|
|
1362
|
+
)
|
|
1363
|
+
scoring, points = item
|
|
1364
|
+
if type(points) is not int:
|
|
1365
|
+
raise ConfigError(
|
|
1366
|
+
f"allowed_game_formats has points that are not a whole number: {_shown(item)}"
|
|
1367
|
+
)
|
|
1368
|
+
if _is_member(scoring, ScoringType):
|
|
1369
|
+
out.add((cast(ScoringType, scoring), points))
|
|
1370
|
+
continue
|
|
1371
|
+
if type(scoring) is not str:
|
|
1372
|
+
raise ConfigError(f"allowed_game_formats has an unknown scoring type: {_shown(item)}")
|
|
1373
|
+
try:
|
|
1374
|
+
out.add((ScoringType(scoring), points))
|
|
1375
|
+
except ValueError as exc:
|
|
1376
|
+
raise ConfigError(
|
|
1377
|
+
f"allowed_game_formats has an unknown scoring type: {_shown(item)}"
|
|
1378
|
+
) from exc
|
|
1379
|
+
return frozenset(out)
|