Coverage for mt_tools/power_rating_audit.py: 96.72%
104 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 14:44 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 14:44 +0000
1"""The admin Massey audit of the MT Power Rating (SB-1812).
3Elo is published; Massey runs beside it every night as a check (design
4"Open decisions" 1). This reads the latest stored run and lists the teams whose
5two places differ by more than `min_gap` (default 30, about the worst 5% at the
62026-11-26 freeze). Investigate, never auto-fix: nothing here changes a rating.
8## Like with like
10The stored `massey_rank` counts ranked teams (6+ matches) **within their
11island**, because separate islands are not on one scale. The national `rank`
12counts the main island only, and only on a national run, so it cannot be the
13other side. The Elo rank here is therefore recomputed the same way the Massey
14one was stored: the same teams, within the same island, by rating, ties by
15team id (`mt_tools.power_rating.rank_gaps` does the same at compute time).
17Two layers, as in `power_rating_read`: `build_audit` is pure over the stored
18rows, `get_power_rating_audit` gathers them.
19"""
21from collections import defaultdict
22from collections.abc import Mapping
23from datetime import date
24from typing import Any, Literal
26import structlog
27from pydantic import BaseModel
29from mt_ai.tools.deps import ToolDeps
30from mt_ai.tools.schemas import ToolError
31from mt_ai.tools.visibility import DataUnavailableError
32from mt_tools.leaderboards import _InvalidArgsError
33from mt_tools.power_rating import MIN_MATCHES, RANK_GAP_FLAG, _ranks
34from mt_tools.power_rating_read import (
35 UNAVAILABLE,
36 RunRef,
37 TeamInfo,
38 _conference_names,
39 _payload,
40 _scope,
41 _team_info,
42 no_run,
43 run_ref,
44)
46logger = structlog.get_logger()
48SCOPE = (
49 "Within each island: ranked teams (6+ matches) ordered by Elo rating and by Massey, so both ranks count "
50 "the same teams."
51)
52NOTE = "Investigate, don't auto-fix: a large gap usually means few matches or few cross-conference matches."
55class AuditRow(BaseModel):
56 team_id: int
57 team: str
58 conference: str | None = None
59 island: int
60 elo_rating: int
61 elo_rank: int # within the island
62 massey_rank: int # within the island
63 gap: int # massey_rank - elo_rank: positive when Elo ranks the team higher
64 mp: int
65 xconf_mp: int
66 badges: list[str]
69class AuditIsland(BaseModel):
70 island: int
71 teams: int # ranked teams compared in this island
72 flagged: int
73 rank_correlation: float | None = None # Spearman; null under 2 teams
76class PowerRatingAuditResult(BaseModel):
77 """Elo vs Massey places in the latest run. `teams` [] with `reason` when there is nothing to compare."""
79 league: str
80 age_group: str | None = None
81 season: str | None = None
82 run: RunRef | None = None
83 min_gap: int = RANK_GAP_FLAG
84 scope: str = SCOPE
85 note: str = NOTE
86 teams_compared: int = 0
87 flagged_count: int = 0
88 rank_correlation: float | None = None # of the largest island
89 islands: list[AuditIsland] = []
90 teams: list[AuditRow] | None = None
91 reason: str | None = None
92 error: ToolError | None = None
95def spearman(a: Mapping[int, int], b: Mapping[int, int]) -> float | None:
96 """Rank correlation of two tie-free rankings of the same teams; None under 2 teams."""
97 n = len(a)
98 if n < 2:
99 return None
100 d2 = sum((a[t] - b[t]) ** 2 for t in a)
101 return round(1 - 6 * d2 / (n * (n * n - 1)), 3)
104def build_audit(
105 payload: Mapping[str, Any],
106 massey_ranks: Mapping[int, int],
107 teams: Mapping[int, TeamInfo],
108 *,
109 league: str,
110 age_group: str,
111 season: str,
112 min_gap: int = RANK_GAP_FLAG,
113) -> PowerRatingAuditResult:
114 """Teams whose Elo and Massey places, within their island, differ by more than `min_gap`.
116 A team missing from `teams` is still compared and listed, by id: it was in
117 the run, so it moved the other teams' places.
118 """
119 conferences = _conference_names(payload)
120 by_island: dict[int, list[Mapping[str, Any]]] = defaultdict(list)
121 for r in payload.get("ratings") or []:
122 if r["mp"] >= MIN_MATCHES and r["team_id"] in massey_ranks:
123 by_island[r["island"]].append(r)
125 rows: list[AuditRow] = []
126 islands: list[AuditIsland] = []
127 for island, members in by_island.items():
128 ids = [r["team_id"] for r in members]
129 elo = _ranks(ids, {r["team_id"]: r["rating"] for r in members})
130 massey = {t: massey_ranks[t] for t in ids}
131 flagged = []
132 for r in members:
133 t = r["team_id"]
134 gap = massey[t] - elo[t]
135 if abs(gap) <= min_gap:
136 continue
137 info = teams.get(t)
138 flagged.append(
139 AuditRow(
140 team_id=t,
141 team=info.name if info else str(t),
142 conference=conferences.get(t),
143 island=island,
144 elo_rating=round(r["rating"]),
145 elo_rank=elo[t],
146 massey_rank=massey[t],
147 gap=gap,
148 mp=r["mp"],
149 xconf_mp=r.get("xconf_mp") or 0,
150 badges=list(r.get("badges") or []),
151 )
152 )
153 rows.extend(flagged)
154 islands.append(
155 AuditIsland(island=island, teams=len(ids), flagged=len(flagged), rank_correlation=spearman(elo, massey))
156 )
158 islands.sort(key=lambda i: (-i.teams, i.island))
159 rows.sort(key=lambda g: (-abs(g.gap), g.team_id))
160 compared = sum(i.teams for i in islands)
161 return PowerRatingAuditResult(
162 league=league,
163 age_group=age_group,
164 season=season,
165 run=run_ref(payload["run"]),
166 min_gap=min_gap,
167 teams_compared=compared,
168 flagged_count=len(rows),
169 rank_correlation=islands[0].rank_correlation if islands else None,
170 islands=islands,
171 teams=rows,
172 reason=None if compared else f"No ranked teams with a Massey rank at {age_group} {league} in {season}.",
173 )
176def get_power_rating_audit(
177 deps: ToolDeps,
178 age_group: str,
179 league: str = "Homegrown",
180 season: str | None = None,
181 *,
182 min_gap: int = RANK_GAP_FLAG,
183 today: date | None = None,
184) -> PowerRatingAuditResult:
185 """The Elo vs Massey audit of the latest run for `league` at `age_group`."""
187 def fail(kind: Literal["unavailable", "invalid_args"], message: str) -> PowerRatingAuditResult:
188 return PowerRatingAuditResult(league=league, min_gap=min_gap, error=ToolError(kind=kind, message=message))
190 if min_gap < 0:
191 return fail("invalid_args", "min_gap must be 0 or more.")
192 store = deps.power_rating
193 try:
194 if store is None: 194 ↛ 195line 194 didn't jump to line 195 because the condition on line 194 was never true
195 raise DataUnavailableError("no power rating source")
196 s = _scope(deps, league, age_group, season, today or date.today())
197 latest = store.latest_run(s.season_id, s.age_group_id, s.league_id)
198 if latest is None:
199 return PowerRatingAuditResult(
200 league=s.league,
201 age_group=s.age_group,
202 season=s.season,
203 min_gap=min_gap,
204 teams=[],
205 reason=no_run(s.league, s.age_group, s.season).reason,
206 )
207 payload = _payload(store, latest["id"])
208 result = build_audit(
209 payload,
210 store.massey_ranks(latest["id"]),
211 _team_info(s.index),
212 league=s.league,
213 age_group=s.age_group,
214 season=s.season,
215 min_gap=min_gap,
216 )
217 except _InvalidArgsError as exc:
218 return fail("invalid_args", str(exc))
219 except DataUnavailableError as exc:
220 logger.warning("power_rating_audit_unavailable", error=str(exc))
221 return fail("unavailable", UNAVAILABLE)
222 except Exception:
223 logger.exception("get_power_rating_audit failed")
224 return fail("unavailable", UNAVAILABLE)
225 logger.info(
226 "power_rating_audit_served",
227 league=result.league,
228 age_group=result.age_group,
229 run_id=result.run.id if result.run else None,
230 compared=result.teams_compared,
231 flagged=result.flagged_count,
232 )
233 return result