Coverage for src/retrospeedlab/runner/allocation.py: 100%

28 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-12-02 22:44 +0000

1import hashlib 

2from dataclasses import dataclass 

3 

4from retrospeedlab.search.settings import SpeedrunSettings 

5 

6KINDS = { 

7 "scout": "scouts", 

8 "backtracker": "backtrackers", 

9 "beam-scout": "beam_scouts", 

10 "vision-scout": "vision_scouts", 

11 "polisher": "polishers", 

12} 

13DRAW_BYTES = 8 

14 

15 

16@dataclass(frozen=True, slots=True) 

17class Allocation: 

18 arm: str 

19 workers: dict[str, int] 

20 

21 

22def static_workers(speedrun: SpeedrunSettings) -> dict[str, int]: 

23 return speedrun.model_dump(include=set(KINDS.values())) 

24 

25 

26def enabled(static: dict[str, int]) -> list[str]: 

27 return [kind for kind, count in static.items() if count > 0] 

28 

29 

30def measured(static: dict[str, int], shares: dict[str, float]) -> list[str]: 

31 return [kind for kind in enabled(static) if kind in shares] 

32 

33 

34def allocated(static: dict[str, int], shares: dict[str, float]) -> dict[str, int]: 

35 kinds = measured(static, shares) 

36 total = sum(static[kind] for kind in kinds) 

37 weight = sum(shares[kind] for kind in kinds) 

38 ideal = {kind: (total - len(kinds)) * shares[kind] / weight for kind in kinds} 

39 counts = {kind: 1 + int(ideal[kind]) for kind in kinds} 

40 remainders = sorted(kinds, key=lambda kind: ideal[kind] - int(ideal[kind]), reverse=True) 

41 for kind in remainders[: total - sum(counts.values())]: 

42 counts[kind] += 1 

43 return {kind: counts[kind] if kind in counts else static[kind] for kind in static} 

44 

45 

46def in_holdout(turn: int, slug: str, holdout: float) -> bool: 

47 digest = hashlib.sha256(f"{turn}/{slug}".encode()).digest() 

48 return int.from_bytes(digest[:DRAW_BYTES]) / 2 ** (8 * DRAW_BYTES) < holdout