localarena 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.
localarena/__init__.py ADDED
@@ -0,0 +1,25 @@
1
+ """A deterministic, zero-dependency Elo arena."""
2
+
3
+ from .core import (
4
+ SCHEMA_VERSION,
5
+ Arena,
6
+ Contestant,
7
+ Match,
8
+ Result,
9
+ Standing,
10
+ expected_score,
11
+ round_robin,
12
+ )
13
+
14
+ __all__ = [
15
+ "SCHEMA_VERSION",
16
+ "Arena",
17
+ "Contestant",
18
+ "Match",
19
+ "Result",
20
+ "Standing",
21
+ "expected_score",
22
+ "round_robin",
23
+ ]
24
+
25
+ __version__ = "0.1.0"
localarena/core.py ADDED
@@ -0,0 +1,770 @@
1
+ """Core data structures and Elo logic for :mod:`localarena`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ from collections.abc import Iterable, Iterator, Mapping
8
+ from dataclasses import dataclass, field
9
+ from enum import Enum
10
+ from itertools import combinations
11
+ from types import MappingProxyType
12
+ from typing import Any
13
+
14
+ SCHEMA_VERSION = 1
15
+ _MAX_SAFE_INTEGER = (1 << 53) - 1
16
+ _MAX_METADATA_DEPTH = 100
17
+
18
+
19
+ class Result(str, Enum):
20
+ """The outcome of a match, expressed relative to its two sides."""
21
+
22
+ LEFT = "left"
23
+ RIGHT = "right"
24
+ DRAW = "draw"
25
+
26
+ def __str__(self) -> str:
27
+ return self.value
28
+
29
+
30
+ class _FrozenDict(Mapping[str, object]):
31
+ """A recursively immutable mapping used by public records."""
32
+
33
+ __slots__ = ("__data",)
34
+
35
+ def __init__(self, data: Mapping[str, object]) -> None:
36
+ object.__setattr__(
37
+ self,
38
+ "_FrozenDict__data",
39
+ MappingProxyType(dict(data)),
40
+ )
41
+
42
+ def __getitem__(self, key: str) -> object:
43
+ return self.__data[key]
44
+
45
+ def __iter__(self) -> Iterator[str]:
46
+ return iter(self.__data)
47
+
48
+ def __len__(self) -> int:
49
+ return len(self.__data)
50
+
51
+ def __repr__(self) -> str:
52
+ return repr(self.__data)
53
+
54
+ def __setattr__(self, name: str, value: object) -> None:
55
+ raise TypeError("metadata is immutable")
56
+
57
+ def __deepcopy__(self, memo: dict[int, object]) -> _FrozenDict:
58
+ return self
59
+
60
+
61
+ def _validate_name(name: object, *, field_name: str = "name") -> str:
62
+ if type(name) is not str:
63
+ raise TypeError(f"{field_name} must be a string")
64
+ if not name.strip():
65
+ raise ValueError(f"{field_name} must not be empty or whitespace")
66
+ return name
67
+
68
+
69
+ def _normalize_json(
70
+ value: object,
71
+ *,
72
+ path: str,
73
+ active: set[int],
74
+ depth: int,
75
+ ) -> object:
76
+ if depth > _MAX_METADATA_DEPTH:
77
+ raise ValueError(
78
+ f"{path} exceeds the maximum metadata depth of {_MAX_METADATA_DEPTH}"
79
+ )
80
+
81
+ if value is None or type(value) is bool:
82
+ return value
83
+ if isinstance(value, str):
84
+ return str(value)
85
+ if type(value) is int:
86
+ if abs(value) > _MAX_SAFE_INTEGER:
87
+ raise ValueError(
88
+ f"{path} must be within the interoperable JSON integer range"
89
+ )
90
+ return value
91
+ if type(value) is float:
92
+ if not math.isfinite(value):
93
+ raise ValueError(f"{path} must be a finite number")
94
+ if value.is_integer() and abs(value) > _MAX_SAFE_INTEGER:
95
+ raise ValueError(
96
+ f"{path} must be within the interoperable JSON integer range"
97
+ )
98
+ return value
99
+
100
+ if isinstance(value, Mapping):
101
+ identity = id(value)
102
+ if identity in active:
103
+ raise ValueError(f"{path} contains a circular reference")
104
+ active.add(identity)
105
+ try:
106
+ normalized: dict[str, object] = {}
107
+ for key, item in value.items():
108
+ if type(key) is not str:
109
+ raise TypeError(f"{path} keys must be strings")
110
+ normalized[key] = _normalize_json(
111
+ item,
112
+ path=f"{path}.{key}",
113
+ active=active,
114
+ depth=depth + 1,
115
+ )
116
+ return normalized
117
+ finally:
118
+ active.remove(identity)
119
+
120
+ if isinstance(value, (list, tuple)):
121
+ identity = id(value)
122
+ if identity in active:
123
+ raise ValueError(f"{path} contains a circular reference")
124
+ active.add(identity)
125
+ try:
126
+ return [
127
+ _normalize_json(
128
+ item,
129
+ path=f"{path}[{index}]",
130
+ active=active,
131
+ depth=depth + 1,
132
+ )
133
+ for index, item in enumerate(value)
134
+ ]
135
+ finally:
136
+ active.remove(identity)
137
+
138
+ raise TypeError(f"{path} contains a non-JSON value of type {type(value).__name__}")
139
+
140
+
141
+ def _normalize_metadata(
142
+ metadata: Mapping[str, object] | None,
143
+ *,
144
+ path: str = "metadata",
145
+ ) -> dict[str, object]:
146
+ if metadata is None:
147
+ return {}
148
+ if not isinstance(metadata, Mapping):
149
+ raise TypeError(f"{path} must be a mapping")
150
+ normalized = _normalize_json(metadata, path=path, active=set(), depth=0)
151
+ # A mapping input always normalizes to a plain dictionary.
152
+ return normalized # type: ignore[return-value]
153
+
154
+
155
+ def _freeze_json(value: object) -> object:
156
+ if isinstance(value, dict):
157
+ return _FrozenDict({key: _freeze_json(item) for key, item in value.items()})
158
+ if isinstance(value, list):
159
+ return tuple(_freeze_json(item) for item in value)
160
+ return value
161
+
162
+
163
+ def _freeze_metadata(metadata: Mapping[str, object] | None) -> _FrozenDict:
164
+ normalized = _normalize_metadata(metadata)
165
+ frozen = _freeze_json(normalized)
166
+ return frozen # type: ignore[return-value]
167
+
168
+
169
+ def _thaw_json(value: object) -> object:
170
+ if isinstance(value, Mapping):
171
+ return {key: _thaw_json(item) for key, item in value.items()}
172
+ if isinstance(value, tuple):
173
+ return [_thaw_json(item) for item in value]
174
+ return value
175
+
176
+
177
+ def _validate_finite_number(value: object, *, field_name: str) -> float:
178
+ if type(value) not in (int, float):
179
+ raise TypeError(f"{field_name} must be a number")
180
+ try:
181
+ number = float(value)
182
+ except OverflowError as error:
183
+ raise ValueError(f"{field_name} must be finite") from error
184
+ if not math.isfinite(number):
185
+ raise ValueError(f"{field_name} must be finite")
186
+ return number
187
+
188
+
189
+ def _validate_configuration_number(
190
+ value: object,
191
+ *,
192
+ field_name: str,
193
+ positive: bool = False,
194
+ ) -> float:
195
+ number = _validate_finite_number(value, field_name=field_name)
196
+ if positive and number <= 0:
197
+ raise ValueError(f"{field_name} must be greater than zero")
198
+ return number
199
+
200
+
201
+ def _portable_number(value: float) -> int | float:
202
+ if abs(value) <= _MAX_SAFE_INTEGER and value.is_integer():
203
+ return int(value)
204
+ return value
205
+
206
+
207
+ def _coerce_result(result: Result | str) -> Result:
208
+ if isinstance(result, Result):
209
+ return result
210
+ if type(result) is not str:
211
+ raise TypeError("result must be a Result or string")
212
+ try:
213
+ return Result(result)
214
+ except ValueError as error:
215
+ values = ", ".join(repr(member.value) for member in Result)
216
+ raise ValueError(f"result must be one of {values}") from error
217
+
218
+
219
+ @dataclass(frozen=True, slots=True)
220
+ class Contestant:
221
+ """An immutable contestant descriptor."""
222
+
223
+ name: str
224
+ metadata: Mapping[str, object] = field(default_factory=dict)
225
+
226
+ def __post_init__(self) -> None:
227
+ object.__setattr__(self, "name", _validate_name(self.name))
228
+ object.__setattr__(self, "metadata", _freeze_metadata(self.metadata))
229
+
230
+
231
+ @dataclass(frozen=True, slots=True)
232
+ class Match:
233
+ """An immutable recorded match."""
234
+
235
+ id: int
236
+ left: str
237
+ right: str
238
+ result: Result
239
+ metadata: Mapping[str, object] = field(default_factory=dict)
240
+
241
+ def __post_init__(self) -> None:
242
+ if type(self.id) is not int:
243
+ raise TypeError("id must be an integer")
244
+ if self.id < 1:
245
+ raise ValueError("id must be greater than zero")
246
+ left = _validate_name(self.left, field_name="left")
247
+ right = _validate_name(self.right, field_name="right")
248
+ if left == right:
249
+ raise ValueError("left and right must be different contestants")
250
+ object.__setattr__(self, "left", left)
251
+ object.__setattr__(self, "right", right)
252
+ object.__setattr__(self, "result", _coerce_result(self.result))
253
+ object.__setattr__(self, "metadata", _freeze_metadata(self.metadata))
254
+
255
+
256
+ @dataclass(frozen=True, slots=True)
257
+ class Standing:
258
+ """An immutable leaderboard row."""
259
+
260
+ rank: int
261
+ name: str
262
+ rating: float
263
+ wins: int
264
+ losses: int
265
+ draws: int
266
+ matches: int
267
+ metadata: Mapping[str, object] = field(default_factory=dict)
268
+
269
+ def __post_init__(self) -> None:
270
+ if type(self.rank) is not int:
271
+ raise TypeError("rank must be an integer")
272
+ if self.rank < 1:
273
+ raise ValueError("rank must be greater than zero")
274
+ object.__setattr__(self, "name", _validate_name(self.name))
275
+ object.__setattr__(
276
+ self,
277
+ "rating",
278
+ _validate_finite_number(self.rating, field_name="rating"),
279
+ )
280
+ for field_name in ("wins", "losses", "draws", "matches"):
281
+ value = getattr(self, field_name)
282
+ if type(value) is not int:
283
+ raise TypeError(f"{field_name} must be an integer")
284
+ if value < 0:
285
+ raise ValueError(f"{field_name} must not be negative")
286
+ if self.wins + self.losses + self.draws != self.matches:
287
+ raise ValueError("wins, losses, and draws must sum to matches")
288
+ object.__setattr__(self, "metadata", _freeze_metadata(self.metadata))
289
+
290
+ @property
291
+ def played(self) -> int:
292
+ """Compatibility alias for :attr:`matches`."""
293
+
294
+ return self.matches
295
+
296
+ @property
297
+ def score(self) -> float:
298
+ """Return match points using one point per win and half per draw."""
299
+
300
+ return self.wins + (self.draws / 2)
301
+
302
+
303
+ @dataclass(slots=True)
304
+ class _Stats:
305
+ played: int = 0
306
+ wins: int = 0
307
+ draws: int = 0
308
+ losses: int = 0
309
+
310
+
311
+ def expected_score(rating: float, opponent_rating: float) -> float:
312
+ """Return the standard Elo expected score for ``rating``.
313
+
314
+ The numerically stable form remains defined even for very large, but
315
+ finite, rating differences.
316
+ """
317
+
318
+ own = _validate_finite_number(rating, field_name="rating")
319
+ opponent = _validate_finite_number(
320
+ opponent_rating, field_name="opponent_rating"
321
+ )
322
+ exponent = (opponent - own) / 400
323
+ # Clamp at the IEEE-754 base-10 boundary used by the JavaScript package.
324
+ # This also avoids platform-specific subnormal rounding in portable runs.
325
+ if exponent >= 308:
326
+ return 0
327
+ if exponent <= -308:
328
+ return 1
329
+ return 1 / (1 + (10**exponent))
330
+
331
+
332
+ def round_robin(
333
+ contestants: Iterable[str],
334
+ rounds: int = 1,
335
+ ) -> tuple[tuple[str, str], ...]:
336
+ """Build a deterministic round-robin schedule.
337
+
338
+ Caller order is preserved within each repetition. Every pair's orientation
339
+ is reversed on odd-numbered repetitions so repeated schedules balance
340
+ left/right placement.
341
+ """
342
+
343
+ if type(rounds) is not int:
344
+ raise TypeError("rounds must be an integer")
345
+ if rounds < 1:
346
+ raise ValueError("rounds must be at least one")
347
+ if rounds > _MAX_SAFE_INTEGER:
348
+ raise ValueError("rounds must be within the interoperable integer range")
349
+ if isinstance(contestants, (str, bytes, bytearray)):
350
+ raise TypeError("contestants must be an iterable of names")
351
+ try:
352
+ names = tuple(
353
+ _validate_name(name, field_name="contestant")
354
+ for name in contestants
355
+ )
356
+ except TypeError as error:
357
+ if "contestant" in str(error):
358
+ raise
359
+ raise TypeError("contestants must be an iterable of names") from error
360
+ if len(set(names)) != len(names):
361
+ raise ValueError("contestant names must be unique")
362
+
363
+ base = tuple(combinations(names, 2))
364
+ schedule: list[tuple[str, str]] = []
365
+ for repetition in range(rounds):
366
+ if repetition % 2:
367
+ schedule.extend((right, left) for left, right in base)
368
+ else:
369
+ schedule.extend(base)
370
+ return tuple(schedule)
371
+
372
+
373
+ class Arena:
374
+ """A deterministic Elo arena with complete, replayable match history."""
375
+
376
+ def __init__(
377
+ self,
378
+ contestants: (
379
+ Iterable[str] | Mapping[str, Mapping[str, object] | None]
380
+ ),
381
+ *,
382
+ initial_rating: float = 1000,
383
+ k_factor: float = 32,
384
+ ) -> None:
385
+ self._initial_rating = _validate_configuration_number(
386
+ initial_rating,
387
+ field_name="initial_rating",
388
+ )
389
+ self._k_factor = _validate_configuration_number(
390
+ k_factor,
391
+ field_name="k_factor",
392
+ positive=True,
393
+ )
394
+ self._contestants: dict[str, Contestant] = {}
395
+ self._ratings: dict[str, float] = {}
396
+ self._stats: dict[str, _Stats] = {}
397
+ self._matches: list[Match] = []
398
+
399
+ if isinstance(contestants, Mapping):
400
+ for name, metadata in contestants.items():
401
+ self.add(name, metadata)
402
+ return
403
+ if isinstance(contestants, (str, bytes, bytearray)):
404
+ raise TypeError(
405
+ "contestants must be an iterable of names or a metadata mapping"
406
+ )
407
+ try:
408
+ for name in contestants:
409
+ self.add(name)
410
+ except TypeError as error:
411
+ if "name must be a string" in str(error):
412
+ raise
413
+ raise TypeError(
414
+ "contestants must be an iterable of names or a metadata mapping"
415
+ ) from error
416
+
417
+ @property
418
+ def initial_rating(self) -> float:
419
+ return self._initial_rating
420
+
421
+ @property
422
+ def k_factor(self) -> float:
423
+ return self._k_factor
424
+
425
+ @property
426
+ def contestants(self) -> tuple[Contestant, ...]:
427
+ """Return contestants in registration order."""
428
+
429
+ return tuple(self._contestants.values())
430
+
431
+ @property
432
+ def matches(self) -> tuple[Match, ...]:
433
+ """Return immutable match records in chronological order."""
434
+
435
+ return tuple(self._matches)
436
+
437
+ def __len__(self) -> int:
438
+ return len(self._contestants)
439
+
440
+ def add(
441
+ self,
442
+ name: str,
443
+ metadata: Mapping[str, object] | None = None,
444
+ ) -> Contestant:
445
+ """Register and return a contestant."""
446
+
447
+ validated_name = _validate_name(name)
448
+ if validated_name in self._contestants:
449
+ raise ValueError(f"contestant {validated_name!r} already exists")
450
+ contestant = Contestant(
451
+ validated_name,
452
+ metadata if metadata is not None else {},
453
+ )
454
+ self._contestants[validated_name] = contestant
455
+ self._ratings[validated_name] = self._initial_rating
456
+ self._stats[validated_name] = _Stats()
457
+ return contestant
458
+
459
+ def rating(self, name: str) -> float:
460
+ """Return the current rating for a registered contestant."""
461
+
462
+ validated_name = _validate_name(name)
463
+ try:
464
+ return self._ratings[validated_name]
465
+ except KeyError:
466
+ raise KeyError(f"unknown contestant {validated_name!r}") from None
467
+
468
+ def record(
469
+ self,
470
+ left: str,
471
+ right: str,
472
+ result: Result | str,
473
+ metadata: Mapping[str, object] | None = None,
474
+ ) -> Match:
475
+ """Record a match, update both ratings, and return its immutable row."""
476
+
477
+ left_name = self._registered_name(left, field_name="left")
478
+ right_name = self._registered_name(right, field_name="right")
479
+ if left_name == right_name:
480
+ raise ValueError("left and right must be different contestants")
481
+ outcome = _coerce_result(result)
482
+ normalized_metadata = _normalize_metadata(metadata)
483
+
484
+ left_expected = expected_score(
485
+ self._ratings[left_name], self._ratings[right_name]
486
+ )
487
+ if outcome is Result.LEFT:
488
+ left_score = 1.0
489
+ elif outcome is Result.RIGHT:
490
+ left_score = 0.0
491
+ else:
492
+ left_score = 0.5
493
+ adjustment = self._k_factor * (left_score - left_expected)
494
+
495
+ match = Match(
496
+ id=len(self._matches) + 1,
497
+ left=left_name,
498
+ right=right_name,
499
+ result=outcome,
500
+ metadata=normalized_metadata,
501
+ )
502
+
503
+ next_left_rating = self._ratings[left_name] + adjustment
504
+ next_right_rating = self._ratings[right_name] - adjustment
505
+ if not math.isfinite(next_left_rating) or not math.isfinite(
506
+ next_right_rating
507
+ ):
508
+ raise OverflowError("rating update produced a non-finite rating")
509
+
510
+ self._ratings[left_name] = next_left_rating
511
+ self._ratings[right_name] = next_right_rating
512
+ self._apply_stats(left_name, right_name, outcome)
513
+ self._matches.append(match)
514
+ return match
515
+
516
+ def history(self) -> tuple[Match, ...]:
517
+ """Return the same immutable chronological data as :attr:`matches`."""
518
+
519
+ return self.matches
520
+
521
+ def standings(self) -> tuple[Standing, ...]:
522
+ """Return leaderboard rows sorted by rating descending, then name."""
523
+
524
+ ordered_names = sorted(
525
+ self._contestants,
526
+ key=lambda name: (-self._ratings[name], name),
527
+ )
528
+ return tuple(
529
+ Standing(
530
+ rank=rank,
531
+ name=name,
532
+ rating=self._ratings[name],
533
+ wins=self._stats[name].wins,
534
+ losses=self._stats[name].losses,
535
+ draws=self._stats[name].draws,
536
+ matches=self._stats[name].played,
537
+ metadata=self._contestants[name].metadata,
538
+ )
539
+ for rank, name in enumerate(ordered_names, start=1)
540
+ )
541
+
542
+ def leaderboard(self) -> tuple[Standing, ...]:
543
+ """Alias for :meth:`standings`."""
544
+
545
+ return self.standings()
546
+
547
+ def next_pair(self) -> tuple[str, str] | None:
548
+ """Choose the least-played unordered pair deterministically."""
549
+
550
+ names = sorted(self._contestants)
551
+ if len(names) < 2:
552
+ return None
553
+
554
+ pair_matches: dict[tuple[str, str], int] = {}
555
+ for match in self._matches:
556
+ pair = tuple(sorted((match.left, match.right)))
557
+ pair_matches[pair] = pair_matches.get(pair, 0) + 1
558
+
559
+ def priority(pair: tuple[str, str]) -> tuple[int, int, int, str, str]:
560
+ left, right = pair
561
+ left_total = self._stats[left].played
562
+ right_total = self._stats[right].played
563
+ return (
564
+ pair_matches.get(pair, 0),
565
+ left_total + right_total,
566
+ max(left_total, right_total),
567
+ left,
568
+ right,
569
+ )
570
+
571
+ return min(combinations(names, 2), key=priority)
572
+
573
+ def snapshot(self) -> dict[str, object]:
574
+ """Return a detached, JSON-compatible schema-v1 snapshot."""
575
+
576
+ return {
577
+ "schema_version": SCHEMA_VERSION,
578
+ "initial_rating": _portable_number(self._initial_rating),
579
+ "k_factor": _portable_number(self._k_factor),
580
+ "contestants": [
581
+ {
582
+ "name": contestant.name,
583
+ "metadata": _thaw_json(contestant.metadata),
584
+ }
585
+ for contestant in sorted(
586
+ self._contestants.values(),
587
+ key=lambda contestant: contestant.name,
588
+ )
589
+ ],
590
+ "matches": [
591
+ {
592
+ "id": match.id,
593
+ "left": match.left,
594
+ "right": match.right,
595
+ "result": match.result.value,
596
+ "metadata": _thaw_json(match.metadata),
597
+ }
598
+ for match in self._matches
599
+ ],
600
+ }
601
+
602
+ def to_json(self, *, indent: int | None = None) -> str:
603
+ """Serialize :meth:`snapshot` to deterministic JSON."""
604
+
605
+ if indent is not None:
606
+ if type(indent) is not int:
607
+ raise TypeError("indent must be an integer or None")
608
+ if indent < 0:
609
+ raise ValueError("indent must not be negative")
610
+ options: dict[str, Any] = {
611
+ "ensure_ascii": False,
612
+ "allow_nan": False,
613
+ "indent": indent,
614
+ }
615
+ if indent is None:
616
+ options["separators"] = (",", ":")
617
+ return json.dumps(self.snapshot(), **options)
618
+
619
+ @classmethod
620
+ def from_snapshot(cls, snapshot: Mapping[str, object]) -> Arena:
621
+ """Validate schema-v1 data and reconstruct ratings by replaying history."""
622
+
623
+ root = _require_mapping(snapshot, path="snapshot")
624
+ _require_fields(
625
+ root,
626
+ {
627
+ "schema_version",
628
+ "initial_rating",
629
+ "k_factor",
630
+ "contestants",
631
+ "matches",
632
+ },
633
+ path="snapshot",
634
+ )
635
+ version = root["schema_version"]
636
+ if type(version) is not int:
637
+ raise TypeError("snapshot.schema_version must be an integer")
638
+ if version != SCHEMA_VERSION:
639
+ raise ValueError(
640
+ f"unsupported schema_version {version!r}; expected {SCHEMA_VERSION}"
641
+ )
642
+
643
+ contestants_data = root["contestants"]
644
+ matches_data = root["matches"]
645
+ if type(contestants_data) is not list:
646
+ raise TypeError("snapshot.contestants must be a list")
647
+ if type(matches_data) is not list:
648
+ raise TypeError("snapshot.matches must be a list")
649
+
650
+ arena = cls(
651
+ [],
652
+ initial_rating=root["initial_rating"], # type: ignore[arg-type]
653
+ k_factor=root["k_factor"], # type: ignore[arg-type]
654
+ )
655
+ for index, raw_contestant in enumerate(contestants_data):
656
+ path = f"snapshot.contestants[{index}]"
657
+ contestant = _require_mapping(raw_contestant, path=path)
658
+ _require_fields(contestant, {"name", "metadata"}, path=path)
659
+ metadata = _require_mapping(
660
+ contestant["metadata"], path=f"{path}.metadata"
661
+ )
662
+ arena.add(contestant["name"], metadata) # type: ignore[arg-type]
663
+
664
+ for index, raw_match in enumerate(matches_data):
665
+ path = f"snapshot.matches[{index}]"
666
+ match = _require_mapping(raw_match, path=path)
667
+ _require_fields(
668
+ match,
669
+ {"id", "left", "right", "result", "metadata"},
670
+ path=path,
671
+ )
672
+ expected_id = index + 1
673
+ match_id = match["id"]
674
+ if type(match_id) is not int:
675
+ raise TypeError(f"{path}.id must be an integer")
676
+ if match_id != expected_id:
677
+ raise ValueError(
678
+ f"{path}.id must be contiguous; expected {expected_id}"
679
+ )
680
+ if type(match["result"]) is not str:
681
+ raise TypeError(f"{path}.result must be a string")
682
+ metadata = _require_mapping(match["metadata"], path=f"{path}.metadata")
683
+ recorded = arena.record(
684
+ match["left"], # type: ignore[arg-type]
685
+ match["right"], # type: ignore[arg-type]
686
+ match["result"],
687
+ metadata,
688
+ )
689
+ if recorded.id != match_id: # Defensive assertion for subclasses.
690
+ raise ValueError(f"{path}.id could not be reproduced")
691
+ return arena
692
+
693
+ @classmethod
694
+ def from_json(cls, payload: str | bytes | bytearray) -> Arena:
695
+ """Parse strict JSON and delegate to :meth:`from_snapshot`."""
696
+
697
+ if not isinstance(payload, (str, bytes, bytearray)):
698
+ raise TypeError("payload must be str, bytes, or bytearray")
699
+
700
+ def reject_constant(value: str) -> object:
701
+ raise ValueError(f"non-standard JSON constant {value!r} is not allowed")
702
+
703
+ def reject_duplicate_keys(
704
+ pairs: list[tuple[str, object]],
705
+ ) -> dict[str, object]:
706
+ parsed: dict[str, object] = {}
707
+ for key, value in pairs:
708
+ if key in parsed:
709
+ raise ValueError(f"duplicate JSON key {key!r}")
710
+ parsed[key] = value
711
+ return parsed
712
+
713
+ try:
714
+ decoded = json.loads(
715
+ payload,
716
+ parse_constant=reject_constant,
717
+ object_pairs_hook=reject_duplicate_keys,
718
+ )
719
+ except (json.JSONDecodeError, UnicodeDecodeError) as error:
720
+ raise ValueError(f"invalid JSON: {error}") from error
721
+ return cls.from_snapshot(decoded)
722
+
723
+ def _registered_name(self, name: object, *, field_name: str) -> str:
724
+ validated_name = _validate_name(name, field_name=field_name)
725
+ if validated_name not in self._contestants:
726
+ raise KeyError(f"unknown contestant {validated_name!r}")
727
+ return validated_name
728
+
729
+ def _apply_stats(self, left: str, right: str, result: Result) -> None:
730
+ left_stats = self._stats[left]
731
+ right_stats = self._stats[right]
732
+ left_stats.played += 1
733
+ right_stats.played += 1
734
+ if result is Result.LEFT:
735
+ left_stats.wins += 1
736
+ right_stats.losses += 1
737
+ elif result is Result.RIGHT:
738
+ right_stats.wins += 1
739
+ left_stats.losses += 1
740
+ else:
741
+ left_stats.draws += 1
742
+ right_stats.draws += 1
743
+
744
+
745
+ def _require_mapping(value: object, *, path: str) -> Mapping[str, object]:
746
+ if not isinstance(value, Mapping):
747
+ raise TypeError(f"{path} must be a mapping")
748
+ for key in value:
749
+ if type(key) is not str:
750
+ raise TypeError(f"{path} keys must be strings")
751
+ return value
752
+
753
+
754
+ def _require_fields(
755
+ value: Mapping[str, object],
756
+ expected: set[str],
757
+ *,
758
+ path: str,
759
+ ) -> None:
760
+ actual = set(value)
761
+ missing = sorted(expected - actual)
762
+ extra = sorted(actual - expected)
763
+ if not missing and not extra:
764
+ return
765
+ details: list[str] = []
766
+ if missing:
767
+ details.append(f"missing {', '.join(missing)}")
768
+ if extra:
769
+ details.append(f"unexpected {', '.join(extra)}")
770
+ raise ValueError(f"{path} has invalid fields: {'; '.join(details)}")
localarena/py.typed ADDED
@@ -0,0 +1 @@
1
+ # Marker file for PEP 561.
@@ -0,0 +1,76 @@
1
+ Metadata-Version: 2.4
2
+ Name: localarena
3
+ Version: 0.1.0
4
+ Summary: A small, deterministic Elo arena for local model comparisons
5
+ Project-URL: Homepage, https://github.com/maziyarpanahi/localarena
6
+ Project-URL: Repository, https://github.com/maziyarpanahi/localarena
7
+ Project-URL: Issues, https://github.com/maziyarpanahi/localarena/issues
8
+ Author: Maziyar Panahi
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: arena,elo,evaluation,leaderboard,local-models
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+
24
+ # localarena
25
+
26
+ `localarena` is a zero-dependency Elo arena for deterministic, local
27
+ head-to-head comparisons. It keeps contestant metadata, match history, and
28
+ ratings together in a portable versioned snapshot.
29
+
30
+ ```bash
31
+ pip install localarena
32
+ ```
33
+
34
+ ```python
35
+ from localarena import Arena, Result
36
+
37
+ arena = Arena(
38
+ {
39
+ "model-a": {"provider": "local"},
40
+ "model-b": {"provider": "local"},
41
+ }
42
+ )
43
+
44
+ arena.record("model-a", "model-b", Result.LEFT, {"prompt_id": "demo-1"})
45
+
46
+ for row in arena.standings():
47
+ print(row.rank, row.name, row.rating)
48
+
49
+ pair = arena.next_pair()
50
+ payload = arena.to_json()
51
+ restored = Arena.from_json(payload)
52
+ ```
53
+
54
+ ## API
55
+
56
+ - `Arena(contestants, initial_rating=1000, k_factor=32)` accepts an iterable
57
+ of unique names or a mapping of names to metadata.
58
+ - `add(name, metadata=None)` registers another contestant.
59
+ - `record(left, right, result, metadata=None)` records a match and applies an
60
+ Elo update. Results are `"left"`, `"right"`, or `"draw"`.
61
+ - `standings()` and its alias `leaderboard()` return immutable rows ordered by
62
+ rating descending, then name.
63
+ - `next_pair()` chooses the least-played unordered pair deterministically.
64
+ - `matches` and `history()` expose immutable match records.
65
+ - `snapshot()` / `to_json()` produce schema-v1 data with contestants sorted by
66
+ name;
67
+ `from_snapshot()` / `from_json()` validate and replay that history.
68
+ - `expected_score()` and `round_robin()` are available as standalone helpers.
69
+
70
+ Metadata must be a JSON object. Nested dictionaries, lists, tuples, strings,
71
+ booleans, `None`, finite numbers, and interoperable safe integers are
72
+ accepted. Public records recursively freeze metadata; snapshots return
73
+ detached ordinary dictionaries and lists.
74
+
75
+ The npm package uses the same result values and schema-v1 snapshot format, so
76
+ match histories can move between Python and JavaScript.
@@ -0,0 +1,7 @@
1
+ localarena/__init__.py,sha256=h1CzcRp8p_ZAANd-C0KoAxwGr27ieys0QaN1PaaqYFk,369
2
+ localarena/core.py,sha256=h1aYHbUtpGElTurrNT5j7sXdW4fTDKK_yP7Y1vxwRng,25693
3
+ localarena/py.typed,sha256=bWew9mHgMy8LqMu7RuqQXFXLBxh2CRx0dUbSx-3wE48,27
4
+ localarena-0.1.0.dist-info/METADATA,sha256=ehadseXHCsZgL7FmqKwXVh2JLskgyYxVs3lYLzUKsXo,2812
5
+ localarena-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
6
+ localarena-0.1.0.dist-info/licenses/LICENSE,sha256=UOZ1F5fFDe3XXvG4oNnkL1-Ecun7zpHzRxjp-XsMeAo,11324
7
+ localarena-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.