Coverage for services/power_rating_service.py: 93.41%

67 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2026-11-30 18:21 +0000

1"""Recompute the MT Power Rating (SB-1807). 

2 

3Orchestration only: per age group, gather the season's matches through the DAO, 

4skip when the input fingerprint matches the latest run, otherwise rate with the 

5pure engine (`mt_tools.power_rating`) and write the run. The nightly Celery beat 

6task (`power_rating.recompute_all`) and `POST /api/admin/power-rating/recompute` 

7both call `recompute`, so the two can never rate differently. 

8 

9One age group failing does not stop the others: it is reported as `failed` in 

10the summary, with the detail in the log. 

11""" 

12 

13from __future__ import annotations 

14 

15from datetime import UTC, datetime 

16from typing import TYPE_CHECKING, Any, Literal, Protocol 

17 

18import structlog 

19from pydantic import BaseModel 

20 

21from dao.power_rating_dao import ( 

22 Gathered, 

23 LeagueScope, 

24 delta_rows, 

25 fingerprint, 

26 matches_excluded, 

27 rating_rows, 

28 run_row, 

29) 

30from mt_tools.power_rating import massey, rate 

31 

32if TYPE_CHECKING: 

33 from collections.abc import Iterable 

34 

35logger = structlog.get_logger() 

36 

37DEFAULT_AGE_GROUPS = ("U15", "U16", "U17", "U19") 

38DEFAULT_LEAGUE = "Homegrown" 

39 

40 

41class PowerRatingStore(Protocol): 

42 """What `recompute` needs of the DAO (`dao.power_rating_dao.PowerRatingDAO`).""" 

43 

44 def current_season_id(self) -> int | None: ... 44 ↛ exitline 44 didn't return from function 'current_season_id' because

45 def resolve_league(self, name: str) -> LeagueScope | None: ... 45 ↛ exitline 45 didn't return from function 'resolve_league' because

46 def age_group_ids(self, names: Iterable[str]) -> dict[str, int]: ... 46 ↛ exitline 46 didn't return from function 'age_group_ids' because

47 def gather(self, season_id: int, age_group_id: int, scope: LeagueScope) -> Gathered: ... 47 ↛ exitline 47 didn't return from function 'gather' because

48 def latest_run(self, season_id: int, age_group_id: int, league_id: int) -> dict | None: ... 48 ↛ exitline 48 didn't return from function 'latest_run' because

49 def write_run(self, run: dict, ratings: list[dict], deltas: list[dict]) -> int: ... 49 ↛ exitline 49 didn't return from function 'write_run' because

50 

51 

52class InvalidRecomputeError(ValueError): 

53 """Unknown league or age group, or no season: the caller's input, not MT's state.""" 

54 

55 

56class AgeGroupSummary(BaseModel): 

57 age_group: str 

58 # written: a new run; unchanged: same input as the latest run, nothing written; 

59 # failed: see the log. 

60 status: Literal["written", "unchanged", "failed"] 

61 run_id: int | None = None # the new run, or the latest one when unchanged 

62 matches_counted: int | None = None 

63 matches_excluded: dict[str, int] | None = None 

64 teams: int | None = None 

65 national: bool | None = None 

66 reason: str | None = None 

67 

68 

69class RecomputeSummary(BaseModel): 

70 season_id: int 

71 league: str 

72 computed_at: datetime 

73 age_groups: list[AgeGroupSummary] 

74 

75 

76def recompute( 

77 store: PowerRatingStore, 

78 season_id: int | None = None, 

79 age_groups: Iterable[str] = DEFAULT_AGE_GROUPS, 

80 league: str = DEFAULT_LEAGUE, 

81 *, 

82 now: datetime | None = None, 

83) -> RecomputeSummary: 

84 """Rate each age group's season and store every run whose input changed. 

85 

86 Raises InvalidRecomputeError for an unknown league or age group, or no current season. 

87 """ 

88 names = list(dict.fromkeys(age_groups)) 

89 computed_at = now or datetime.now(UTC) 

90 if season_id is None: 

91 season_id = store.current_season_id() 

92 if season_id is None: 

93 raise InvalidRecomputeError("No current season is set.") 

94 scope = store.resolve_league(league) 

95 if scope is None: 

96 raise InvalidRecomputeError(f"No top-level league named {league!r}.") 

97 ids = store.age_group_ids(names) 

98 unknown = [n for n in names if n not in ids] 

99 if unknown: 

100 raise InvalidRecomputeError(f"Unknown age group(s): {', '.join(unknown)}.") 

101 

102 summaries = [] 

103 for name in names: 

104 try: 

105 summaries.append(_one(store, season_id, ids[name], name, scope, computed_at)) 

106 except Exception: 

107 logger.exception("power_rating_recompute_failed", season_id=season_id, age_group=name) 

108 summaries.append(AgeGroupSummary(age_group=name, status="failed", reason="Could not recompute.")) 

109 summary = RecomputeSummary(season_id=season_id, league=scope.name, computed_at=computed_at, age_groups=summaries) 

110 logger.info( 

111 "power_rating_recomputed", 

112 season_id=season_id, 

113 league=scope.name, 

114 **{s.age_group: s.status for s in summaries}, 

115 ) 

116 return summary 

117 

118 

119def _one( 

120 store: PowerRatingStore, 

121 season_id: int, 

122 age_group_id: int, 

123 name: str, 

124 scope: LeagueScope, 

125 computed_at: datetime, 

126) -> AgeGroupSummary: 

127 gathered = store.gather(season_id, age_group_id, scope) 

128 digest = fingerprint(gathered) 

129 latest = store.latest_run(season_id, age_group_id, scope.league_id) 

130 if latest and latest.get("input_fingerprint") == digest: 

131 return AgeGroupSummary(age_group=name, status="unchanged", run_id=latest["id"]) 

132 

133 result = rate(gathered.matches) 

134 audit = massey(gathered.matches) 

135 run: dict[str, Any] = run_row( 

136 season_id=season_id, 

137 age_group_id=age_group_id, 

138 league_id=scope.league_id, 

139 result=result, 

140 gathered=gathered, 

141 input_fingerprint=digest, 

142 computed_at=computed_at, 

143 ) 

144 run_id = store.write_run(run, rating_rows(result, audit, gathered.conference_ids), delta_rows(result)) 

145 return AgeGroupSummary( 

146 age_group=name, 

147 status="written", 

148 run_id=run_id, 

149 matches_counted=result.matches_counted, 

150 matches_excluded=matches_excluded(result, gathered), 

151 teams=len(result.teams), 

152 national=result.publication.national, 

153 reason=result.publication.reason, 

154 )